tabnas-abnf 0.5.1

ABNF (RFC 5234) grammar compiler for the tabnas parsing engine: ABNF text in, tabnas GrammarSpec out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright (c) 2025-2026 Richard Rodger and other contributors, MIT License

//! An ABNF (RFC 5234) grammar compiler for the
//! [`tabnas`](https://github.com/tabnas/parser) parsing engine.
//!
//! Where most tabnas grammar crates carry one fixed grammar, this one is
//! a META compiler: the grammar it installs is whatever ABNF text it is
//! handed at run time.
//!
//! ```text
//! ABNF text ──parse_abnf──▶ Grammar ──emit_grammar_spec──▶ GrammarSpec
//! ```
//!
//! [`parse_abnf`] is the RFC 5234 front-end and is what this crate adds;
//! everything downstream of the IR lives in
//! [`tabnas_bnf`](https://github.com/tabnas/bnf) and is shared with the
//! GBNF and EBNF front-ends.
//!
//! ```
//! let mut parser = tabnas::Tabnas::new();
//! tabnas_abnf::abnf(&mut parser, "greet = \"hi\" / \"hello\"", None).unwrap();
//! let tree = parser.parse("hello").unwrap();
//! assert_eq!(tree.to_json()["rule"], "greet");
//! ```
//!
//! This is the Rust port of the canonical TypeScript implementation in
//! `ts/src`; the TypeScript version is authoritative and this crate
//! tracks it.

mod compile;
mod converter;
mod numeric;
mod parser_abnf;
mod tree;

/// The README's Rust examples run as doctests, so a stale one fails the
/// gate rather than misleading the reader. Its `toml` and `bash` fences
/// are skipped; rustdoc runs only the `rust` ones.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

use std::fmt;

use tabnas::{Plugin, PluginError, Tabnas, Value};

pub use compile::abnf_compile;
pub use converter::{parse_abnf, AbnfParseError};
pub use parser_abnf::abnf_rules;
pub use tree::{make, parse_abnf_tree};

pub use tabnas_bnf::{
    attach_action_slots, attach_actions, eliminate_left_recursion, mark_listing, to_jsonic,
    to_pure_spec, to_recognition_spec, transduce_alc, ActionError as AbnfActionError, ActionFn,
    ActionsMap, AltSpec, CompileError as AbnfCompileError, ConvertOptions as AbnfConvertOptions,
    Element, EmitError, Grammar, GrammarSpec, JsonicOptions, Kind, NodeKind, Production, RefAction,
    RuleSpec, Sequence, SrcSpan, TransducePart, ValueAnnotation,
};

/// This crate's version. It MUST equal `ts/package.json` "version": the
/// release orchestrator rewrites both, and `tests/version_test.rs` fails
/// the build if they drift. Mirrors `VERSION` in `ts/src/abnf.ts` and
/// `const VERSION` in `go/abnf.go`.
pub const VERSION: &str = "0.5.1";

/// The group tag stamped on every emitted alt, and the prefix of every
/// diagnostic this crate raises through the shared compiler.
pub const TAG: &str = "abnf";

/// Anything that can go wrong turning ABNF source into a grammar.
#[derive(Debug, Clone, PartialEq)]
pub enum AbnfError {
    /// The ABNF source itself could not be read.
    Parse(AbnfParseError),
    /// The shared compiler refused the grammar.
    Emit(EmitError),
    /// The emitted spec could not be lowered to pure data.
    Compile(AbnfCompileError),
    /// A user action could not be attached.
    Action(AbnfActionError),
    /// The engine refused the emitted grammar.
    Install(String),
}

impl fmt::Display for AbnfError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(error) => error.fmt(formatter),
            Self::Emit(error) => error.fmt(formatter),
            Self::Compile(error) => error.fmt(formatter),
            Self::Action(error) => error.fmt(formatter),
            Self::Install(message) => formatter.write_str(message),
        }
    }
}

impl std::error::Error for AbnfError {}

impl From<AbnfParseError> for AbnfError {
    fn from(error: AbnfParseError) -> Self {
        Self::Parse(error)
    }
}

impl From<EmitError> for AbnfError {
    fn from(error: EmitError) -> Self {
        Self::Emit(error)
    }
}

impl From<AbnfCompileError> for AbnfError {
    fn from(error: AbnfCompileError) -> Self {
        Self::Compile(error)
    }
}

impl From<AbnfActionError> for AbnfError {
    fn from(error: AbnfActionError) -> Self {
        Self::Action(error)
    }
}

/// Options for [`abnf_compile`]: what to convert, and how to serialize
/// it.
///
/// The shared compiler's own `CompileOptions` carries only the
/// serialization half, because the conversion half is the front-end's;
/// this adds `start` and `tag`, exactly as `AbnfCompileOptions` does in
/// the Go port.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbnfCompileOptions {
    /// Start rule name (default: the first production).
    pub start: Option<String>,
    /// Group tag stamped on every emitted alt (default `abnf`).
    pub tag: Option<String>,
    /// Emit a pure RECOGNITION grammar, with tree building dropped.
    /// `false` keeps the tree builtins, still as pure data.
    pub recognition: bool,
    /// Valid JSON rather than relaxed jsonic.
    pub strict: bool,
    /// Spaces per level (default 2).
    pub indent: Option<usize>,
}

impl Default for AbnfCompileOptions {
    fn default() -> Self {
        Self {
            start: None,
            tag: None,
            recognition: true,
            strict: false,
            indent: None,
        }
    }
}

/// Options for [`abnf`], the install path.
///
/// Mirrors the canonical `AbnfPluginOptions`: the conversion options,
/// plus the user actions to attach. Supplying actions forces closure
/// mode and requests marks, because a user action wraps the compiler's
/// own closures.
#[derive(Clone, Default)]
pub struct AbnfOptions {
    /// How to convert the source.
    pub convert: AbnfConvertOptions,
    /// User semantic actions, by `@<rule>:<phase>` or
    /// `@<rule>:o|c:<mark>` reference.
    pub actions: Option<ActionsMap>,
}

impl AbnfOptions {
    /// Conversion options alone.
    pub fn new(convert: AbnfConvertOptions) -> Self {
        Self {
            convert,
            actions: None,
        }
    }

    /// The same options carrying user actions.
    pub fn with_actions(mut self, actions: ActionsMap) -> Self {
        self.actions = Some(actions);
        self
    }
}

impl fmt::Debug for AbnfOptions {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AbnfOptions")
            .field("convert", &self.convert)
            .field(
                "actions",
                &self.actions.as_ref().map(|actions| actions.len()),
            )
            .finish()
    }
}

/// Emit a spec from an already-parsed ABNF grammar.
///
/// Wraps the shared emitter to keep this crate's historical `abnf` tag
/// default, which consumers use to group and inspect the emitted alts.
/// An explicit tag still wins.
pub fn emit_grammar_spec(
    grammar: &Grammar,
    opts: Option<&AbnfConvertOptions>,
) -> Result<GrammarSpec, EmitError> {
    let mut options = opts.cloned().unwrap_or_default();
    if options.tag.is_none() {
        options.tag = Some(TAG.to_string());
    }
    tabnas_bnf::emit_grammar_spec(grammar, &options)
}

/// Convert ABNF source into a tabnas grammar spec, without installing
/// it. The Rust spelling of `tn.abnf.toSpec(src)`.
pub fn abnf_convert(
    src: &str,
    opts: Option<&AbnfConvertOptions>,
) -> Result<GrammarSpec, AbnfError> {
    let grammar = parse_abnf(src)?;
    Ok(emit_grammar_spec(&grammar, opts)?)
}

/// The transducer part of an ABNF grammar, `<name>-transduce`: the alchemy
/// program that streams the JSON events of the value its `; @object` and
/// `; @array` annotations build, from its rule passes, or why its
/// documents are read whole ([`transduce_alc`] says when). Converts as
/// [`abnf_convert`] does, with `opts`. The Rust spelling of
/// `abnfTransduce`.
pub fn abnf_transduce(
    src: &str,
    name: &str,
    opts: Option<&AbnfConvertOptions>,
) -> Result<TransducePart, AbnfError> {
    Ok(transduce_alc(&abnf_convert(src, opts)?, name))
}

/// Convert ABNF source and install the resulting grammar on `parser`.
///
/// The Rust spelling of the callable `tn.abnf(src, opts)` the canonical
/// plugin decorates an instance with. With actions supplied, conversion
/// runs in closure mode with marks and the actions are attached before
/// the grammar is installed.
pub fn abnf(
    parser: &mut Tabnas,
    src: &str,
    opts: Option<&AbnfOptions>,
) -> Result<GrammarSpec, AbnfError> {
    let mut convert = opts.map(|opts| opts.convert.clone()).unwrap_or_default();
    let actions = opts.and_then(|opts| opts.actions.clone());
    if actions.is_some() {
        // User actions wrap the compiler's closures, so convert in
        // closure mode (never builtins) and request marks.
        convert.builtins = false;
        convert.marks = true;
    }
    let mut spec = abnf_convert(src, Some(&convert))?;
    if let Some(actions) = actions {
        attach_actions(&mut spec, actions)?;
    }
    spec.install(parser)
        .map_err(|error| AbnfError::Install(error.to_string()))?;
    Ok(spec)
}

/// The plugin descriptor, for [`Tabnas::use_plugin`].
///
/// A grammar this crate installs is whatever ABNF the caller hands over,
/// so the plugin has nothing of its own to install and records itself on
/// the instance instead, exactly as the Go `Plugin` does. Pass
/// `{"src": "<abnf text>"}` in the option bag to have it convert and
/// install that source; otherwise call [`abnf`] directly, which is the
/// typed way in.
pub fn plugin() -> Plugin {
    Plugin::new("Abnf", |parser, options| {
        let source = match options {
            Value::Object(entries) => match entries.get("src") {
                Some(Value::String(src)) => Some(src.clone()),
                _ => None,
            },
            _ => None,
        };
        let Some(source) = source else {
            return Ok(());
        };
        abnf(parser, &source, None)
            .map(|_| ())
            .map_err(|error| PluginError(error.to_string()))
    })
}

/// One optional alchemy translation source and its explicit entry point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The definition a host calls after linking the source.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional embedding of a plain tree in the format's schema, with its reverse.
    pub embed: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
    /// The transducer part: the tree's events from the parser's rule passes.
    pub transduce: Option<TranslationPart>,
    /// The render of the grammar-spec route, the manifest's
    /// `translate.spec`: a compiled grammar spec written back as ABNF.
    pub spec: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: None,
    embed: None,
    render: Some(TranslationPart {
        entry: "abnf-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
    transduce: Some(TranslationPart {
        entry: "abnf-transduce",
        source: Some(include_str!("../translate/transduce.alc")),
    }),
    spec: Some(TranslationPart {
        entry: "abnf-render-spec",
        source: Some(include_str!("../translate/render-spec.alc")),
    }),
};

/// Return the translation parts of ABNF documents: the manifest, the part
/// that streams a document's tree, its rules in source order (the schema
/// `grammar-rules`, which EBNF and GBNF share), from the rule passes of
/// [`make`], the render that writes such a tree back as ABNF, and, as
/// `spec`, the render of the grammar-spec route, which writes the
/// GrammarSpec the compiler emits back as ABNF (the tree a host reads on
/// that route is [`abnf_compile`] with `recognition` false and `strict`
/// true). There is no lift and no embed.
///
/// ```
/// let parts = tabnas_abnf::translate().expect("abnf carries translation parts");
/// assert_eq!(parts.render.map(|part| part.entry), Some("abnf-render"));
/// assert_eq!(parts.transduce.map(|part| part.entry), Some("abnf-transduce"));
/// assert_eq!(parts.spec.map(|part| part.entry), Some("abnf-render-spec"));
/// assert_eq!(parts.embed, None);
/// ```
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shape a document is read as and written from (`tree`), the schema of
/// that tree (`grammar-rules`), the root the render needs (`object`), the
/// files that hold the part and the render, the sentences that say what a
/// written grammar does not keep, and `spec`, the grammar-spec route. The
/// crate embeds its own copy, `translate/manifest.json`, since a packaged
/// crate holds nothing outside `rs/`; `tests/translate_test.rs` holds the
/// copy to the file.
///
/// ```
/// assert!(tabnas_abnf::manifest_text().contains("\"grammar-rules\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// The text of a part, or the empty text.
fn part_text(part: Option<TranslationPart>) -> &'static str {
    match part {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}

/// The render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `abnf-render` writes a grammar-rules
/// tree's events as one ABNF document that reads back as the same tree.
/// A host links it with its own program. The crate embeds its own copy,
/// `translate/render.alc`, held to the file as the manifest's is.
///
/// ```
/// assert!(tabnas_abnf::render_text().contains("def abnf-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    part_text(TRANSLATION.render)
}

/// The part, `alchemy/transduce.alc`, the file the manifest's
/// `translate.transduce` names: its entry point `abnf-transduce` makes the
/// tree's events from the rule passes of [`make`]. The crate embeds its
/// own copy, `translate/transduce.alc`.
///
/// ```
/// assert!(tabnas_abnf::transduce_text().contains("def abnf-transduce [input]"));
/// ```
pub fn transduce_text() -> &'static str {
    part_text(TRANSLATION.transduce)
}

/// The grammar-spec route's render, `alchemy/render-spec.alc`, the file
/// the manifest's `translate.spec.render` names: its entry point
/// `abnf-render-spec` writes a grammar spec's events as one ABNF document
/// that compiles back to the same spec. The crate embeds its own copy,
/// `translate/render-spec.alc`.
///
/// ```
/// assert!(tabnas_abnf::render_spec_text().contains("def abnf-render-spec [input]"));
/// ```
pub fn render_spec_text() -> &'static str {
    part_text(TRANSLATION.spec)
}