tabnas-bnf 0.1.26

Shared compiler for BNF-family grammar front-ends on the tabnas parser: grammar IR in, tabnas GrammarSpec out
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
// Copyright (c) 2026 Richard Rodger and other contributors, MIT License

//! The passes that run on the grammar as written, before any structural
//! rewrite: prose resolution, literal lifting, built-in token
//! normalisation and the nullability of the start rule. Mirrors
//! `resolveProseTerminals`, `liftLiteralTokens`, `normalizeBuiltinTokens`
//! and `nullableRules` in `ts/src/compiler.ts`.

use indexmap::{IndexMap, IndexSet};

use crate::ir::{
    builtin_token, diag_name, is_prose_name, origin_of, regex_key, term_key, term_key_of, Element,
    EmitError, Grammar, Kind, NodeKind, Production, Sequence, BUILTIN_TOKENS, MAX_REPEAT_EXPANSION,
    REMOVE_ALL, REMOVE_PROSE,
};

/// Resolve RFC 5234 `prose-val` terminals (`<free text>`).
///
/// Prose is informational, so the compiler accepts it in exactly one
/// position: as the ENTIRE body of a production naming a built-in lexer
/// token (`NR = <number>`), which is then dropped so references fall
/// through to the built-in. `<remove>` is the one prose form that does
/// compile to something: a removal directive. Prose anywhere else is an
/// error.
pub(crate) fn resolve_prose_terminals(grammar: &mut Grammar) -> Result<(), EmitError> {
    let mut kept: Vec<Production> = Vec::new();

    fn find_stray(el: &Element) -> Option<&Element> {
        match &el.kind {
            Kind::Prose { .. } => Some(el),
            Kind::Opt { inner }
            | Kind::Star { inner, .. }
            | Kind::Plus { inner }
            | Kind::Rep { inner, .. } => find_stray(inner),
            Kind::Group { alts } => alts.iter().flatten().find_map(find_stray),
            _ => None,
        }
    }

    for prod in grammar.productions.drain(..) {
        let only_prose = prod.alts.len() == 1
            && prod.alts[0].len() == 1
            && matches!(prod.alts[0][0].kind, Kind::Prose { .. });

        // A prose name is only ever the removal directive. Checked here as
        // well as in the prose-body branch below, because `<all> = "x"` has
        // a LITERAL body and would otherwise be lifted into a token
        // literally named `#<all>`.
        if is_prose_name(&prod.name) && !only_prose {
            return Err(EmitError::new(format!(
                "{}: '{}' is prose, and prose is only valid as a production name for \
                 the removal directive '<all> = <remove>'.",
                diag_name(),
                prod.name
            )));
        }

        if only_prose {
            let Kind::Prose { text } = &prod.alts[0][0].kind else {
                unreachable!()
            };

            if REMOVE_PROSE == text.trim().to_lowercase() {
                if is_prose_name(&prod.name) {
                    let target = prod.name[1..prod.name.len() - 1].trim().to_lowercase();
                    if REMOVE_ALL != target {
                        return Err(EmitError::new(format!(
                            "{}: '<{}>' is not a removal target. The only prose name is \
                             '<all>', as in '<all> = <remove>', which clears the whole \
                             grammar. To remove one rule or token, name it directly: \
                             '{} = <remove>'.",
                            diag_name(),
                            target,
                            target
                        )));
                    }
                    grammar.clear_all = true;
                } else {
                    grammar.remove.push(prod.name.clone());
                }
                continue;
            }

            if is_prose_name(&prod.name) {
                return Err(EmitError::new(format!(
                    "{}: '{}' is prose, and prose is only valid as a production name \
                     for the removal directive '<all> = <remove>'.",
                    diag_name(),
                    prod.name
                )));
            }

            if builtin_token(&prod.name).is_some() {
                continue; // informational: the lexer defines it
            }
            return Err(EmitError::at(
                format!(
                    "{}: rule '{}' is defined only by prose ('<{}>'), which describes a \
                     terminal but does not define one. Prose is allowed only for \
                     built-in lexer tokens ({}).",
                    diag_name(),
                    prod.name,
                    text,
                    BUILTIN_TOKENS
                        .iter()
                        .map(|(bare, _)| *bare)
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                &prod.name,
                prod.sp,
            ));
        }

        // Any surviving prose is embedded in a larger expression, where it
        // cannot be given a meaning.
        for alt in &prod.alts {
            for el in alt {
                if let Some(stray) = find_stray(el) {
                    let Kind::Prose { text } = &stray.kind else {
                        unreachable!()
                    };
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' uses prose ('<{}>') inside an expression; prose \
                             may only stand alone as the whole definition of a built-in \
                             lexer token.",
                            diag_name(),
                            prod.name,
                            text
                        ),
                        &prod.name,
                        stray.sp.or(prod.sp),
                    ));
                }
            }
        }
        kept.push(prod);
    }

    if kept.is_empty() && !grammar.clear_all && grammar.remove.is_empty() {
        return Err(EmitError::new(format!(
            "{}: grammar defines no rules — only informational prose terminals.",
            diag_name()
        )));
    }

    grammar.productions = kept;
    Ok(())
}

/// Token names the engine's own matchers produce. A production so named
/// is never lifted: `TX = "literal"` stays an ordinary rule shadowing the
/// bareword, since the engine refuses to bind a matcher-owned name to a
/// fixed literal. This is the engine's `MATCHER_TOKEN_NAMES`.
pub(crate) fn is_matcher_token_name(name: &str) -> bool {
    matches!(
        name,
        "BD" | "ZZ" | "UK" | "AA" | "SP" | "LN" | "CM" | "NR" | "ST" | "TX" | "VL"
    )
}

/// Lift single-literal productions into NAMED lexer tokens.
///
/// A production whose whole body is one string literal (`PL = "+"`) is a
/// lexical definition, not a syntactic rule: lifting binds the literal to
/// `#PL` directly and drops the rule. The start rule is never lifted,
/// multi-alternative productions are real choices and are left alone, as
/// are the core rules, annotated rules, matcher-owned names and the empty
/// literal. Two names claiming one literal cancel each other. Returns
/// every lifted definition, referenced or not, so the emitter can
/// allocate the token even when nothing references it.
pub(crate) fn lift_literal_tokens(grammar: &mut Grammar, start: &str) -> Vec<Element> {
    let mut lifted: IndexMap<String, (String, Option<bool>)> = IndexMap::new();

    for prod in &grammar.productions {
        if prod.name == start
            || is_matcher_token_name(&prod.name)
            || prod.node_kind == NodeKind::Core
            || prod.value.is_some()
        {
            continue;
        }
        if prod.alts.len() != 1 || prod.alts[0].len() != 1 {
            continue;
        }
        let Kind::Term {
            literal,
            case_sensitive,
            ..
        } = &prod.alts[0][0].kind
        else {
            continue;
        };
        // `path-empty = ""` matches the empty string: a rule that derives
        // epsilon, not a token the lexer could ever emit.
        if literal.is_empty() {
            continue;
        }
        lifted.insert(prod.name.clone(), (literal.clone(), *case_sensitive));
    }

    // The engine keys its fixed tokens by literal, so one literal is one
    // token: when two names claim the same literal, neither is lifted.
    let mut by_literal: IndexMap<String, Vec<String>> = IndexMap::new();
    for (name, (literal, cs)) in &lifted {
        by_literal
            .entry(term_key(literal, *cs))
            .or_default()
            .push(name.clone());
    }
    for names in by_literal.values() {
        if names.len() > 1 {
            for n in names {
                lifted.shift_remove(n);
            }
        }
    }

    if lifted.is_empty() {
        return Vec::new();
    }

    let mk = |name: &str, literal: &str, cs: Option<bool>| Element {
        kind: Kind::Term {
            literal: literal.to_string(),
            case_sensitive: cs,
            token_name: Some(name.to_string()),
        },
        sp: None,
    };

    fn walk(el: &Element, lifted: &IndexMap<String, (String, Option<bool>)>) -> Element {
        match &el.kind {
            Kind::Ref { name, .. } => match lifted.get(name) {
                Some((literal, cs)) => Element {
                    kind: Kind::Term {
                        literal: literal.clone(),
                        case_sensitive: *cs,
                        token_name: Some(name.clone()),
                    },
                    sp: None,
                },
                None => el.clone(),
            },
            Kind::Opt { inner } => Element {
                kind: Kind::Opt {
                    inner: Box::new(walk(inner, lifted)),
                },
                sp: el.sp,
            },
            Kind::Star { inner, debt_guard } => Element {
                kind: Kind::Star {
                    inner: Box::new(walk(inner, lifted)),
                    debt_guard: debt_guard.clone(),
                },
                sp: el.sp,
            },
            Kind::Plus { inner } => Element {
                kind: Kind::Plus {
                    inner: Box::new(walk(inner, lifted)),
                },
                sp: el.sp,
            },
            Kind::Rep { min, max, inner } => Element {
                kind: Kind::Rep {
                    min: *min,
                    max: *max,
                    inner: Box::new(walk(inner, lifted)),
                },
                sp: el.sp,
            },
            Kind::Group { alts } => Element::group(
                alts.iter()
                    .map(|a| a.iter().map(|e| walk(e, lifted)).collect())
                    .collect(),
            ),
            _ => el.clone(),
        }
    }

    grammar.productions = grammar
        .productions
        .drain(..)
        .filter(|p| !lifted.contains_key(&p.name))
        .map(|mut p| {
            p.alts = p
                .alts
                .iter()
                .map(|alt| alt.iter().map(|e| walk(e, &lifted)).collect::<Sequence>())
                .collect();
            p
        })
        .collect();

    lifted
        .iter()
        .map(|(name, (literal, cs))| mk(name, literal, *cs))
        .collect()
}

/// Rewrite every bareword reference whose name is a built-in token AND is
/// not a defined production into a token terminal.
pub(crate) fn normalize_builtin_tokens(grammar: &mut Grammar) {
    let defined: IndexSet<String> = grammar.productions.iter().map(|p| p.name.clone()).collect();

    fn walk(el: &Element, defined: &IndexSet<String>) -> Element {
        match &el.kind {
            Kind::Ref { name, .. } => match builtin_token(name) {
                Some(tok) if !defined.contains(name) => Element::token(tok),
                _ => el.clone(),
            },
            Kind::Opt { inner } => Element {
                kind: Kind::Opt {
                    inner: Box::new(walk(inner, defined)),
                },
                sp: el.sp,
            },
            Kind::Star { inner, debt_guard } => Element {
                kind: Kind::Star {
                    inner: Box::new(walk(inner, defined)),
                    debt_guard: debt_guard.clone(),
                },
                sp: el.sp,
            },
            Kind::Plus { inner } => Element {
                kind: Kind::Plus {
                    inner: Box::new(walk(inner, defined)),
                },
                sp: el.sp,
            },
            Kind::Rep { min, max, inner } => Element {
                kind: Kind::Rep {
                    min: *min,
                    max: *max,
                    inner: Box::new(walk(inner, defined)),
                },
                sp: el.sp,
            },
            Kind::Group { alts } => Element::group(
                alts.iter()
                    .map(|a| a.iter().map(|e| walk(e, defined)).collect())
                    .collect(),
            ),
            _ => el.clone(),
        }
    }

    for prod in &mut grammar.productions {
        prod.alts = prod
            .alts
            .iter()
            .map(|alt| alt.iter().map(|e| walk(e, &defined)).collect())
            .collect();
    }
}

/// Whether a regex terminal can match nothing, decided by asking the
/// regex. An invalid pattern answers false so the compiler's specific
/// invalid-regex diagnostic takes precedence over derived nullability.
fn regex_derives_empty(pattern: &str, flags: &str) -> bool {
    let mut builder = regex::RegexBuilder::new(&format!("^(?:{pattern})$"));
    builder.case_insensitive(flags.contains('i'));
    match builder.build() {
        Ok(re) => re.is_match(""),
        Err(_) => false,
    }
}

/// Whether a regex can succeed without consuming in some following
/// context. `\b` before a word character is the important case: it does
/// not match the wholly empty input, but it still lets a repetition
/// re-enter at one source position. Assertions become an empty group rather
/// than disappearing: deleting one from a quantified group can leave an
/// invalid skeleton and hide a valid non-consuming matcher.
fn regex_may_match_without_consuming(pattern: &str, flags: &str) -> bool {
    let mut seen = String::new();
    for flag in flags.chars() {
        if !"dgimsuvy".contains(flag) || seen.contains(flag) {
            return false;
        }
        seen.push(flag);
    }
    if seen.contains('u') && seen.contains('v') {
        return false;
    }
    let mut valid = regex::RegexBuilder::new(pattern);
    valid.case_insensitive(flags.contains('i'));
    if valid.build().is_err() {
        return false;
    }
    if regex_derives_empty(pattern, flags) {
        return true;
    }

    let bytes = pattern.as_bytes();
    let mut skeleton = Vec::with_capacity(bytes.len());
    let mut in_class = false;
    let mut extended = false;
    let mut extended_stack = Vec::new();
    let mut changed = false;
    let mut i = 0;
    while i < bytes.len() {
        let ch = bytes[i];
        if ch == b'\\' && i + 1 < bytes.len() {
            let next = bytes[i + 1];
            if !in_class && matches!(next, b'b' | b'B' | b'A' | b'z' | b'<' | b'>') {
                changed = true;
                skeleton.extend_from_slice(b"()");
                i += 2;
                // regex-syntax extends `\b` with four named boundary
                // assertions. Consume the whole assertion; leaving the
                // brace suffix behind makes the analysis skeleton invalid
                // and can hide a real zero-width matcher. Ordinary
                // quantifiers such as `\b{5}` deliberately remain.
                if next == b'b' {
                    for suffix in [
                        b"{start}".as_slice(),
                        b"{end}".as_slice(),
                        b"{start-half}".as_slice(),
                        b"{end-half}".as_slice(),
                    ] {
                        if bytes[i..].starts_with(suffix) {
                            i += suffix.len();
                            break;
                        }
                    }
                }
                continue;
            }
            skeleton.extend_from_slice(&bytes[i..=i + 1]);
            i += 2;
            continue;
        }
        if !in_class && extended && ch == b'#' {
            // In extended mode a comment runs to the next LF. Its contents
            // are not regex syntax: in particular, an unmatched `[` in the
            // comment must not hide a real boundary on the following line.
            while i < bytes.len() {
                let comment = bytes[i];
                skeleton.push(comment);
                i += 1;
                if comment == b'\n' {
                    break;
                }
            }
            continue;
        }
        if in_class {
            skeleton.push(ch);
            if ch == b']' {
                in_class = false;
            }
            i += 1;
            continue;
        }
        if ch == b'(' && i + 2 < bytes.len() && bytes[i + 1] == b'?' {
            let mut j = i + 2;
            let mut enabled = true;
            let mut next_extended = extended;
            while j < bytes.len() {
                match bytes[j] {
                    b'-' => enabled = false,
                    b'x' => next_extended = enabled,
                    b'i' | b'm' | b's' | b'R' | b'U' | b'u' => {}
                    _ => break,
                }
                j += 1;
            }
            if j < bytes.len() && bytes[j] == b':' {
                // `(?:...)` is the empty flag set; `(?x:...)` and
                // `(?-x:...)` change extended mode only for this group.
                extended_stack.push(extended);
                extended = next_extended;
                skeleton.extend_from_slice(&bytes[i..=j]);
                i = j + 1;
                continue;
            }
            if i + 2 < j && j < bytes.len() && bytes[j] == b')' {
                // A flag-only group changes the rest of the current scope.
                extended = next_extended;
                skeleton.extend_from_slice(&bytes[i..=j]);
                i = j + 1;
                continue;
            }
        }
        if ch == b'(' {
            extended_stack.push(extended);
            skeleton.push(ch);
        } else if ch == b')' {
            if let Some(outer) = extended_stack.pop() {
                extended = outer;
            }
            skeleton.push(ch);
        } else if ch == b'[' {
            in_class = true;
            skeleton.push(ch);
        } else if ch == b'^' || ch == b'$' {
            changed = true;
            skeleton.extend_from_slice(b"()");
        } else {
            skeleton.push(ch);
        }
        i += 1;
    }
    changed
        && String::from_utf8(skeleton)
            .ok()
            .is_some_and(|skeleton| regex_derives_empty(&skeleton, flags))
}

pub(crate) fn element_derives_empty(el: &Element, nullable: &IndexSet<String>) -> bool {
    match &el.kind {
        Kind::Opt { .. } | Kind::Star { .. } => true,
        Kind::Plus { inner } => element_derives_empty(inner, nullable),
        Kind::Rep { min, inner, .. } => *min == 0 || element_derives_empty(inner, nullable),
        Kind::Group { alts } => alts.iter().any(|alt| sequence_derives_empty(alt, nullable)),
        Kind::Ref { name, .. } => nullable.contains(name),
        // An empty literal is kept rather than refused, and a terminal
        // matching nothing matches nothing.
        Kind::Term { literal, .. } => literal.is_empty(),
        Kind::Regex { pattern, flags } => regex_derives_empty(pattern, flags),
        // Two of the engine's own tokens are satisfied without consuming
        // anything: `#ZZ`, end of source, and `#AA`, the ANY wildcard.
        Kind::Token { name } => name == "#ZZ" || name == "#AA",
        Kind::Prose { .. } => false,
    }
}

pub(crate) fn element_may_match_without_consuming(
    el: &Element,
    nullable: &IndexSet<String>,
) -> bool {
    match &el.kind {
        Kind::Opt { .. } | Kind::Star { .. } => true,
        Kind::Plus { inner } => element_may_match_without_consuming(inner, nullable),
        Kind::Rep { min, inner, .. } => {
            *min == 0 || element_may_match_without_consuming(inner, nullable)
        }
        Kind::Group { alts } => alts.iter().any(|alt| {
            alt.iter()
                .all(|child| element_may_match_without_consuming(child, nullable))
        }),
        Kind::Ref { name, .. } => nullable.contains(name),
        Kind::Term { literal, .. } => literal.is_empty(),
        Kind::Regex { pattern, flags } => regex_may_match_without_consuming(pattern, flags),
        Kind::Token { name } => name == "#ZZ" || name == "#AA",
        Kind::Prose { .. } => false,
    }
}

pub(crate) fn non_consuming_rules(prods: &[Production]) -> IndexSet<String> {
    let mut nullable = IndexSet::new();
    let mut changed = true;
    while changed {
        changed = false;
        for prod in prods {
            if nullable.contains(&prod.name) {
                continue;
            }
            if prod.alts.iter().any(|alt| {
                alt.iter()
                    .all(|el| element_may_match_without_consuming(el, &nullable))
            }) {
                nullable.insert(prod.name.clone());
                changed = true;
            }
        }
    }
    nullable
}

fn sequence_derives_empty(alt: &[Element], nullable: &IndexSet<String>) -> bool {
    alt.iter().all(|el| element_derives_empty(el, nullable))
}

/// The rules that derive the empty string: a least fixed point.
pub(crate) fn nullable_rules(prods: &[Production]) -> IndexSet<String> {
    let mut nullable: IndexSet<String> = IndexSet::new();
    let mut changed = true;
    while changed {
        changed = false;
        for p in prods {
            if nullable.contains(&p.name) {
                continue;
            }
            if p.alts
                .iter()
                .any(|alt| sequence_derives_empty(alt, &nullable))
            {
                nullable.insert(p.name.clone());
                changed = true;
            }
        }
    }
    nullable
}

/// Bound numeric repetition expansion and refuse unbounded loops whose item
/// can derive epsilon. Run after structural rewrites, which may duplicate an
/// authored repetition, and before desugaring allocates any helper.
pub(crate) fn validate_repetitions(grammar: &Grammar) -> Result<(), EmitError> {
    let mut expansion = 0usize;

    fn refuse(el: &Element, prod: &Production, message: String) -> EmitError {
        let rule = origin_of(prod);
        let sp = el.sp.or(prod.sp);
        EmitError::at(
            format!("{}: rule '{}' {message}", diag_name(), rule),
            rule,
            sp,
        )
    }

    fn vocab_key(el: &Element) -> Option<String> {
        match &el.kind {
            Kind::Term { .. } => Some(term_key_of(el)),
            Kind::Regex { pattern, flags } => Some(regex_key(pattern, flags)),
            Kind::Token { name } => Some(name.clone()),
            _ => None,
        }
    }

    fn find_vocab_origin(
        el: &Element,
        grammar: &Grammar,
        key: &str,
        current: &Production,
        visited: &mut IndexSet<String>,
    ) -> Option<(String, Option<crate::ir::SrcSpan>)> {
        match &el.kind {
            Kind::Term { .. } | Kind::Regex { .. } | Kind::Token { .. } => {
                (vocab_key(el).as_deref() == Some(key))
                    .then(|| (origin_of(current).to_string(), current.sp))
            }
            Kind::Ref { name, .. } => {
                if !visited.insert(name.clone()) {
                    return None;
                }
                let found =
                    grammar.find(name).and_then(|source| {
                        source.alts.iter().flatten().find_map(|child| {
                            find_vocab_origin(child, grammar, key, source, visited)
                        })
                    });
                visited.shift_remove(name);
                found
            }
            Kind::Opt { inner }
            | Kind::Star { inner, .. }
            | Kind::Plus { inner }
            | Kind::Rep { inner, .. } => find_vocab_origin(inner, grammar, key, current, visited),
            Kind::Group { alts } => alts
                .iter()
                .flatten()
                .find_map(|child| find_vocab_origin(child, grammar, key, current, visited)),
            Kind::Prose { .. } => None,
        }
    }

    // A probe helper contains cloned terminals rather than references, but
    // diagnostics still belong to the author-written production that supplied
    // each terminal. Rewalk the committed `with` branch in the same X-then-Y
    // order used to build the vocabulary and recover that source rule.
    fn probe_vocab_origin(
        grammar: &Grammar,
        helper: &Production,
        el: &Element,
    ) -> Option<(String, Option<crate::ir::SrcSpan>)> {
        let key = vocab_key(el)?;
        let dispatch = grammar.productions.iter().find(|prod| {
            prod.probe_dispatch
                .as_ref()
                .is_some_and(|spec| spec.probe_rule == helper.name)
        })?;
        let with_name = &dispatch.probe_dispatch.as_ref()?.with_branch;
        let with_prod = grammar.find(with_name)?;
        let mut visited = IndexSet::new();
        with_prod
            .alts
            .iter()
            .flatten()
            .find_map(|child| find_vocab_origin(child, grammar, &key, with_prod, &mut visited))
    }

    fn validate_bounds(el: &Element, prod: &Production) -> Result<(), EmitError> {
        if let Kind::Group { alts } = &el.kind {
            for child in alts.iter().flatten() {
                validate_bounds(child, prod)?;
            }
            return Ok(());
        }
        if let Kind::Rep { min, max, .. } = &el.kind {
            if max.is_some_and(|max| max < *min) {
                return Err(refuse(
                    el,
                    prod,
                    format!(
                        "has invalid repetition bounds '{}*{}'. Bounds must be non-negative \
                         integers and the upper bound must not be lower than the lower bound.",
                        min,
                        max.expect("checked as present")
                    ),
                ));
            }
        }
        match &el.kind {
            Kind::Opt { inner }
            | Kind::Star { inner, .. }
            | Kind::Plus { inner }
            | Kind::Rep { inner, .. } => validate_bounds(inner, prod),
            _ => Ok(()),
        }
    }

    for prod in &grammar.productions {
        for el in prod.alts.iter().flatten() {
            validate_bounds(el, prod)?;
        }
    }

    let nullable = non_consuming_rules(&grammar.productions);

    fn non_consuming_witness<'a>(
        el: &'a Element,
        nullable: &IndexSet<String>,
    ) -> Option<&'a Element> {
        if !element_may_match_without_consuming(el, nullable) {
            return None;
        }
        if let Kind::Group { alts } = &el.kind {
            let alt = alts.iter().find(|alt| {
                alt.iter()
                    .all(|child| element_may_match_without_consuming(child, nullable))
            })?;
            for child in alt {
                if let Some(witness) = non_consuming_witness(child, nullable) {
                    return Some(witness);
                }
            }
            return Some(el);
        }
        match &el.kind {
            Kind::Plus { inner }
            | Kind::Rep {
                min: 1.., inner, ..
            } => non_consuming_witness(inner, nullable).or(Some(el)),
            _ => Some(el),
        }
    }

    fn walk(
        el: &Element,
        prod: &Production,
        nullable: &IndexSet<String>,
        expansion: &mut usize,
    ) -> Result<(), EmitError> {
        if let Kind::Group { alts } = &el.kind {
            for child in alts.iter().flatten() {
                walk(child, prod, nullable, expansion)?;
            }
            return Ok(());
        }

        let inner = match &el.kind {
            Kind::Opt { inner }
            | Kind::Star { inner, .. }
            | Kind::Plus { inner }
            | Kind::Rep { inner, .. } => inner.as_ref(),
            _ => return Ok(()),
        };
        let unbounded = matches!(&el.kind, Kind::Star { .. } | Kind::Plus { .. })
            || matches!(&el.kind, Kind::Rep { max: None, .. });
        if unbounded && element_may_match_without_consuming(inner, nullable) {
            return Err(refuse(
                non_consuming_witness(inner, nullable).unwrap_or(el),
                prod,
                "has an unbounded repetition whose item can succeed without consuming input. \
                 An unbounded repetition must consume input on every iteration."
                    .to_string(),
            ));
        }

        if let Kind::Rep { min, max, .. } = &el.kind {
            let remaining = MAX_REPEAT_EXPANSION - *expansion;
            let mut cost = 1usize;
            let mut too_large = cost > remaining || *min > remaining.saturating_sub(cost);
            if !too_large {
                cost += *min;
                match max {
                    None => {
                        too_large = cost >= remaining;
                        cost += 1;
                    }
                    Some(max) => {
                        let optional = max.saturating_sub(*min);
                        too_large = optional > remaining.saturating_sub(cost) / 2;
                        if !too_large {
                            cost += 2 * optional;
                        }
                    }
                }
            }
            if too_large {
                let upper = max.map_or_else(String::new, |max| max.to_string());
                return Err(refuse(
                    el,
                    prod,
                    format!(
                        "exceeds the repetition expansion limit of {MAX_REPEAT_EXPANSION} \
                         while expanding '{min}*{upper}'. Split the repetition into named \
                         rules or lower its bounds."
                    ),
                ));
            }
            *expansion += cost;
        }
        walk(inner, prod, nullable, expansion)
    }

    for prod in &grammar.productions {
        for el in prod.alts.iter().flatten() {
            walk(el, prod, &nullable, &mut expansion)?;
        }
        if let Some(helper) = &prod.probe_helper {
            // Probe-helper vocabulary lives outside `alts`. Every successful
            // matcher re-enters the helper, so a nullable matcher would loop
            // forever at one source position.
            for el in &helper.vocab_elements {
                if element_may_match_without_consuming(el, &nullable) {
                    let witness = non_consuming_witness(el, &nullable).unwrap_or(el);
                    let (rule, source_sp) = probe_vocab_origin(grammar, prod, el)
                        .unwrap_or_else(|| (origin_of(prod).to_string(), prod.sp));
                    return Err(EmitError::at(
                        format!(
                            "{}: rule '{}' has a probe helper matcher that can succeed without \
                             consuming input. An unbounded repetition must consume input on every \
                             iteration.",
                            diag_name(),
                            rule
                        ),
                        &rule,
                        witness.sp.or(source_sp),
                    ));
                }
            }
        }
        if let Some(tail) = &prod.tail_repeat {
            let cycle = tail.sep.iter().chain(prod.alts[0].iter());
            if cycle.clone().next().is_some()
                && cycle
                    .clone()
                    .all(|el| element_may_match_without_consuming(el, &nullable))
            {
                let fallback = tail
                    .sep
                    .first()
                    .or_else(|| prod.alts.first().and_then(|alt| alt.first()))
                    .expect("a non-empty tail cycle has an element");
                let witness = cycle
                    .filter_map(|el| non_consuming_witness(el, &nullable))
                    .next()
                    .unwrap_or(fallback);
                return Err(refuse(
                    witness,
                    prod,
                    "has an unbounded tail repetition that can succeed without consuming input. \
                     An unbounded repetition must consume input on every iteration."
                        .to_string(),
                ));
            }
        }
    }
    Ok(())
}