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
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
// 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 indexmap::{IndexMap, IndexSet};

use crate::annotate::exempt_alias;
use crate::ir::{
    diag_name, refs_in, Element, EmitError, Grammar, Kind, Production, Sequence, SrcSpan,
    TailRepeatSpec,
};
use crate::prose::{element_may_match_without_consuming, non_consuming_rules};

/// 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.
#[derive(Clone)]
struct RewriteSource {
    rule: String,
    sp: Option<SrcSpan>,
    children: RewriteSourceChildren,
}

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

type RewriteSources = IndexMap<String, Vec<Vec<RewriteSource>>>;
type DirectRewrite = (Production, Vec<Vec<RewriteSource>>);

/// 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(Box::new(authored_source(inner, prod)))
        }
        Kind::Group { alts } => RewriteSourceChildren::Group(
            alts.iter()
                .map(|alt| {
                    alt.iter()
                        .map(|child| authored_source(child, prod))
                        .collect()
                })
                .collect(),
        ),
        _ => RewriteSourceChildren::None,
    };
    RewriteSource {
        rule: crate::ir::origin_of(prod).to_string(),
        sp: el.sp.or(prod.sp),
        children,
    }
}

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

fn nullable_sugar_sources(el: &Element, source: &RewriteSource) -> Option<Vec<RewriteSource>> {
    let inner = match &source.children {
        RewriteSourceChildren::Inner(inner) => inner.as_ref().clone(),
        _ => return None,
    };
    match &el.kind {
        Kind::Opt { .. } => Some(vec![inner]),
        Kind::Star { .. } => Some(vec![inner, source.clone()]),
        Kind::Rep { min: 0, max, .. } => match max {
            Some(0) => None,
            None => Some(vec![inner, source.clone()]),
            Some(1) => Some(vec![inner]),
            Some(_) => Some(vec![inner, source.clone()]),
        },
        _ => 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: &Element) -> Option<Sequence> {
    match &el.kind {
        Kind::Opt { inner } => Some(vec![(**inner).clone()]),
        Kind::Star { inner, .. } => Some(vec![(**inner).clone(), el.clone()]),
        Kind::Rep { min: 0, max, inner } => match max {
            Some(0) => None,
            None => Some(vec![(**inner).clone(), el.clone()]),
            Some(1) => Some(vec![(**inner).clone()]),
            Some(max) => Some(vec![
                (**inner).clone(),
                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: &[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"`
fn expand_nullable_left_prefixes(
    prods: Vec<Production>,
    sources: &mut RewriteSources,
) -> Vec<Production> {
    prods
        .into_iter()
        .map(|p| {
            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");
                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
            }
        })
        .collect()
}

/// 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.
pub fn eliminate_left_recursion(grammar: &Grammar) -> Result<Grammar, EmitError> {
    eliminate_left_recursion_keeping(grammar, &IndexSet::new()).map(EliminatedGrammar::into_grammar)
}

/// [`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();

    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| 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));

    // 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) {
            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;
                    }
                    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.
                        let class_name = prods[j].name.clone();
                        let target_name = prods[i].name.clone();
                        let target_sources = sources[&target_name].clone();
                        let (next, next_sources) = substitute_leading_ref_by_token(
                            &prods[i],
                            &target_sources,
                            &class_name,
                        );
                        prods[i] = next;
                        sources.insert(target_name, next_sources);
                    } else {
                        let source = prods[j].clone();
                        let target_name = prods[i].name.clone();
                        let target_sources = sources[&target_name].clone();
                        let source_sources = sources[&source.name].clone();
                        let (next, next_sources) = substitute_leading_ref(
                            &prods[i],
                            &target_sources,
                            &source,
                            &source_sources,
                        );
                        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.
    let mut by_name: IndexMap<String, Production> =
        prods.into_iter().map(|p| (p.name.clone(), p)).collect();
    let mut ordered = Vec::new();
    for name in &original_order {
        if let Some(p) = by_name.shift_remove(name) {
            ordered.push(p);
        }
    }
    ordered.extend(by_name.into_values());

    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)))
}

/// 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: &[Vec<RewriteSource>],
    source: &Production,
    source_sources: &[Vec<RewriteSource>],
) -> (Production, Vec<Vec<RewriteSource>>) {
    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: &[Vec<RewriteSource>],
    class_name: &str,
) -> (Production, Vec<Vec<RewriteSource>>) {
    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![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: &[Vec<RewriteSource>],
    debt_names: &mut IndexSet<String>,
) -> Result<DirectRewrite, EmitError> {
    let mut recursive: Vec<(Sequence, Vec<RewriteSource>)> = Vec::new();
    let mut seeds: Vec<(Sequence, Vec<RewriteSource>)> = 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, Vec<RewriteSource>)> = 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<Vec<RewriteSource>>) = seeds.into_iter().unzip();
    let (non_trivial, tail_sources): (Vec<Sequence>, Vec<Vec<RewriteSource>>) =
        non_trivial.into_iter().unzip();
    let seed_element = if seeds.len() == 1 && seeds[0].len() == 1 {
        seeds[0][0].clone()
    } else {
        Element::group(seeds.clone())
    };
    let tail_inner = if non_trivial.len() == 1 && non_trivial[0].len() == 1 {
        non_trivial[0][0].clone()
    } else {
        Element::group(non_trivial.clone())
    };

    // 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.clone()),
            debt_guard,
        },
        sp: None,
    };

    let fallback = RewriteSource {
        rule: crate::ir::origin_of(prod).to_string(),
        sp: prod.sp,
        children: RewriteSourceChildren::None,
    };
    let seed_source = if seed_sources.len() == 1 && seed_sources[0].len() == 1 {
        seed_sources[0][0].clone()
    } else {
        generated_group_source(seed_sources, &fallback)
    };
    let tail_inner_source = if tail_sources.len() == 1 && tail_sources[0].len() == 1 {
        tail_sources[0][0].clone()
    } else {
        generated_group_source(tail_sources, &fallback)
    };
    let mut tail_source = tail_inner_source.clone();
    tail_source.children = RewriteSourceChildren::Inner(Box::new(tail_inner_source));
    Ok((
        prod.rebuilt(vec![vec![seed_element, star]]),
        vec![vec![seed_source, 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: 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: 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(Element::is_terminal) {
            continue;
        }

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