Skip to main content

tabnas_bnf/
ir.rs

1// Copyright (c) 2026 Richard Rodger and other contributors, MIT License
2
3//! The grammar IR: what a front-end lowers its notation into, and the
4//! options and errors around compiling it. Mirrors the type half of
5//! `ts/src/compiler.ts`.
6//!
7//! Nothing here knows what notation a grammar was WRITTEN in. A
8//! front-end parses its own syntax into a [`Grammar`] and hands it to
9//! [`emit_grammar_spec`](crate::emit_grammar_spec).
10
11use std::cell::RefCell;
12use std::fmt;
13
14use indexmap::{IndexMap, IndexSet};
15use serde::{Deserialize, Serialize};
16
17/// Where an IR node came from in the front-end's grammar text.
18///
19/// `s` is the start offset (inclusive), `e` the end offset (exclusive),
20/// `r` the 1-based row of the start and `c` the 1-based column, the last
21/// two optional. Offsets and row/column are in the SAME UNITS the
22/// front-end's own engine tokens use, so a front-end copies them straight
23/// across with no arithmetic. That does mean the units are runtime-native
24/// and not identical across ports: TypeScript offsets count UTF-16 code
25/// units, Go's and this port's count bytes, the same divergence the
26/// engine already records for token positions.
27///
28/// Spans are optional everywhere. A front-end that records them gets
29/// ranged compile errors (see [`EmitError::sp`]); one that does not
30/// compiles to exactly the same grammar.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32pub struct SrcSpan {
33    pub s: usize,
34    pub e: usize,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub r: Option<usize>,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub c: Option<usize>,
39}
40
41impl SrcSpan {
42    pub fn new(s: usize, e: usize) -> Self {
43        Self {
44            s,
45            e,
46            r: None,
47            c: None,
48        }
49    }
50
51    pub fn at(s: usize, e: usize, r: usize, c: usize) -> Self {
52        Self {
53            s,
54            e,
55            r: Some(r),
56            c: Some(c),
57        }
58    }
59}
60
61/// One element of a sequence: a terminal in one of its spellings, a rule
62/// reference, or EBNF sugar around further elements. The `kind` carries
63/// the variant; `sp` is where the element came from, when the front-end
64/// recorded it. Mirrors the TypeScript `Element` union.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct Element {
67    #[serde(flatten)]
68    pub kind: Kind,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub sp: Option<SrcSpan>,
71}
72
73/// The element variants. Serialized with the TypeScript field names, so
74/// an IR built in one runtime loads in the other.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "lowercase")]
77pub enum Kind {
78    /// A string literal. ABNF quoted strings are case-insensitive by
79    /// default; `case_sensitive` is the front-end's statement of intent
80    /// (omitting it preserves the RFC 5234 default). `token_name` is the
81    /// preferred lexer token name, set by literal lifting when this
82    /// terminal came from a production that names it (`PL = "+"` gives
83    /// `#PL`).
84    Term {
85        literal: String,
86        #[serde(
87            default,
88            rename = "caseSensitive",
89            skip_serializing_if = "Option::is_none"
90        )]
91        case_sensitive: Option<bool>,
92        #[serde(default, rename = "tokenName", skip_serializing_if = "Option::is_none")]
93        token_name: Option<String>,
94    },
95    /// A rule reference. `debt` holds the suffix-debt counter mutations to
96    /// emit on the alt that pushes this reference, written by
97    /// `resolve_suffix_debts`; absent on every reference in a grammar with
98    /// no contested tail loop.
99    Ref {
100        name: String,
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        debt: Option<IndexMap<String, i64>>,
103    },
104    /// A terminal that matches a built-in engine lexer token directly
105    /// (`#TX`, `#NR`, `#ST`, `#VL`). `name` is the full token name.
106    Token { name: String },
107    /// RFC 5234 `prose-val`, `<free text>`. Informational: accepted only as
108    /// the entire body of a production naming a built-in lexer token, or
109    /// as the `<remove>` directive. Anywhere else it is an error.
110    Prose { text: String },
111    /// A character class or other regular expression terminal.
112    Regex { pattern: String, flags: String },
113    /// `[ A ]`
114    Opt { inner: Box<Element> },
115    /// `*A`. `debt_guard` names the suffix-debt counter guarding this
116    /// repetition, set by left-recursion elimination on the tail loop it
117    /// generates.
118    Star {
119        inner: Box<Element>,
120        #[serde(default, rename = "debtGuard", skip_serializing_if = "Option::is_none")]
121        debt_guard: Option<String>,
122    },
123    /// `1*A`
124    Plus { inner: Box<Element> },
125    /// `m*nA`. `max` is `None` for an unbounded upper bound (TypeScript's
126    /// `Infinity`, which JSON carries as `null`).
127    Rep {
128        min: usize,
129        #[serde(default, deserialize_with = "deserialize_max")]
130        max: Option<usize>,
131        inner: Box<Element>,
132    },
133    /// `( A / B )`
134    Group { alts: Vec<Sequence> },
135}
136
137/// TypeScript writes `Infinity` for an unbounded repetition, which
138/// `JSON.stringify` turns into `null`; a missing key means the same.
139fn deserialize_max<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
140where
141    D: serde::Deserializer<'de>,
142{
143    let value: Option<f64> = Option::deserialize(deserializer)?;
144    let out = match value {
145        None => None,
146        Some(n) if n.is_finite() && n >= 0.0 && n.fract() == 0.0 => Some(n as usize),
147        Some(n) => {
148            return Err(serde::de::Error::custom(format!(
149                "invalid repetition upper bound {n}: expected a non-negative integer or null"
150            )))
151        }
152    };
153    Ok(out)
154}
155
156/// A sequence of elements: one alternative of a production.
157pub type Sequence = Vec<Element>;
158
159impl Element {
160    fn of(kind: Kind) -> Self {
161        Self { kind, sp: None }
162    }
163
164    /// A literal with the notation's default case-sensitivity unstated.
165    pub fn term(literal: impl Into<String>) -> Self {
166        Self::of(Kind::Term {
167            literal: literal.into(),
168            case_sensitive: None,
169            token_name: None,
170        })
171    }
172
173    /// A literal whose case-sensitivity the front-end states.
174    pub fn term_cs(literal: impl Into<String>, case_sensitive: bool) -> Self {
175        Self::of(Kind::Term {
176            literal: literal.into(),
177            case_sensitive: Some(case_sensitive),
178            token_name: None,
179        })
180    }
181
182    /// A rule reference.
183    pub fn reference(name: impl Into<String>) -> Self {
184        Self::of(Kind::Ref {
185            name: name.into(),
186            debt: None,
187        })
188    }
189
190    /// A built-in engine lexer token, named with its `#`.
191    pub fn token(name: impl Into<String>) -> Self {
192        Self::of(Kind::Token { name: name.into() })
193    }
194
195    /// A prose terminal (`<text>`).
196    pub fn prose(text: impl Into<String>) -> Self {
197        Self::of(Kind::Prose { text: text.into() })
198    }
199
200    /// A regular expression terminal.
201    pub fn regex(pattern: impl Into<String>, flags: impl Into<String>) -> Self {
202        Self::of(Kind::Regex {
203            pattern: pattern.into(),
204            flags: flags.into(),
205        })
206    }
207
208    /// `[ inner ]`
209    pub fn opt(inner: Element) -> Self {
210        Self::of(Kind::Opt {
211            inner: Box::new(inner),
212        })
213    }
214
215    /// `*inner`
216    pub fn star(inner: Element) -> Self {
217        Self::of(Kind::Star {
218            inner: Box::new(inner),
219            debt_guard: None,
220        })
221    }
222
223    /// `1*inner`
224    pub fn plus(inner: Element) -> Self {
225        Self::of(Kind::Plus {
226            inner: Box::new(inner),
227        })
228    }
229
230    /// `min*max inner`; `None` is an unbounded maximum.
231    pub fn rep(min: usize, max: Option<usize>, inner: Element) -> Self {
232        Self::of(Kind::Rep {
233            min,
234            max,
235            inner: Box::new(inner),
236        })
237    }
238
239    /// `( alts... )`
240    pub fn group(alts: Vec<Sequence>) -> Self {
241        Self::of(Kind::Group { alts })
242    }
243
244    /// The same element carrying a source span.
245    pub fn with_span(mut self, sp: SrcSpan) -> Self {
246        self.sp = Some(sp);
247        self
248    }
249
250    /// The referenced rule name, for a reference.
251    pub fn ref_name(&self) -> Option<&str> {
252        match &self.kind {
253            Kind::Ref { name, .. } => Some(name),
254            _ => None,
255        }
256    }
257
258    pub fn is_ref(&self) -> bool {
259        matches!(self.kind, Kind::Ref { .. })
260    }
261
262    pub fn is_ref_to(&self, name: &str) -> bool {
263        matches!(&self.kind, Kind::Ref { name: n, .. } if n == name)
264    }
265
266    /// The literal, for a term.
267    pub fn literal(&self) -> Option<&str> {
268        match &self.kind {
269            Kind::Term { literal, .. } => Some(literal),
270            _ => None,
271        }
272    }
273
274    /// Whether this is a terminal in any of its consuming spellings.
275    pub fn is_terminal(&self) -> bool {
276        matches!(
277            self.kind,
278            Kind::Term { .. } | Kind::Token { .. } | Kind::Regex { .. }
279        )
280    }
281
282    pub(crate) fn inner(&self) -> Option<&Element> {
283        match &self.kind {
284            Kind::Opt { inner }
285            | Kind::Star { inner, .. }
286            | Kind::Plus { inner }
287            | Kind::Rep { inner, .. } => Some(inner),
288            _ => None,
289        }
290    }
291}
292
293/// How a production contributes to the output AST.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
295#[serde(rename_all = "lowercase")]
296pub enum NodeKind {
297    /// Emit a tagged node `{ rule, src, kids }`.
298    #[default]
299    User,
300    /// The RFC 5234 core rules: flatten into the enclosing rule's `src`.
301    Core,
302    /// Synthetic sugar, dispatcher and chain rules: also flatten.
303    Helper,
304}
305
306impl NodeKind {
307    pub fn as_str(self) -> &'static str {
308        match self {
309            NodeKind::User => "user",
310            NodeKind::Core => "core",
311            NodeKind::Helper => "helper",
312        }
313    }
314}
315
316/// What a production builds when it carries a value annotation.
317///
318/// `members` names one member per PUSHING segment of the alternative, in
319/// order: the parts the author named. An array has no member names; every
320/// pushing segment is an element. `kind` is `"object"` or `"array"`; it
321/// stays a string because a grammar deserialized from JSON reaches the
322/// compiler with anything, and the refusal for an unknown kind is part of
323/// the contract.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325pub struct ValueAnnotation {
326    pub kind: String,
327    #[serde(default, skip_serializing_if = "Vec::is_empty")]
328    pub members: Vec<String>,
329}
330
331impl ValueAnnotation {
332    pub fn object(members: impl IntoIterator<Item = impl Into<String>>) -> Self {
333        Self {
334            kind: "object".into(),
335            members: members.into_iter().map(Into::into).collect(),
336        }
337    }
338
339    pub fn array() -> Self {
340        Self {
341            kind: "array".into(),
342            members: Vec::new(),
343        }
344    }
345}
346
347/// Configuration attached to a synthesised dispatcher production for an
348/// ambiguous `[X D] Y` subsequence. See `rewrite_probe_dispatches`.
349#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
350pub struct ProbeDispatchSpec {
351    #[serde(rename = "probeRule")]
352    pub probe_rule: String,
353    pub disambiguator: Element,
354    #[serde(rename = "withBranch")]
355    pub with_branch: String,
356    #[serde(rename = "noBranch")]
357    pub no_branch: String,
358}
359
360/// The vocabulary of a synthesised probe-helper production.
361#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
362pub struct ProbeHelperSpec {
363    #[serde(rename = "vocabElements")]
364    pub vocab_elements: Vec<Element>,
365}
366
367/// The separator of a production rewritten as a tail repeat.
368#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
369pub struct TailRepeatSpec {
370    pub sep: Sequence,
371}
372
373/// One rule of the grammar. Mirrors the TypeScript `Production`.
374///
375/// The fields after `value` are written by the rewrite passes; a
376/// front-end leaves them at their defaults.
377#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
378pub struct Production {
379    pub name: String,
380    pub alts: Vec<Sequence>,
381    /// ABNF `name =/ alt`, flagged during parse and merged away before the
382    /// grammar reaches the emitter.
383    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
384    pub incremental: bool,
385    #[serde(default, rename = "nodeKind")]
386    pub node_kind: NodeKind,
387    /// The author-written production this one descends from. Absent
388    /// means the production is itself author-written; read it through
389    /// [`origin_of`].
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub origin: Option<String>,
392    /// Where the author wrote this production, when the front-end records
393    /// it.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub sp: Option<SrcSpan>,
396    /// A value this production should BUILD rather than the AST node the
397    /// tree builders produce by default. Set by a front-end.
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub value: Option<ValueAnnotation>,
400    #[serde(
401        default,
402        rename = "tailRepeat",
403        skip_serializing_if = "Option::is_none"
404    )]
405    pub tail_repeat: Option<TailRepeatSpec>,
406    #[serde(
407        default,
408        rename = "repeatHelper",
409        skip_serializing_if = "std::ops::Not::not"
410    )]
411    pub repeat_helper: bool,
412    /// Set by `desugar` on the helper every unbounded repetition becomes:
413    /// the star `*A`, and the tail of a plus `1*A` or of a rep `m*A`. Its
414    /// `alts` stay `[[A, self], []]`, which is the language the loop
415    /// describes and what FIRST, FOLLOW, the dispatch prefixes and the
416    /// suffix-debt analysis all read. The EMITTER does not compile the
417    /// self-reference as a push: it emits a same-depth loop, every
418    /// iteration of which runs in the frame the loop was pushed into, and
419    /// re-enters the loop by replacement (`r:`). See `emit_repeat_loop`.
420    #[serde(
421        default,
422        rename = "repeatLoop",
423        skip_serializing_if = "std::ops::Not::not"
424    )]
425    pub repeat_loop: bool,
426    #[serde(default, rename = "debtGuard", skip_serializing_if = "Option::is_none")]
427    pub debt_guard: Option<String>,
428    #[serde(default, rename = "debtOwed", skip_serializing_if = "Option::is_none")]
429    pub debt_owed: Option<Vec<String>>,
430    #[serde(
431        default,
432        rename = "probeDispatch",
433        skip_serializing_if = "Option::is_none"
434    )]
435    pub probe_dispatch: Option<ProbeDispatchSpec>,
436    #[serde(
437        default,
438        rename = "probeHelper",
439        skip_serializing_if = "Option::is_none"
440    )]
441    pub probe_helper: Option<ProbeHelperSpec>,
442}
443
444impl Production {
445    pub fn new(name: impl Into<String>, alts: Vec<Sequence>) -> Self {
446        Self {
447            name: name.into(),
448            alts,
449            ..Default::default()
450        }
451    }
452}
453
454/// The author-written production a (possibly synthesised) production
455/// descends from.
456pub fn origin_of(prod: &Production) -> &str {
457    prod.origin.as_deref().unwrap_or(&prod.name)
458}
459
460/// One entry of the probe-dispatch analyser's report.
461#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
462pub struct AmbiguityReport {
463    pub rule: String,
464    #[serde(rename = "altIdx")]
465    pub alt_idx: usize,
466    #[serde(rename = "optIdx")]
467    pub opt_idx: usize,
468    pub reason: String,
469    pub resolved: bool,
470}
471
472/// A grammar: the productions a front-end lowered, plus the `<remove>`
473/// directives and the ambiguity report.
474#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
475pub struct Grammar {
476    pub productions: Vec<Production>,
477    #[serde(default, skip_serializing_if = "Vec::is_empty")]
478    pub ambiguities: Vec<AmbiguityReport>,
479    /// Rules and tokens to drop.
480    #[serde(default, skip_serializing_if = "Vec::is_empty")]
481    pub remove: Vec<String>,
482    /// `<all> = <remove>`: wipe the instance first.
483    #[serde(
484        default,
485        rename = "clearAll",
486        skip_serializing_if = "std::ops::Not::not"
487    )]
488    pub clear_all: bool,
489}
490
491impl Grammar {
492    pub fn new(productions: Vec<Production>) -> Self {
493        Self {
494            productions,
495            ..Default::default()
496        }
497    }
498}
499
500/// Compiler options. Mirrors the TypeScript `ConvertOptions`.
501#[derive(Debug, Clone, PartialEq, Eq)]
502pub struct ConvertOptions {
503    /// Start rule name (default: the first production).
504    pub start: Option<String>,
505    /// Group tag stamped on every emitted alt, and the prefix the shared
506    /// compiler's own diagnostics carry (default `bnf`; a front-end
507    /// passes its own). It reaches a diagnostic only from the moment
508    /// [`emit_grammar_spec`](crate::emit_grammar_spec) applies these
509    /// options, so a front-end's parse error on the grammar source is
510    /// raised earlier and keeps that front-end's own fixed prefix.
511    pub tag: Option<String>,
512    /// Emit the probe/phase-retry dispatcher and the tree builders as
513    /// engine `$`-builtin refs plus `k` config instead of registered
514    /// closures. This keeps the spec function-free so it survives
515    /// compilation (pure-recognition) mode.
516    pub builtins: bool,
517    /// Emit a stable `m` mark on each user-rule alt, enabling
518    /// `@<rule>:o|c:<mark>` user-action references.
519    pub marks: bool,
520    /// Treat word-like literals as whole-word keywords, so `"option"`
521    /// does not match the prefix of `optional`.
522    pub word_keywords: bool,
523    /// Emit `meta.provenance`, the map from each generated rule name back
524    /// to the author-written production it came from. On by default.
525    pub provenance: bool,
526    /// Compile a token class (a production whose every alternative is a
527    /// single literal or engine token, `ident = TX / "message" / "option"`)
528    /// as one engine token SET wherever another rule looks ahead at it,
529    /// and keep it as a rule of its own rather than inlining it into the
530    /// rules it leads. A lookahead position that can hold any of N members
531    /// then costs one alternate rather than N, and a contextual keyword is
532    /// one class member. Off by default: the class is inlined where it
533    /// leads an alternative and its members are enumerated, exactly as
534    /// before. Mirrors the TypeScript `tokenClasses`.
535    pub token_classes: bool,
536}
537
538impl Default for ConvertOptions {
539    fn default() -> Self {
540        Self {
541            start: None,
542            tag: None,
543            builtins: false,
544            marks: false,
545            word_keywords: false,
546            provenance: true,
547            token_classes: false,
548        }
549    }
550}
551
552impl ConvertOptions {
553    pub fn tag(tag: impl Into<String>) -> Self {
554        Self {
555            tag: Some(tag.into()),
556            ..Default::default()
557        }
558    }
559
560    pub fn start(mut self, start: impl Into<String>) -> Self {
561        self.start = Some(start.into());
562        self
563    }
564
565    pub fn builtins(mut self, on: bool) -> Self {
566        self.builtins = on;
567        self
568    }
569
570    pub fn marks(mut self, on: bool) -> Self {
571        self.marks = on;
572        self
573    }
574
575    pub fn word_keywords(mut self, on: bool) -> Self {
576        self.word_keywords = on;
577        self
578    }
579
580    pub fn provenance(mut self, on: bool) -> Self {
581        self.provenance = on;
582        self
583    }
584
585    pub fn token_classes(mut self, on: bool) -> Self {
586        self.token_classes = on;
587        self
588    }
589}
590
591/// A compile failure that can say WHERE.
592///
593/// `rule` is the rule being compiled when the failure was raised and `sp`
594/// where in the grammar source, when the IR knew. Both are populated only
595/// when the offending IR node carries the information, so a front-end
596/// that records no spans gets the message it always got. Every diagnostic
597/// this compiler raises is one of these; the message text matches the
598/// TypeScript compiler byte for byte.
599#[derive(Debug, Clone, PartialEq, Eq)]
600pub struct EmitError {
601    pub message: String,
602    pub rule: Option<String>,
603    pub sp: Option<SrcSpan>,
604}
605
606impl EmitError {
607    pub fn new(message: impl Into<String>) -> Self {
608        Self {
609            message: message.into(),
610            rule: None,
611            sp: None,
612        }
613    }
614
615    pub fn at(message: impl Into<String>, rule: &str, sp: Option<SrcSpan>) -> Self {
616        Self {
617            message: message.into(),
618            rule: Some(rule.to_string()),
619            sp,
620        }
621    }
622}
623
624impl fmt::Display for EmitError {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        f.write_str(&self.message)
627    }
628}
629
630impl std::error::Error for EmitError {}
631
632// Diagnostics name the NOTATION the grammar was written in, not this
633// package: a front-end's users should not see "bnf:" on an error about
634// their own syntax. `emit_grammar_spec` sets this from `opts.tag` for the
635// duration of one emit, exactly as the TypeScript compiler's module-scoped
636// `_diagName`. Thread-local rather than global so two conversions on two
637// threads each keep their own prefix, which is what Go's emit lock buys.
638thread_local! {
639    static DIAG_NAME: RefCell<String> = RefCell::new("bnf".to_string());
640}
641
642/// The prefix the shared compiler's own diagnostics carry: the tag of the
643/// most recent emit on this thread, or `bnf` when no emit has run on it.
644///
645/// A diagnostic raised before an emit applies its options, a front-end's
646/// parse error on the grammar source being the usual one, is outside this
647/// and carries that front-end's own fixed prefix.
648pub fn diag_name() -> String {
649    DIAG_NAME.with(|name| name.borrow().clone())
650}
651
652pub(crate) fn set_diag_name(tag: &str) {
653    DIAG_NAME.with(|name| *name.borrow_mut() = tag.to_string());
654}
655
656/// How deeply one element of the IR may nest before `emit_grammar_spec`
657/// refuses the grammar.
658///
659/// The passes over an element (desugaring, FIRST sets, factoring, the
660/// emitter itself) are written as the canonical TypeScript writes them,
661/// one recursive call per level, and a Rust stack that runs out aborts
662/// the process rather than unwinding. A grammar is untrusted input, so
663/// nesting that deep has to become an error return instead. The limit is
664/// the same one `serde_json` applies by default to a nested document, so
665/// an IR that arrives as JSON is already held to it, and it is an order
666/// of magnitude past anything a grammar author writes: the deepest
667/// nesting in the ABNF conformance corpus is in single figures.
668///
669/// TypeScript raises a catchable `RangeError` instead, several hundred
670/// levels later; `DIVERGENCE.md` records the difference.
671pub const MAX_ELEMENT_DEPTH: usize = 128;
672
673/// The most numeric-repetition work desugaring will allocate. One unit is
674/// one mandatory copy or one generated helper.
675pub const MAX_REPEAT_EXPANSION: usize = 8192;
676
677/// The most alternatives one rule may gain from Paull's substitution
678/// before left-recursion elimination refuses the grammar.
679///
680/// Substituting a rule into the alternatives that begin with it turns
681/// each of them into one alternative per alternative of that rule, a gain
682/// of `led × (|source| − 1)` for `led` such alternatives, summed over every
683/// substitution into the rule. Without a bound a cycle of k rules whose
684/// alternatives lead with the next one multiplies to 2^(k+1) alternatives,
685/// and at k = 20 exhausted memory before the substitution finished. No
686/// grammar in the downstream corpora gains more than 28 (dhall.abnf, which
687/// does not compile within abnf's 60 s budget for another reason, gains
688/// 85); the cycle gains 508 at k = 8 and 1020 at k = 9.
689/// `MAX_LEFT_RECURSION_EXPANSION` in `ts/src/compiler.ts` records the
690/// measurement.
691pub const MAX_LEFT_RECURSION_EXPANSION: usize = 512;
692
693/// What left-recursion elimination may add to the whole grammar, counted
694/// in elements and alternatives, before it refuses the grammar.
695///
696/// An element counts 1 and everything nested in it, all the way down: 1
697/// for each alternative of a group and the deep sizes of the elements in
698/// it, and the deep size of the inner element of an option or a
699/// repetition. That is its deep size. An alternative counts the same way:
700/// 1 for itself and the deep size of each of its elements. Two steps of the
701/// pass write more than they replace, and each is charged before it
702/// allocates, as what it writes less what it replaces, floored at zero;
703/// this bound holds the sum over every one of them in the grammar.
704/// Substituting a rule into an alternative that begins with it replaces
705/// that alternative by one per alternative of the rule, `a_1 … a_m`, each
706/// followed by the replaced alternative's tail, which adds
707/// `(m − 1)·(1 + deep|tail|) + Σ deep|a_i| − 1`. Splitting a hidden left
708/// recursion's leading element `s`, which can match nothing, off an
709/// alternative `s rest` writes `present(s) rest` and `rest`, which adds
710/// `1 + deep|present(s)| + deep|rest| − deep|s|`: `deep|rest|` for an
711/// option, `deep|s| + deep|rest|` for a repetition.
712/// [`MAX_LEFT_RECURSION_EXPANSION`] bounds the alternatives one rule gains;
713/// this bounds what all of them hold. A chain of n rules, each one
714/// alternative that begins with the next, gains no alternatives at all, but
715/// ends with every rule holding the rest of the chain: (n − 2)(n − 1)/2
716/// added. `A = [x1] … [xk] A "y" / "z"` needs no substitution, and its
717/// split adds k(k + 1). No grammar in the downstream corpora adds more than
718/// 6,615 (dhall.abnf), and none that compiles more than 2,600; the chain is
719/// refused from n = 514 on, and the options from k = 362 on.
720/// `MAX_LEFT_RECURSION_ELEMENTS` in `ts/src/compiler.ts` records the
721/// measurement.
722pub const MAX_LEFT_RECURSION_ELEMENTS: usize = 131072;
723
724/// Refuse a grammar whose element nesting would overflow the stack of a
725/// pass that walks it. Measured with an explicit stack: finding the depth
726/// must not be able to overflow either.
727pub(crate) fn check_element_depth(grammar: &Grammar) -> Result<(), EmitError> {
728    for prod in &grammar.productions {
729        let mut roots: Vec<&Element> = Vec::new();
730        for alt in &prod.alts {
731            roots.extend(alt.iter());
732        }
733        if let Some(tail) = &prod.tail_repeat {
734            roots.extend(tail.sep.iter());
735        }
736        if let Some(helper) = &prod.probe_helper {
737            roots.extend(helper.vocab_elements.iter());
738        }
739        let mut stack: Vec<(&Element, usize)> = roots.into_iter().map(|el| (el, 1)).collect();
740        while let Some((el, depth)) = stack.pop() {
741            if depth > MAX_ELEMENT_DEPTH {
742                return Err(EmitError::at(
743                    format!(
744                        "{}: rule '{}' nests elements more than {} deep, which is \
745                         past what this compiler will walk. Split the \
746                         rule into named rules.",
747                        diag_name(),
748                        prod.name,
749                        MAX_ELEMENT_DEPTH
750                    ),
751                    &prod.name,
752                    prod.sp,
753                ));
754            }
755            match &el.kind {
756                Kind::Opt { inner }
757                | Kind::Star { inner, .. }
758                | Kind::Plus { inner }
759                | Kind::Rep { inner, .. } => stack.push((inner, depth + 1)),
760                Kind::Group { alts } => {
761                    for alt in alts {
762                        for inner in alt.iter() {
763                            stack.push((inner, depth + 1));
764                        }
765                    }
766                }
767                _ => {}
768            }
769        }
770    }
771    Ok(())
772}
773
774/// Built-in engine lexer tokens that a rule may reference by a bare
775/// uppercase name, mapping the name to the token the lexer emits. A user
776/// (or core) rule of the same name always wins.
777pub const BUILTIN_TOKENS: [(&str, &str); 4] =
778    [("TX", "#TX"), ("NR", "#NR"), ("ST", "#ST"), ("VL", "#VL")];
779
780/// The engine token a bare built-in name resolves to, if it is one.
781pub fn builtin_token(name: &str) -> Option<&'static str> {
782    BUILTIN_TOKENS
783        .iter()
784        .find(|(bare, _)| *bare == name)
785        .map(|(_, token)| *token)
786}
787
788/// The one prose directive the compiler acts on, matched
789/// case-insensitively after trimming.
790pub const REMOVE_PROSE: &str = "remove";
791
792/// The one prose NAME: `<all> = <remove>` clears the whole grammar.
793pub const REMOVE_ALL: &str = "all";
794
795/// Whether a production name came from a prose token. Such a name keeps
796/// its angle brackets, which no ordinary rulename can contain.
797pub fn is_prose_name(name: &str) -> bool {
798    name.starts_with('<') && name.ends_with('>')
799}
800
801/// Collect the rule references in a sequence, sugar included.
802pub fn refs_in(alt: &[Element], out: &mut IndexSet<String>) {
803    crate::shared::refs_in(alt, out)
804}
805
806/// A quoted-string literal is effectively case-sensitive either when the
807/// front-end said so or when it contains no ASCII letters (there is
808/// nothing to fold: `"+"` matches `+` in any "case").
809pub fn is_effectively_case_sensitive(literal: &str, case_sensitive: Option<bool>) -> bool {
810    if case_sensitive == Some(true) {
811        return true;
812    }
813    !literal.bytes().any(|b| b.is_ascii_alphabetic())
814}
815
816/// The key a term is looked up (or allocated) under: the literal and its
817/// effective case-sensitivity, so a sensitive and an insensitive
818/// occurrence of the same string are distinct tokens.
819pub fn term_key(literal: &str, case_sensitive: Option<bool>) -> String {
820    let prefix = if is_effectively_case_sensitive(literal, case_sensitive) {
821        "cs:"
822    } else {
823        "ci:"
824    };
825    format!("{prefix}{literal}")
826}
827
828/// `term_key` of a term element. Panics on any other kind: the callers
829/// have already matched on it.
830pub(crate) fn term_key_of(el: &Element) -> String {
831    match &el.kind {
832        Kind::Term {
833            literal,
834            case_sensitive,
835            ..
836        } => term_key(literal, *case_sensitive),
837        _ => unreachable!("term_key_of on a non-term element"),
838    }
839}
840
841pub(crate) fn regex_key(pattern: &str, flags: &str) -> String {
842    format!("/{pattern}/{flags}")
843}
844
845/// Escape the regular-expression metacharacters in a literal, so the
846/// literal matches itself.
847pub fn escape_regexp(s: &str) -> String {
848    let mut out = String::with_capacity(s.len());
849    for c in s.chars() {
850        if matches!(
851            c,
852            '\\' | '^' | '$' | '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|'
853        ) {
854            out.push('\\');
855        }
856        out.push(c);
857    }
858    out
859}