Skip to main content

tabnas_debug/
abnf.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Emit an ABNF representation of an instance's *live* grammar.
4//!
5//! This reads ONLY the running engine (options + installed rule specs); it
6//! never depends on `@tabnas/abnf`. That independence is a hard constraint
7//! — the emitter is the inverse of abnf's forward encoding, and proving it
8//! with abnf as a dependency would be circular.
9//!
10//! The mapping: tabnas rules become ABNF productions, OPEN alts become
11//! `/`-separated alternatives, the token sequence (`s`) plus any
12//! push/replace target (`p`/`r`) becomes a space-separated element list,
13//! and each token resolves to an ABNF terminal via the fixed-literal /
14//! match-regex config.
15//!
16//! Actions carry no ABNF meaning and are ignored. Constructs that cannot
17//! be represented (an arbitrary match regex, say) are emitted as ABNF
18//! comments, so the output stays valid and self-documenting even though
19//! such rules will not round-trip.
20//!
21//! Ported from `ts/src/debug.ts` (`emitAbnf` and friends), which is
22//! canonical.
23
24use std::collections::BTreeSet;
25
26use indexmap::{IndexMap, IndexSet};
27use tabnas::{AltSpec, RuleSpec, Tabnas, Tin};
28
29/// Map engine rule and token names onto legal ABNF rule names.
30///
31/// RFC 5234: `rulename = ALPHA *(ALPHA / DIGIT / "-")`. Engine names are
32/// not so constrained — the abnf compiler synthesises `_gen1_star_term`
33/// and `…$alt0`, and a regex token arrives as `RX___U0030__U0039`.
34/// Emitted verbatim those are rejected by every conforming ABNF tool, so
35/// each is mapped to a legal name ONCE and reused for the production head
36/// and every reference.
37///
38/// Distinct source names can sanitise to the same string (`a_b` and `a-b`
39/// both give `a-b`), so collisions get a numeric suffix — without it the
40/// grammar would silently merge two rules.
41///
42/// RULES AND TOKENS ARE SEPARATE NAMESPACES, which is what the two caches
43/// are for. A token's bare name and a rule's name come from different
44/// sources and can coincide: `#NR` beside a rule called `NR` is ordinary.
45/// One shared cache merged them — the token looked up `NR`, hit the entry
46/// `new` had made for the RULE, and the emitter wrote the rule's own name
47/// for a terminal. A grammar whose rule `NR` referenced token `#NR` came
48/// out as a self-referential `NR = NR` plus a second `NR = <number>`
49/// definition: two definitions of one rule with `=` rather than
50/// incremental `=/`, and a production that recognises nothing.
51///
52/// Keeping the caches apart while sharing `taken` is the fix. A token
53/// still sanitises the same way, but allocates against everything already
54/// claimed, so it suffixes to `NR-2` instead of borrowing the rule's name.
55struct AbnfNamer {
56    rule_cache: IndexMap<String, String>,
57    token_cache: IndexMap<String, String>,
58    /// Claimed names, lowercased. RFC 5234 §2.1: "ABNF rule names are
59    /// case-insensitive", so `Foo-Bar` and `foo-bar` ARE the same rule and
60    /// the collision check has to fold case — comparing exact spellings
61    /// would let a sanitised `foo_bar` land beside a reserved `Foo-Bar`
62    /// and emit two definitions of one rule.
63    taken: BTreeSet<String>,
64}
65
66fn is_legal_abnf_name(name: &str) -> bool {
67    let mut chars = name.chars();
68    match chars.next() {
69        Some(first) if first.is_ascii_alphabetic() => {}
70        _ => return false,
71    }
72    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
73}
74
75impl AbnfNamer {
76    /// Seed with names that are already legal, claiming each up front:
77    /// otherwise a sanitised synthetic could take `foo-bar` first and
78    /// rename the user's real `foo-bar` rule out from under them.
79    fn new(reserve: impl IntoIterator<Item = String>) -> Self {
80        let mut namer = Self {
81            rule_cache: IndexMap::new(),
82            token_cache: IndexMap::new(),
83            taken: BTreeSet::new(),
84        };
85        for name in reserve {
86            if is_legal_abnf_name(&name) && !namer.is_taken(&name) {
87                namer.claim(&name);
88                namer.rule_cache.insert(name.clone(), name);
89            }
90        }
91        namer
92    }
93
94    fn claim(&mut self, name: &str) {
95        self.taken.insert(name.to_lowercase());
96    }
97
98    fn is_taken(&self, name: &str) -> bool {
99        self.taken.contains(&name.to_lowercase())
100    }
101
102    /// A rule name. Already-legal names were claimed by `new`, so this is
103    /// a cache hit for every user-authored rule.
104    fn rule(&mut self, name: &str) -> String {
105        if let Some(hit) = self.rule_cache.get(name) {
106            return hit.clone();
107        }
108        let out = self.allocate(name);
109        self.rule_cache.insert(name.to_string(), out.clone());
110        out
111    }
112
113    /// A token's bare name. A rule may already hold this spelling, and the
114    /// token must not borrow it, so this allocates rather than reading the
115    /// rule cache.
116    fn token(&mut self, bare: &str) -> String {
117        if let Some(hit) = self.token_cache.get(bare) {
118            return hit.clone();
119        }
120        let out = self.allocate(bare);
121        self.token_cache.insert(bare.to_string(), out.clone());
122        out
123    }
124
125    /// Sanitise to a legal rulename, then make it unique against every
126    /// name claimed so far — reserved rule names and previously allocated
127    /// names alike, since `taken` is shared by both namespaces.
128    fn allocate(&mut self, name: &str) -> String {
129        let mut out: String = name
130            .chars()
131            .map(|ch| {
132                if ch.is_ascii_alphanumeric() || ch == '-' {
133                    ch
134                } else {
135                    '-'
136                }
137            })
138            .collect();
139        if !out
140            .chars()
141            .next()
142            .is_some_and(|ch| ch.is_ascii_alphabetic())
143        {
144            out = format!("r{out}");
145        }
146        if self.is_taken(&out) {
147            let mut suffix = 2;
148            while self.is_taken(&format!("{out}-{suffix}")) {
149                suffix += 1;
150            }
151            out = format!("{out}-{suffix}");
152        }
153        self.claim(&out);
154        out
155    }
156}
157
158/// Emit the ABNF for `parser`'s live grammar.
159pub fn abnf(parser: &Tabnas) -> String {
160    Emitter::new(parser).emit()
161}
162
163struct Emitter<'a> {
164    parser: &'a Tabnas,
165    /// Rule name -> spec, in installation order (the engine's `IndexMap`),
166    /// which is the TypeScript insertion order the emitter's rule ordering
167    /// depends on.
168    rules: IndexMap<String, &'a RuleSpec>,
169    namer: AbnfNamer,
170    /// Token legend, in first-reference order.
171    used: IndexMap<String, String>,
172    end_tin: Option<Tin>,
173    /// `bnf` wraps grammars in a synthetic `__start__` rule; when present
174    /// it is skipped and the real start leads.
175    synth_wrapper: Option<String>,
176}
177
178impl<'a> Emitter<'a> {
179    fn new(parser: &'a Tabnas) -> Self {
180        let rules: IndexMap<String, &RuleSpec> = parser
181            .rule_specs()
182            .into_iter()
183            .map(|spec| (spec.name.clone(), spec))
184            .collect();
185        let synth_wrapper =
186            ("__start__" == parser.options.rule.start).then(|| parser.options.rule.start.clone());
187        Self {
188            namer: AbnfNamer::new(rules.keys().cloned()),
189            rules,
190            used: IndexMap::new(),
191            end_tin: parser.options.token("#ZZ"),
192            synth_wrapper,
193            parser,
194        }
195    }
196
197    /// A rule the abnf forward-compiler synthesised for a `[...]` /
198    /// `*(...)` / `1*(...)` / group / chain-step: named `_gen<n>_…` or
199    /// carrying a `$`. These are never user-authored, so instead of
200    /// emitting them as their own productions each is folded back into the
201    /// ABNF construct it encodes — a reasonable round-trip (`tn.abnf(G)`
202    /// then `abnf()` reproduces `G`, not the expanded internal form).
203    fn is_synthetic(&self, name: &str) -> bool {
204        if Some(name) == self.synth_wrapper.as_deref() {
205            return false;
206        }
207        name.contains('$') || is_gen_name(name)
208    }
209
210    /// Only the clean cases fold — `[…]` optionals plus the group / chain
211    /// helpers they inline through. Repetition (`_star` / `_plus`) uses a
212    /// probe-optimised subgraph that does not reconstruct reliably, so
213    /// those rules (and their `$alt…` helpers) are emitted as productions
214    /// unchanged — still a valid, recognition-equivalent grammar.
215    fn is_foldable(&self, name: &str) -> bool {
216        self.is_synthetic(name)
217            && !name.contains("_star")
218            && !name.contains("_plus")
219            && !name.contains("$alt")
220    }
221
222    fn emit(mut self) -> String {
223        let start_rule = self.start_rule();
224
225        // Real start first, then the remaining USER (non-synthetic) rules.
226        let user_rules: Vec<String> = self
227            .rules
228            .keys()
229            .filter(|name| {
230                Some(name.as_str()) != self.synth_wrapper.as_deref() && !self.is_foldable(name)
231            })
232            .cloned()
233            .collect();
234
235        let mut ordered: Vec<String> = Vec::new();
236        let mut seen_rules: BTreeSet<String> = BTreeSet::new();
237        if let Some(start) =
238            start_rule.filter(|start| self.rules.contains_key(start) && !self.is_foldable(start))
239        {
240            seen_rules.insert(start.clone());
241            ordered.push(start);
242        }
243        for name in user_rules {
244            if seen_rules.insert(name.clone()) {
245                ordered.push(name);
246            }
247        }
248
249        let mut lines: Vec<String> = Vec::new();
250        for name in ordered {
251            let seen = BTreeSet::from([name.clone()]);
252            let body = self.emit_body(&name, &seen);
253            let head = self.namer.rule(&name);
254            lines.push(format!("{head} = {body}"));
255        }
256
257        // Define each token as its own ABNF rule (named terminals), after
258        // the productions, with `=` aligned for readability.
259        if !self.used.is_empty() {
260            let pad = self.used.keys().map(String::len).max().unwrap_or(0);
261            lines.push(String::new());
262            for (name, form) in &self.used {
263                lines.push(format!("{name:pad$} = {form}"));
264            }
265        }
266        lines.join("\n")
267    }
268
269    /// The grammar's real start rule, seeing through a `__start__` wrapper.
270    fn start_rule(&self) -> Option<String> {
271        let Some(wrapper) = self.synth_wrapper.clone() else {
272            return Some(self.parser.options.rule.start.clone());
273        };
274        let spec = self.rules.get(&wrapper)?;
275        for alt in &spec.open {
276            if let Some(target) = alt.p.as_ref().or(alt.r.as_ref()) {
277                return Some(target.clone());
278            }
279        }
280        None
281    }
282
283    /// Full production body: open alternatives joined by `/`, then any
284    /// close continuation — but PRESERVING an empty open alternative,
285    /// which is essential for kept `*(…)` repetition rules, whose empty
286    /// alt is what makes them zero-or-more.
287    ///
288    /// The empty alternative is rendered by wrapping the rest in `[ … ]`,
289    /// NOT as a trailing `/`. ABNF's grammar is
290    ///   alternation = concatenation *(*c-wsp "/" *c-wsp concatenation)
291    /// so every `/` must be followed by a concatenation: `x = A x /` is a
292    /// syntax error that every conforming ABNF tool rejects. `[ A x ]`
293    /// says the same thing and is valid.
294    fn emit_body(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
295        let opens: Vec<AltSpec> = self
296            .rules
297            .get(name)
298            .map(|spec| spec.open.clone())
299            .unwrap_or_default();
300        let raw: Vec<String> = opens.iter().map(|alt| self.seq_of_alt(alt, seen)).collect();
301        let optional = raw.iter().any(String::is_empty);
302        let non_empty: IndexSet<String> = raw.into_iter().filter(|item| !item.is_empty()).collect();
303        let cont = self.close_cont(name, seen);
304
305        // Nothing but an empty alternative. `option = "[" *c-wsp
306        // alternation *c-wsp "]"` and `alternation` needs at least one
307        // concatenation, so `[ ]` is not a legal option — there is nothing
308        // to make optional.
309        //
310        // With a continuation, the open contributes nothing and the rule
311        // IS its continuation. Without one, `x = ` is not a production at
312        // all, and ABNF has no epsilon terminal — but an empty char-val is
313        // legal (`char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE` permits
314        // zero chars) and matches exactly the empty string, which is what
315        // this rule does.
316        if optional && non_empty.is_empty() {
317            return if cont.is_empty() {
318                "\"\"".to_string()
319            } else {
320                cont
321            };
322        }
323
324        let joined = non_empty.into_iter().collect::<Vec<_>>().join(" / ");
325        let body = if optional {
326            format!("[ {joined} ]")
327        } else {
328            joined
329        };
330        format!("{body} {cont}").trim().to_string()
331    }
332
333    /// Open alternatives joined by `/`, then any close continuation. Unlike
334    /// [`Emitter::emit_body`] an empty open alternative is dropped, because
335    /// an inlined construct contributes only its content.
336    fn rule_seq(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
337        let opens = self.content_opens(name);
338        let alts: IndexSet<String> = opens
339            .iter()
340            .map(|alt| self.seq_of_alt(alt, seen))
341            .filter(|item| !item.is_empty())
342            .collect();
343        let joined = alts.into_iter().collect::<Vec<_>>().join(" / ");
344        let cont = self.close_cont(name, seen);
345        format!("{joined} {cont}").trim().to_string()
346    }
347
348    /// The close-alt continuation of a rule: its trailing element
349    /// sequence, wrapped in `[ … ]` when an epsilon (empty) close alt
350    /// makes it optional.
351    fn close_cont(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
352        let closes: Vec<AltSpec> = self
353            .rules
354            .get(name)
355            .map(|spec| spec.close.clone())
356            .unwrap_or_default();
357        let has_epsilon = closes
358            .iter()
359            .any(|alt| !self.is_end_alt(alt) && !has_content(alt));
360        for alt in &closes {
361            if self.is_end_alt(alt) || !has_content(alt) {
362                continue;
363            }
364            let cont = self.seq_of_alt(alt, seen);
365            if cont.is_empty() {
366                continue;
367            }
368            return if has_epsilon {
369                format!("[ {cont} ]")
370            } else {
371                cont
372            };
373        }
374        String::new()
375    }
376
377    /// An alt whose whole sequence is the single end-of-source token.
378    fn is_end_alt(&self, alt: &AltSpec) -> bool {
379        let Some(end) = self.end_tin else {
380            return false;
381        };
382        1 == alt.s.len() && 1 == alt.s[0].len() && end == alt.s[0][0]
383    }
384
385    fn content_opens(&self, name: &str) -> Vec<AltSpec> {
386        self.rules
387            .get(name)
388            .map(|spec| {
389                spec.open
390                    .iter()
391                    .filter(|alt| has_content(alt))
392                    .cloned()
393                    .collect()
394            })
395            .unwrap_or_default()
396    }
397
398    /// Render one alt as an ABNF element sequence: its `s` tokens then its
399    /// `p`/`r` target (synthetic targets are inlined).
400    ///
401    /// An alt consumes `len(s) - b` tokens — the engine records "matched
402    /// minus backtrack". Tokens beyond that are LOOKAHEAD only: matched to
403    /// choose the alt, then pushed back. Rendering them as ABNF elements
404    /// would claim input the alt never eats.
405    ///
406    /// Deriving the count this way also covers the FIRST-set-guarded
407    /// epsilon — `{ s: '#Y', b: 1 }` with no target, which the abnf
408    /// compiler emits for the skip branch of an optional, where `#Y` is
409    /// the FOLLOW token. Rendered as a consuming alternative,
410    /// `top = [ X "@" ] Y` came back as `top = [ X T / Y ] Y`: the
411    /// optional could swallow the follow.
412    fn seq_of_alt(&mut self, alt: &AltSpec, seen: &BTreeSet<String>) -> String {
413        let mut elements: Vec<String> = Vec::new();
414        let keep = alt.s.len().saturating_sub(alt.b);
415        for position in alt.s.iter().take(keep) {
416            match position.len() {
417                0 => continue,
418                1 => {
419                    let tin = position[0];
420                    if Some(tin) == self.end_tin {
421                        continue;
422                    }
423                    let terminal = self.terminal(tin);
424                    elements.push(terminal);
425                }
426                _ => {
427                    let inner: Vec<String> = position
428                        .iter()
429                        .filter(|tin| Some(**tin) != self.end_tin)
430                        .copied()
431                        .collect::<Vec<_>>()
432                        .into_iter()
433                        .map(|tin| self.terminal(tin))
434                        .collect();
435                    if !inner.is_empty() {
436                        elements.push(format!("( {} )", inner.join(" / ")));
437                    }
438                }
439            }
440        }
441        let target = alt.p.clone().or_else(|| alt.r.clone());
442        if let Some(target) = target {
443            let reference = self.inline_ref(&target, seen);
444            if !reference.is_empty() {
445                elements.push(reference);
446            }
447        }
448        elements.join(" ")
449    }
450
451    /// Inline a reference: a user rule stays a bareword; a synthetic rule
452    /// folds back into the ABNF construct it encodes.
453    fn inline_ref(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
454        // A user rule, or a kept (non-foldable, e.g. repetition) synthetic
455        // rule, stays a bareword reference; only foldable synthetics inline.
456        if !self.is_foldable(name) {
457            return self.namer.rule(name);
458        }
459        if seen.contains(name) {
460            // A foldable loop-back — returning empty terminates the loop.
461            return String::new();
462        }
463        if !self.rules.contains_key(name) {
464            return self.namer.rule(name);
465        }
466        let mut inner = seen.clone();
467        inner.insert(name.to_string());
468        if name.contains("_opt") {
469            let body = self.rule_seq(name, &inner);
470            return format!("[ {body} ]");
471        }
472        // group / chain-step: inline the body, parenthesising a bare
473        // multi-way alternation that will sit inside a larger sequence.
474        let body = self.rule_seq(name, &inner);
475        let multi = 1 < self.content_opens(name).len();
476        if multi && self.close_cont(name, &inner).is_empty() {
477            format!("( {body} )")
478        } else {
479            body
480        }
481    }
482
483    /// Render a token reference: every token appears by its bare NAME
484    /// (`#PL` -> `PL`), and its definition is recorded in the legend. A
485    /// token name that is actually a rule name is a nonterminal reference
486    /// and is returned as-is, with no legend entry.
487    fn terminal(&mut self, tin: Tin) -> String {
488        let full_name = self.parser.token_name(tin);
489        if self.rules.contains_key(&full_name) {
490            return self.namer.rule(&full_name);
491        }
492        let bare = full_name
493            .strip_prefix('#')
494            .unwrap_or(&full_name)
495            .to_string();
496        // Strip the '#' sigil first so '#NR' asks for 'NR' rather than
497        // being sanitised to '-NR' and then prefixed.
498        //
499        // This goes through the TOKEN namespace. A rule may already hold
500        // this spelling — a grammar with a rule `NR` and the `#NR` number
501        // token is perfectly ordinary — and the token must not borrow it:
502        // that emitted a self-referential `NR = NR` plus a duplicate
503        // definition. The token namespace suffixes to `NR-2` instead.
504        let name = self.namer.token(&bare);
505        if !self.used.contains_key(&name) {
506            let form = token_form(self.parser, tin, &full_name);
507            self.used.insert(name.clone(), form);
508        }
509        name
510    }
511}
512
513/// A rule the abnf forward-compiler synthesised, named `_gen<n>_…`.
514fn is_gen_name(name: &str) -> bool {
515    name.strip_prefix("_gen")
516        .and_then(|rest| rest.chars().next())
517        .is_some_and(|ch| ch.is_ascii_digit())
518}
519
520/// An alt that contributes something to the emitted sequence.
521fn has_content(alt: &AltSpec) -> bool {
522    !alt.s.is_empty() || alt.p.is_some() || alt.r.is_some()
523}
524
525/// The legend definition for a token — what it matches:
526///   - fixed literal       -> `%s"<lit>"` (letters) / `"<lit>"` (punctuation)
527///   - match regex         -> a char range, a literal, or an ABNF comment
528///   - built-in matcher    -> `<number>` / `<string>` / …
529///
530/// The `%s` prefix is RFC 7405, which updates RFC 5234 — the only
531/// construct emitted here that RFC 5234 alone does not define. It is kept
532/// because it is what every current ABNF tool implements and it stays
533/// readable; `%x48.69` would be pure RFC 5234 but unreadable, and a bare
534/// char-val would silently lose case-sensitivity.
535fn token_form(parser: &Tabnas, tin: Tin, full_name: &str) -> String {
536    if let Some(literal) = parser.fixed_source(tin) {
537        // RFC 5234: `char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE` — so a
538        // literal holding a control character, a `"`, or anything above
539        // %x7E CANNOT go inside quotes. A token fixed to CRLF used to emit
540        // `CRLF = "<CR>"`, an unterminated char-val. The numeric form has
541        // no such restriction (and is case-sensitive already, so it
542        // carries the `%s` meaning too).
543        return if is_abnf_quotable_body(literal) {
544            if literal.chars().any(|ch| ch.is_ascii_alphabetic()) {
545                format!("%s\"{literal}\"")
546            } else {
547                format!("\"{literal}\"")
548            }
549        } else {
550            numeric_val(literal)
551        };
552    }
553
554    if let Some(matcher) = parser
555        .options
556        .match_tokens
557        .values()
558        .find(|matcher| matcher.tin == tin)
559    {
560        if let tabnas::MatchTokenMatcher::Regex(regex) = &matcher.matcher {
561            return regex_to_abnf(regex.as_str());
562        }
563        // A function-backed matcher has no ABNF form to recover. The
564        // canonical runtime only special-cases a RegExp and otherwise
565        // falls through to the description below, so do the same rather
566        // than inventing a form this port alone would emit.
567    }
568
569    // Built-in lexer token: describe it. It is lexer-provided, so a
570    // grammar using it does not round-trip through bnf.
571    let bare = full_name.strip_prefix('#').unwrap_or(full_name);
572    let described = match bare {
573        "NR" => "number",
574        "ST" => "string",
575        "TX" => "text",
576        "VL" => "value",
577        "SP" => "space",
578        "LN" => "line",
579        "CM" => "comment",
580        "AA" => "any",
581        "UK" => "unknown",
582        "BD" => "bad",
583        "ZZ" => "end-of-source",
584        _ => return prose_val(&format!("built-in {bare}")),
585    };
586    prose_val(described)
587}
588
589/// A literal as an ABNF num-val: `%x0D`, or dot-concatenated for several
590/// characters (`%x0D.0A`). RFC 5234 gives this no character restriction,
591/// so it is the safe rendering for anything char-val cannot hold.
592fn numeric_val(literal: &str) -> String {
593    let parts: Vec<String> = literal
594        .chars()
595        .map(|ch| {
596            let hex = format!("{:X}", ch as u32);
597            if hex.len() % 2 == 1 {
598                format!("0{hex}")
599            } else {
600                hex
601            }
602        })
603        .collect();
604    format!("%x{}", parts.join("."))
605}
606
607/// Every character of `text` fits inside an ABNF char-val: %x20-21 /
608/// %x23-7E (printable ASCII except the double quote). An empty string
609/// qualifies — `char-val` permits zero characters.
610fn is_abnf_quotable_body(text: &str) -> bool {
611    text.chars().all(|ch| {
612        let code = ch as u32;
613        (0x20..=0x21).contains(&code) || (0x23..=0x7E).contains(&code)
614    })
615}
616
617/// An ABNF char-val holding at least one character.
618fn is_abnf_quotable(text: &str) -> bool {
619    !text.is_empty() && is_abnf_quotable_body(text)
620}
621
622/// Translate the anchored regex the abnf compiler installs for a match
623/// token back to ABNF, covering the shapes it actually emits.
624///
625/// The Rust engine's matchers are `regex::Regex`, whose source carries
626/// inline flags (`(?i)`) rather than the separate flag set a JavaScript
627/// `RegExp` has; the case-insensitive branch reads that prefix instead.
628fn regex_to_abnf(source: &str) -> String {
629    let original = source;
630    // Inline flags come first, then the anchor the compiler prepends.
631    let (case_insensitive, source) = match source.strip_prefix("(?i)") {
632        Some(rest) => (true, rest),
633        None => (false, source),
634    };
635    let source = source.strip_prefix('^').unwrap_or(source);
636
637    // Single char-class range: [\uXXXX-\uYYYY] -> %xXX-YY
638    if let Some(range) = char_class_range(source, "\\u", 4) {
639        return range;
640    }
641    // Single char-class range with bare hex escapes: [\xXX-\xYY].
642    if let Some(range) = char_class_range(source, "\\x", 2) {
643        return range;
644    }
645
646    // Case-insensitive literal: the abnf compiler encodes a bare ABNF
647    // string `"foo"` containing at least one letter as an anchored,
648    // case-insensitive regex over the escaped literal. Recover the literal
649    // by unescaping, then verify the round-trip so a genuine regex is
650    // never misread as a literal.
651    if case_insensitive {
652        let literal = unescape_regex_literal(source);
653        if escape_regex_like(&literal) == source && is_abnf_quotable(&literal) {
654            return format!("\"{literal}\"");
655        }
656    }
657
658    // Anything else: no ABNF construct expresses this regex, so say so in
659    // the one the grammar provides for exactly that — RFC 5234 §4
660    // prose-val, "a last resort" for describing a rule in prose. It does
661    // not round-trip, and is not meant to; it is a legal element naming
662    // what the token matches.
663    //
664    // This returned `; /…/` before: a bare comment. `;` runs to end of
665    // line, so the legend entry it produced (`T = ; /…/`) held no elements
666    // at all — not merely non-round-tripping but unparseable, and one such
667    // token made the WHOLE emitted grammar invalid rather than just that
668    // rule.
669    prose_val(&format!("regex /{original}/"))
670}
671
672/// Render `text` as an RFC 5234 §4 prose-val:
673/// `prose-val = "<" *(%x20-3D / %x3F-7E) ">"`. A `>` would close the value
674/// early and anything outside printable ASCII is not permitted, so both are
675/// escaped rather than dropped — the text is here to say what the token
676/// matches, and silently losing characters from it would defeat that.
677fn prose_val(text: &str) -> String {
678    let mut out = String::from("<");
679    for ch in text.chars() {
680        let cp = ch as u32;
681        if (0x20..=0x3d).contains(&cp) || (0x3f..=0x7e).contains(&cp) {
682            out.push(ch);
683        } else {
684            out.push_str(&format!("\\u{cp:04X}"));
685        }
686    }
687    out.push('>');
688    out
689}
690
691/// `[\uXXXX-\uYYYY]` or `[\xXX-\xYY]` as `%xLO-HI`.
692fn char_class_range(source: &str, prefix: &str, digits: usize) -> Option<String> {
693    let inner = source.strip_prefix('[')?.strip_suffix(']')?;
694    let (low, rest) = inner.strip_prefix(prefix)?.split_at_checked(digits)?;
695    let high = rest.strip_prefix('-')?.strip_prefix(prefix)?;
696    if high.len() != digits {
697        return None;
698    }
699    let low = u32::from_str_radix(low, 16).ok()?;
700    let high = u32::from_str_radix(high, 16).ok()?;
701    Some(format!("%x{low:X}-{high:X}"))
702}
703
704/// Mirror of the abnf compiler's `escapeRegExp`, used only to validate
705/// that an unescaped candidate literal re-escapes to exactly the observed
706/// regex source.
707fn escape_regex_like(text: &str) -> String {
708    let mut out = String::with_capacity(text.len());
709    for ch in text.chars() {
710        if "\\^$.*+?()[]{}|".contains(ch) {
711            out.push('\\');
712        }
713        out.push(ch);
714    }
715    out
716}
717
718/// Undo [`escape_regex_like`], plus the forward slash a JavaScript
719/// `RegExp` source escapes automatically.
720fn unescape_regex_literal(source: &str) -> String {
721    let mut out = String::with_capacity(source.len());
722    let mut chars = source.chars().peekable();
723    while let Some(ch) = chars.next() {
724        if ch == '\\' {
725            if let Some(next) = chars.peek().copied() {
726                if "\\^$.*+?()[]{}|/".contains(next) {
727                    out.push(next);
728                    chars.next();
729                    continue;
730                }
731            }
732        }
733        out.push(ch);
734    }
735    out
736}
737
738#[cfg(test)]
739mod tests {
740    use super::*;
741
742    #[test]
743    fn namer_sanitises_and_disambiguates() {
744        let mut namer = AbnfNamer::new(["keep-me".to_string()]);
745        assert_eq!(namer.rule("keep-me"), "keep-me");
746        assert_eq!(namer.rule("a_b"), "a-b");
747        // `a-b` sanitises to the same string, so it gets a suffix.
748        assert_eq!(namer.rule("a.b"), "a-b-2");
749        // Not starting with a letter gets an `r` prefix.
750        assert_eq!(namer.rule("1st"), "r1st");
751        // Case-insensitive collision: `KEEP-ME` folds onto the claim.
752        assert_eq!(namer.rule("KEEP-ME"), "KEEP-ME-2");
753        // Memoised: the same source name always maps to the same output.
754        assert_eq!(namer.rule("a_b"), "a-b");
755    }
756
757    #[test]
758    fn namer_keeps_rules_and_tokens_apart() {
759        // A rule `NR` and the built-in `#NR` token is an ordinary grammar.
760        // The token must NOT be handed the rule's name: doing so emitted a
761        // self-referential `NR = NR` plus a duplicate `NR = <number>`.
762        let mut namer = AbnfNamer::new(["NR".to_string()]);
763        assert_eq!(namer.rule("NR"), "NR");
764        assert_eq!(namer.token("NR"), "NR-2");
765        // Each namespace is memoised on its own, and neither drifts.
766        assert_eq!(namer.token("NR"), "NR-2");
767        assert_eq!(namer.rule("NR"), "NR");
768        // A token whose name no rule claims is unaffected.
769        assert_eq!(namer.token("PL"), "PL");
770    }
771
772    #[test]
773    fn numeric_val_pads_to_whole_bytes() {
774        assert_eq!(numeric_val("\r\n"), "%x0D.0A");
775        assert_eq!(numeric_val("A"), "%x41");
776    }
777
778    #[test]
779    fn regex_ranges_and_literals_translate() {
780        assert_eq!(regex_to_abnf("^[\\u0030-\\u0039]"), "%x30-39");
781        assert_eq!(regex_to_abnf("^[\\x30-\\x39]"), "%x30-39");
782        assert_eq!(regex_to_abnf("(?i)^foo"), "\"foo\"");
783        // An escaped literal round-trips through the validation.
784        assert_eq!(regex_to_abnf("(?i)^a\\.b"), "\"a.b\"");
785        // A genuine regex is never misread as a literal. With no ABNF
786        // form it becomes a prose-val, which is an ELEMENT: the bare
787        // `; /…/` comment this used to emit left the legend entry with
788        // nothing in it, so the whole grammar failed to parse.
789        assert_eq!(regex_to_abnf("(?i)^a.b"), "<regex /(?i)^a.b/>");
790        assert_eq!(regex_to_abnf("^\\d+"), "<regex /^\\d+/>");
791    }
792
793    #[test]
794    fn prose_val_escapes_what_it_cannot_hold() {
795        // RFC 5234 §4 allows %x20-3D / %x3F-7E only, so a '>' would close
796        // the value early and must be escaped rather than dropped.
797        assert_eq!(prose_val("plain"), "<plain>");
798        assert_eq!(regex_to_abnf("^a>b"), "<regex /^a\\u003Eb/>");
799        // Every angle-bracket form the emitter produces is a prose-val,
800        // the built-in descriptions included.
801        assert_eq!(prose_val("number"), "<number>");
802    }
803
804    #[test]
805    fn quotable_rejects_control_and_quote_characters() {
806        assert!(is_abnf_quotable("hi"));
807        assert!(!is_abnf_quotable(""));
808        assert!(!is_abnf_quotable("a\"b"));
809        assert!(!is_abnf_quotable("\r\n"));
810    }
811}