Skip to main content

tabnas_abnf/
lib.rs

1// Copyright (c) 2025-2026 Richard Rodger and other contributors, MIT License
2
3//! An ABNF (RFC 5234) grammar compiler for the
4//! [`tabnas`](https://github.com/tabnas/parser) parsing engine.
5//!
6//! Where most tabnas grammar crates carry one fixed grammar, this one is
7//! a META compiler: the grammar it installs is whatever ABNF text it is
8//! handed at run time.
9//!
10//! ```text
11//! ABNF text ──parse_abnf──▶ Grammar ──emit_grammar_spec──▶ GrammarSpec
12//! ```
13//!
14//! [`parse_abnf`] is the RFC 5234 front-end and is what this crate adds;
15//! everything downstream of the IR lives in
16//! [`tabnas_bnf`](https://github.com/tabnas/bnf) and is shared with the
17//! GBNF and EBNF front-ends.
18//!
19//! ```
20//! let mut parser = tabnas::Tabnas::new();
21//! tabnas_abnf::abnf(&mut parser, "greet = \"hi\" / \"hello\"", None).unwrap();
22//! let tree = parser.parse("hello").unwrap();
23//! assert_eq!(tree.to_json()["rule"], "greet");
24//! ```
25//!
26//! This is the Rust port of the canonical TypeScript implementation in
27//! `ts/src`; the TypeScript version is authoritative and this crate
28//! tracks it.
29
30mod compile;
31mod converter;
32mod numeric;
33mod parser_abnf;
34mod tree;
35
36/// The README's Rust examples run as doctests, so a stale one fails the
37/// gate rather than misleading the reader. Its `toml` and `bash` fences
38/// are skipped; rustdoc runs only the `rust` ones.
39#[cfg(doctest)]
40#[doc = include_str!("../README.md")]
41mod readme_examples {}
42
43use std::fmt;
44
45use tabnas::{Plugin, PluginError, Tabnas, Value};
46
47pub use compile::abnf_compile;
48pub use converter::{parse_abnf, AbnfParseError};
49pub use parser_abnf::abnf_rules;
50pub use tree::{make, parse_abnf_tree};
51
52pub use tabnas_bnf::{
53    attach_action_slots, attach_actions, eliminate_left_recursion, mark_listing, to_jsonic,
54    to_pure_spec, to_recognition_spec, transduce_alc, ActionError as AbnfActionError, ActionFn,
55    ActionsMap, AltSpec, CompileError as AbnfCompileError, ConvertOptions as AbnfConvertOptions,
56    Element, EmitError, Grammar, GrammarSpec, JsonicOptions, Kind, NodeKind, Production, RefAction,
57    RuleSpec, Sequence, SrcSpan, TransducePart, ValueAnnotation,
58};
59
60/// This crate's version. It MUST equal `ts/package.json` "version": the
61/// release orchestrator rewrites both, and `tests/version_test.rs` fails
62/// the build if they drift. Mirrors `VERSION` in `ts/src/abnf.ts` and
63/// `const VERSION` in `go/abnf.go`.
64pub const VERSION: &str = "0.5.1";
65
66/// The group tag stamped on every emitted alt, and the prefix of every
67/// diagnostic this crate raises through the shared compiler.
68pub const TAG: &str = "abnf";
69
70/// Anything that can go wrong turning ABNF source into a grammar.
71#[derive(Debug, Clone, PartialEq)]
72pub enum AbnfError {
73    /// The ABNF source itself could not be read.
74    Parse(AbnfParseError),
75    /// The shared compiler refused the grammar.
76    Emit(EmitError),
77    /// The emitted spec could not be lowered to pure data.
78    Compile(AbnfCompileError),
79    /// A user action could not be attached.
80    Action(AbnfActionError),
81    /// The engine refused the emitted grammar.
82    Install(String),
83}
84
85impl fmt::Display for AbnfError {
86    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            Self::Parse(error) => error.fmt(formatter),
89            Self::Emit(error) => error.fmt(formatter),
90            Self::Compile(error) => error.fmt(formatter),
91            Self::Action(error) => error.fmt(formatter),
92            Self::Install(message) => formatter.write_str(message),
93        }
94    }
95}
96
97impl std::error::Error for AbnfError {}
98
99impl From<AbnfParseError> for AbnfError {
100    fn from(error: AbnfParseError) -> Self {
101        Self::Parse(error)
102    }
103}
104
105impl From<EmitError> for AbnfError {
106    fn from(error: EmitError) -> Self {
107        Self::Emit(error)
108    }
109}
110
111impl From<AbnfCompileError> for AbnfError {
112    fn from(error: AbnfCompileError) -> Self {
113        Self::Compile(error)
114    }
115}
116
117impl From<AbnfActionError> for AbnfError {
118    fn from(error: AbnfActionError) -> Self {
119        Self::Action(error)
120    }
121}
122
123/// Options for [`abnf_compile`]: what to convert, and how to serialize
124/// it.
125///
126/// The shared compiler's own `CompileOptions` carries only the
127/// serialization half, because the conversion half is the front-end's;
128/// this adds `start` and `tag`, exactly as `AbnfCompileOptions` does in
129/// the Go port.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct AbnfCompileOptions {
132    /// Start rule name (default: the first production).
133    pub start: Option<String>,
134    /// Group tag stamped on every emitted alt (default `abnf`).
135    pub tag: Option<String>,
136    /// Emit a pure RECOGNITION grammar, with tree building dropped.
137    /// `false` keeps the tree builtins, still as pure data.
138    pub recognition: bool,
139    /// Valid JSON rather than relaxed jsonic.
140    pub strict: bool,
141    /// Spaces per level (default 2).
142    pub indent: Option<usize>,
143}
144
145impl Default for AbnfCompileOptions {
146    fn default() -> Self {
147        Self {
148            start: None,
149            tag: None,
150            recognition: true,
151            strict: false,
152            indent: None,
153        }
154    }
155}
156
157/// Options for [`abnf`], the install path.
158///
159/// Mirrors the canonical `AbnfPluginOptions`: the conversion options,
160/// plus the user actions to attach. Supplying actions forces closure
161/// mode and requests marks, because a user action wraps the compiler's
162/// own closures.
163#[derive(Clone, Default)]
164pub struct AbnfOptions {
165    /// How to convert the source.
166    pub convert: AbnfConvertOptions,
167    /// User semantic actions, by `@<rule>:<phase>` or
168    /// `@<rule>:o|c:<mark>` reference.
169    pub actions: Option<ActionsMap>,
170}
171
172impl AbnfOptions {
173    /// Conversion options alone.
174    pub fn new(convert: AbnfConvertOptions) -> Self {
175        Self {
176            convert,
177            actions: None,
178        }
179    }
180
181    /// The same options carrying user actions.
182    pub fn with_actions(mut self, actions: ActionsMap) -> Self {
183        self.actions = Some(actions);
184        self
185    }
186}
187
188impl fmt::Debug for AbnfOptions {
189    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
190        formatter
191            .debug_struct("AbnfOptions")
192            .field("convert", &self.convert)
193            .field(
194                "actions",
195                &self.actions.as_ref().map(|actions| actions.len()),
196            )
197            .finish()
198    }
199}
200
201/// Emit a spec from an already-parsed ABNF grammar.
202///
203/// Wraps the shared emitter to keep this crate's historical `abnf` tag
204/// default, which consumers use to group and inspect the emitted alts.
205/// An explicit tag still wins.
206pub fn emit_grammar_spec(
207    grammar: &Grammar,
208    opts: Option<&AbnfConvertOptions>,
209) -> Result<GrammarSpec, EmitError> {
210    let mut options = opts.cloned().unwrap_or_default();
211    if options.tag.is_none() {
212        options.tag = Some(TAG.to_string());
213    }
214    tabnas_bnf::emit_grammar_spec(grammar, &options)
215}
216
217/// Convert ABNF source into a tabnas grammar spec, without installing
218/// it. The Rust spelling of `tn.abnf.toSpec(src)`.
219pub fn abnf_convert(
220    src: &str,
221    opts: Option<&AbnfConvertOptions>,
222) -> Result<GrammarSpec, AbnfError> {
223    let grammar = parse_abnf(src)?;
224    Ok(emit_grammar_spec(&grammar, opts)?)
225}
226
227/// The transducer part of an ABNF grammar, `<name>-transduce`: the alchemy
228/// program that streams the JSON events of the value its `; @object` and
229/// `; @array` annotations build, from its rule passes, or why its
230/// documents are read whole ([`transduce_alc`] says when). Converts as
231/// [`abnf_convert`] does, with `opts`. The Rust spelling of
232/// `abnfTransduce`.
233pub fn abnf_transduce(
234    src: &str,
235    name: &str,
236    opts: Option<&AbnfConvertOptions>,
237) -> Result<TransducePart, AbnfError> {
238    Ok(transduce_alc(&abnf_convert(src, opts)?, name))
239}
240
241/// Convert ABNF source and install the resulting grammar on `parser`.
242///
243/// The Rust spelling of the callable `tn.abnf(src, opts)` the canonical
244/// plugin decorates an instance with. With actions supplied, conversion
245/// runs in closure mode with marks and the actions are attached before
246/// the grammar is installed.
247pub fn abnf(
248    parser: &mut Tabnas,
249    src: &str,
250    opts: Option<&AbnfOptions>,
251) -> Result<GrammarSpec, AbnfError> {
252    let mut convert = opts.map(|opts| opts.convert.clone()).unwrap_or_default();
253    let actions = opts.and_then(|opts| opts.actions.clone());
254    if actions.is_some() {
255        // User actions wrap the compiler's closures, so convert in
256        // closure mode (never builtins) and request marks.
257        convert.builtins = false;
258        convert.marks = true;
259    }
260    let mut spec = abnf_convert(src, Some(&convert))?;
261    if let Some(actions) = actions {
262        attach_actions(&mut spec, actions)?;
263    }
264    spec.install(parser)
265        .map_err(|error| AbnfError::Install(error.to_string()))?;
266    Ok(spec)
267}
268
269/// The plugin descriptor, for [`Tabnas::use_plugin`].
270///
271/// A grammar this crate installs is whatever ABNF the caller hands over,
272/// so the plugin has nothing of its own to install and records itself on
273/// the instance instead, exactly as the Go `Plugin` does. Pass
274/// `{"src": "<abnf text>"}` in the option bag to have it convert and
275/// install that source; otherwise call [`abnf`] directly, which is the
276/// typed way in.
277pub fn plugin() -> Plugin {
278    Plugin::new("Abnf", |parser, options| {
279        let source = match options {
280            Value::Object(entries) => match entries.get("src") {
281                Some(Value::String(src)) => Some(src.clone()),
282                _ => None,
283            },
284            _ => None,
285        };
286        let Some(source) = source else {
287            return Ok(());
288        };
289        abnf(parser, &source, None)
290            .map(|_| ())
291            .map_err(|error| PluginError(error.to_string()))
292    })
293}
294
295/// One optional alchemy translation source and its explicit entry point.
296#[derive(Clone, Copy, Debug, Eq, PartialEq)]
297pub struct TranslationPart {
298    /// The definition a host calls after linking the source.
299    pub entry: &'static str,
300    /// The source text, or `None` for an entry supplied by alchemy.
301    pub source: Option<&'static str>,
302}
303
304/// The package-local structural translation interface.
305#[derive(Clone, Copy, Debug, Eq, PartialEq)]
306pub struct TranslationParts {
307    /// The complete `tabnas.plugin.json` text.
308    pub manifest: &'static str,
309    /// An optional lift from the grammar's events to its first read shape.
310    pub lift: Option<TranslationPart>,
311    /// An optional embedding of a plain tree in the format's schema, with its reverse.
312    pub embed: Option<TranslationPart>,
313    /// An optional render from the write shape to text.
314    pub render: Option<TranslationPart>,
315    /// The transducer part: the tree's events from the parser's rule passes.
316    pub transduce: Option<TranslationPart>,
317    /// The render of the grammar-spec route, the manifest's
318    /// `translate.spec`: a compiled grammar spec written back as ABNF.
319    pub spec: Option<TranslationPart>,
320}
321
322const TRANSLATION: TranslationParts = TranslationParts {
323    manifest: include_str!("../translate/manifest.json"),
324    lift: None,
325    embed: None,
326    render: Some(TranslationPart {
327        entry: "abnf-render",
328        source: Some(include_str!("../translate/render.alc")),
329    }),
330    transduce: Some(TranslationPart {
331        entry: "abnf-transduce",
332        source: Some(include_str!("../translate/transduce.alc")),
333    }),
334    spec: Some(TranslationPart {
335        entry: "abnf-render-spec",
336        source: Some(include_str!("../translate/render-spec.alc")),
337    }),
338};
339
340/// Return the translation parts of ABNF documents: the manifest, the part
341/// that streams a document's tree, its rules in source order (the schema
342/// `grammar-rules`, which EBNF and GBNF share), from the rule passes of
343/// [`make`], the render that writes such a tree back as ABNF, and, as
344/// `spec`, the render of the grammar-spec route, which writes the
345/// GrammarSpec the compiler emits back as ABNF (the tree a host reads on
346/// that route is [`abnf_compile`] with `recognition` false and `strict`
347/// true). There is no lift and no embed.
348///
349/// ```
350/// let parts = tabnas_abnf::translate().expect("abnf carries translation parts");
351/// assert_eq!(parts.render.map(|part| part.entry), Some("abnf-render"));
352/// assert_eq!(parts.transduce.map(|part| part.entry), Some("abnf-transduce"));
353/// assert_eq!(parts.spec.map(|part| part.entry), Some("abnf-render-spec"));
354/// assert_eq!(parts.embed, None);
355/// ```
356#[must_use]
357pub const fn translate() -> Option<TranslationParts> {
358    Some(TRANSLATION)
359}
360
361/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
362/// it. Its `translate` object is what a host that translates reads: the
363/// shape a document is read as and written from (`tree`), the schema of
364/// that tree (`grammar-rules`), the root the render needs (`object`), the
365/// files that hold the part and the render, the sentences that say what a
366/// written grammar does not keep, and `spec`, the grammar-spec route. The
367/// crate embeds its own copy, `translate/manifest.json`, since a packaged
368/// crate holds nothing outside `rs/`; `tests/translate_test.rs` holds the
369/// copy to the file.
370///
371/// ```
372/// assert!(tabnas_abnf::manifest_text().contains("\"grammar-rules\""));
373/// ```
374pub fn manifest_text() -> &'static str {
375    TRANSLATION.manifest
376}
377
378/// The text of a part, or the empty text.
379fn part_text(part: Option<TranslationPart>) -> &'static str {
380    match part {
381        Some(part) => part.source.unwrap_or_default(),
382        None => "",
383    }
384}
385
386/// The render, `alchemy/render.alc`, the file the manifest's
387/// `translate.render` names: a library of alchemy definitions, with no
388/// `export`, whose entry point `abnf-render` writes a grammar-rules
389/// tree's events as one ABNF document that reads back as the same tree.
390/// A host links it with its own program. The crate embeds its own copy,
391/// `translate/render.alc`, held to the file as the manifest's is.
392///
393/// ```
394/// assert!(tabnas_abnf::render_text().contains("def abnf-render [input]"));
395/// ```
396pub fn render_text() -> &'static str {
397    part_text(TRANSLATION.render)
398}
399
400/// The part, `alchemy/transduce.alc`, the file the manifest's
401/// `translate.transduce` names: its entry point `abnf-transduce` makes the
402/// tree's events from the rule passes of [`make`]. The crate embeds its
403/// own copy, `translate/transduce.alc`.
404///
405/// ```
406/// assert!(tabnas_abnf::transduce_text().contains("def abnf-transduce [input]"));
407/// ```
408pub fn transduce_text() -> &'static str {
409    part_text(TRANSLATION.transduce)
410}
411
412/// The grammar-spec route's render, `alchemy/render-spec.alc`, the file
413/// the manifest's `translate.spec.render` names: its entry point
414/// `abnf-render-spec` writes a grammar spec's events as one ABNF document
415/// that compiles back to the same spec. The crate embeds its own copy,
416/// `translate/render-spec.alc`.
417///
418/// ```
419/// assert!(tabnas_abnf::render_spec_text().contains("def abnf-render-spec [input]"));
420/// ```
421pub fn render_spec_text() -> &'static str {
422    part_text(TRANSLATION.spec)
423}