mpl-macro 0.2.1

Derive parsers from MPL's one-rule grammar files. Includes the FastParse static-codegen backend (cascade detection, first-byte dispatch, Squirrel left recursion).
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
//! Static-codegen generator for the `FastParse` derive.
//!
//! Emits one `fn parse_<rule>(state, pos) -> Result<u32, ()>` per grammar
//! rule plus a small public surface (`var` ids, `recognize`, `parse`).
//! Layout matches `examples/paren_bench/src/mpl_fast_bub.rs`.

use crate::generator::{
    analyze_char_classes, analyze_first_byte_dispatch, classify_rules, compute_first_sets,
    is_left_recursive, is_tail_loop, DispatchCascade,
};
use crate::mplg::MplgOutput;
use mpl::symbols::{Metasymbol, TerminalSymbol, E};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::BTreeSet;
use syn::{Expr, ExprCall, ExprLit, ExprPath, Ident, Lit};

/// Convert PascalCase / CamelCase to snake_case so the generated fn names
/// follow Rust convention. `BubFn1` → `bub_fn1`, `OrOrExpr` → `or_or_expr`.
fn snake(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            out.push('_');
        }
        out.push(c.to_ascii_lowercase());
    }
    out
}

fn fn_ident(name: &str) -> Ident {
    format_ident!("parse_{}", snake(name))
}

fn const_ident(name: &str) -> Ident {
    format_ident!("{}", snake(name).to_uppercase())
}

/// Emit code that evaluates `e` at the position bound to `pos_tok`. The
/// result is a `Result<u32, ()>` — `Ok(end_pos)` on success, `Err(())` on
/// failure. On success the appropriate token(s) have already been pushed
/// (only when `EMIT` is true; check-mode skips them).
fn eval_e(e: &E<&str, &str>, pos_tok: TokenStream) -> TokenStream {
    match e {
        E::V(v) => {
            let f = fn_ident(v);
            quote! { #f::<S, EMIT>(state, #pos_tok) }
        }
        E::T(t) => match t {
            TerminalSymbol::Metasymbol(m) => match m {
                Metasymbol::Empty => quote! {
                    {
                        let p = #pos_tok;
                        if EMIT {
                            state.push_leaf(::mpl::fast::kind::EMPTY, p, p);
                        }
                        Ok::<u32, ()>(p)
                    }
                },
                Metasymbol::Failure => quote! { Err::<u32, ()>(()) },
                Metasymbol::Any(n) => {
                    let n_lit = *n as u32;
                    quote! {
                        {
                            let p = #pos_tok;
                            let want = p as usize + #n_lit as usize;
                            if want <= state.input().len() {
                                if EMIT {
                                    state.push_leaf(::mpl::fast::kind::ANY, p, want as u32);
                                }
                                Ok::<u32, ()>(want as u32)
                            } else {
                                state.note_failure_at(p);
                                Err::<u32, ()>(())
                            }
                        }
                    }
                }
                Metasymbol::All => quote! {
                    {
                        let p = #pos_tok;
                        let end = state.input().len() as u32;
                        if EMIT {
                            state.push_leaf(::mpl::fast::kind::ALL, p, end);
                        }
                        Ok::<u32, ()>(end)
                    }
                },
                Metasymbol::Omit => unimplemented!("Omit metasymbol not supported in FastParse"),
            },
            TerminalSymbol::Original(raw) => emit_terminal(raw, pos_tok),
        },
    }
}

/// Translate a `{ Char('c') }` / `{ Str("...") }` original-symbol into a
/// byte-level match. Other shapes fall back to a generic note-failure
/// stub (intentional: the FastParse path expects byte input only for now).
fn emit_terminal(raw: &str, pos_tok: TokenStream) -> TokenStream {
    let parsed: Expr = syn::parse_str(raw).unwrap_or_else(|_| {
        panic!("FastParse: cannot parse terminal expression `{raw}`");
    });

    if let Expr::Call(ExprCall { func, args, .. }) = &parsed {
        if let Expr::Path(ExprPath { path, .. }) = &**func {
            if path.is_ident("Char") {
                if let Some(Expr::Lit(ExprLit {
                    lit: Lit::Char(c), ..
                })) = args.first()
                {
                    let byte = c.value() as u32 as u8;
                    return quote! {
                        {
                            let p = #pos_tok;
                            let pi = p as usize;
                            if pi < state.input().len() && state.input()[pi] == #byte {
                                if EMIT {
                                    state.push_leaf(::mpl::fast::kind::TERMINAL, p, p + 1);
                                }
                                Ok::<u32, ()>(p + 1)
                            } else {
                                state.note_failure_at(p);
                                Err::<u32, ()>(())
                            }
                        }
                    };
                }
            } else if path.is_ident("Str") {
                if let Some(Expr::Lit(ExprLit {
                    lit: Lit::Str(s), ..
                })) = args.first()
                {
                    let bytes_lit = syn::LitByteStr::new(s.value().as_bytes(), s.span());
                    return quote! {
                        {
                            let p = #pos_tok;
                            let pi = p as usize;
                            let pat: &[u8] = #bytes_lit;
                            let end = pi + pat.len();
                            if end <= state.input().len() && &state.input()[pi..end] == pat {
                                if EMIT {
                                    state.push_leaf(::mpl::fast::kind::TERMINAL, p, end as u32);
                                }
                                Ok::<u32, ()>(end as u32)
                            } else {
                                state.note_failure_at(p);
                                Err::<u32, ()>(())
                            }
                        }
                    };
                }
            }
        }
    }

    panic!("FastParse: unsupported terminal expression `{raw}`")
}

/// True when this `E` is the `Failure` metasymbol — the second-choice
/// alternative is then a no-op rather than emitting a leaf.
fn is_failure(e: &E<&str, &str>) -> bool {
    matches!(e, E::T(TerminalSymbol::Metasymbol(Metasymbol::Failure)))
}

/// True when this `E` is a variable reference (so the second choice should
/// be wrapped in Start/End for the parent rule). Terminals as the second
/// choice are returned directly per current mpl semantics.
fn is_variable(e: &E<&str, &str>) -> bool {
    matches!(e, E::V(_))
}

/// Generate a `[bool; 256]` byte-table init expression that flags every
/// byte in `bytes` as accepted.
fn generate_byte_table(bytes: &BTreeSet<u8>) -> TokenStream {
    let entries = bytes.iter().map(|b| {
        let b = *b;
        quote! { __t[#b as usize] = true; }
    });
    quote! {
        {
            let mut __t = [false; 256];
            #(#entries)*
            __t
        }
    }
}

/// Emit an EMIT-mode-only fast path for char-class cascade rules. The
/// recognition path becomes a single byte-table lookup; the emit path
/// falls through to the original cascade body for AST-shape preservation.
fn generate_cascade_dispatcher(
    rule: &mpl::rules::Rule<&str, &str>,
    bytes: &BTreeSet<u8>,
    cascade_body: TokenStream,
) -> TokenStream {
    let name = rule.value;
    let f = fn_ident(name);
    let table_ident = format_ident!("__{}_BYTES", const_ident(name));
    let table_init = generate_byte_table(bytes);

    quote! {
        const #table_ident: [bool; 256] = #table_init;

        #[inline(always)]
        fn #f<S: ::mpl::fast::ParseState, const EMIT: bool>(
            state: &mut S,
            pos: u32,
        ) -> ::core::result::Result<u32, ()> {
            if !EMIT {
                let p = pos as usize;
                if p < state.input().len() && #table_ident[state.input()[p] as usize] {
                    return Ok(pos + 1);
                }
                state.note_failure_at(pos);
                return Err(());
            }
            // EMIT=true: original cascade preserves AST shape.
            #cascade_body
        }
    }
}

fn generate_rule_inner(rule: &mpl::rules::Rule<&str, &str>) -> TokenStream {
    let name = rule.value;
    let f = fn_ident(name);
    let kind_const = const_ident(name);

    let lhs = &rule.equal.first.lhs;
    let rhs = &rule.equal.first.rhs;
    let alt = &rule.equal.second.0;

    let eval_lhs = eval_e(lhs, quote! { pos });
    let eval_rhs = eval_e(rhs, quote! { end_b });

    let first_choice = quote! {
        {
            let cp = if EMIT { state.checkpoint() } else { 0 };
            let s = if EMIT { state.push_start(var::#kind_const, pos) } else { 0 };
            if let Ok(end_b) = #eval_lhs {
                if let Ok(end_c) = #eval_rhs {
                    if EMIT {
                        state.push_end(var::#kind_const, end_c, s);
                    }
                    return Ok(end_c);
                }
            }
            if EMIT {
                state.truncate(cp);
            }
        }
    };

    let second_choice = if is_failure(alt) {
        quote! { Err(()) }
    } else if is_variable(alt) {
        // Wrap variable result in Start/End for this rule.
        let eval_alt = eval_e(alt, quote! { pos });
        quote! {
            {
                let cp2 = if EMIT { state.checkpoint() } else { 0 };
                let s = if EMIT { state.push_start(var::#kind_const, pos) } else { 0 };
                if let Ok(end) = #eval_alt {
                    if EMIT {
                        state.push_end(var::#kind_const, end, s);
                    }
                    return Ok(end);
                }
                if EMIT {
                    state.truncate(cp2);
                }
                Err(())
            }
        }
    } else {
        // Terminal / metasymbol second choice: returned directly per mpl
        // semantics (no wrapping in this rule's Start/End).
        let eval_alt = eval_e(alt, quote! { pos });
        quote! {
            { #eval_alt }
        }
    };

    quote! {
        #[inline]
        fn #f<S: ::mpl::fast::ParseState, const EMIT: bool>(
            state: &mut S,
            pos: u32,
        ) -> ::core::result::Result<u32, ()> {
            #first_choice
            #second_choice
        }
    }
}

/// Like [`generate_rule_inner`] but returns just the body tokens (no
/// surrounding `fn` wrapper). Used by the cascade dispatcher to embed
/// the original cascade as the EMIT=true fallback.
fn generate_rule_body(rule: &mpl::rules::Rule<&str, &str>) -> TokenStream {
    let kind_const = const_ident(rule.value);
    let lhs = &rule.equal.first.lhs;
    let rhs = &rule.equal.first.rhs;
    let alt = &rule.equal.second.0;

    let eval_lhs = eval_e(lhs, quote! { pos });
    let eval_rhs = eval_e(rhs, quote! { end_b });

    let first_choice = quote! {
        {
            let cp = if EMIT { state.checkpoint() } else { 0 };
            let s = if EMIT { state.push_start(var::#kind_const, pos) } else { 0 };
            if let Ok(end_b) = #eval_lhs {
                if let Ok(end_c) = #eval_rhs {
                    if EMIT {
                        state.push_end(var::#kind_const, end_c, s);
                    }
                    return Ok(end_c);
                }
            }
            if EMIT {
                state.truncate(cp);
            }
        }
    };

    let second_choice = if is_failure(alt) {
        quote! { Err(()) }
    } else if is_variable(alt) {
        let eval_alt = eval_e(alt, quote! { pos });
        quote! {
            {
                let cp2 = if EMIT { state.checkpoint() } else { 0 };
                let s = if EMIT { state.push_start(var::#kind_const, pos) } else { 0 };
                if let Ok(end) = #eval_alt {
                    if EMIT {
                        state.push_end(var::#kind_const, end, s);
                    }
                    return Ok(end);
                }
                if EMIT {
                    state.truncate(cp2);
                }
                Err(())
            }
        }
    } else {
        let eval_alt = eval_e(alt, quote! { pos });
        quote! {
            { #eval_alt }
        }
    };

    quote! {
        #first_choice
        #second_choice
    }
}

/// Emit a first-byte-dispatch fast path for cascades with mostly disjoint
/// FIRST sets. Each alternative's FIRST bytes route to its parser; bytes
/// shared between alternatives are tried in cascade order via or_else.
fn generate_first_byte_dispatcher(
    rule: &mpl::rules::Rule<&str, &str>,
    cascade: &DispatchCascade<'_>,
    cascade_body: TokenStream,
) -> TokenStream {
    let name = rule.value;
    let f = fn_ident(name);

    // Group alternatives by each byte they can start. The cascade stays
    // priority-ordered so earlier alternatives win on shared bytes.
    let mut byte_to_alts: [Vec<usize>; 256] = std::array::from_fn(|_| Vec::new());
    for (i, alt) in cascade.alternatives.iter().enumerate() {
        for b in alt.first.iter_bytes() {
            byte_to_alts[b as usize].push(i);
        }
    }

    // Bucket bytes by which alternative-list they map to so we can emit
    // a single match arm per group (e.g. all digits → Float-then-Integer).
    let mut groups: std::collections::BTreeMap<Vec<usize>, BTreeSet<u8>> =
        std::collections::BTreeMap::new();
    for (b, alts) in byte_to_alts.iter().enumerate() {
        if alts.is_empty() {
            continue;
        }
        groups.entry(alts.clone()).or_default().insert(b as u8);
    }

    let arms = groups.iter().map(|(alt_indices, bytes)| {
        let byte_pat: Vec<TokenStream> = bytes
            .iter()
            .map(|b| {
                let b = *b;
                quote! { #b }
            })
            .collect();
        let pat = if byte_pat.len() == 1 {
            let b = &byte_pat[0];
            quote! { #b }
        } else {
            quote! { #(#byte_pat)|* }
        };

        // Build chained `parse_<alt>::<S, EMIT>(state, pos).or_else(|_| ...)`
        // for shared-byte alternatives; single alternative → just call.
        let mut call_chain = TokenStream::new();
        for (idx, alt_idx) in alt_indices.iter().enumerate() {
            let alt_name = cascade.alternatives[*alt_idx].rule_name;
            let alt_fn = fn_ident(alt_name);
            if idx == 0 {
                call_chain = quote! { #alt_fn::<S, EMIT>(state, pos) };
            } else {
                call_chain = quote! {
                    #call_chain.or_else(|_| #alt_fn::<S, EMIT>(state, pos))
                };
            }
        }
        quote! { #pat => #call_chain, }
    });

    quote! {
        #[inline(always)]
        fn #f<S: ::mpl::fast::ParseState, const EMIT: bool>(
            state: &mut S,
            pos: u32,
        ) -> ::core::result::Result<u32, ()> {
            if EMIT {
                #cascade_body
            } else {
                let p = pos as usize;
                if p >= state.input().len() {
                    state.note_failure_at(pos);
                    return Err(());
                }
                match state.input()[p] {
                    #(#arms)*
                    _ => {
                        state.note_failure_at(pos);
                        Err(())
                    }
                }
            }
        }
    }
}

/// Emit a `loop {}`-based fast path for `R = X R / ()` rules. Rust does
/// not guarantee TCO; LLVM's `tailcallelim` typically fails for
/// `&mut State + Result<u32, ()>`-shaped recursive returns, leaving a
/// real call/ret pair per iteration. We sidestep it by generating an
/// explicit loop in the EMIT=false path; EMIT=true keeps the original
/// recursion so the AST shape (right-recursive Internal nodes) is preserved.
fn generate_tail_loop(
    rule: &mpl::rules::Rule<&str, &str>,
    cascade_body: TokenStream,
) -> TokenStream {
    let name = rule.value;
    let f = fn_ident(name);
    let lhs = &rule.equal.first.lhs;
    let eval_lhs_loop = eval_e(lhs, quote! { p });

    quote! {
        #[inline(always)]
        fn #f<S: ::mpl::fast::ParseState, const EMIT: bool>(
            state: &mut S,
            pos: u32,
        ) -> ::core::result::Result<u32, ()> {
            if EMIT {
                #cascade_body
            } else {
                let mut p = pos;
                loop {
                    match #eval_lhs_loop {
                        Ok(np) => p = np,
                        Err(_) => break,
                    }
                }
                Ok(p)
            }
        }
    }
}

/// Squirrel-style seed-growing wrapper for directly left-recursive rules.
/// EMIT=false uses position-only seed (matches [`crate::parser::squirrel_recognize`]
/// — same algorithmic family as peg's `#[cache_left_rec]`). EMIT=true
/// panics: AST construction with seed-growing is O(n²) in this codegen
/// path, so the user is steered to [`crate::parser::squirrel_parse`] for
/// the parse tree.
fn generate_left_recursive(
    rule: &mpl::rules::Rule<&str, &str>,
    cascade_body: TokenStream,
) -> TokenStream {
    let name = rule.value;
    let f = fn_ident(name);
    let kind_const = const_ident(name);

    quote! {
        #[inline(always)]
        fn #f<S: ::mpl::fast::ParseState, const EMIT: bool>(
            state: &mut S,
            pos: u32,
        ) -> ::core::result::Result<u32, ()> {
            if EMIT {
                // The token-emitting AST path is not seed-growing-aware
                // in this codegen; use `Parser::squirrel_parse` instead.
                // We still emit the cascade body so a non-LR call site
                // (e.g. when the LR alternative cannot fire) parses correctly.
                #cascade_body
            } else {
                // Position-only seed-growing — peg-compatible LR family.
                let key_kind = var::#kind_const;
                if let Some(entry) = state.lr_memo_get(key_kind, pos) {
                    return match entry {
                        ::mpl::fast::LrMemoEntry::Done { result } |
                        ::mpl::fast::LrMemoEntry::InProgress { seed: result } => {
                            result.map(Ok).unwrap_or(Err(()))
                        }
                    };
                }

                state.lr_memo_set(
                    key_kind,
                    pos,
                    ::mpl::fast::LrMemoEntry::InProgress { seed: None },
                );

                let mut best: Option<u32> = None;
                loop {
                    let result: ::core::result::Result<u32, ()> = (|| -> ::core::result::Result<u32, ()> {
                        #cascade_body
                    })();
                    let new_end = result.ok();
                    let grew = match (new_end, best) {
                        (Some(_), None) => true,
                        (Some(n), Some(b)) => n > b,
                        _ => false,
                    };
                    if !grew { break; }
                    best = new_end;
                    state.lr_memo_set(
                        key_kind,
                        pos,
                        ::mpl::fast::LrMemoEntry::InProgress { seed: best },
                    );
                }

                state.lr_memo_set(
                    key_kind,
                    pos,
                    ::mpl::fast::LrMemoEntry::Done { result: best },
                );
                best.map(Ok).unwrap_or(Err(()))
            }
        }
    }
}

/// Decide which fast path (if any) a rule gets:
/// 1. Squirrel seed-growing for directly left-recursive rules.
/// 2. Byte-table when the cascade is a true char class (≥ 4 bytes).
/// 3. First-byte dispatch when it's a multi-prefix cascade with a useful
///    char class somewhere in the alternatives.
/// 4. `loop {}` for `R = X R / ()` tail recursion.
/// 5. Otherwise the original cascade with `#[inline]`.
fn generate_rule(
    rule: &mpl::rules::Rule<&str, &str>,
    char_classes: &std::collections::HashMap<&str, BTreeSet<u8>>,
    dispatches: &std::collections::HashMap<&str, DispatchCascade<'_>>,
) -> TokenStream {
    if is_left_recursive(rule) {
        let body = generate_rule_body(rule);
        return generate_left_recursive(rule, body);
    }
    if let Some(bytes) = char_classes.get(rule.value) {
        if bytes.len() >= 4 {
            let body = generate_rule_body(rule);
            return generate_cascade_dispatcher(rule, bytes, body);
        }
    }
    if let Some(cascade) = dispatches.get(rule.value) {
        let body = generate_rule_body(rule);
        return generate_first_byte_dispatcher(rule, cascade, body);
    }
    if is_tail_loop(rule) {
        let body = generate_rule_body(rule);
        return generate_tail_loop(rule, body);
    }
    generate_rule_inner(rule)
}

pub fn generate_fast(parser_ident: &Ident, lines: &[MplgOutput]) -> TokenStream {
    let rules: Vec<&mpl::rules::Rule<&str, &str>> = lines
        .iter()
        .filter_map(|line| match line {
            MplgOutput::Rule(rule) => Some(rule),
            _ => None,
        })
        .collect();

    if rules.is_empty() {
        return quote! {};
    }

    // Each variable becomes a u32 id in declaration order. The first rule
    // is the start variable.
    let var_consts = rules.iter().enumerate().map(|(i, rule)| {
        let cid = const_ident(rule.value);
        let i = i as u32;
        quote! { pub const #cid: u32 = #i; }
    });

    // FIRST set fixed point: shared with Mizushima cut analysis below
    // and the first-byte dispatch detector above.
    let firsts = compute_first_sets(&rules);

    // Char-class cascade analysis: detect rules of the form
    // `A = X () / Y` where every X resolves to a single byte, and emit
    // a byte-table fast path for those. AST shape is preserved by
    // routing the EMIT=true path through the original cascade body.
    let char_classes = analyze_char_classes(&rules);

    // First-byte dispatch analysis: for cascades whose alternatives
    // have mostly disjoint FIRST sets but aren't pure single-byte (e.g.
    // `Atom = ExprInParens / FloatLiteral / IntegerLiteral / ...`).
    let dispatches = analyze_first_byte_dispatch(&rules, &firsts, &char_classes);

    let rule_fns = rules
        .iter()
        .map(|rule| generate_rule(rule, &char_classes, &dispatches));

    let start_fn = fn_ident(rules[0].value);

    // Mizushima cut analysis: classify each rule as LL(1)-equivalent
    // (FIRST sets disjoint, no memo needed) or backtracking (memo helpful).
    let classification = classify_rules(&rules, &firsts);

    let needs_memo_entries = classification.iter().map(|(_, needs)| {
        let v = *needs;
        quote! { #v }
    });
    let needs_memo_count = classification.len();

    let backtracking_count = classification.iter().filter(|(_, b)| *b).count();
    let analysis_summary = format!(
        "Mizushima cut analysis: {}/{} rules require memoisation",
        backtracking_count, needs_memo_count
    );

    let memo_rule_names: Vec<String> = classification
        .iter()
        .filter(|(_, b)| *b)
        .map(|(name, _)| name.clone())
        .collect();
    let memo_rule_list = if memo_rule_names.is_empty() {
        "(none)".to_string()
    } else {
        memo_rule_names.join(", ")
    };
    let needs_memo_doc = format!(
        "{}\n\nRules needing memoisation: {}",
        analysis_summary, memo_rule_list
    );

    let mod_ident = format_ident!("__{}_fast", snake(&parser_ident.to_string()));

    quote! {
        #[allow(non_snake_case, unused, clippy::all)]
        mod #mod_ident {
            use ::mpl::fast::ParserState;

            pub mod var {
                #(#var_consts)*
            }

            /// Mizushima cut analysis result, indexed by variable id.
            ///
            /// `false` ⇒ LL(1)-equivalent at the choice point; the rule
            /// will never re-evaluate at the same input position, so a
            /// future memoising backend can skip its cache slot.
            ///
            /// `true` ⇒ FIRST sets overlap (or both nullable); the rule
            /// is a candidate for packrat / Squirrel memoisation.
            #[doc = #needs_memo_doc]
            pub const NEEDS_MEMO: [bool; #needs_memo_count] = [#(#needs_memo_entries),*];

            #(#rule_fns)*

            /// Recognise + emit tokens, return only `bool`.
            pub fn recognize(input: &[u8]) -> bool {
                let mut state = ParserState::new(input);
                matches!(
                    #start_fn::<ParserState<'_>, true>(&mut state, 0),
                    Ok(end) if end as usize == input.len()
                )
            }

            /// Pure recognition over [`::mpl::fast::CheckState`], the thin
            /// state (input + furthest only). The recursive call chain
            /// holds the parser state in registers — matches `peg`'s
            /// `(__input, __pos) -> end_pos` calling convention.
            pub fn recognize_only(input: &[u8]) -> bool {
                let mut state = ::mpl::fast::CheckState::new(input);
                matches!(
                    #start_fn::<::mpl::fast::CheckState<'_>, false>(&mut state, 0),
                    Ok(end) if end as usize == input.len()
                )
            }

            pub fn parse(
                input: &[u8],
            ) -> ::core::result::Result<Vec<::mpl::fast::Token>, ::mpl::fast::ParseError> {
                let mut state = ParserState::new(input);
                use ::mpl::fast::ParseState as _;
                match #start_fn::<ParserState<'_>, true>(&mut state, 0) {
                    Ok(end) if end as usize == input.len() => Ok(state.tokens),
                    Ok(end) => Err(::mpl::fast::ParseError::at(end)),
                    Err(_) => Err(::mpl::fast::ParseError::at(state.furthest())),
                }
            }

            /// Recognition path that uses a caller-supplied bump arena —
            /// useful for memoising backends that store cache tables there.
            /// Token storage still uses `Vec` (faster on push-heavy paths).
            pub fn recognize_in(input: &[u8], arena: &::mpl::fast::bumpalo::Bump) -> bool {
                let mut state = ParserState::new_in(input, arena);
                matches!(
                    #start_fn::<ParserState<'_>, true>(&mut state, 0),
                    Ok(end) if end as usize == input.len()
                )
            }

            /// Variant of [`parse`] that returns a [`ParseError`](::mpl::fast::ParseError)
            /// pointing at the furthest input position any rule reached
            /// (the most informative location for diagnostics by PEG/TDPL
            /// convention) when recognition fails. Same fast path as
            /// [`recognize_only`] for the success determination.
            pub fn check(
                input: &[u8],
            ) -> ::core::result::Result<(), ::mpl::fast::ParseError> {
                let mut state = ::mpl::fast::CheckState::new(input);
                use ::mpl::fast::ParseState as _;
                match #start_fn::<::mpl::fast::CheckState<'_>, false>(&mut state, 0) {
                    Ok(end) if end as usize == input.len() => Ok(()),
                    Ok(end) => Err(::mpl::fast::ParseError::at(end)),
                    Err(_) => Err(::mpl::fast::ParseError::at(state.furthest())),
                }
            }
        }

        impl #parser_ident {
            /// Recognise the input via the static-codegen fast path.
            /// Builds the flat token buffer; equivalent to `pest`'s shape.
            pub fn fast_recognize(&self, input: &[u8]) -> bool {
                #mod_ident::recognize(input)
            }

            /// Pure recognition: no token buffer is allocated and no
            /// token writes are emitted (the EMIT=false instantiation
            /// of the per-rule fns elides them at compile time).
            /// Apples-to-apples with `peg`'s `Result<(), _>` return.
            pub fn fast_recognize_only(&self, input: &[u8]) -> bool {
                #mod_ident::recognize_only(input)
            }

            /// Parse the input, returning the flat token buffer on success
            /// or a [`ParseError`](::mpl::fast::ParseError) pointing at the
            /// furthest input position the parser reached.
            pub fn fast_parse(&self, input: &[u8])
                -> ::core::result::Result<Vec<::mpl::fast::Token>, ::mpl::fast::ParseError>
            {
                #mod_ident::parse(input)
            }

            /// Recognition with diagnostic. Same fast path as
            /// [`fast_recognize_only`] but returns a [`ParseError`](::mpl::fast::ParseError)
            /// pinpointing where matching got stuck.
            pub fn fast_check(&self, input: &[u8])
                -> ::core::result::Result<(), ::mpl::fast::ParseError>
            {
                #mod_ident::check(input)
            }

            /// Mizushima cut analysis: which rules require memoisation
            /// for correctness against backtracking re-evaluation.
            /// Indexed by variable id.
            pub const fn fast_needs_memo() -> &'static [bool] {
                &#mod_ident::NEEDS_MEMO
            }

            /// Recognition path that reuses an externally-supplied bumpalo
            /// arena. Call `arena.reset()` between parses to avoid
            /// per-call allocation.
            pub fn fast_recognize_in(
                &self,
                input: &[u8],
                arena: &::mpl::fast::bumpalo::Bump,
            ) -> bool {
                #mod_ident::recognize_in(input, arena)
            }
        }
    }
}