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//! A repetition is read by SHAPE, not by name. Since tabnas/bnf#80 the
22//! BNF compiler (which abnf, ebnf and gbnf compile through) emits every
23//! `*A` as a replace loop: a helper `H` whose first open alternative is
24//! the entry `{ c: [n.rep == 0], n: {rep: 1}, r: H }` — it consumes
25//! nothing, pushes nothing and replaces the rule with itself under the
26//! guard, allocating the node and counting the iteration — followed by
27//! the continue alternatives that take one item and come back to `H`,
28//! and by the exits (a FOLLOW peek `{ s: FOLLOW, b: 1 }` and `{ }`).
29//! The guard is part of the shape: `s`, `b`, `p` and `r` alone also
30//! describe a user rule's own non-consuming self-replace, a guarded or
31//! counted state transition, which is no repetition. Such a rule is
32//! rendered wherever it is referenced as `*A` / `*( a b )`, and neither
33//! it nor its iteration helpers — `H$alt0` and `H$alt0$step1`, and the
34//! `$alt` / `$step` chains of the foldable groups the iteration pushes,
35//! everything the iteration reaches short of a kept production — is
36//! emitted as a production. The older push chain (`H = A H / ε`, one
37//! frame per item) carries no such entry and renders as before, as a
38//! kept production, wherever it sits, inside a loop's iteration included.
39//!
40//! Ported from `ts/src/debug.ts` (`emitAbnf` and friends), which is
41//! canonical. The repeat loop above was rendered here first, and the
42//! canonical has since followed, function for function; the Go port
43//! still lists the loop's entry as one of the rule's own alternatives
44//! and follows later. See `docs/reference.md`, "The repeat loop: the Go
45//! port follows".
46
47use std::collections::BTreeSet;
48
49use indexmap::{IndexMap, IndexSet};
50use tabnas::{AltSpec, CompareOp, Condition, RuleSpec, Tabnas, Tin, Value};
51
52/// Map engine rule and token names onto legal ABNF rule names.
53///
54/// RFC 5234: `rulename = ALPHA *(ALPHA / DIGIT / "-")`. Engine names are
55/// not so constrained — the abnf compiler synthesises `_gen1_star_term`
56/// and `…$alt0`, and a regex token arrives as `RX___U0030__U0039`.
57/// Emitted verbatim those are rejected by every conforming ABNF tool, so
58/// each is mapped to a legal name ONCE and reused for the production head
59/// and every reference.
60///
61/// Distinct source names can sanitise to the same string (`a_b` and `a-b`
62/// both give `a-b`), so collisions get a numeric suffix — without it the
63/// grammar would silently merge two rules.
64///
65/// RULES AND TOKENS ARE SEPARATE NAMESPACES, which is what the two caches
66/// are for. A token's bare name and a rule's name come from different
67/// sources and can coincide: `#NR` beside a rule called `NR` is ordinary.
68/// One shared cache merged them — the token looked up `NR`, hit the entry
69/// `new` had made for the RULE, and the emitter wrote the rule's own name
70/// for a terminal. A grammar whose rule `NR` referenced token `#NR` came
71/// out as a self-referential `NR = NR` plus a second `NR = <number>`
72/// definition: two definitions of one rule with `=` rather than
73/// incremental `=/`, and a production that recognises nothing.
74///
75/// Keeping the caches apart while sharing `taken` is the fix. A token
76/// still sanitises the same way, but allocates against everything already
77/// claimed, so it suffixes to `NR-2` instead of borrowing the rule's name.
78struct AbnfNamer {
79    rule_cache: IndexMap<String, String>,
80    token_cache: IndexMap<String, String>,
81    /// Claimed names, lowercased. RFC 5234 §2.1: "ABNF rule names are
82    /// case-insensitive", so `Foo-Bar` and `foo-bar` ARE the same rule and
83    /// the collision check has to fold case — comparing exact spellings
84    /// would let a sanitised `foo_bar` land beside a reserved `Foo-Bar`
85    /// and emit two definitions of one rule.
86    taken: BTreeSet<String>,
87}
88
89fn is_legal_abnf_name(name: &str) -> bool {
90    let mut chars = name.chars();
91    match chars.next() {
92        Some(first) if first.is_ascii_alphabetic() => {}
93        _ => return false,
94    }
95    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
96}
97
98impl AbnfNamer {
99    /// Seed with names that are already legal, claiming each up front:
100    /// otherwise a sanitised synthetic could take `foo-bar` first and
101    /// rename the user's real `foo-bar` rule out from under them.
102    fn new(reserve: impl IntoIterator<Item = String>) -> Self {
103        let mut namer = Self {
104            rule_cache: IndexMap::new(),
105            token_cache: IndexMap::new(),
106            taken: BTreeSet::new(),
107        };
108        for name in reserve {
109            if is_legal_abnf_name(&name) && !namer.is_taken(&name) {
110                namer.claim(&name);
111                namer.rule_cache.insert(name.clone(), name);
112            }
113        }
114        namer
115    }
116
117    fn claim(&mut self, name: &str) {
118        self.taken.insert(name.to_lowercase());
119    }
120
121    fn is_taken(&self, name: &str) -> bool {
122        self.taken.contains(&name.to_lowercase())
123    }
124
125    /// A rule name. Already-legal names were claimed by `new`, so this is
126    /// a cache hit for every user-authored rule.
127    fn rule(&mut self, name: &str) -> String {
128        if let Some(hit) = self.rule_cache.get(name) {
129            return hit.clone();
130        }
131        let out = self.allocate(name);
132        self.rule_cache.insert(name.to_string(), out.clone());
133        out
134    }
135
136    /// A token's bare name. A rule may already hold this spelling, and the
137    /// token must not borrow it, so this allocates rather than reading the
138    /// rule cache.
139    fn token(&mut self, bare: &str) -> String {
140        if let Some(hit) = self.token_cache.get(bare) {
141            return hit.clone();
142        }
143        let out = self.allocate(bare);
144        self.token_cache.insert(bare.to_string(), out.clone());
145        out
146    }
147
148    /// Sanitise to a legal rulename, then make it unique against every
149    /// name claimed so far — reserved rule names and previously allocated
150    /// names alike, since `taken` is shared by both namespaces.
151    fn allocate(&mut self, name: &str) -> String {
152        let mut out: String = name
153            .chars()
154            .map(|ch| {
155                if ch.is_ascii_alphanumeric() || ch == '-' {
156                    ch
157                } else {
158                    '-'
159                }
160            })
161            .collect();
162        if !out
163            .chars()
164            .next()
165            .is_some_and(|ch| ch.is_ascii_alphabetic())
166        {
167            out = format!("r{out}");
168        }
169        if self.is_taken(&out) {
170            let mut suffix = 2;
171            while self.is_taken(&format!("{out}-{suffix}")) {
172                suffix += 1;
173            }
174            out = format!("{out}-{suffix}");
175        }
176        self.claim(&out);
177        out
178    }
179}
180
181/// Emit the ABNF for `parser`'s live grammar.
182pub fn abnf(parser: &Tabnas) -> String {
183    Emitter::new(parser).emit()
184}
185
186struct Emitter<'a> {
187    parser: &'a Tabnas,
188    /// Rule name -> spec, in installation order (the engine's `IndexMap`),
189    /// which is the TypeScript insertion order the emitter's rule ordering
190    /// depends on.
191    rules: IndexMap<String, &'a RuleSpec>,
192    namer: AbnfNamer,
193    /// Token legend, in first-reference order.
194    used: IndexMap<String, String>,
195    end_tin: Option<Tin>,
196    /// `bnf` wraps grammars in a synthetic `__start__` rule; when present
197    /// it is skipped and the real start leads.
198    synth_wrapper: Option<String>,
199    /// The repeat loops: every rule whose open alternatives are the
200    /// compiler's whole scaffold, the entry, the continues that come back
201    /// and an exit (see [`Emitter::is_loop`]). Decided by shape, so a
202    /// hand-built loop and a compiled one read the same, and neither a
203    /// user rule's own self-replace nor an entry without its back edge
204    /// does.
205    loops: BTreeSet<String>,
206    /// The synthetic rules a loop's iteration runs through (`H$alt0`,
207    /// `H$alt0$step1`, and the `$alt` / `$step` chains of the groups it
208    /// pushes), bounded by the kept productions (see
209    /// [`Emitter::find_loop_helpers`]). Inlined into the repetition
210    /// wherever the loop is referenced, never productions.
211    loop_helpers: BTreeSet<String>,
212}
213
214impl<'a> Emitter<'a> {
215    fn new(parser: &'a Tabnas) -> Self {
216        let rules: IndexMap<String, &RuleSpec> = parser
217            .rule_specs()
218            .into_iter()
219            .map(|spec| (spec.name.clone(), spec))
220            .collect();
221        let synth_wrapper =
222            ("__start__" == parser.options.rule.start).then(|| parser.options.rule.start.clone());
223        let mut emitter = Self {
224            namer: AbnfNamer::new(rules.keys().cloned()),
225            rules,
226            used: IndexMap::new(),
227            end_tin: parser.options.token("#ZZ"),
228            synth_wrapper,
229            loops: BTreeSet::new(),
230            loop_helpers: BTreeSet::new(),
231            parser,
232        };
233        emitter.loops = emitter
234            .rules
235            .iter()
236            .filter(|(name, spec)| emitter.is_loop(name, spec))
237            .map(|(name, _)| name.clone())
238            .collect();
239        emitter.loop_helpers = emitter.find_loop_helpers();
240        emitter
241    }
242
243    /// `rule` is a repeat loop: its open alternatives are the compiler's
244    /// whole scaffold, in the compiler's order, not its entry alone. The
245    /// entry comes first ([`is_loop_entry`]); then at least one continue,
246    /// an alternative that consumes, pushes or replaces, and every
247    /// continue comes back to `rule` having made progress
248    /// ([`Emitter::continues_loop`]); and the empty exit `{ }`, an
249    /// alternative that consumes, pushes and replaces nothing and carries
250    /// no condition, since a repetition can stop whatever comes next. No
251    /// continue may follow it: it takes whatever comes and so shadows
252    /// every alternative after it. The FOLLOW peek `{ s: FOLLOW, b: 1 }`
253    /// may stand among the exits too, and shadows only what it peeks: the
254    /// compiler puts one before the continues where a keyword must end
255    /// the loop rather than be taken as an item (`*word "end"` with
256    /// `word = 1*ALPHA`). The compiler never guards an exit, and a rule
257    /// with a contentless alternative under a condition is no loop: the
258    /// condition may never hold, leaving the rule no way to stop, and
259    /// before a continue it shadows it whenever it holds. The
260    /// entry alone read a rule as a loop whose continue never came back:
261    /// the entry, `{ s: A }` and `{ }` take `A` at most once, and were
262    /// emitted as `*A`. A continue that does not come back ends the rule
263    /// after one item, and one that comes back having taken nothing
264    /// repeats nothing, so a rule with either is no repetition. An
265    /// alternative whose route or backtrack a function decides (`p_fn`,
266    /// `r_fn`, `b_fn` and their `_match` forms, a modifier `h`) cannot be
267    /// read, and a rule with one is no loop either. An exit gives back
268    /// exactly what it peeks, and a synthetic loop's closes, if it has
269    /// any, do nothing at all ([`is_idle`]), as the compiler's never do.
270    fn is_loop(&self, rule: &str, spec: &RuleSpec) -> bool {
271        let Some((first, rest)) = spec.open.split_first() else {
272            return false;
273        };
274        if !is_loop_entry(first, rule) || is_dynamic(first) {
275            return false;
276        }
277        let (mut continues, mut exit, mut shadowed) = (false, false, false);
278        let dead = shadowed_by_peeks(&spec.open, rule);
279        let (mut live_items, mut dead_items) = (Vec::new(), Vec::new());
280        for (index, alt) in rest.iter().enumerate() {
281            // The compiler writes one entry; a second can never be taken
282            // (the first set its counter) and is neither continue nor exit.
283            if is_dynamic(alt) || is_loop_entry(alt, rule) {
284                return false;
285            }
286            if !has_content(alt, rule, true) {
287                // The compiler never guards an exit: one with a condition
288                // may never stop the rule, and one before a continue
289                // shadows it whenever the condition holds.
290                // The compiler's exits give back exactly what they peek:
291                // the empty exit nothing, a FOLLOW peek its tokens.
292                if !is_plain_way(alt) || alt.b != alt.s.len() || alt.s.iter().any(Vec::is_empty) {
293                    return false;
294                }
295                // Only the empty exit stops the rule whatever comes next,
296                // and shadows every alternative after it.
297                if alt.s.is_empty() {
298                    exit = true;
299                    shadowed = true;
300                }
301            } else if !shadowed && self.continues_loop(alt, rule) {
302                // A continue a FOLLOW peek before it covers never runs, and
303                // does not make the rule a loop. It still renders, as every
304                // continue does, so its item must be one a live continue
305                // takes too, as the compiler's dead continues' are (the
306                // same iteration helper, or the same token with less
307                // lookahead); one with an item of its own would render as
308                // an alternative the rule never takes.
309                let item = self.continue_item(alt, rule);
310                if dead[index + 1] {
311                    dead_items.push(item);
312                } else {
313                    continues = true;
314                    live_items.push(item);
315                }
316            } else {
317                return false;
318            }
319        }
320        continues
321            && exit
322            && dead_items.iter().all(|item| live_items.contains(item))
323            && (!self.is_synthetic(rule) || spec.close.iter().all(is_idle))
324    }
325
326    /// The item a continue of the loop `rule` takes, one of the two shapes
327    /// [`Emitter::continues_loop`] accepts: the token a terminal continue
328    /// consumes, or the rule the iteration helper pushes.
329    fn continue_item(&self, alt: &AltSpec, rule: &str) -> Option<Item> {
330        if alt.r.as_deref() == Some(rule) {
331            return alt.s.first().cloned().map(Item::Token);
332        }
333        let helper = self.rules.get(alt.r.as_deref()?)?;
334        helper.open.first()?.p.clone().map(Item::Rule)
335    }
336
337    /// A continue in one of the compiler's two shapes, coming back to its
338    /// loop `rule` having taken one item. A terminal continue consumes
339    /// its token and replaces with `rule`, giving back any it peeked
340    /// after it (`{ s: [A], r: H }`, `{ s: [A, X], b: 1, r: H }`). A rule
341    /// continue peeks the item's first tokens, gives them all back and
342    /// replaces with the loop's iteration helper
343    /// ([`Emitter::is_iteration_helper`]), which pushes the item and comes
344    /// back. Either sets no counter, carries no guard but the
345    /// suffix-debt counter, and matches no empty token slot, which takes
346    /// any token and renders as nothing. Any other shape, a push beside
347    /// the replace (which the engine takes instead), a helper of another
348    /// shape, one with an empty way through, or one that pushes the loop
349    /// itself, is no continue the compiler writes, and a rule with one is
350    /// no loop.
351    fn continues_loop(&self, alt: &AltSpec, rule: &str) -> bool {
352        if alt.p.is_some()
353            || alt.s.is_empty()
354            || alt.s.iter().any(Vec::is_empty)
355            || !alt.n.is_empty()
356            || !is_guarded_as_compiled(alt)
357        {
358            return false;
359        }
360        match alt.r.as_deref() {
361            Some(target) if target == rule => alt.s.len() == alt.b + 1,
362            Some(target) => alt.s.len() == alt.b && self.is_iteration_helper(target, rule),
363            None => false,
364        }
365    }
366
367    /// `helper` is the iteration helper the compiler gives the loop
368    /// `rule` over a rule item, and nothing else: its one open pushes the
369    /// item (a rule other than `rule`, which reaches `rule` by no
370    /// synthetic way of its own), its one close replaces with its step,
371    /// and the step's one open replaces with `rule`, all matching no
372    /// token and setting no counter but `rep` (`H$alt0` → `H$alt0$step1`
373    /// → `H`).
374    fn is_iteration_helper(&self, helper: &str, rule: &str) -> bool {
375        let bare =
376            |alt: &AltSpec| alt.s.is_empty() && alt.b == 0 && alt.p.is_none() && is_helper_way(alt);
377        let Some(spec) = self.rules.get(helper) else {
378            return false;
379        };
380        let ([open], [close]) = (spec.open.as_slice(), spec.close.as_slice()) else {
381            return false;
382        };
383        let item = match open.p.as_deref() {
384            Some(item) if item != rule => item,
385            _ => return false,
386        };
387        if !open.s.is_empty() || open.b != 0 || open.r.is_some() || !is_helper_way(open) {
388            return false;
389        }
390        if !self.is_synthetic(helper) || !bare(close) || self.reaches(item, rule) {
391            return false;
392        }
393        let Some(step) = close.r.as_deref() else {
394            return false;
395        };
396        let Some(step_spec) = self.rules.get(step) else {
397            return false;
398        };
399        let [step_open] = step_spec.open.as_slice() else {
400            return false;
401        };
402        self.is_synthetic(step)
403            && bare(step_open)
404            && step_open.r.as_deref() == Some(rule)
405            && step_spec.close.iter().all(is_idle)
406    }
407
408    /// `from` reaches `rule`, by a push or a replace, itself or through
409    /// synthetic rules: an item that does repeats `rule` inside its own
410    /// iteration, which the repetition cannot render (its references to
411    /// `rule` read as the iteration's back edge). The compiler's items
412    /// reach their loop, when they do, through a user rule.
413    fn reaches(&self, from: &str, rule: &str) -> bool {
414        let mut visited: BTreeSet<&str> = BTreeSet::new();
415        let mut pending = vec![from];
416        while let Some(name) = pending.pop() {
417            if name == rule {
418                return true;
419            }
420            if (name != from && !self.is_synthetic(name)) || !visited.insert(name) {
421                continue;
422            }
423            if let Some(spec) = self.rules.get(name) {
424                pending.extend(
425                    spec.open
426                        .iter()
427                        .chain(spec.close.iter())
428                        .filter_map(|alt| alt.p.as_deref().or(alt.r.as_deref())),
429                );
430            }
431        }
432        false
433    }
434
435    /// The iteration helpers of every loop `H`: the synthetic rules
436    /// reachable from its continue alternatives without passing through
437    /// a KEPT PRODUCTION, which the walk neither enters nor adds
438    /// ([`Emitter::bounds_loop_helpers`]): `H$alt0`, pushing the item,
439    /// `H$alt0$step1`, replacing with `H`, and the `$alt` / `$step` chain
440    /// the compiler gives a group whose alternative starts with a rule
441    /// (`_gen2_group$alt0`, `_gen2_group$alt0$step1`, `_gen2_group$alt1`
442    /// for `( *A B / C )`). A user rule the iteration pushes keeps its
443    /// production; a nested loop is a loop of its own; an old push-chain
444    /// star stays a kept production, as does a `_plus`, which
445    /// [`Emitter::is_foldable`] judges for itself, a synthetic rule that
446    /// repeats by a cycle of its own ([`Emitter::cycles`]), and one with
447    /// an empty way through ([`Emitter::is_nullable_unfolded`]).
448    ///
449    /// The bound is by kept productions, not by name. A walk that
450    /// stopped only at user rules and other loops reached through a
451    /// foldable group to the old star inside `*( B *A C )` and folded it
452    /// away with its epsilon branch and its back edge: `*( B A C )`. A
453    /// scan for the rules named `H$…` never reached the group's own
454    /// chain, whose `$alt` names [`Emitter::is_foldable`] refuses, so
455    /// `*( *A B / C )` came out as `*( r-gen2-group-alt0 /
456    /// r-gen2-group-alt1 )` over three kept productions, and the `_plus`
457    /// over the same group, refused by [`Emitter::plus_folds`] for the
458    /// same names, as `X *X` in place of `1*X`.
459    fn find_loop_helpers(&self) -> BTreeSet<String> {
460        let mut helpers = BTreeSet::new();
461        let mut pending: Vec<String> = self
462            .loops
463            .iter()
464            .filter_map(|name| self.rules.get(name).map(|spec| (name, spec)))
465            .flat_map(|(name, spec)| {
466                spec.open
467                    .iter()
468                    .filter_map(|alt| alt.p.as_deref().or(alt.r.as_deref()))
469                    .filter(|target| *target != name.as_str())
470                    .map(str::to_owned)
471                    .collect::<Vec<_>>()
472            })
473            .collect();
474        while let Some(name) = pending.pop() {
475            if self.bounds_loop_helpers(&name)
476                || helpers.contains(&name)
477                || self.cycles(&name)
478                || self.is_nullable_unfolded(&name)
479            {
480                continue;
481            }
482            let Some(spec) = self.rules.get(&name) else {
483                continue;
484            };
485            helpers.insert(name.clone());
486            for alt in spec.open.iter().chain(spec.close.iter()) {
487                if let Some(target) = alt.p.as_deref().or(alt.r.as_deref()) {
488                    pending.push(target.to_owned());
489                }
490            }
491        }
492        helpers
493    }
494
495    /// A synthetic rule with an empty way through its opens, one that
496    /// takes nothing (`{ }`, or a peek it gives back), which nothing but
497    /// a loop's inlining would inline: not an optional's own helper,
498    /// which inlines as `[ … ]`, nor a foldable rule, which inlines
499    /// wherever it is referenced. Inlined as a loop's helper its empty
500    /// way was dropped, `*( A B )` for an iteration that also takes `B`
501    /// alone, so it stays a production of its own, referenced by name,
502    /// as it always was.
503    fn is_nullable_unfolded(&self, name: &str) -> bool {
504        !is_helper(name, "opt")
505            && !self.is_foldable(name)
506            && self
507                .rules
508                .get(name)
509                .is_some_and(|spec| spec.open.iter().any(|alt| !has_content(alt, name, false)))
510    }
511
512    /// A synthetic rule that reaches itself again through synthetic rules
513    /// none of which bounds a loop's helpers ([`Emitter::bounds_loop_helpers`]):
514    /// a repetition of its own, which no loop's iteration accounts for.
515    /// Inlined as a loop's helper, the way back to itself rendered as
516    /// nothing, through `seen`, so the helper `A H / B` pushed from a loop
517    /// came out as `*( A / B )` where the loop takes `*( *A B )`. It stays
518    /// what it was before the loop was read: a production of its own,
519    /// referenced by name. A loop's own `H$alt0` reaches itself only
520    /// through `H`, a loop, and is no cycle.
521    fn cycles(&self, name: &str) -> bool {
522        let targets = |rule: &str| -> Vec<&str> {
523            self.rules
524                .get(rule)
525                .map(|spec| {
526                    spec.open
527                        .iter()
528                        .chain(spec.close.iter())
529                        .filter_map(|alt| alt.p.as_deref().or(alt.r.as_deref()))
530                        .collect()
531                })
532                .unwrap_or_default()
533        };
534        let mut visited: BTreeSet<&str> = BTreeSet::new();
535        let mut pending = targets(name);
536        while let Some(target) = pending.pop() {
537            if target == name {
538                return true;
539            }
540            if self.bounds_loop_helpers(target) || !visited.insert(target) {
541                continue;
542            }
543            pending.extend(targets(target));
544        }
545        false
546    }
547
548    /// A rule that is a production of its own, or decides that for
549    /// itself, and so bounds the iteration helpers of every loop: a user
550    /// rule, a loop, or a repetition helper that is no loop's own — an old
551    /// push-chain `_star` with its `$alt` helpers
552    /// ([`Emitter::is_kept_repetition`]), and a `_plus` in either shape,
553    /// which [`Emitter::is_foldable`] judges through
554    /// [`Emitter::plus_folds`]. A loop's own `H$alt0` and `H$alt0$step1`
555    /// carry the loop's whole name, star and all, and are read by their
556    /// own segment: the loop.
557    fn bounds_loop_helpers(&self, name: &str) -> bool {
558        if !self.is_synthetic(name) || self.loops.contains(name) {
559            return true;
560        }
561        matches!(gen_kind(name), Some("star" | "plus")) && !self.loops.contains(own_segment(name))
562    }
563
564    /// A repetition helper in the old push-chain shape, kept as a
565    /// production as it always was: a `_star` that is not a loop, or one
566    /// of its `$alt0` / `$alt0$step1` iteration helpers, which carry its
567    /// name. A loop's own `H$alt0` is not one (its own segment is the
568    /// loop), nor is the `$alt` chain of a group or the `$step` chain of
569    /// a `_plus`.
570    fn is_kept_repetition(&self, name: &str) -> bool {
571        gen_kind(name) == Some("star") && !self.loops.contains(own_segment(name))
572    }
573
574    /// A rule the abnf forward-compiler synthesised for a `[...]` /
575    /// `*(...)` / `1*(...)` / group / chain-step: named `_gen<n>_…` or
576    /// carrying a `$`. These are never user-authored, so instead of
577    /// emitting them as their own productions each is folded back into the
578    /// ABNF construct it encodes — a reasonable round-trip (`tn.abnf(G)`
579    /// then `abnf()` reproduces `G`, not the expanded internal form).
580    fn is_synthetic(&self, name: &str) -> bool {
581        if Some(name) == self.synth_wrapper.as_deref() {
582            return false;
583        }
584        name.contains('$') || is_gen_name(name)
585    }
586
587    /// Only the clean cases fold — `[…]` optionals plus the group / chain
588    /// helpers they inline through. A repetition in the old push-chain
589    /// shape (`_star` / `_plus` and their `$alt…` helpers) does not
590    /// reconstruct reliably, so those rules are emitted as productions
591    /// unchanged — still a valid, recognition-equivalent grammar. A
592    /// repetition in the loop shape is not decided here: see
593    /// [`Emitter::is_folded`]. The kind is read from the rule's own
594    /// segment ([`gen_kind`]), so a helper named after a repetition it
595    /// merely contains is judged by what it is.
596    fn is_foldable(&self, name: &str) -> bool {
597        if !self.is_synthetic(name) || gen_kind(name) == Some("star") || name.contains("$alt") {
598            return false;
599        }
600        gen_kind(name) != Some("plus") || self.plus_folds(name)
601    }
602
603    /// `1*A` compiles to a `_plus` helper: `A` followed by the star of `A`.
604    /// The helper folds to `A *A` when that star is a loop; with an
605    /// old-shape star, a kept production, the helper stays a production
606    /// too, as it always has. Its own chain is the helper and its `$step`
607    /// helpers, which share its own segment, and only the repetition that
608    /// chain reaches is its trailing star: an old-shape star inside the
609    /// item is the item's, a production of its own referenced by name,
610    /// and neither folds nor stops the fold. It folds only when its own
611    /// chain reaches a loop, and meets no cycle on the way: a helper that
612    /// re-enters itself, or a chain of helpers that comes back round
613    /// without passing through a loop, repeats by that cycle, and folded,
614    /// the cycle's back edge rendered as nothing, so `A*` came out as one
615    /// `A`. Reaches through the chain steps (`_plus$step1`) a non-terminal
616    /// item puts between the helper and its star, and through the group
617    /// it pushes and that group's own `$alt` / `$step` chain, which fold:
618    /// the `_plus` over `( *A B / C )` is `1*( *A B / C )`. Refusing
619    /// every `$alt` name here refused that chain, and the helper came out
620    /// as `X *X`, which does not round-trip on a nullable item.
621    fn plus_folds(&self, name: &str) -> bool {
622        // A depth-first walk with an explicit stack: `open` holds the
623        // rules on the current path, so reaching one again is a cycle;
624        // `done` those whose walk has finished, which a second path may
625        // reach without one. A step is judged by the plus it belongs to,
626        // through the segment they share.
627        let mut open: BTreeSet<String> = BTreeSet::new();
628        let mut done: BTreeSet<String> = BTreeSet::new();
629        let mut reached_loop = false;
630        let mut stack: Vec<(String, Vec<String>)> = Vec::new();
631        let targets = |current: &str| -> Vec<String> {
632            self.rules
633                .get(current)
634                .map(|spec| {
635                    spec.open
636                        .iter()
637                        .chain(spec.close.iter())
638                        .filter_map(|alt| alt.p.as_deref().or(alt.r.as_deref()))
639                        .map(str::to_owned)
640                        .collect()
641                })
642                .unwrap_or_default()
643        };
644        open.insert(name.to_owned());
645        stack.push((name.to_owned(), targets(name)));
646        while let Some((current, pending)) = stack.last_mut() {
647            let Some(target) = pending.pop() else {
648                open.remove(current.as_str());
649                done.insert(current.clone());
650                stack.pop();
651                continue;
652            };
653            let own = own_segment(current) == own_segment(name);
654            if !self.rules.contains_key(&target) || !self.is_synthetic(&target) {
655                continue;
656            }
657            if self.loops.contains(&target) || self.loop_helpers.contains(&target) {
658                reached_loop |= own && self.loops.contains(&target);
659                continue;
660            }
661            if self.is_kept_repetition(&target) {
662                // The plus's own trailing star in the old shape keeps the
663                // plus a production; one inside the item stays the item's
664                // production, referenced by name.
665                if own {
666                    return false;
667                }
668                continue;
669            }
670            if open.contains(&target) {
671                return false;
672            }
673            if done.contains(&target) {
674                continue;
675            }
676            open.insert(target.clone());
677            let next = targets(&target);
678            stack.push((target, next));
679        }
680        let plus = own_segment(name);
681        reached_loop
682            && self
683                .loop_after(plus)
684                .is_some_and(|tail| self.counted_by_construction(plus, &tail).is_some())
685    }
686
687    /// A rule rendered where it is referenced and never as a production
688    /// of its own, unless it is the start rule: a foldable synthetic, a
689    /// synthetic loop, or a loop's iteration helper. A loop that is a
690    /// USER rule keeps its production (its body is the repetition) and is
691    /// referenced by name.
692    fn is_folded(&self, name: &str) -> bool {
693        self.is_foldable(name)
694            || (self.loops.contains(name) && self.is_synthetic(name))
695            || self.loop_helpers.contains(name)
696    }
697
698    fn emit(mut self) -> String {
699        let start_rule = self.start_rule();
700
701        // Real start first, then the remaining USER (non-synthetic) rules.
702        let user_rules: Vec<String> = self
703            .rules
704            .keys()
705            .filter(|name| {
706                Some(name.as_str()) != self.synth_wrapper.as_deref() && !self.is_folded(name)
707            })
708            .cloned()
709            .collect();
710
711        // The start rule is always a production, folded or not: nothing
712        // encloses it to render it where it is referenced, and a grammar
713        // whose start is a synthetic loop (a standalone `*A`) otherwise
714        // came out with no production at all.
715        let mut ordered: Vec<String> = Vec::new();
716        let mut seen_rules: BTreeSet<String> = BTreeSet::new();
717        if let Some(start) = start_rule.filter(|start| self.rules.contains_key(start)) {
718            seen_rules.insert(start.clone());
719            ordered.push(start);
720        }
721        for name in user_rules {
722            if seen_rules.insert(name.clone()) {
723                ordered.push(name);
724            }
725        }
726
727        let mut lines: Vec<String> = Vec::new();
728        for name in ordered {
729            let seen = BTreeSet::from([name.clone()]);
730            let body = self.emit_body(&name, &seen);
731            let head = self.namer.rule(&name);
732            lines.push(format!("{head} = {body}"));
733        }
734
735        // Define each token as its own ABNF rule (named terminals), after
736        // the productions, with `=` aligned for readability.
737        if !self.used.is_empty() {
738            let pad = self.used.keys().map(String::len).max().unwrap_or(0);
739            lines.push(String::new());
740            for (name, form) in &self.used {
741                lines.push(format!("{name:pad$} = {form}"));
742            }
743        }
744        lines.join("\n")
745    }
746
747    /// The grammar's real start rule, seeing through a `__start__` wrapper.
748    fn start_rule(&self) -> Option<String> {
749        let Some(wrapper) = self.synth_wrapper.clone() else {
750            return Some(self.parser.options.rule.start.clone());
751        };
752        let spec = self.rules.get(&wrapper)?;
753        for alt in &spec.open {
754            if let Some(target) = alt.p.as_ref().or(alt.r.as_ref()) {
755                return Some(target.clone());
756            }
757        }
758        None
759    }
760
761    /// Full production body: open alternatives joined by `/`, then any
762    /// close continuation — but PRESERVING an empty open alternative,
763    /// which is essential for kept `*(…)` repetition rules, whose empty
764    /// alt is what makes them zero-or-more.
765    ///
766    /// The empty alternative is rendered by wrapping the rest in `[ … ]`,
767    /// NOT as a trailing `/`. ABNF's grammar is
768    ///   alternation = concatenation *(*c-wsp "/" *c-wsp concatenation)
769    /// so every `/` must be followed by a concatenation: `x = A x /` is a
770    /// syntax error that every conforming ABNF tool rejects. `[ A x ]`
771    /// says the same thing and is valid.
772    fn emit_body(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
773        // A user rule that is a loop: its production IS the repetition.
774        // One that repeats nothing matches exactly the empty string, which
775        // `""` says and an empty production cannot (see below).
776        if self.loops.contains(name) {
777            let body = self.repetition(name, seen);
778            return if body.is_empty() {
779                "\"\"".to_string()
780            } else {
781                body
782            };
783        }
784        let opens: Vec<AltSpec> = self
785            .rules
786            .get(name)
787            .map(|spec| spec.open.clone())
788            .unwrap_or_default();
789        let raw: Vec<String> = opens.iter().map(|alt| self.seq_of_alt(alt, seen)).collect();
790        let optional = raw.iter().any(String::is_empty);
791        let non_empty: IndexSet<String> = raw.into_iter().filter(|item| !item.is_empty()).collect();
792        let cont = self.close_cont(name, seen);
793
794        // Nothing but an empty alternative. `option = "[" *c-wsp
795        // alternation *c-wsp "]"` and `alternation` needs at least one
796        // concatenation, so `[ ]` is not a legal option — there is nothing
797        // to make optional.
798        //
799        // With a continuation, the open contributes nothing and the rule
800        // IS its continuation. Without one, `x = ` is not a production at
801        // all, and ABNF has no epsilon terminal — but an empty char-val is
802        // legal (`char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE` permits
803        // zero chars) and matches exactly the empty string, which is what
804        // this rule does.
805        if optional && non_empty.is_empty() {
806            return if cont.is_empty() {
807                "\"\"".to_string()
808            } else {
809                cont
810            };
811        }
812
813        let joined = non_empty.into_iter().collect::<Vec<_>>().join(" / ");
814        let body = if optional {
815            format!("[ {joined} ]")
816        } else {
817            joined
818        };
819        format!("{body} {cont}").trim().to_string()
820    }
821
822    /// Open alternatives joined by `/`, then any close continuation. Unlike
823    /// [`Emitter::emit_body`] an empty open alternative is dropped, because
824    /// an inlined construct contributes only its content.
825    fn rule_seq(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
826        let opens = self.content_opens(name);
827        let alts: IndexSet<String> = opens
828            .iter()
829            .map(|alt| self.seq_of_alt(alt, seen))
830            .filter(|item| !item.is_empty())
831            .collect();
832        let joined = alts.into_iter().collect::<Vec<_>>().join(" / ");
833        let cont = self.close_cont(name, seen);
834        format!("{joined} {cont}").trim().to_string()
835    }
836
837    /// The close-alt continuation of a rule: its trailing element
838    /// sequence, wrapped in `[ … ]` when an epsilon (empty) close alt
839    /// makes it optional.
840    fn close_cont(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
841        let closes: Vec<AltSpec> = self
842            .rules
843            .get(name)
844            .map(|spec| spec.close.clone())
845            .unwrap_or_default();
846        let has_epsilon = closes
847            .iter()
848            .any(|alt| !self.is_end_alt(alt) && !self.has_content(alt, name));
849        for alt in &closes {
850            if self.is_end_alt(alt) || !self.has_content(alt, name) {
851                continue;
852            }
853            let cont = self.seq_of_alt(alt, seen);
854            if cont.is_empty() {
855                continue;
856            }
857            return if has_epsilon {
858                format!("[ {cont} ]")
859            } else {
860                cont
861            };
862        }
863        String::new()
864    }
865
866    /// An alt whose whole sequence is the single end-of-source token.
867    fn is_end_alt(&self, alt: &AltSpec) -> bool {
868        let Some(end) = self.end_tin else {
869            return false;
870        };
871        1 == alt.s.len() && 1 == alt.s[0].len() && end == alt.s[0][0]
872    }
873
874    fn content_opens(&self, name: &str) -> Vec<AltSpec> {
875        self.rules
876            .get(name)
877            .map(|spec| {
878                spec.open
879                    .iter()
880                    .filter(|alt| self.has_content(alt, name))
881                    .cloned()
882                    .collect()
883            })
884            .unwrap_or_default()
885    }
886
887    /// [`has_content`] for an alt of `name`, which is a loop or is not:
888    /// only a loop has an entry to skip.
889    fn has_content(&self, alt: &AltSpec, name: &str) -> bool {
890        has_content(alt, name, self.loops.contains(name))
891    }
892
893    /// A loop, as a repetition of its iteration: `*A` when the iteration
894    /// is one element, `*( a b )` otherwise. The iteration is the ` / `-
895    /// joined rendering of the continue alternatives — the open
896    /// alternatives with content — and its back edges render nothing: the
897    /// loop is in `seen`, so `r: H` (from a terminal continue, or from
898    /// `H$alt0$step1` at the end of a ref continue) terminates like any
899    /// other loop-back. The entry, `{ r: H }` consuming nothing, and the
900    /// exits, `{ s: FOLLOW, b: 1 }` and `{ }`, have no content and are
901    /// skipped: they are bookkeeping, not syntax. Any close continuation
902    /// of the loop rule runs once, after the last item, and follows the
903    /// repetition.
904    fn repetition(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
905        let opens = self.content_opens(name);
906        let parts: IndexSet<String> = opens
907            .iter()
908            .map(|alt| self.seq_of_alt(alt, seen))
909            .filter(|item| !item.is_empty())
910            .collect();
911        let iteration = repeat_of(&parts.into_iter().collect::<Vec<_>>());
912        // The loop's own name is seen so that the iteration's back edges
913        // render nothing; a close that re-enters a user loop is no back
914        // edge but the rule again, and renders as its name. (A synthetic
915        // loop's closes do nothing at all: see [`is_idle`].)
916        let cont = if self.is_synthetic(name) {
917            self.close_cont(name, seen)
918        } else {
919            let mut outer = seen.clone();
920            outer.remove(name);
921            self.close_cont(name, &outer)
922        };
923        format!("{iteration} {cont}").trim().to_string()
924    }
925
926    /// Render one alt as an ABNF element sequence: its `s` tokens then its
927    /// `p`/`r` target (synthetic targets are inlined).
928    ///
929    /// An alt consumes `len(s) - b` tokens — the engine records "matched
930    /// minus backtrack". Tokens beyond that are LOOKAHEAD only: matched to
931    /// choose the alt, then pushed back. Rendering them as ABNF elements
932    /// would claim input the alt never eats.
933    ///
934    /// Deriving the count this way also covers the FIRST-set-guarded
935    /// epsilon — `{ s: '#Y', b: 1 }` with no target, which the abnf
936    /// compiler emits for the skip branch of an optional, where `#Y` is
937    /// the FOLLOW token. Rendered as a consuming alternative,
938    /// `top = [ X "@" ] Y` came back as `top = [ X T / Y ] Y`: the
939    /// optional could swallow the follow.
940    fn seq_of_alt(&mut self, alt: &AltSpec, seen: &BTreeSet<String>) -> String {
941        let mut elements: Vec<String> = Vec::new();
942        let keep = alt.s.len().saturating_sub(alt.b);
943        for position in alt.s.iter().take(keep) {
944            match position.len() {
945                0 => continue,
946                1 => {
947                    let tin = position[0];
948                    if Some(tin) == self.end_tin {
949                        continue;
950                    }
951                    let terminal = self.terminal(tin);
952                    elements.push(terminal);
953                }
954                _ => {
955                    let inner: Vec<String> = position
956                        .iter()
957                        .filter(|tin| Some(**tin) != self.end_tin)
958                        .copied()
959                        .collect::<Vec<_>>()
960                        .into_iter()
961                        .map(|tin| self.terminal(tin))
962                        .collect();
963                    if !inner.is_empty() {
964                        elements.push(format!("( {} )", inner.join(" / ")));
965                    }
966                }
967            }
968        }
969        let target = alt.p.clone().or_else(|| alt.r.clone());
970        if let Some(target) = target {
971            let reference = self.inline_ref(&target, seen);
972            if !reference.is_empty() {
973                elements.push(reference);
974            }
975        }
976        elements.join(" ")
977    }
978
979    /// Inline a reference: a user rule stays a bareword; a synthetic rule
980    /// folds back into the ABNF construct it encodes.
981    fn inline_ref(&mut self, name: &str, seen: &BTreeSet<String>) -> String {
982        if self.loops.contains(name) {
983            if seen.contains(name) {
984                // The back edge out of the loop's own iteration.
985                return String::new();
986            }
987            if !self.is_synthetic(name) {
988                // A user rule that is a loop keeps its production.
989                return self.namer.rule(name);
990            }
991            let mut inner = seen.clone();
992            inner.insert(name.to_string());
993            return self.repetition(name, &inner);
994        }
995        // A user rule, or a kept (non-foldable, e.g. old-shape repetition)
996        // synthetic rule, stays a bareword reference; only foldable
997        // synthetics and a loop's iteration helpers inline.
998        if !self.is_foldable(name) && !self.loop_helpers.contains(name) {
999            return self.namer.rule(name);
1000        }
1001        if seen.contains(name) {
1002            // A foldable loop-back — returning empty terminates the loop.
1003            return String::new();
1004        }
1005        if !self.rules.contains_key(name) {
1006            return self.namer.rule(name);
1007        }
1008        let mut inner = seen.clone();
1009        inner.insert(name.to_string());
1010        // The optional's own helper, and only that: a star over an
1011        // optional is named after it (`_gen3_star__gen2_opt__gen1_group`),
1012        // and so are its iteration helpers, and a substring test for
1013        // `_opt` wrapped each of those in `[ … ]` too — `*[ [ T ] [  ] ]`,
1014        // with the step, whose only content is the back edge, as an empty
1015        // option, which RFC 5234 has no room for. (The canonical reads
1016        // the segment too, since it followed with the loop. The Go port
1017        // still tests the substring; it never inlines those names, so it
1018        // never meets them.)
1019        if is_helper(name, "opt") {
1020            let body = self.rule_seq(name, &inner);
1021            return format!("[ {body} ]");
1022        }
1023        let body = self.rule_seq(name, &inner);
1024        if is_helper(name, "plus") || is_helper(name, "rep") {
1025            if let Some(counted) = self.counted_repetition(name, &inner) {
1026                return counted;
1027            }
1028        }
1029        // group / chain-step: inline the body, parenthesising a bare
1030        // multi-way alternation that will sit inside a larger sequence.
1031        let multi = 1 < self.content_opens(name).len();
1032        if multi && self.close_cont(name, &inner).is_empty() {
1033            format!("( {body} )")
1034        } else {
1035            body
1036        }
1037    }
1038
1039    /// `1*A` compiles to a `_plus` helper that is `A` followed by the star
1040    /// of `A`, and `n*A` to a `_rep` helper that is `A` `n` times followed
1041    /// by it. Rendered element by element those read `A *A` and `A A *A`:
1042    /// the same language as `1*A` and `2*A`, but not the same recogniser
1043    /// once recompiled. The abnf crate compiles `A *A` and `1*A`
1044    /// differently, and where `A` is nullable, or its FIRST meets its
1045    /// FOLLOW, the recompiled `A *A` rejects inputs the original accepts:
1046    /// `1*( [ "+" "e" ] )` on `+e`, `1*item` with `item = "]" "e" / [ "d" ]`
1047    /// on `]e`. So a helper whose body is the item of the loop it ends in,
1048    /// `n` times, then that loop's repetition is written back as the
1049    /// repetition it was compiled from: `1*A`, `1*[ A ]`, `2*( a b )`. Any
1050    /// other body renders as it is: a bounded `2*4A` compiles to nested
1051    /// optionals and ends in no loop, and a hand-built rule that merely
1052    /// carries the name is whatever it says.
1053    fn counted_repetition(&mut self, name: &str, seen: &BTreeSet<String>) -> Option<String> {
1054        let loop_name = self.loop_after(name)?;
1055        let count = self.counted_by_construction(name, &loop_name)?;
1056        let mut inner = seen.clone();
1057        inner.insert(loop_name.clone());
1058        let repetition = self.repetition(&loop_name, &inner);
1059        repetition
1060            .starts_with('*')
1061            .then(|| format!("{count}{repetition}"))
1062    }
1063
1064    /// How many times the chain of the `_plus` / `_rep` helper `name`
1065    /// takes the item of the loop `tail` it ends in, when it is the
1066    /// compiler's construction and nothing else: each rule of the chain
1067    /// has one plain open alternative, consuming the loop's item token
1068    /// (`{ s: [A], p: tail }` for `1*"a"`, `{ s: [A A], … }` for `2*"a"`)
1069    /// or pushing the loop's item rule (`{ p: item }`, then a close
1070    /// replace to the next step), and the last pushes `tail` and ends.
1071    /// A chain that takes anything else, or a different rule that
1072    /// merely renders the same, is no counted repetition: `X *X` and
1073    /// `1*X` compile to different recognisers, and only the compiler's
1074    /// own construction is the `1*X` it was compiled from.
1075    fn counted_by_construction(&self, name: &str, tail: &str) -> Option<usize> {
1076        let item = self.loop_item(tail)?;
1077        let mut visited: BTreeSet<&str> = BTreeSet::new();
1078        let mut current = name;
1079        let mut count = 0usize;
1080        loop {
1081            if !visited.insert(current) {
1082                return None;
1083            }
1084            let spec = self.rules.get(current)?;
1085            let [open] = spec.open.as_slice() else {
1086                return None;
1087            };
1088            if !is_plain_way(open) || open.b != 0 || open.r.is_some() {
1089                return None;
1090            }
1091            for slot in &open.s {
1092                if item != Item::Token(slot.clone()) {
1093                    return None;
1094                }
1095                count += 1;
1096            }
1097            match open.p.as_deref() {
1098                Some(target) if target == tail => {
1099                    let ends = spec.close.iter().all(|alt| {
1100                        is_plain_way(alt) && alt.s.is_empty() && alt.p.is_none() && alt.r.is_none()
1101                    });
1102                    return (ends && 0 < count).then_some(count);
1103                }
1104                Some(target) if item == Item::Rule(target.to_owned()) => count += 1,
1105                Some(_) => return None,
1106                None => {}
1107            }
1108            let [close] = spec.close.as_slice() else {
1109                return None;
1110            };
1111            if !is_plain_way(close) || !close.s.is_empty() || close.p.is_some() {
1112                return None;
1113            }
1114            current = close.r.as_deref()?;
1115        }
1116    }
1117
1118    /// The one item the loop `rule` repeats, as the compiler builds it:
1119    /// the token its terminal continues consume (`{ s: [A], r: rule }`,
1120    /// or `{ s: [A, X], b: 1, r: rule }` with a token of lookahead),
1121    /// or the rule its iteration helper pushes, after a continue that
1122    /// peeks one of that rule's FIRST tokens (`{ s: [A], b: 1, r:
1123    /// rule$alt0 }`, `rule$alt0` opening `{ p: item }`). None for a loop
1124    /// over anything else.
1125    fn loop_item(&self, rule: &str) -> Option<Item> {
1126        let spec = self.rules.get(rule)?;
1127        let mut item: Option<Item> = None;
1128        for alt in spec.open.iter().skip(1) {
1129            if !has_content(alt, rule, true) {
1130                continue;
1131            }
1132            let this = if alt.r.as_deref() == Some(rule) && alt.s.len() == alt.b + 1 {
1133                // It consumes its one token and gives back any it peeked
1134                // after it (`{ s: [A, X], b: 1 }`, where the compiler looks
1135                // two tokens ahead).
1136                Item::Token(alt.s[0].clone())
1137            } else if alt.s.len() == alt.b {
1138                let helper = self.rules.get(alt.r.as_deref()?)?;
1139                let [open] = helper.open.as_slice() else {
1140                    return None;
1141                };
1142                if !open.s.is_empty() || open.r.is_some() || !is_plain_way(open) {
1143                    return None;
1144                }
1145                Item::Rule(open.p.clone()?)
1146            } else {
1147                return None;
1148            };
1149            match &item {
1150                None => item = Some(this),
1151                Some(seen) if *seen == this => {}
1152                Some(_) => return None,
1153            }
1154        }
1155        item
1156    }
1157
1158    /// The loop a `_plus` / `_rep` helper ends in: the open target of the
1159    /// last rule of its chain (`H`, `H$step1`, … linked by their close
1160    /// replaces), when that target is a loop. The chain is followed by its
1161    /// close edges only, never into the pushed item, which may hold a
1162    /// loop of its own.
1163    fn loop_after(&self, name: &str) -> Option<String> {
1164        let mut visited: BTreeSet<String> = BTreeSet::new();
1165        let mut current = name.to_string();
1166        loop {
1167            if !visited.insert(current.clone()) {
1168                return None;
1169            }
1170            let spec = self.rules.get(&current)?;
1171            match spec.close.iter().find_map(|alt| alt.r.clone()) {
1172                Some(next) if self.rules.contains_key(&next) => current = next,
1173                _ => break,
1174            }
1175        }
1176        let spec = self.rules.get(&current)?;
1177        spec.open
1178            .iter()
1179            .find_map(|alt| alt.p.clone().or_else(|| alt.r.clone()))
1180            .filter(|target| self.loops.contains(target))
1181    }
1182
1183    /// Render a token reference: every token appears by its bare NAME
1184    /// (`#PL` -> `PL`), and its definition is recorded in the legend. A
1185    /// token name that is actually a rule name is a nonterminal reference
1186    /// and is returned as-is, with no legend entry.
1187    fn terminal(&mut self, tin: Tin) -> String {
1188        let full_name = self.parser.token_name(tin);
1189        if self.rules.contains_key(&full_name) {
1190            return self.namer.rule(&full_name);
1191        }
1192        let bare = full_name
1193            .strip_prefix('#')
1194            .unwrap_or(&full_name)
1195            .to_string();
1196        // Strip the '#' sigil first so '#NR' asks for 'NR' rather than
1197        // being sanitised to '-NR' and then prefixed.
1198        //
1199        // This goes through the TOKEN namespace. A rule may already hold
1200        // this spelling — a grammar with a rule `NR` and the `#NR` number
1201        // token is perfectly ordinary — and the token must not borrow it:
1202        // that emitted a self-referential `NR = NR` plus a duplicate
1203        // definition. The token namespace suffixes to `NR-2` instead.
1204        let name = self.namer.token(&bare);
1205        if !self.used.contains_key(&name) {
1206            let form = token_form(self.parser, tin, &full_name);
1207            self.used.insert(name.clone(), form);
1208        }
1209        name
1210    }
1211}
1212
1213/// A rule the abnf forward-compiler synthesised, named `_gen<n>_…`.
1214fn is_gen_name(name: &str) -> bool {
1215    name.strip_prefix("_gen")
1216        .and_then(|rest| rest.chars().next())
1217        .is_some_and(|ch| ch.is_ascii_digit())
1218}
1219
1220/// The construct a synthesised name encodes — `opt`, `group`, `star`,
1221/// `plus`, `rep` — read from the rule's OWN segment: the word after
1222/// `_gen<n>_` in the part before any `$`. A repetition's helper is named
1223/// after its item, so `_gen3_star__gen2_opt__gen1_group` is the star over
1224/// the optional over the group, and its iteration helpers
1225/// `…$alt0` / `…$alt0$step1` carry the whole of that name; a substring
1226/// test for `_opt` reached all of them. A chain step (`_gen1_group$step1`)
1227/// answers with the kind of the rule it continues.
1228fn gen_kind(name: &str) -> Option<&str> {
1229    let rest = own_segment(name).strip_prefix("_gen")?;
1230    let digits = rest.len()
1231        - rest
1232            .trim_start_matches(|ch: char| ch.is_ascii_digit())
1233            .len();
1234    if digits == 0 {
1235        return None;
1236    }
1237    let rest = rest[digits..].strip_prefix('_')?;
1238    let kind = rest.split('_').next().unwrap_or(rest);
1239    (!kind.is_empty()).then_some(kind)
1240}
1241
1242/// The rule a synthesised name belongs to: the part before any `$`. A
1243/// chain step (`_gen1_group$step1`) and an iteration helper (`H$alt0`,
1244/// `H$alt0$step1`) answer with the rule they continue.
1245fn own_segment(name: &str) -> &str {
1246    name.split('$').next().unwrap_or(name)
1247}
1248
1249/// `name` is the helper of `kind` itself — not a chain step or an
1250/// iteration helper of it, which carry a `$`.
1251fn is_helper(name: &str, kind: &str) -> bool {
1252    !name.contains('$') && gen_kind(name) == Some(kind)
1253}
1254
1255/// An alt that contributes something to the emitted sequence of `rule`,
1256/// decided by what it CONSUMES: it eats a token (`len(s) - b > 0`), or
1257/// pushes a rule, or replaces with a rule — unless `rule` is a loop and
1258/// this is its entry ([`is_loop_entry`]). `{ }`, the FOLLOW peek
1259/// `{ s: FOLLOW, b: 1 }` and the entry `{ c: [n.rep == 0], n: {rep: 1},
1260/// r: rule }` are all epsilon: none of them moves the parse past any
1261/// input. Counting the peek as content rendered a follow-guarded exit
1262/// as a consuming alternative, and counting the entry rendered a loop
1263/// as one of its own alternatives. Every other replace with `rule`
1264/// itself is content, as it always was: the close `{ s: A, b: 1, r: rule }`
1265/// after an open that consumed `A` is the `[ rule ]` of
1266/// `rule = A [ rule ]`, and calling it empty for the self-replace alone
1267/// emitted `rule = A`, exactly one where the rule takes one or more. The
1268/// same close carrying the entry's guard and counter is content too when
1269/// `rule` is no loop (`rule_is_loop`, decided by its OPEN alternatives):
1270/// a rule that is not a loop has no entry, only alternatives, and
1271/// `odd = A [ odd ]` renders as it always did.
1272fn has_content(alt: &AltSpec, rule: &str, rule_is_loop: bool) -> bool {
1273    !(rule_is_loop && is_loop_entry(alt, rule))
1274        && (alt.s.len() > alt.b || alt.p.is_some() || alt.r.is_some())
1275}
1276
1277/// The one item a loop repeats ([`Emitter::loop_item`]): a token slot its
1278/// continue consumes, or the rule its iteration helper pushes.
1279#[derive(Clone, Debug, PartialEq, Eq)]
1280enum Item {
1281    Token(Vec<Tin>),
1282    Rule(String),
1283}
1284
1285/// An alternative whose route, backtrack or whole shape a function
1286/// decides when it matches, so what it pushes, replaces or consumes
1287/// cannot be read from the spec.
1288fn is_dynamic(alt: &AltSpec) -> bool {
1289    alt.p_fn.is_some()
1290        || alt.p_match.is_some()
1291        || alt.r_fn.is_some()
1292        || alt.r_match.is_some()
1293        || alt.b_fn.is_some()
1294        || alt.b_match.is_some()
1295        || alt.h.is_some()
1296        || alt.h_match.is_some()
1297}
1298
1299/// A continue guarded as the compiler guards one: by nothing, or by the
1300/// suffix-debt counter alone (`n.debt_… == 0`, which tabnas-bnf puts on
1301/// a left-recursion tail loop's contested branches). Any other
1302/// condition may contradict the state the entry leaves (`n.rep == 0`
1303/// after the entry has set it to 1) and keep the continue from ever
1304/// running, so a rule with one is no loop.
1305fn is_guarded_as_compiled(alt: &AltSpec) -> bool {
1306    !is_dynamic(alt)
1307        && matches!(alt.c.as_slice(), [] | [_])
1308        && alt.c.iter().all(is_debt_guard)
1309        && alt.c_ref.is_none()
1310        && alt.c_fn.is_none()
1311        && alt.c_match.is_none()
1312        && alt.c_lex.is_none()
1313        && alt.c_lex_match.is_none()
1314}
1315
1316/// The suffix-debt guard, `n.debt_… == 0`.
1317fn is_debt_guard(condition: &Condition) -> bool {
1318    matches!(condition.path.as_slice(), [bag, counter] if bag == "n" && counter.starts_with("debt_"))
1319        && condition.op == CompareOp::Eq
1320        && matches!(condition.value, Value::Number(count) if count == 0.0)
1321}
1322
1323/// An alternative that does nothing: it matches no token, pushes and
1324/// replaces nothing, and carries no condition. The compiler's loops have
1325/// no closes, and a synthetic rule is a loop only when its closes, if it
1326/// has any, are all idle. A synthetic loop renders inline, wherever a
1327/// rule refers to it, with no name of its own to render there, so a
1328/// close that could run it again would be lost: one that re-enters it,
1329/// directly or through helpers, one that pushes, which comes back to the
1330/// close phase when the pushed rule ends and runs the closes again, or
1331/// one a function routes. Each was found in turn, and the compiler writes
1332/// none of them.
1333fn is_idle(alt: &AltSpec) -> bool {
1334    alt.s.is_empty() && alt.b == 0 && alt.p.is_none() && alt.r.is_none() && is_plain_way(alt)
1335}
1336
1337/// An alternative on a loop's way back, as the compiler writes one: a
1338/// plain way ([`is_plain_way`]) that sets no counter but the loop's own
1339/// `rep` (the iteration helper counts it). Another counter could turn a
1340/// guarded continue off for the next iteration.
1341fn is_helper_way(alt: &AltSpec) -> bool {
1342    is_plain_way(alt) && alt.n.keys().all(|counter| counter == "rep")
1343}
1344
1345/// For each open alternative of the loop `rule`, whether it is a continue
1346/// that a FOLLOW peek before it covers, and so never runs: the peek
1347/// matches wherever the continue would. The compiler writes such dead
1348/// continues where FIRST meets FOLLOW (`{ s: [C], b: 1 }`, then
1349/// `{ s: [C], b: 1, r: H$alt0 }`, with the live continues that look
1350/// further ahead before both); a rule is a loop only when some continue
1351/// is live, and a hand-built one with nothing but dead ones (`{ s: A,
1352/// b: 1 }` before `{ s: A, r: H }`) takes no item at all.
1353fn shadowed_by_peeks(open: &[AltSpec], rule: &str) -> Vec<bool> {
1354    let mut peeks: Vec<&[Vec<Tin>]> = Vec::new();
1355    open.iter()
1356        .map(|alt| {
1357            if !has_content(alt, rule, true) {
1358                if !alt.s.is_empty() {
1359                    peeks.push(&alt.s);
1360                }
1361                false
1362            } else {
1363                peeks.iter().any(|peek| covers(peek, &alt.s))
1364            }
1365        })
1366        .collect()
1367}
1368
1369/// The token sequence `peek` matches wherever `item` does: it is no
1370/// longer, and each of its slots holds every token `item`'s does.
1371fn covers(peek: &[Vec<Tin>], item: &[Vec<Tin>]) -> bool {
1372    peek.len() <= item.len()
1373        && peek
1374            .iter()
1375            .zip(item)
1376            .all(|(slot, other)| other.iter().all(|tin| slot.contains(tin)))
1377}
1378
1379/// An alternative a loop's helper can come back through: read from the
1380/// spec alone, and taken whatever the rule's state, with no condition of
1381/// any kind.
1382fn is_plain_way(alt: &AltSpec) -> bool {
1383    !is_dynamic(alt)
1384        && alt.c.is_empty()
1385        && alt.c_ref.is_none()
1386        && alt.c_fn.is_none()
1387        && alt.c_match.is_none()
1388        && alt.c_lex.is_none()
1389        && alt.c_lex_match.is_none()
1390}
1391
1392/// A repeat loop's entry, the whole of the compiler's shape: the
1393/// alternative matches no token, not even a peeked one (which would
1394/// leave the counter unset wherever that token is not next), pushes
1395/// nothing, replaces `rule` with
1396/// itself, is guarded by `n.rep == 0` and by nothing else, and sets that
1397/// counter to 1 and no other — allocating the node and counting the iteration on the
1398/// way in. A further condition, in `c` or any other channel, may keep
1399/// the entry from running, and with it the counter it sets, which the
1400/// continues may be guarded on. It is
1401/// what marks a rule as a loop. `s`, `b`, `p` and `r` alone are not
1402/// enough: a user rule's own non-consuming self-replace, a guarded or
1403/// counted state transition, has the same four and is no repetition, and
1404/// reading it as one rewrote the whole rule as `*…`, accepting empty and
1405/// repeated inputs the original need not.
1406fn is_loop_entry(alt: &AltSpec, rule: &str) -> bool {
1407    alt.s.is_empty()
1408        && alt.b == 0
1409        && alt.p.is_none()
1410        && alt.r.as_deref() == Some(rule)
1411        && alt.n.len() == 1
1412        && alt.n.get("rep") == Some(&1)
1413        && matches!(alt.c.as_slice(), [guard] if is_rep_guard(guard))
1414        && alt.c_ref.is_none()
1415        && alt.c_fn.is_none()
1416        && alt.c_match.is_none()
1417        && alt.c_lex.is_none()
1418        && alt.c_lex_match.is_none()
1419}
1420
1421/// The entry's guard, `n.rep == 0`: the counter the entry sets is still
1422/// at its start, so this is the first time through.
1423fn is_rep_guard(condition: &Condition) -> bool {
1424    condition.path == ["n", "rep"]
1425        && condition.op == CompareOp::Eq
1426        && matches!(condition.value, Value::Number(count) if count == 0.0)
1427}
1428
1429/// A repetition over the ` / `-joined alternatives of an iteration:
1430/// `*A` and `*"a"` when the iteration is one element, `*( a b )` and
1431/// `*( a / b )` otherwise. A single element that is already a group or an
1432/// option (`( A / B )`, the rendering of an inlined multi-way group) is
1433/// not wrapped again. An empty iteration is an empty repetition: nothing.
1434fn repeat_of(parts: &[String]) -> String {
1435    match parts {
1436        [] => String::new(),
1437        [only] if is_one_element(only) => format!("*{only}"),
1438        _ => format!("*( {} )", parts.join(" / ")),
1439    }
1440}
1441
1442/// `text` is one ABNF element: a bare name or terminal, or one bracket
1443/// pair enclosing the whole of it. A repetition is not an element
1444/// (`repetition = [repeat] element`), so a nested `*I` has to be grouped:
1445/// `*( *I )`, never `**I`. A production body holds only names, `( … )`,
1446/// `[ … ]`, `*…` and `""`, so counting brackets is exact.
1447fn is_one_element(text: &str) -> bool {
1448    if text.starts_with(|ch: char| ch == '*' || ch.is_ascii_digit()) {
1449        return false;
1450    }
1451    if !text.contains(' ') {
1452        return true;
1453    }
1454    let mut chars = text.chars();
1455    let (Some(open), Some(close)) = (chars.next(), chars.next_back()) else {
1456        return false;
1457    };
1458    if !matches!((open, close), ('(', ')') | ('[', ']')) {
1459        return false;
1460    }
1461    // The opening bracket must be the one the last character closes.
1462    let mut depth = 0usize;
1463    for (index, ch) in text.char_indices() {
1464        match ch {
1465            '(' | '[' => depth += 1,
1466            ')' | ']' => {
1467                depth = depth.saturating_sub(1);
1468                if depth == 0 && index + ch.len_utf8() < text.len() {
1469                    return false;
1470                }
1471            }
1472            _ => {}
1473        }
1474    }
1475    depth == 0
1476}
1477
1478/// The legend definition for a token — what it matches:
1479///   - fixed literal       -> `%s"<lit>"` (letters) / `"<lit>"` (punctuation)
1480///   - match regex         -> a char range, a literal, or an ABNF comment
1481///   - built-in matcher    -> `<number>` / `<string>` / …
1482///
1483/// The `%s` prefix is RFC 7405, which updates RFC 5234 — the only
1484/// construct emitted here that RFC 5234 alone does not define. It is kept
1485/// because it is what every current ABNF tool implements and it stays
1486/// readable; `%x48.69` would be pure RFC 5234 but unreadable, and a bare
1487/// char-val would silently lose case-sensitivity.
1488fn token_form(parser: &Tabnas, tin: Tin, full_name: &str) -> String {
1489    if let Some(literal) = parser.fixed_source(tin) {
1490        // RFC 5234: `char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE` — so a
1491        // literal holding a control character, a `"`, or anything above
1492        // %x7E CANNOT go inside quotes. A token fixed to CRLF used to emit
1493        // `CRLF = "<CR>"`, an unterminated char-val. The numeric form has
1494        // no such restriction (and is case-sensitive already, so it
1495        // carries the `%s` meaning too).
1496        return if is_abnf_quotable_body(literal) {
1497            if literal.chars().any(|ch| ch.is_ascii_alphabetic()) {
1498                format!("%s\"{literal}\"")
1499            } else {
1500                format!("\"{literal}\"")
1501            }
1502        } else {
1503            numeric_val(literal)
1504        };
1505    }
1506
1507    if let Some(matcher) = parser
1508        .options
1509        .match_tokens
1510        .values()
1511        .find(|matcher| matcher.tin == tin)
1512    {
1513        if let tabnas::MatchTokenMatcher::Regex(regex) = &matcher.matcher {
1514            return regex_to_abnf(regex.as_str());
1515        }
1516        // A function-backed matcher has no ABNF form to recover. The
1517        // canonical runtime only special-cases a RegExp and otherwise
1518        // falls through to the description below, so do the same rather
1519        // than inventing a form this port alone would emit.
1520    }
1521
1522    // Built-in lexer token: describe it. It is lexer-provided, so a
1523    // grammar using it does not round-trip through bnf.
1524    let bare = full_name.strip_prefix('#').unwrap_or(full_name);
1525    let described = match bare {
1526        "NR" => "number",
1527        "ST" => "string",
1528        "TX" => "text",
1529        "VL" => "value",
1530        "SP" => "space",
1531        "LN" => "line",
1532        "CM" => "comment",
1533        "AA" => "any",
1534        "UK" => "unknown",
1535        "BD" => "bad",
1536        "ZZ" => "end-of-source",
1537        _ => return prose_val(&format!("built-in {bare}")),
1538    };
1539    prose_val(described)
1540}
1541
1542/// A literal as an ABNF num-val: `%x0D`, or dot-concatenated for several
1543/// characters (`%x0D.0A`). RFC 5234 gives this no character restriction,
1544/// so it is the safe rendering for anything char-val cannot hold.
1545fn numeric_val(literal: &str) -> String {
1546    let parts: Vec<String> = literal
1547        .chars()
1548        .map(|ch| {
1549            let hex = format!("{:X}", ch as u32);
1550            if hex.len() % 2 == 1 {
1551                format!("0{hex}")
1552            } else {
1553                hex
1554            }
1555        })
1556        .collect();
1557    format!("%x{}", parts.join("."))
1558}
1559
1560/// Every character of `text` fits inside an ABNF char-val: %x20-21 /
1561/// %x23-7E (printable ASCII except the double quote). An empty string
1562/// qualifies — `char-val` permits zero characters.
1563fn is_abnf_quotable_body(text: &str) -> bool {
1564    text.chars().all(|ch| {
1565        let code = ch as u32;
1566        (0x20..=0x21).contains(&code) || (0x23..=0x7E).contains(&code)
1567    })
1568}
1569
1570/// An ABNF char-val holding at least one character.
1571fn is_abnf_quotable(text: &str) -> bool {
1572    !text.is_empty() && is_abnf_quotable_body(text)
1573}
1574
1575/// Translate the anchored regex the abnf compiler installs for a match
1576/// token back to ABNF, covering the shapes it actually emits.
1577///
1578/// The Rust engine's matchers are `regex::Regex`, whose source carries
1579/// inline flags (`(?i)`) rather than the separate flag set a JavaScript
1580/// `RegExp` has; the case-insensitive branch reads that prefix instead.
1581fn regex_to_abnf(source: &str) -> String {
1582    let original = source;
1583    // Inline flags come first, then the anchor the compiler prepends.
1584    let (case_insensitive, source) = match source.strip_prefix("(?i)") {
1585        Some(rest) => (true, rest),
1586        None => (false, source),
1587    };
1588    let source = source.strip_prefix('^').unwrap_or(source);
1589
1590    // Single char-class range: [\uXXXX-\uYYYY] -> %xXX-YY
1591    if let Some(range) = char_class_range(source, "\\u", 4) {
1592        return range;
1593    }
1594    // Single char-class range with bare hex escapes: [\xXX-\xYY].
1595    if let Some(range) = char_class_range(source, "\\x", 2) {
1596        return range;
1597    }
1598
1599    // Case-insensitive literal: the abnf compiler encodes a bare ABNF
1600    // string `"foo"` containing at least one letter as an anchored,
1601    // case-insensitive regex over the escaped literal. Recover the literal
1602    // by unescaping, then verify the round-trip so a genuine regex is
1603    // never misread as a literal.
1604    if case_insensitive {
1605        let literal = unescape_regex_literal(source);
1606        if escape_regex_like(&literal) == source && is_abnf_quotable(&literal) {
1607            return format!("\"{literal}\"");
1608        }
1609    }
1610
1611    // Anything else: no ABNF construct expresses this regex, so say so in
1612    // the one the grammar provides for exactly that — RFC 5234 §4
1613    // prose-val, "a last resort" for describing a rule in prose. It does
1614    // not round-trip, and is not meant to; it is a legal element naming
1615    // what the token matches.
1616    //
1617    // This returned `; /…/` before: a bare comment. `;` runs to end of
1618    // line, so the legend entry it produced (`T = ; /…/`) held no elements
1619    // at all — not merely non-round-tripping but unparseable, and one such
1620    // token made the WHOLE emitted grammar invalid rather than just that
1621    // rule.
1622    prose_val(&format!("regex /{original}/"))
1623}
1624
1625/// Render `text` as an RFC 5234 §4 prose-val:
1626/// `prose-val = "<" *(%x20-3D / %x3F-7E) ">"`. A `>` would close the value
1627/// early and anything outside printable ASCII is not permitted, so both are
1628/// escaped rather than dropped — the text is here to say what the token
1629/// matches, and silently losing characters from it would defeat that.
1630fn prose_val(text: &str) -> String {
1631    let mut out = String::from("<");
1632    for ch in text.chars() {
1633        let cp = ch as u32;
1634        if (0x20..=0x3d).contains(&cp) || (0x3f..=0x7e).contains(&cp) {
1635            out.push(ch);
1636        } else {
1637            out.push_str(&format!("\\u{cp:04X}"));
1638        }
1639    }
1640    out.push('>');
1641    out
1642}
1643
1644/// `[\uXXXX-\uYYYY]` or `[\xXX-\xYY]` as `%xLO-HI`.
1645fn char_class_range(source: &str, prefix: &str, digits: usize) -> Option<String> {
1646    let inner = source.strip_prefix('[')?.strip_suffix(']')?;
1647    let (low, rest) = inner.strip_prefix(prefix)?.split_at_checked(digits)?;
1648    let high = rest.strip_prefix('-')?.strip_prefix(prefix)?;
1649    if high.len() != digits {
1650        return None;
1651    }
1652    let low = u32::from_str_radix(low, 16).ok()?;
1653    let high = u32::from_str_radix(high, 16).ok()?;
1654    Some(format!("%x{low:X}-{high:X}"))
1655}
1656
1657/// Mirror of the abnf compiler's `escapeRegExp`, used only to validate
1658/// that an unescaped candidate literal re-escapes to exactly the observed
1659/// regex source.
1660fn escape_regex_like(text: &str) -> String {
1661    let mut out = String::with_capacity(text.len());
1662    for ch in text.chars() {
1663        if "\\^$.*+?()[]{}|".contains(ch) {
1664            out.push('\\');
1665        }
1666        out.push(ch);
1667    }
1668    out
1669}
1670
1671/// Undo [`escape_regex_like`], plus the forward slash a JavaScript
1672/// `RegExp` source escapes automatically.
1673fn unescape_regex_literal(source: &str) -> String {
1674    let mut out = String::with_capacity(source.len());
1675    let mut chars = source.chars().peekable();
1676    while let Some(ch) = chars.next() {
1677        if ch == '\\' {
1678            if let Some(next) = chars.peek().copied() {
1679                if "\\^$.*+?()[]{}|/".contains(next) {
1680                    out.push(next);
1681                    chars.next();
1682                    continue;
1683                }
1684            }
1685        }
1686        out.push(ch);
1687    }
1688    out
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use std::collections::HashMap;
1694
1695    use super::*;
1696
1697    #[test]
1698    fn namer_sanitises_and_disambiguates() {
1699        let mut namer = AbnfNamer::new(["keep-me".to_string()]);
1700        assert_eq!(namer.rule("keep-me"), "keep-me");
1701        assert_eq!(namer.rule("a_b"), "a-b");
1702        // `a-b` sanitises to the same string, so it gets a suffix.
1703        assert_eq!(namer.rule("a.b"), "a-b-2");
1704        // Not starting with a letter gets an `r` prefix.
1705        assert_eq!(namer.rule("1st"), "r1st");
1706        // Case-insensitive collision: `KEEP-ME` folds onto the claim.
1707        assert_eq!(namer.rule("KEEP-ME"), "KEEP-ME-2");
1708        // Memoised: the same source name always maps to the same output.
1709        assert_eq!(namer.rule("a_b"), "a-b");
1710    }
1711
1712    #[test]
1713    fn namer_keeps_rules_and_tokens_apart() {
1714        // A rule `NR` and the built-in `#NR` token is an ordinary grammar.
1715        // The token must NOT be handed the rule's name: doing so emitted a
1716        // self-referential `NR = NR` plus a duplicate `NR = <number>`.
1717        let mut namer = AbnfNamer::new(["NR".to_string()]);
1718        assert_eq!(namer.rule("NR"), "NR");
1719        assert_eq!(namer.token("NR"), "NR-2");
1720        // Each namespace is memoised on its own, and neither drifts.
1721        assert_eq!(namer.token("NR"), "NR-2");
1722        assert_eq!(namer.rule("NR"), "NR");
1723        // A token whose name no rule claims is unaffected.
1724        assert_eq!(namer.token("PL"), "PL");
1725    }
1726
1727    fn alt(s: &[Tin], b: usize, p: Option<&str>, r: Option<&str>) -> AltSpec {
1728        AltSpec {
1729            s: s.iter().map(|tin| vec![*tin]).collect(),
1730            b,
1731            p: p.map(str::to_owned),
1732            r: r.map(str::to_owned),
1733            ..Default::default()
1734        }
1735    }
1736
1737    /// The compiler's loop entry: `{ c: [n.rep == 0], n: {rep: 1}, r: rule }`.
1738    fn entry(rule: &str) -> AltSpec {
1739        AltSpec {
1740            c: vec![Condition {
1741                path: vec!["n".into(), "rep".into()],
1742                op: CompareOp::Eq,
1743                value: Value::Number(0.0),
1744            }],
1745            n: HashMap::from([("rep".to_string(), 1)]),
1746            r: Some(rule.to_owned()),
1747            ..Default::default()
1748        }
1749    }
1750
1751    #[test]
1752    fn content_is_what_an_alt_consumes() {
1753        // `H` is a loop here; the last case renders a rule that is not.
1754        let in_loop = |alt: &AltSpec| has_content(alt, "H", true);
1755        // Eats a token.
1756        assert!(in_loop(&alt(&[7], 0, None, None)));
1757        // Peeks one and gives it back: the follow-guarded exit.
1758        assert!(!in_loop(&alt(&[7], 1, None, None)));
1759        // Nothing at all.
1760        assert!(!in_loop(&alt(&[], 0, None, None)));
1761        // Pushes a rule.
1762        assert!(in_loop(&alt(&[], 0, Some("item"), None)));
1763        // Replaces with another rule, after a peek.
1764        assert!(in_loop(&alt(&[7], 1, None, Some("H$alt0"))));
1765        // The loop entry: replaces with the rule being rendered, guarded.
1766        assert!(!in_loop(&entry("H")));
1767        // The same alt is content from any OTHER rule's point of view.
1768        assert!(has_content(&entry("H"), "H$alt0$step1", false));
1769        // A self-replace WITHOUT the guard is not the entry and keeps its
1770        // content: a user rule's own state transition.
1771        assert!(in_loop(&alt(&[], 0, None, Some("H"))));
1772        // So does the guarded one-or-more continuation, a close alt
1773        // `{ s: A, b: 1, r: H }`: the `[ H ]` of `H = A [ H ]`.
1774        assert!(in_loop(&alt(&[7], 1, None, Some("H"))));
1775        // And the entry's own shape, guard and counter included, when the
1776        // rule being rendered is NOT a loop: it has no entry to skip.
1777        assert!(has_content(&entry("odd"), "odd", false));
1778        assert!(!has_content(&entry("odd"), "odd", true));
1779        // With a peek it is no entry at all, whatever the rule: the close
1780        // `{ c: [n.rep == 0], n: {rep: 1}, s: A, b: 1, r: odd }` is the
1781        // `[ odd ]` of `odd = A [ odd ]`.
1782        let guarded_close = AltSpec {
1783            s: vec![vec![7]],
1784            b: 1,
1785            ..entry("odd")
1786        };
1787        assert!(has_content(&guarded_close, "odd", false));
1788        assert!(has_content(&guarded_close, "odd", true));
1789    }
1790
1791    #[test]
1792    fn a_synthesised_name_belongs_to_its_own_segment() {
1793        assert_eq!(own_segment("_gen2_group"), "_gen2_group");
1794        assert_eq!(own_segment("_gen2_group$alt0$step1"), "_gen2_group");
1795        assert_eq!(
1796            own_segment("_gen3_star__gen2_group$alt0"),
1797            "_gen3_star__gen2_group"
1798        );
1799        assert_eq!(own_segment("top"), "top");
1800    }
1801
1802    #[test]
1803    fn a_loop_entry_is_the_whole_compiler_shape() {
1804        assert!(is_loop_entry(&entry("H"), "H"));
1805        // A terminal continue consumes its token first.
1806        let terminal = AltSpec {
1807            s: vec![vec![7]],
1808            ..entry("H")
1809        };
1810        assert!(!is_loop_entry(&terminal, "H"));
1811        // A peek, even one given back, is not the entry either: it sets
1812        // the counter only where that token comes next.
1813        let peek = AltSpec {
1814            s: vec![vec![7]],
1815            b: 1,
1816            ..entry("H")
1817        };
1818        assert!(!is_loop_entry(&peek, "H"));
1819        // Replacing with another rule, or pushing, is not the entry.
1820        let other = AltSpec {
1821            r: Some("H$alt0".into()),
1822            ..entry("H")
1823        };
1824        assert!(!is_loop_entry(&other, "H"));
1825        let push = AltSpec {
1826            p: Some("H".into()),
1827            ..entry("H")
1828        };
1829        assert!(!is_loop_entry(&push, "H"));
1830        // Nor is the same self-replace without the guard, with another
1831        // guard, with the guard on another value, or without the counter:
1832        // `s`, `b`, `p` and `r` alone do not make a loop.
1833        assert!(!is_loop_entry(&alt(&[], 0, None, Some("H")), "H"));
1834        let unguarded = AltSpec {
1835            c: vec![],
1836            ..entry("H")
1837        };
1838        assert!(!is_loop_entry(&unguarded, "H"));
1839        let other_guard = AltSpec {
1840            c: vec![Condition {
1841                path: vec!["n".into(), "mode".into()],
1842                op: CompareOp::Eq,
1843                value: Value::Number(0.0),
1844            }],
1845            ..entry("H")
1846        };
1847        assert!(!is_loop_entry(&other_guard, "H"));
1848        let second_time = AltSpec {
1849            c: vec![Condition {
1850                path: vec!["n".into(), "rep".into()],
1851                op: CompareOp::Eq,
1852                value: Value::Number(1.0),
1853            }],
1854            ..entry("H")
1855        };
1856        assert!(!is_loop_entry(&second_time, "H"));
1857        let uncounted = AltSpec {
1858            n: HashMap::new(),
1859            ..entry("H")
1860        };
1861        assert!(!is_loop_entry(&uncounted, "H"));
1862    }
1863
1864    #[test]
1865    fn a_synthetic_kind_is_read_from_its_own_segment() {
1866        assert_eq!(gen_kind("_gen1_star_term"), Some("star"));
1867        assert_eq!(gen_kind("_gen2_opt__gen1_group"), Some("opt"));
1868        assert_eq!(gen_kind("_gen1_group"), Some("group"));
1869        // A star over an optional is named after it, and is a star.
1870        assert_eq!(gen_kind("_gen3_star__gen2_opt__gen1_group"), Some("star"));
1871        assert_eq!(gen_kind("_gen3_plus__gen2_opt__gen1_group"), Some("plus"));
1872        // The iteration helpers and chain steps answer for their rule.
1873        assert_eq!(
1874            gen_kind("_gen3_star__gen2_opt__gen1_group$alt0"),
1875            Some("star")
1876        );
1877        assert_eq!(
1878            gen_kind("_gen3_star__gen2_opt__gen1_group$alt0$step1"),
1879            Some("star")
1880        );
1881        assert_eq!(gen_kind("_gen1_group$step1"), Some("group"));
1882        // Not synthesised: a user rule, whatever it embeds.
1883        assert_eq!(gen_kind("my_opt"), None);
1884        assert_eq!(gen_kind("top$step1"), None);
1885        assert_eq!(gen_kind("_genx_opt"), None);
1886        assert_eq!(gen_kind("_gen1"), None);
1887        assert_eq!(gen_kind("_gen1__x"), None);
1888        // The helper itself, and only the helper, is wrapped as one.
1889        assert!(is_helper("_gen2_opt__gen1_group", "opt"));
1890        assert!(!is_helper("_gen3_star__gen2_opt__gen1_group", "opt"));
1891        assert!(!is_helper("_gen3_star__gen2_opt__gen1_group$alt0", "opt"));
1892        assert!(!is_helper(
1893            "_gen3_star__gen2_opt__gen1_group$alt0$step1",
1894            "opt"
1895        ));
1896        assert!(!is_helper("_gen3_plus__gen2_opt__gen1_group$step1", "plus"));
1897        assert!(is_helper("_gen3_plus__gen2_opt__gen1_group", "plus"));
1898    }
1899
1900    #[test]
1901    fn a_repetition_groups_all_but_one_element() {
1902        let parts = |items: &[&str]| items.iter().map(|s| s.to_string()).collect::<Vec<_>>();
1903        assert_eq!(repeat_of(&parts(&[])), "");
1904        assert_eq!(repeat_of(&parts(&["A"])), "*A");
1905        assert_eq!(repeat_of(&parts(&["a b"])), "*( a b )");
1906        assert_eq!(repeat_of(&parts(&["A", "B"])), "*( A / B )");
1907        // An inlined multi-way group is already one element.
1908        assert_eq!(repeat_of(&parts(&["( A / B )"])), "*( A / B )");
1909        assert_eq!(repeat_of(&parts(&["[ A ]"])), "*[ A ]");
1910        // Two groups are two elements, whatever the ends look like.
1911        assert_eq!(repeat_of(&parts(&["( A ) ( B )"])), "*( ( A ) ( B ) )");
1912        // A repetition is not an element: `**I` is not ABNF.
1913        assert_eq!(repeat_of(&parts(&["*I"])), "*( *I )");
1914    }
1915
1916    #[test]
1917    fn numeric_val_pads_to_whole_bytes() {
1918        assert_eq!(numeric_val("\r\n"), "%x0D.0A");
1919        assert_eq!(numeric_val("A"), "%x41");
1920    }
1921
1922    #[test]
1923    fn regex_ranges_and_literals_translate() {
1924        assert_eq!(regex_to_abnf("^[\\u0030-\\u0039]"), "%x30-39");
1925        assert_eq!(regex_to_abnf("^[\\x30-\\x39]"), "%x30-39");
1926        assert_eq!(regex_to_abnf("(?i)^foo"), "\"foo\"");
1927        // An escaped literal round-trips through the validation.
1928        assert_eq!(regex_to_abnf("(?i)^a\\.b"), "\"a.b\"");
1929        // A genuine regex is never misread as a literal. With no ABNF
1930        // form it becomes a prose-val, which is an ELEMENT: the bare
1931        // `; /…/` comment this used to emit left the legend entry with
1932        // nothing in it, so the whole grammar failed to parse.
1933        assert_eq!(regex_to_abnf("(?i)^a.b"), "<regex /(?i)^a.b/>");
1934        assert_eq!(regex_to_abnf("^\\d+"), "<regex /^\\d+/>");
1935    }
1936
1937    #[test]
1938    fn prose_val_escapes_what_it_cannot_hold() {
1939        // RFC 5234 §4 allows %x20-3D / %x3F-7E only, so a '>' would close
1940        // the value early and must be escaped rather than dropped.
1941        assert_eq!(prose_val("plain"), "<plain>");
1942        assert_eq!(regex_to_abnf("^a>b"), "<regex /^a\\u003Eb/>");
1943        // Every angle-bracket form the emitter produces is a prose-val,
1944        // the built-in descriptions included.
1945        assert_eq!(prose_val("number"), "<number>");
1946    }
1947
1948    #[test]
1949    fn quotable_rejects_control_and_quote_characters() {
1950        assert!(is_abnf_quotable("hi"));
1951        assert!(!is_abnf_quotable(""));
1952        assert!(!is_abnf_quotable("a\"b"));
1953        assert!(!is_abnf_quotable("\r\n"));
1954    }
1955}