tabnas-bnf 0.1.30

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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
// Copyright (c) 2026 Richard Rodger and other contributors, MIT License

//! Left-recursion elimination (Paull's algorithm, with hidden left
//! recursion behind nullable sugar made direct first) and the tail-repeat
//! rewrite. Mirrors `eliminateLeftRecursion` and `rewriteTailRepeats` in
//! `ts/src/compiler.ts`.

use std::collections::HashMap;
use std::rc::Rc;

use indexmap::{IndexMap, IndexSet};

use crate::annotate::exempt_alias;
use crate::ir::{
    self, diag_name, Element, EmitError, Kind, SrcSpan, TailRepeatSpec,
    MAX_LEFT_RECURSION_ELEMENTS, MAX_LEFT_RECURSION_EXPANSION,
};
use crate::prose::{element_may_match_without_consuming, non_consuming_rules};
use crate::shared::{owned, refs_in, AsElement, Grammar, Production, Sequence};

/// Rewrite provenance is compiler-private. Rust callers can therefore keep
/// constructing the public `Element { kind, sp }` shape while Paull
/// substitution still attributes a synthesized loop to the element that was
/// copied into it. The vectors mirror production alternatives and their
/// top-level elements; every rewrite below updates both in lockstep. A
/// source is shared exactly as the element it mirrors is (see
/// `crate::shared`): a substitution that copies an element's pointer copies
/// its source's.
#[derive(Clone)]
struct RewriteSource {
    rule: String,
    sp: Option<SrcSpan>,
    children: RewriteSourceChildren,
}

#[derive(Clone)]
enum RewriteSourceChildren {
    None,
    Inner(Rc<RewriteSource>),
    Group(Vec<AltSources>),
}

/// The sources of one alternative's elements, in order.
type AltSources = Vec<Rc<RewriteSource>>;
type RewriteSources = IndexMap<String, Vec<AltSources>>;
type DirectRewrite = (Production, Vec<AltSources>);

/// The private result used by full emission. The public standalone pass
/// returns only `grammar`, preserving its historical transformation-only
/// contract; emission first validates repetitions while this source tree is
/// still available.
pub(crate) struct EliminatedGrammar {
    grammar: Grammar,
    sources: RewriteSources,
}

impl EliminatedGrammar {
    pub(crate) fn into_grammar(self) -> Grammar {
        self.grammar
    }

    pub(crate) fn validate_repetitions(&self) -> Result<(), EmitError> {
        // Source-aware checks that must run before private provenance is
        // discarded live here. Expansion cost is deliberately left to the
        // ordinary post-factoring validator: factoring may remove duplicate
        // repetitions, and only the surviving IR should spend that budget.
        validate_rewrite_repetitions(&self.grammar, &self.sources)
    }
}

fn authored_source(el: &Element, prod: &Production) -> RewriteSource {
    let children = match &el.kind {
        Kind::Opt { inner }
        | Kind::Star { inner, .. }
        | Kind::Plus { inner }
        | Kind::Rep { inner, .. } => {
            RewriteSourceChildren::Inner(Rc::new(authored_source(inner, prod)))
        }
        Kind::Group { alts } => RewriteSourceChildren::Group(
            alts.iter()
                .map(|alt| {
                    alt.iter()
                        .map(|child| Rc::new(authored_source(child, prod)))
                        .collect()
                })
                .collect(),
        ),
        _ => RewriteSourceChildren::None,
    };
    RewriteSource {
        rule: crate::shared::origin_of(prod).to_string(),
        sp: el.sp.or(prod.sp),
        children,
    }
}

fn generated_group_source(alts: Vec<AltSources>, fallback: &RewriteSource) -> RewriteSource {
    let mut source = alts
        .iter()
        .flatten()
        .next()
        .map(|first| RewriteSource::clone(first))
        .unwrap_or_else(|| fallback.clone());
    source.children = RewriteSourceChildren::Group(alts);
    source
}

fn nullable_sugar_sources(el: &Element, source: &Rc<RewriteSource>) -> Option<AltSources> {
    let inner = match &source.children {
        RewriteSourceChildren::Inner(inner) => Rc::clone(inner),
        _ => return None,
    };
    match &el.kind {
        Kind::Opt { .. } => Some(vec![inner]),
        Kind::Star { .. } => Some(vec![inner, Rc::clone(source)]),
        Kind::Rep { min: 0, max, .. } => match max {
            Some(0) => None,
            None => Some(vec![inner, Rc::clone(source)]),
            Some(1) => Some(vec![inner]),
            Some(_) => Some(vec![inner, Rc::clone(source)]),
        },
        _ => None,
    }
}

fn non_consuming_source<'a>(
    el: &Element,
    source: &'a RewriteSource,
    nullable: &IndexSet<String>,
) -> Option<&'a RewriteSource> {
    if !element_may_match_without_consuming(el, nullable) {
        return None;
    }
    match (&el.kind, &source.children) {
        (Kind::Group { alts }, RewriteSourceChildren::Group(alt_sources)) => {
            let (alt, sources) = alts.iter().zip(alt_sources).find(|(alt, _)| {
                alt.iter()
                    .all(|child| element_may_match_without_consuming(child, nullable))
            })?;
            alt.iter()
                .zip(sources)
                .find_map(|(child, child_source)| {
                    non_consuming_source(child, child_source, nullable)
                })
                .or(Some(source))
        }
        (
            Kind::Plus { inner }
            | Kind::Rep {
                min: 1.., inner, ..
            },
            RewriteSourceChildren::Inner(inner_source),
        ) => non_consuming_source(inner, inner_source, nullable).or(Some(source)),
        _ => Some(source),
    }
}

fn validate_rewrite_repetitions(
    grammar: &Grammar,
    sources: &RewriteSources,
) -> Result<(), EmitError> {
    fn refuse(source: &RewriteSource, message: String) -> EmitError {
        EmitError::at(
            format!("{}: rule '{}' {message}", diag_name(), source.rule),
            &source.rule,
            source.sp,
        )
    }

    fn validate_bounds(el: &Element, source: &RewriteSource) -> Result<(), EmitError> {
        if let Kind::Group { alts } = &el.kind {
            if let RewriteSourceChildren::Group(source_alts) = &source.children {
                for (alt, source_alt) in alts.iter().zip(source_alts) {
                    for (child, child_source) in alt.iter().zip(source_alt) {
                        validate_bounds(child, child_source)?;
                    }
                }
            }
            return Ok(());
        }
        if let Kind::Rep { min, max, .. } = &el.kind {
            if max.is_some_and(|max| max < *min) {
                return Err(refuse(
                    source,
                    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, &source.children) {
            (
                Kind::Opt { inner }
                | Kind::Star { inner, .. }
                | Kind::Plus { inner }
                | Kind::Rep { inner, .. },
                RewriteSourceChildren::Inner(inner_source),
            ) => validate_bounds(inner, inner_source),
            _ => Ok(()),
        }
    }

    fn walk(
        el: &Element,
        source: &RewriteSource,
        nullable: &IndexSet<String>,
    ) -> Result<(), EmitError> {
        if let Kind::Group { alts } = &el.kind {
            if let RewriteSourceChildren::Group(source_alts) = &source.children {
                for (alt, source_alt) in alts.iter().zip(source_alts) {
                    for (child, child_source) in alt.iter().zip(source_alt) {
                        walk(child, child_source, nullable)?;
                    }
                }
            }
            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 inner_source = match &source.children {
            RewriteSourceChildren::Inner(inner_source) => inner_source.as_ref(),
            _ => source,
        };
        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) {
            let witness =
                non_consuming_source(inner, inner_source, nullable).unwrap_or(inner_source);
            return Err(refuse(
                witness,
                "has an unbounded repetition whose item can succeed without consuming input. \
                 An unbounded repetition must consume input on every iteration."
                    .to_string(),
            ));
        }

        walk(inner, inner_source, nullable)
    }

    for prod in &grammar.productions {
        let prod_sources = sources
            .get(&prod.name)
            .expect("every rewrite production has source metadata");
        for (alt, source_alt) in prod.alts.iter().zip(prod_sources) {
            for (el, source) in alt.iter().zip(source_alt) {
                validate_bounds(el, source)?;
            }
        }
    }

    let nullable = non_consuming_rules(&grammar.productions);
    for prod in &grammar.productions {
        let prod_sources = &sources[&prod.name];
        for (alt, source_alt) in prod.alts.iter().zip(prod_sources) {
            for (el, source) in alt.iter().zip(source_alt) {
                walk(el, source, &nullable)?;
            }
        }
    }
    Ok(())
}

/// Sugar that can match nothing: `[X]`, `*X`, and `m*nX` with m = 0.
/// Returns the element sequence for the branch where the sugar DOES
/// match at least once, or `None` if the element is not nullable sugar.
///
/// Deliberately narrow: a nullable REFERENCE is already handled by
/// Paull's substitution; what that machinery cannot see is sugar,
/// because this pass runs before desugaring.
fn nullable_sugar_present(el: &Rc<Element>) -> Option<Sequence> {
    match &el.kind {
        Kind::Opt { inner } => Some(vec![inner.share()]),
        Kind::Star { inner, .. } => Some(vec![inner.share(), Rc::clone(el)]),
        Kind::Rep { min: 0, max, inner } => match max {
            Some(0) => None,
            None => Some(vec![inner.share(), Rc::clone(el)]),
            Some(1) => Some(vec![inner.share()]),
            Some(max) => Some(vec![
                inner.share(),
                Rc::new(Element::rep(0, Some(max - 1), (**inner).clone())),
            ]),
        },
        _ => None,
    }
}

/// Does this alternative re-enter `name` at the same input position,
/// reachable only because everything before the self-reference can
/// match nothing? `A = ["x"] A "y"` is the shape. Direct left recursion
/// is excluded: there is no sugar to split.
fn is_hidden_left_recursive(alt: &[Rc<Element>], name: &str) -> bool {
    let mut saw_sugar = false;
    for el in alt {
        if let Kind::Ref { name: n, .. } = &el.kind {
            return saw_sugar && n == name;
        }
        if nullable_sugar_present(el).is_none() {
            return false;
        }
        saw_sugar = true;
    }
    false
}

/// Split leading nullable sugar into explicit present/absent
/// alternatives, so that hidden left recursion becomes DIRECT left
/// recursion that `eliminate_direct_left_rec` can remove:
///
/// `A = ["x"] A "y" / "z"` becomes `A = "x" A "y" / A "y" / "z"`
///
/// Each split copies the rest of the alternative, so k such elements in
/// front of the recursion write k alternatives holding about k²/2
/// elements between them. Every split is charged to the grammar-wide
/// budget ([`charge_expansion`]) before it is made, and `added` carries
/// the total on to the substitution that follows.
fn expand_nullable_left_prefixes(
    prods: Vec<Production>,
    sources: &mut RewriteSources,
    added: &mut usize,
) -> Result<Vec<Production>, EmitError> {
    let mut out = Vec::with_capacity(prods.len());
    for p in prods {
        out.push({
            let mut alts = p.alts.clone();
            let mut changed = false;
            // Each expansion shortens the leading sugar run of the
            // alternative it splits, so this terminates; the guard is
            // belt-and-braces.
            let guard = alts.iter().map(Vec::len).sum::<usize>() + 1;
            for _ in 0..guard {
                let Some(idx) = alts
                    .iter()
                    .position(|a| is_hidden_left_recursive(a, &p.name))
                else {
                    break;
                };
                let alt = alts[idx].clone();
                let present = nullable_sugar_present(&alt[0])
                    .expect("hidden left recursion starts with nullable sugar");
                *added = charge_expansion(&p, &alt, &present, *added)?;
                let present_len = present.len();
                let mut with: Sequence = present;
                with.extend(alt[1..].iter().cloned());
                let without: Sequence = alt[1..].to_vec();
                alts.splice(idx..=idx, [with, without]);
                let alt_sources = sources
                    .get_mut(&p.name)
                    .expect("every rewrite production has source metadata");
                let original = alt_sources[idx].clone();
                let first = original
                    .first()
                    .expect("hidden left recursion starts with an element");
                let mut with_sources = nullable_sugar_sources(&alt[0], first)
                    .expect("source metadata mirrors nullable sugar");
                debug_assert_eq!(present_len, with_sources.len());
                with_sources.extend(original[1..].iter().cloned());
                let without_sources = original[1..].to_vec();
                alt_sources.splice(idx..=idx, [with_sources, without_sources]);
                changed = true;
            }
            if changed {
                Production { alts, ..p }
            } else {
                p
            }
        });
    }
    Ok(out)
}

/// Eliminate left recursion, both direct (P → P α) and indirect
/// (P → Q α, Q → P β), via Paull's algorithm. Order the productions,
/// and for each A_i walk back over A_1..A_{i-1} inlining any leading
/// reference into A_i's alternatives; once the only remaining leading
/// self-reference on A_i is direct, rewrite to the iterative form
/// `P → (β_1 | … | β_m) (α_1 | … | α_n)*`.
///
/// Returns a new grammar carrying only productions, in the caller's
/// declared order. The input is not modified.
///
/// The result holds an owned element per occurrence, as the public IR
/// does, where [`emit_grammar_spec`](crate::emit_grammar_spec) shares one
/// element between every sequence that holds it. Substitution can repeat
/// a sequence in every rule it begins: a chain of n rules, each one
/// alternative that begins with the next, would come back holding about
/// n²/2 elements, so the pass refuses a grammar it would add more than
/// [`MAX_LEFT_RECURSION_ELEMENTS`] to,
/// the chain from n = 514 on, before it copies them.
pub fn eliminate_left_recursion(grammar: &ir::Grammar) -> Result<ir::Grammar, EmitError> {
    eliminate_left_recursion_keeping(&Grammar::from_ir(grammar), &IndexSet::new())
        .map(|eliminated| eliminated.into_grammar().into_ir())
}

/// [`eliminate_left_recursion`] with a set of productions that are never
/// substituted into the alternatives they lead: the token classes of
/// `ConvertOptions::token_classes`. A class holds no reference, so no
/// left-recursive cycle can run through it, and Paull's invariant is
/// unaffected by leaving it in place.
pub(crate) fn eliminate_left_recursion_keeping(
    grammar: &Grammar,
    keep: &IndexSet<String>,
) -> Result<EliminatedGrammar, EmitError> {
    let original_order: Vec<String> = grammar.productions.iter().map(|p| p.name.clone()).collect();
    // Suffix-debt counter names handed out across the whole grammar.
    let mut debt_names: IndexSet<String> = IndexSet::new();
    // What elimination has added to the grammar so far, in elements and
    // alternatives, held to MAX_LEFT_RECURSION_ELEMENTS before each step
    // that adds is made: first the splitting of nullable prefixes, then
    // each substitution.
    let mut added = 0usize;

    let copies: Vec<Production> = grammar
        .productions
        .iter()
        .map(|p| p.rebuilt(p.alts.clone()))
        .collect();
    let mut sources: RewriteSources = grammar
        .productions
        .iter()
        .map(|p| {
            let alts = p
                .alts
                .iter()
                .map(|alt| {
                    alt.iter()
                        .map(|el| Rc::new(authored_source(el, p)))
                        .collect()
                })
                .collect();
            (p.name.clone(), alts)
        })
        .collect();
    // Order productions so that rules referenced at a leading position
    // are processed before the rules that reference them. Source metadata
    // is keyed by production name, so reordering cannot detach it.
    let mut prods = topo_order_for_paull(expand_nullable_left_prefixes(
        copies,
        &mut sources,
        &mut added,
    )?);

    // Substitution normally runs for every production, even a cycle-free
    // one. One case is exempt: a PURE ALIAS, a production whose single
    // alternative is a single rule reference. Inlining it dissolves the
    // alias name, so the rule vanishes from the emitted AST. Aliases
    // caught up in a leading-reference cycle are still inlined.
    let cyclic = find_leading_ref_cycle_members(&prods);

    for i in 0..prods.len() {
        // Paull's invariant is that after this inner loop no alternative
        // of A_i begins with a ref to any A_j, j < i. The pure-alias
        // exemption leaves some A_j un-substituted, so inlining such an
        // alias can (re)introduce a leading ref to an earlier A_k. Re-run
        // the pass until it reaches a fixed point.
        if !exempt_alias(&prods[i], &cyclic) {
            // The alternatives A_i has gained from substitution so far, held
            // to MAX_LEFT_RECURSION_EXPANSION before each substitution is
            // made.
            let mut gained = 0usize;
            let guard = prods.len() + 1;
            for _ in 0..guard {
                let mut changed = false;
                for j in 0..i {
                    if !has_leading_ref_to(&prods[i], &prods[j].name) {
                        continue;
                    }
                    // Both rules, and their sources, are read where they
                    // stand: nothing is copied but the pointers the new
                    // alternatives hold.
                    let target_name = prods[i].name.clone();
                    let (next, next_sources) = if keep.contains(&prods[j].name) {
                        // A token class: substituted, exactly where any
                        // other leading reference is, by ONE token element
                        // naming its set (`#ident`) rather than by its
                        // alternatives. The tree is the one the plain
                        // substitution gives (the token consumed, no node)
                        // without the one-alternate-per-member fan-out.
                        substitute_leading_ref_by_token(
                            &prods[i],
                            &sources[&target_name],
                            &prods[j].name,
                        )
                    } else {
                        gained = charge_substitution(&prods[i], &prods[j], gained)?;
                        added = charge_elements(&prods[i], &prods[j], added)?;
                        substitute_leading_ref(
                            &prods[i],
                            &sources[&target_name],
                            &prods[j],
                            &sources[&prods[j].name],
                        )
                    };
                    prods[i] = next;
                    sources.insert(target_name, next_sources);
                    changed = true;
                }
                if !changed {
                    break;
                }
            }
        }
        let name = prods[i].name.clone();
        let (next, next_sources) =
            eliminate_direct_left_rec(&prods[i], &sources[&name], &mut debt_names)?;
        prods[i] = next;
        sources.insert(name, next_sources);
    }

    // Restore the caller's declared order, so the start rule still ends
    // up first. Taken from slots rather than removed from an ordered map,
    // whose removal shifts every later entry: once per production, that
    // was quadratic in the size of the grammar. The slots keep the map's
    // semantics: a repeated name keeps its first place and its last
    // production, and is taken once.
    let mut slot_of: HashMap<String, usize> = HashMap::with_capacity(prods.len());
    let mut slots: Vec<Option<Production>> = Vec::with_capacity(prods.len());
    for p in prods {
        match slot_of.get(&p.name) {
            Some(&at) => slots[at] = Some(p),
            None => {
                slot_of.insert(p.name.clone(), slots.len());
                slots.push(Some(p));
            }
        }
    }
    let mut ordered = Vec::with_capacity(slots.len());
    for name in &original_order {
        if let Some(p) = slot_of.get(name).and_then(|&at| slots[at].take()) {
            ordered.push(p);
        }
    }
    ordered.extend(slots.into_iter().flatten());

    Ok(EliminatedGrammar {
        grammar: Grammar {
            productions: ordered,
            ..Default::default()
        },
        sources,
    })
}

/// Tarjan-flavoured SCC scan over the leading-reference graph: the names
/// of productions that participate in at least one cycle (self-loop or
/// longer).
pub(crate) fn find_leading_ref_cycle_members(prods: &[Production]) -> IndexSet<String> {
    let by_name: IndexMap<&str, &Production> = prods.iter().map(|p| (p.name.as_str(), p)).collect();
    let leading_refs = |p: &Production| -> Vec<String> {
        p.alts
            .iter()
            .filter_map(|alt| alt.first())
            .filter_map(|first| first.ref_name())
            .filter(|name| by_name.contains_key(name))
            .map(str::to_string)
            .collect()
    };

    struct State<'a> {
        index: usize,
        stack: Vec<String>,
        on_stack: IndexSet<String>,
        indices: IndexMap<String, usize>,
        lowlinks: IndexMap<String, usize>,
        cyclic: IndexSet<String>,
        by_name: &'a IndexMap<&'a str, &'a Production>,
    }

    // Tarjan's algorithm, with the depth-first search carried on an
    // explicit stack rather than the call stack. A grammar is untrusted
    // input and its reference graph is as deep as the author made it: a
    // chain of a few thousand rules is enough to overflow a recursive
    // walk, and a Rust stack that runs out aborts the process. The order
    // of visits, of the lowlink updates and of the popped components is
    // exactly the recursive one.
    struct Frame {
        name: String,
        targets: Vec<String>,
        next: usize,
    }

    fn open_frame(
        name: &str,
        st: &mut State<'_>,
        leading_refs: &dyn Fn(&Production) -> Vec<String>,
    ) -> Frame {
        st.indices.insert(name.to_string(), st.index);
        st.lowlinks.insert(name.to_string(), st.index);
        st.index += 1;
        st.stack.push(name.to_string());
        st.on_stack.insert(name.to_string());
        let targets = st
            .by_name
            .get(name)
            .map(|prod| leading_refs(prod))
            .unwrap_or_default();
        Frame {
            name: name.to_string(),
            targets,
            next: 0,
        }
    }

    fn strong_connect(
        root: &str,
        st: &mut State<'_>,
        leading_refs: &dyn Fn(&Production) -> Vec<String>,
    ) {
        let mut frames: Vec<Frame> = vec![open_frame(root, st, leading_refs)];
        while let Some(frame) = frames.last_mut() {
            if frame.next < frame.targets.len() {
                let target = frame.targets[frame.next].clone();
                frame.next += 1;
                if !st.indices.contains_key(&target) {
                    let child = open_frame(&target, st, leading_refs);
                    frames.push(child);
                } else if st.on_stack.contains(&target) {
                    let name = frame.name.clone();
                    let low = st.lowlinks[&name].min(st.indices[&target]);
                    st.lowlinks.insert(name, low);
                }
                continue;
            }

            let name = frames
                .pop()
                .expect("the frame just read is still there")
                .name;
            if st.lowlinks[&name] == st.indices[&name] {
                let mut scc = Vec::new();
                loop {
                    let w = st.stack.pop().expect("the SCC root is on the stack");
                    st.on_stack.shift_remove(&w);
                    let done = w == name;
                    scc.push(w);
                    if done {
                        break;
                    }
                }
                let is_cycle = scc.len() > 1
                    || (scc.len() == 1
                        && st
                            .by_name
                            .get(scc[0].as_str())
                            .is_some_and(|p| leading_refs(p).contains(&scc[0])));
                if is_cycle {
                    for n in scc {
                        st.cyclic.insert(n);
                    }
                }
            }
            // What the recursive call did on return: carry the child's
            // lowlink up to the parent that pushed it.
            if let Some(parent) = frames.last() {
                let low = st.lowlinks[&parent.name].min(st.lowlinks[&name]);
                st.lowlinks.insert(parent.name.clone(), low);
            }
        }
    }

    let mut st = State {
        index: 0,
        stack: Vec::new(),
        on_stack: IndexSet::new(),
        indices: IndexMap::new(),
        lowlinks: IndexMap::new(),
        cyclic: IndexSet::new(),
        by_name: &by_name,
    };
    for p in prods {
        if !st.indices.contains_key(&p.name) {
            strong_connect(&p.name, &mut st, &leading_refs);
        }
    }
    st.cyclic
}

/// Topological order over the leading-position reference graph: an edge
/// A → B exists when A has an alternative whose first element is a
/// reference to B. Cycles are preserved as-is.
fn topo_order_for_paull(prods: Vec<Production>) -> Vec<Production> {
    let names: Vec<String> = prods.iter().map(|p| p.name.clone()).collect();
    let mut by_name: IndexMap<String, Production> =
        prods.into_iter().map(|p| (p.name.clone(), p)).collect();
    let mut colour: IndexMap<String, u8> = IndexMap::new(); // 0 unseen, 1 in progress, 2 done
    let mut order: Vec<Production> = Vec::new();

    // Depth first, on an explicit stack for the same reason Tarjan above
    // uses one: the graph's depth is the grammar author's choice. `Exit`
    // is what the recursive call did after its children returned, so the
    // post-order is unchanged.
    enum Step {
        Enter(String),
        Exit(String),
    }

    fn visit(
        root: &str,
        by_name: &mut IndexMap<String, Production>,
        colour: &mut IndexMap<String, u8>,
        order: &mut Vec<Production>,
    ) {
        let mut steps: Vec<Step> = vec![Step::Enter(root.to_string())];
        while let Some(step) = steps.pop() {
            match step {
                Step::Enter(name) => {
                    if colour.get(&name).copied().unwrap_or(0) != 0 {
                        continue;
                    }
                    colour.insert(name.clone(), 1);
                    let leading: Option<Vec<String>> = by_name.get(&name).map(|p| {
                        p.alts
                            .iter()
                            .filter_map(|alt| alt.first().and_then(|el| el.ref_name()))
                            .filter(|n| by_name.contains_key(*n))
                            .map(str::to_string)
                            .collect()
                    });
                    match leading {
                        Some(targets) => {
                            steps.push(Step::Exit(name));
                            for target in targets.into_iter().rev() {
                                steps.push(Step::Enter(target));
                            }
                        }
                        None => {
                            colour.insert(name, 2);
                        }
                    }
                }
                Step::Exit(name) => {
                    colour.insert(name.clone(), 2);
                    if let Some(p) = by_name.get(&name) {
                        order.push(p.clone());
                    }
                }
            }
        }
    }

    for name in &names {
        visit(name, &mut by_name, &mut colour, &mut order);
    }
    order
}

/// True when at least one alternative of `prod` begins with a reference
/// to `name`.
fn has_leading_ref_to(prod: &Production, name: &str) -> bool {
    prod.alts
        .iter()
        .any(|alt| alt.first().is_some_and(|el| el.is_ref_to(name)))
}

/// Charge a substitution of `source` into `target` against what `target`
/// may gain ([`MAX_LEFT_RECURSION_EXPANSION`]), BEFORE it is made, and
/// return the new total; `gained` is what the rule has gained so far. Each
/// of the `led` alternatives of `target` that begin with `source` becomes
/// one alternative per alternative of `source`, a gain of
/// `led × (|source| − 1)`. Mirrors `chargeSubstitution` in
/// `ts/src/compiler.ts`.
fn charge_substitution(
    target: &Production,
    source: &Production,
    gained: usize,
) -> Result<usize, EmitError> {
    let led = target
        .alts
        .iter()
        .filter(|alt| alt.first().is_some_and(|el| el.is_ref_to(&source.name)))
        .count();
    let gain = led.checked_mul(source.alts.len().saturating_sub(1));
    match gain {
        Some(gain) if gain <= MAX_LEFT_RECURSION_EXPANSION.saturating_sub(gained) => {
            Ok(gained + gain)
        }
        _ => Err(EmitError::at(
            format!(
                "{}: rule '{}' exceeds the left-recursion expansion limit of {} alternatives \
                 while inlining '{}', which begins {} of its alternatives and has {} of its \
                 own. Factor '{}' out of the alternatives it begins.",
                diag_name(),
                target.name,
                MAX_LEFT_RECURSION_EXPANSION,
                source.name,
                led,
                source.alts.len(),
                source.name
            ),
            &target.name,
            target.sp,
        )),
    }
}

/// The deep size of a run of elements: each element counts 1 and
/// everything nested in it, all the way down: 1 for each alternative of a
/// group and the deep sizes of the elements in it, and the deep size of the
/// inner element of an option or a repetition. Walked with a stack of its
/// own, since the passes before this one can nest elements deeper than the
/// grammar did, and given up as soon as the count reaches `cap`, which it
/// then returns: a caller asks only whether a size passes what is left of
/// the bound, so a walk never costs more than that.
fn deep_size<'a>(elements: impl IntoIterator<Item = &'a Element>, cap: usize) -> usize {
    let mut stack: Vec<&Element> = elements.into_iter().collect();
    let mut size = 0usize;
    while let Some(el) = stack.pop() {
        size = size.saturating_add(match &el.kind {
            Kind::Group { alts } => 1 + alts.len(),
            _ => 1,
        });
        if size >= cap {
            return cap;
        }
        match &el.kind {
            Kind::Opt { inner }
            | Kind::Star { inner, .. }
            | Kind::Plus { inner }
            | Kind::Rep { inner, .. } => stack.push(inner),
            Kind::Group { alts } => stack.extend(alts.iter().flatten()),
            _ => {}
        }
    }
    size
}

/// Charge a substitution of `source` into `target` against what the whole
/// grammar may gain ([`MAX_LEFT_RECURSION_ELEMENTS`]), BEFORE it is made,
/// and return the new total; `added` is what the substitutions so far have
/// added. An alternative costs 1 for itself and the deep size of each of
/// its elements ([`deep_size`]). Each alternative of `target` that begins
/// with `source` is replaced by one alternative per alternative of
/// `source`, `a_1 … a_m`, each followed by the replaced alternative's tail,
/// which adds `(m − 1)·(1 + deep|tail|) + Σ deep|a_i| − 1`, floored at zero.
/// Mirrors `chargeElements` in `ts/src/compiler.ts`.
fn charge_elements(
    target: &Production,
    source: &Production,
    added: usize,
) -> Result<usize, EmitError> {
    let remaining = MAX_LEFT_RECURSION_ELEMENTS - added;
    let led_alts: Vec<&Sequence> = target
        .alts
        .iter()
        .filter(|alt| alt.first().is_some_and(|el| el.is_ref_to(&source.name)))
        .collect();
    let refuse = || {
        Err(EmitError::at(
            format!(
                "{}: rule '{}' exceeds the left-recursion element limit of {} elements while \
                 inlining '{}', which begins {} of its alternatives and would add more than {} \
                 elements to the {} already added to the grammar. Factor '{}' out of the \
                 alternatives it begins.",
                diag_name(),
                target.name,
                MAX_LEFT_RECURSION_ELEMENTS,
                source.name,
                led_alts.len(),
                remaining,
                added,
                source.name
            ),
            &target.name,
            target.sp,
        ))
    };
    let m = source.alts.len();
    // Each alternative replaced adds at least `held - 1`, so a source whose
    // alternatives hold more than `remaining + 1` is refused before a tail is
    // read.
    let held = deep_size(source.alts.iter().flatten().map(|el| &**el), remaining + 2);
    if !led_alts.is_empty() && held > remaining + 1 {
        return refuse();
    }
    let mut gain = 0usize;
    for alt in &led_alts {
        // A tail is copied once per alternative of the source after the
        // first, so it counts only when there are several, and then adds at
        // least its own size.
        let tail = if m > 1 {
            deep_size(alt[1..].iter().map(|el| &**el), remaining - gain + 2)
        } else {
            0
        };
        // What the new alternatives cost, `m·(1 + tail) + held`, less what
        // the one they replace cost, `1 + 1 + tail`.
        let written = m.saturating_mul(1 + tail).saturating_add(held);
        gain = gain.saturating_add(written.saturating_sub(2 + tail));
        if gain > remaining {
            return refuse();
        }
    }
    Ok(added + gain)
}

/// Charge splitting `alt`, whose leading element `s` can match nothing,
/// into `present rest` and `rest` ([`expand_nullable_left_prefixes`])
/// against what the whole grammar may gain
/// ([`MAX_LEFT_RECURSION_ELEMENTS`]), BEFORE the two alternatives are
/// made, and return the new total. They cost
/// `(1 + deep|present| + deep|rest|) + (1 + deep|rest|)`, and the one they
/// replace cost `1 + deep|s| + deep|rest|`, so the split adds
/// `1 + deep|present| + deep|rest| − deep|s|`, floored at zero. Mirrors
/// `chargeExpansion` in `ts/src/compiler.ts`.
fn charge_expansion(
    prod: &Production,
    alt: &[Rc<Element>],
    present: &[Rc<Element>],
    added: usize,
) -> Result<usize, EmitError> {
    let remaining = MAX_LEFT_RECURSION_ELEMENTS - added;
    let lead = deep_size([&*alt[0]], usize::MAX);
    // Counted until it passes what could still fit once `lead` is taken
    // off, so the decision is exact.
    let cap = remaining.saturating_add(lead).saturating_add(2);
    let written = deep_size(present.iter().chain(&alt[1..]).map(|el| &**el), cap);
    let gain = (written + 1).saturating_sub(lead);
    if gain > remaining {
        return Err(EmitError::at(
            format!(
                "{}: rule '{}' exceeds the left-recursion element limit of {} elements while \
                 splitting the elements that can match nothing before '{}' in one of its \
                 alternatives, which would add more than {} elements to the {} already added \
                 to the grammar. Write that alternative with fewer elements that can match \
                 nothing before '{}'.",
                diag_name(),
                prod.name,
                MAX_LEFT_RECURSION_ELEMENTS,
                prod.name,
                remaining,
                added,
                prod.name
            ),
            &prod.name,
            prod.sp,
        ));
    }
    Ok(added + gain)
}

/// For every alternative of `target` that begins with a ref to `source`,
/// replace that alt with |source.alts| copies, each with the leading
/// source-ref expanded to one of source's alts.
fn substitute_leading_ref(
    target: &Production,
    target_sources: &[AltSources],
    source: &Production,
    source_sources: &[AltSources],
) -> (Production, Vec<AltSources>) {
    let mut new_alts: Vec<Sequence> = Vec::new();
    let mut new_sources = Vec::new();
    for (alt, alt_sources) in target.alts.iter().zip(target_sources) {
        if alt.first().is_some_and(|el| el.is_ref_to(&source.name)) {
            let tail = &alt[1..];
            let tail_sources = &alt_sources[1..];
            for (src_alt, src_sources) in source.alts.iter().zip(source_sources) {
                let mut combined = src_alt.clone();
                combined.extend(tail.iter().cloned());
                new_alts.push(combined);
                let mut combined_sources = src_sources.clone();
                combined_sources.extend(tail_sources.iter().cloned());
                new_sources.push(combined_sources);
            }
        } else {
            new_alts.push(alt.clone());
            new_sources.push(alt_sources.clone());
        }
    }
    (target.rebuilt(new_alts), new_sources)
}

/// Replace a leading reference to a token class by the token element
/// naming the class's set (`ident` -> `#ident`). The set is minted by
/// `emit_grammar_spec` under exactly that name; see `token_class_names`.
fn substitute_leading_ref_by_token(
    target: &Production,
    target_sources: &[AltSources],
    class_name: &str,
) -> (Production, Vec<AltSources>) {
    let mut new_sources = Vec::with_capacity(target.alts.len());
    let new_alts: Vec<Sequence> = target
        .alts
        .iter()
        .zip(target_sources)
        .map(|(alt, alt_sources)| {
            if alt.first().is_some_and(|el| el.is_ref_to(class_name)) {
                let mut combined = vec![Rc::new(Element::token(format!("#{class_name}")))];
                combined.extend(alt[1..].iter().cloned());
                new_sources.push(alt_sources.clone());
                combined
            } else {
                new_sources.push(alt_sources.clone());
                alt.clone()
            }
        })
        .collect();
    (target.rebuilt(new_alts), new_sources)
}

/// Allocate a suffix-debt counter name for a production. Counter names
/// end up in a declarative condition path (`n.<counter>`), which the
/// engine splits on `.`, so reduce the rule name to word characters (one
/// underscore per code point) and disambiguate against what has already
/// been handed out.
fn fresh_debt_counter(rule_name: &str, used: &mut IndexSet<String>) -> String {
    let mut base = String::from("debt_");
    for c in rule_name.chars() {
        if c.is_ascii_alphanumeric() || c == '_' {
            base.push(c);
        } else {
            base.push('_');
        }
    }
    let mut name = base.clone();
    let mut i = 0;
    while used.contains(&name) {
        i += 1;
        name = format!("{base}_{i}");
    }
    used.insert(name.clone());
    name
}

/// Does any seed alternative re-enter this rule at all? A cheap
/// pre-filter for allocating a counter; `resolve_suffix_debts` does the
/// real analysis on the desugared grammar.
fn seeds_reference_self(seeds: &[Sequence], name: &str) -> bool {
    let mut refs = IndexSet::new();
    for alt in seeds {
        refs_in(alt, &mut refs);
    }
    refs.contains(name)
}

/// Rewrite a single production's direct left recursion to its iterative
/// equivalent.
fn eliminate_direct_left_rec(
    prod: &Production,
    prod_sources: &[AltSources],
    debt_names: &mut IndexSet<String>,
) -> Result<DirectRewrite, EmitError> {
    let mut recursive: Vec<(Sequence, AltSources)> = Vec::new();
    let mut seeds: Vec<(Sequence, AltSources)> = Vec::new();
    for (alt, alt_sources) in prod.alts.iter().zip(prod_sources) {
        if alt.first().is_some_and(|el| el.is_ref_to(&prod.name)) {
            recursive.push((alt[1..].to_vec(), alt_sources[1..].to_vec()));
        } else {
            seeds.push((alt.clone(), alt_sources.clone()));
        }
    }

    // A trivial recursive alt (P ::= P, nothing else) derives P from P
    // with no progress. Drop it silently: nullable-prefix expansion can
    // legitimately produce one.
    let non_trivial: Vec<(Sequence, AltSources)> = recursive
        .into_iter()
        .filter(|(tail, _)| !tail.is_empty())
        .collect();
    if non_trivial.is_empty() {
        let (seed_alts, seed_sources): (Vec<_>, Vec<_>) = seeds.into_iter().unzip();
        return Ok((prod.rebuilt(seed_alts), seed_sources));
    }
    if seeds.is_empty() {
        return Err(EmitError::at(
            format!(
                "{}: rule '{}' is purely left-recursive (no seed alternative); cannot eliminate",
                diag_name(),
                prod.name
            ),
            &prod.name,
            prod.sp,
        ));
    }

    let (seeds, seed_sources): (Vec<Sequence>, Vec<AltSources>) = seeds.into_iter().unzip();
    let (non_trivial, tail_sources): (Vec<Sequence>, Vec<AltSources>) =
        non_trivial.into_iter().unzip();
    // A group holds owned elements (it is the public `Kind`), so the
    // sequences it is made of are copied into it.
    let seed_element = if seeds.len() == 1 && seeds[0].len() == 1 {
        Rc::clone(&seeds[0][0])
    } else {
        Rc::new(Element::group(seeds.iter().map(|s| owned(s)).collect()))
    };
    let tail_inner = if non_trivial.len() == 1 && non_trivial[0].len() == 1 {
        Element::clone(&non_trivial[0][0])
    } else {
        Element::group(non_trivial.iter().map(|s| owned(s)).collect())
    };

    // The rewrite is correct as a CFG, but it introduces a repetition
    // whose greediness can compete with a suffix of the very alternative
    // it was derived from. Flag the loop here; `resolve_suffix_debts`
    // confirms the contest against real FIRST sets and wires up the
    // counter, or drops the flag when the suffix and the loop cannot
    // collide.
    let debt_guard = if seeds_reference_self(&seeds, &prod.name) {
        Some(fresh_debt_counter(&prod.name, debt_names))
    } else {
        None
    };
    let star = Element {
        kind: Kind::Star {
            inner: Box::new(tail_inner),
            debt_guard,
        },
        sp: None,
    };

    let fallback = RewriteSource {
        rule: crate::shared::origin_of(prod).to_string(),
        sp: prod.sp,
        children: RewriteSourceChildren::None,
    };
    let seed_source = if seed_sources.len() == 1 && seed_sources[0].len() == 1 {
        Rc::clone(&seed_sources[0][0])
    } else {
        Rc::new(generated_group_source(seed_sources, &fallback))
    };
    let tail_inner_source = if tail_sources.len() == 1 && tail_sources[0].len() == 1 {
        Rc::clone(&tail_sources[0][0])
    } else {
        Rc::new(generated_group_source(tail_sources, &fallback))
    };
    let mut tail_source = RewriteSource::clone(&tail_inner_source);
    tail_source.children = RewriteSourceChildren::Inner(tail_inner_source);
    Ok((
        prod.rebuilt(vec![vec![seed_element, Rc::new(star)]]),
        vec![vec![seed_source, Rc::new(tail_source)]],
    ))
}

/// Rewrite tail self-references into same-depth repeats:
/// `X = prefix [ sep X ]` compiles to a rule that repeats itself (`r: X`)
/// from its close phase.
///
/// This is the special case of the rule every repetition follows (see
/// `Production::repeat_loop`): a star, a plus and an unbounded rep are
/// sequence, and compile to a loop that replaces itself. What is special
/// here is only where the loop comes from. The author wrote a repetition
/// as right recursion through an option, so the loop is the author's own
/// rule rather than a generated helper, and each iteration folds a node
/// of that rule into the parent: a list of `X` siblings, which a star
/// over the same text would not give. The general path does not subsume
/// it for that reason, and it stays.
///
/// Applies only when the production has exactly one alternative, its
/// last element is an option wrapping `sep… X` with the self-reference
/// LAST, every prefix and separator element is a terminal, and the
/// production is not the start production.
pub(crate) fn rewrite_tail_repeats(mut grammar: Grammar, start: &str) -> Grammar {
    for prod in &mut grammar.productions {
        if prod.probe_dispatch.is_some() || prod.probe_helper.is_some() {
            continue;
        }
        if prod.name == start || prod.alts.len() != 1 {
            continue;
        }
        let alt = &prod.alts[0];
        if alt.len() < 2 {
            continue;
        }
        let Kind::Opt { inner: last_inner } = &alt[alt.len() - 1].kind else {
            continue;
        };

        // Normalize the option body to a sequence: `[ a b ]` parses as
        // opt(group([[a, b]])); `[ a ]` as opt(a).
        let seq: ir::Sequence = match &last_inner.kind {
            Kind::Group { alts } => {
                if alts.len() != 1 {
                    continue;
                }
                alts[0].clone()
            }
            _ => vec![(**last_inner).clone()],
        };
        if seq.len() < 2 {
            continue;
        }
        if !seq[seq.len() - 1].is_ref_to(&prod.name) {
            continue;
        }
        let sep: ir::Sequence = seq[..seq.len() - 1].to_vec();
        if !sep.iter().all(Element::is_terminal) {
            continue;
        }
        let prefix: Sequence = alt[..alt.len() - 1].to_vec();
        if prefix.is_empty() || !prefix.iter().all(|el| el.is_terminal()) {
            continue;
        }

        prod.alts = vec![prefix];
        prod.tail_repeat = Some(TailRepeatSpec { sep });
    }
    grammar
}