dsl-kit-parse 0.11.1

Parser trunk for dsl-kit DSLs (ParseTree, schema conformance, serde bridge, DslBuild consumer).
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
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
//! PEG grammar AST + recursive-descent interpreter (G-2).
//!
//! The [`Peg`] enum is the grammar AST. It derives `DslNode` + `DslSchema`
//! from the kit — grammars therefore get the L1-L4.6 toolchain for free
//! (walk traversal, schema JSON, lint, `variant_name`, MCP pretty-print)
//! per `parser-design §2`. Parse *execution* is a small dedicated
//! recursive-descent interpreter that walks a [`Grammar`] value against
//! input text and produces a [`ParseTree`] (crate root).
//!
//! # Quality bar (parser-design §3.5, non-negotiable)
//!
//! - **PEG semantics, exactly.** Ordered [`Peg::Choice`] commits on the
//!   first alternative that matches (no reparse of committed input);
//!   [`Peg::Repeat`] is greedy and never backtracks into completed
//!   iterations; a failed alternative restores the input position fully
//!   (no partial-consume leaks).
//! - **Farthest-failure tracking from day one.** The interpreter records
//!   the rightmost failure position + the expected set at that point *as
//!   it runs*. `dsl_kit_load` sees a diagnostic with position + expected
//!   set on failure.
//! - **Termination guarantees at runtime.** Left recursion (a rule
//!   re-entered at the same input position) and nullable-body
//!   [`Peg::Repeat`] (body succeeds without consuming) both trip
//!   guards that either error out (left recursion) or break the loop
//!   (nullable repeat) rather than hanging. G-3's `GrammarCheck` will
//!   catch these statically.
//!
//! # Capture model
//!
//! Three capture primitives:
//!
//! - [`Peg::Node`] `{ variant, body }` — opens a `ParseTree` scope with
//!   the given variant name. Inside `body`, every [`Peg::Field`] binding
//!   becomes a field or child slot on the tree. On success the tree is
//!   *contributed* upwards (to an enclosing Field, or to the top-level
//!   result at the root).
//! - [`Peg::Field`] `{ name, body }` — captures body's *productions*
//!   (raw text spans from [`Peg::Token`] + trees from [`Peg::Node`]) and
//!   binds them under `name` on the enclosing Node scope. Productions
//!   that are all text → one [`RawValue::Text`] field (joined). All
//!   trees → child slot with one or more subtrees. Mixed → tree
//!   productions win (raw text is dropped as syntactic noise from
//!   sub-Nodes' brackets etc.); empty → the Field silently no-ops.
//!   G-3's `GrammarCheck` will surface Mixed as a grammar bug.
//! - [`Peg::KeyedEntry`] `{ slot, key, value }` — one entry of a keyed
//!   child slot (`Multiplicity::Map`). `key` produces the entry's key
//!   text, `value` the entry's subtree, and the pair lands in
//!   [`ParseTree::keyed_children`] under `slot`. A separate primitive
//!   rather than a `Field` convention because a `Field` binds *one*
//!   name to its productions, which cannot express a name the input
//!   supplies; pairing adjacent text and tree productions inside a
//!   `Field` instead would make the capture depend on production
//!   order, which every backtracking path is free to disturb.
//!   [`Peg::Node`] sorts each keyed slot by key before emitting, so
//!   grammars need not care what order the source was written in —
//!   the canonical order [`ParseTree`] requires falls out.
//!
//! # Whitespace policy (parser-design §3.5, decided in G-2)
//!
//! **Implicit skip of `[ \t\r\n]*` before every [`Peg::Token`]** (except
//! the `%ws` class itself, which matches one-or-more whitespace
//! literally). No per-rule opt-out yet — deferred until a concrete
//! consumer demands it. Leading and trailing whitespace at the input
//! boundary are also skipped by [`Grammar::parse`].
//!
//! # Token pattern language
//!
//! [`Peg::Token`]'s `pat` string is either a literal or a class:
//!
//! - `%ident` — `[A-Za-z_][A-Za-z_0-9]*`
//! - `%int`   — `-?[0-9]+`
//! - `%str`   — a double-quoted string literal with `\"` `\\` `\n`
//!   `\t` `\r` escapes. Unlike every other token, the production it
//!   contributes is the **decoded inner content** (quotes stripped,
//!   escapes resolved), so a `Field` wrapping `%str` binds the string
//!   value directly.
//! - `%str_raw` — same matching rules as `%str`, but the production
//!   is the **raw source slice** (quotes and escape sequences kept
//!   verbatim). Field authors use this when downstream consumers need
//!   the JSON-compatible literal — typically the built-in
//!   `Vec<String>` mapping in `schema_gen`, which relies on
//!   `serde_json::from_str` in `build_field_vec` to reparse the
//!   captured `["a", "b"]` text.
//! - `%ws`    — `[ \t\r\n]+` (skip is disabled for this class)
//! - `%kw:<word>` — literal `<word>` with a word-boundary guard: the
//!   byte immediately after the match must not be a word char. This is
//!   how you write reserved words like `let` / `in` without swallowing
//!   the prefix of identifiers such as `letme`.
//! - anything else — plain literal match with no boundary guard. Use
//!   this for punctuation like `+`, `*`, `(`, `)`, `=`.

#![allow(clippy::result_unit_err)]

use crate::{BuildError, Diagnostic, ParseTree, RawValue, Span};
use dsl_kit_core::{NodeId, Suggester};
use dsl_kit_macros::{DslNode as DslNodeDerive, DslSchema as DslSchemaDerive};
use std::collections::{BTreeSet, HashMap};

// ---------------------------------------------------------------------------
// Peg AST
// ---------------------------------------------------------------------------

/// PEG grammar AST.
///
/// One value per primitive; the [`Grammar`] wrapper carries the flat
/// list of rules and the start-rule name.
#[derive(Debug, Clone, DslNodeDerive, DslSchemaDerive)]
pub enum Peg {
    /// Named rule definition. Top-level entries in
    /// [`Grammar::rules`] must be `Rule`s; nested `Rule` variants are
    /// legal but unusual and are treated as anonymous scopes by the
    /// interpreter (they run `body` and forward its productions).
    Rule {
        /// Stable node id.
        id: NodeId,
        /// Rule name (referenced by [`Peg::RuleRef`]).
        name: String,
        /// Rule body.
        body: Box<Peg>,
    },
    /// Sequence — every item must succeed in order.
    Seq {
        /// Stable node id.
        id: NodeId,
        /// Ordered sequence items.
        items: Vec<Peg>,
    },
    /// Ordered choice — first alternative that succeeds commits.
    Choice {
        /// Stable node id.
        id: NodeId,
        /// Alternatives, tried left to right.
        alts: Vec<Peg>,
    },
    /// Greedy repetition — runs `body` between `min` and `max` times.
    Repeat {
        /// Stable node id.
        id: NodeId,
        /// Repeated body.
        body: Box<Peg>,
        /// Minimum successful iterations (inclusive).
        min: u32,
        /// Maximum successful iterations (inclusive); `None` = unbounded.
        max: Option<u32>,
    },
    /// Reference to another rule by name.
    RuleRef {
        /// Stable node id.
        id: NodeId,
        /// Referenced rule name.
        name: String,
    },
    /// Terminal — matches a literal string or a small character class
    /// (see the module docs' token pattern language).
    Token {
        /// Stable node id.
        id: NodeId,
        /// Token pattern (literal or `%ident` / `%int` / `%str` /
        /// `%ws` / `%kw:<word>`).
        pat: String,
    },
    /// Opens a `ParseTree` capture scope with the given `variant` name.
    Node {
        /// Stable node id.
        id: NodeId,
        /// Variant name on the produced `ParseTree`.
        variant: String,
        /// Scope body.
        body: Box<Peg>,
    },
    /// Captures body's productions and binds them under `name` on the
    /// enclosing [`Peg::Node`] scope.
    Field {
        /// Stable node id.
        id: NodeId,
        /// Field or child-slot name on the enclosing Node.
        name: String,
        /// Capture body.
        body: Box<Peg>,
    },
    /// Captures one `key → subtree` entry of a keyed child slot
    /// ([`dsl_kit_schema::Multiplicity::Map`]) on the enclosing
    /// [`Peg::Node`] scope.
    ///
    /// `key` must produce text (typically `%str` or `%ident`) and
    /// `value` must produce exactly one tree (typically a `RuleRef`
    /// reaching a [`Peg::Node`]). Anything else is a grammar bug: the
    /// entry is dropped and the parse fails rather than contributing a
    /// half-formed pair, because a keyed entry missing its key has
    /// nowhere to go.
    KeyedEntry {
        /// Stable node id.
        id: NodeId,
        /// Keyed child-slot name on the enclosing Node.
        slot: String,
        /// Production for the entry's key.
        key: Box<Peg>,
        /// Production for the entry's subtree.
        value: Box<Peg>,
    },
}

// ---------------------------------------------------------------------------
// Grammar wrapper
// ---------------------------------------------------------------------------

/// A PEG grammar: a flat list of top-level [`Peg::Rule`]s plus the name
/// of the start rule.
///
/// Kept as a plain wrapper struct deriving nothing so the `Peg` enum
/// stays clean (parser-design §3.4).
#[derive(Debug, Clone)]
pub struct Grammar {
    /// Top-level rules. Every element should be a [`Peg::Rule`]
    /// variant — the interpreter looks up rules by name against this
    /// list.
    pub rules: Vec<Peg>,
    /// Name of the start rule.
    pub start: String,
}

impl Grammar {
    /// Constructs a new [`Grammar`].
    pub fn new(rules: Vec<Peg>, start: impl Into<String>) -> Self {
        Self {
            rules,
            start: start.into(),
        }
    }

    /// Parses `input` against this grammar.
    ///
    /// On success returns a single top-level [`ParseTree`] (produced by
    /// exactly one [`Peg::Node`] reached from the start rule).
    ///
    /// On failure returns a [`BuildError`] whose diagnostics carry the
    /// farthest-failure position + expected set, formatted in the shared
    /// dialect (`{ severity, code, message, location }`).
    pub fn parse(&self, input: &str) -> Result<ParseTree, BuildError> {
        let mut rules_by_name: HashMap<&str, &Peg> = HashMap::new();
        for r in &self.rules {
            if let Peg::Rule { name, .. } = r {
                rules_by_name.insert(name.as_str(), r);
            }
        }
        let start_rule = rules_by_name
            .get(self.start.as_str())
            .copied()
            .ok_or_else(|| {
                let names: Vec<&str> = rules_by_name.keys().copied().collect();
                let base = format!("start rule `{}` is not defined in the grammar", self.start);
                let msg = match crate::BuiltinLevenshteinSuggester
                    .enrich_unknown(self.start.as_str(), &names)
                {
                    Some(hint) => format!("{base} ({hint})"),
                    None => base,
                };
                BuildError::single(Diagnostic::error(codes::UNKNOWN_RULE, msg))
            })?;

        let mut interp = Interpreter::new(input, rules_by_name);
        // Skip leading whitespace at the input boundary.
        interp.skip_ws();
        // Push the top-level sink.
        interp.sink_stack.push(ActiveSink::Top(TopSink::default()));

        match interp.run_peg(start_rule) {
            Ok(()) => {}
            Err(()) => {
                if let Some(fatal) = interp.fatal_error.take() {
                    return Err(BuildError::single(fatal));
                }
                return Err(BuildError::single(interp.expected_diagnostic()));
            }
        }

        // Trailing whitespace + EOF check.
        interp.skip_ws();
        if interp.pos != input.len() {
            // Try to attribute to the farthest expected set if we have
            // one at/after this position; otherwise raw "trailing input".
            let diag = if interp.farthest_pos >= interp.pos && !interp.farthest_expected.is_empty()
            {
                interp.expected_diagnostic()
            } else {
                Diagnostic::error(
                    codes::UNEXPECTED,
                    format!("unexpected trailing input at byte {}", interp.pos),
                )
                .with_span(Some(Span::new(interp.pos, input.len())))
            };
            return Err(BuildError::single(diag));
        }

        let top = match interp.sink_stack.pop() {
            Some(ActiveSink::Top(t)) => t,
            _ => unreachable!("top sink must be present"),
        };
        let tree = top.tree.ok_or_else(|| {
            BuildError::single(Diagnostic::error(
                codes::NO_TOP_TREE,
                format!(
                    "parse succeeded but produced no top-level `Node`; \
                     start rule `{}` must reach exactly one `Peg::Node`",
                    self.start
                ),
            ))
        })?;
        // Reserved `@allow` wrappers are surface syntax, not tree
        // shape: fold them onto the nodes they annotate before anyone
        // downstream can see one. Unconditional because a grammar
        // without `crate::allow::add_allow_syntax` cannot produce a
        // wrapper, which makes this a plain walk over the result.
        crate::allow::collapse(tree)
    }
}

// ---------------------------------------------------------------------------
// Diagnostic codes
// ---------------------------------------------------------------------------

/// Diagnostic codes emitted by the PEG interpreter.
pub mod codes {
    /// Input did not match at the farthest failure position; message
    /// carries the expected set.
    pub const UNEXPECTED: &str = "dsl_kit::parse::peg::unexpected";
    /// [`super::Peg::RuleRef`] pointed to a rule name not present in
    /// [`super::Grammar::rules`], or [`super::Grammar::start`] itself is
    /// unresolved.
    pub const UNKNOWN_RULE: &str = "dsl_kit::parse::peg::unknown_rule";
    /// A rule was re-entered at the same input position without any
    /// progress — indicates left recursion. G-3's `GrammarCheck` will
    /// catch this statically; the runtime guard is a backstop that
    /// errors out rather than hanging.
    pub const LEFT_RECURSION: &str = "dsl_kit::parse::peg::left_recursion";
    /// A [`super::Peg::Repeat`] iteration succeeded without consuming
    /// input. The interpreter breaks the loop (per §3.5 termination
    /// guarantee); this diagnostic is attached when the `min` bound is
    /// also not yet met, turning the situation into a hard failure.
    pub const NULLABLE_REPEAT: &str = "dsl_kit::parse::peg::nullable_repeat";
    /// Parse succeeded but the start rule never reached a
    /// [`super::Peg::Node`], so there is no top-level `ParseTree`.
    pub const NO_TOP_TREE: &str = "dsl_kit::parse::peg::no_top_tree";
}

// ---------------------------------------------------------------------------
// Interpreter
// ---------------------------------------------------------------------------

/// A raw production captured inside a [`FieldSink`]. Text comes from
/// [`Peg::Token`] matches, trees from [`Peg::Node`] captures. The span
/// on `Text` is retained for future span-carrying `RawValue::Text`
/// support (post-G-2).
#[derive(Debug, Clone)]
enum Production {
    #[allow(dead_code)] // span kept for post-G-2 span-carrying Text values
    Text(String, Span),
    Tree(ParseTree),
}

#[derive(Debug, Default, Clone)]
struct FieldSink {
    productions: Vec<Production>,
}

#[derive(Debug, Default, Clone)]
struct NodeSink {
    fields: Vec<(String, RawValue)>,
    children: Vec<(String, Vec<ParseTree>)>,
    keyed_children: Vec<(String, Vec<(String, ParseTree)>)>,
}

#[derive(Debug, Default, Clone)]
struct TopSink {
    tree: Option<ParseTree>,
}

/// The active-sink stack entry. Only the top sink is ever mutated by
/// productions.
#[derive(Debug, Clone)]
enum ActiveSink {
    Top(TopSink),
    Node(NodeSink),
    Field(FieldSink),
}

struct Interpreter<'g, 'i> {
    input: &'i str,
    pos: usize,
    rules_by_name: HashMap<&'g str, &'g Peg>,
    sink_stack: Vec<ActiveSink>,
    // Farthest-failure tracking (parser-design §3.5).
    farthest_pos: usize,
    farthest_expected: BTreeSet<String>,
    // Left-recursion guard: (rule name, position at entry).
    call_stack: Vec<(&'g str, usize)>,
    // Fatal errors (unknown rule / left recursion) — trip Err(()) and
    // short-circuit past normal recovery.
    fatal_error: Option<Diagnostic>,
}

impl<'g, 'i> Interpreter<'g, 'i> {
    fn new(input: &'i str, rules_by_name: HashMap<&'g str, &'g Peg>) -> Self {
        Self {
            input,
            pos: 0,
            rules_by_name,
            sink_stack: Vec::new(),
            farthest_pos: 0,
            farthest_expected: BTreeSet::new(),
            call_stack: Vec::new(),
            fatal_error: None,
        }
    }

    // -----------------------------------------------------------------------
    // Sink helpers
    // -----------------------------------------------------------------------

    fn top_sink_snapshot(&self) -> ActiveSink {
        self.sink_stack
            .last()
            .cloned()
            .expect("sink stack has at least the top-level entry during parse")
    }

    fn restore_top_sink(&mut self, snap: ActiveSink) {
        let last = self
            .sink_stack
            .last_mut()
            .expect("sink stack has at least the top-level entry during parse");
        *last = snap;
    }

    fn contribute_text(&mut self, text: String, span: Span) {
        match self.sink_stack.last_mut() {
            Some(ActiveSink::Field(s)) => s.productions.push(Production::Text(text, span)),
            _ => {
                // Discard — Token outside a Field is syntactic (like "+" or "let").
            }
        }
    }

    fn contribute_tree(&mut self, tree: ParseTree) {
        match self.sink_stack.last_mut() {
            Some(ActiveSink::Field(s)) => s.productions.push(Production::Tree(tree)),
            Some(ActiveSink::Node(_)) => {
                // Nested Node not wrapped in Field — silently discarded
                // at runtime. G-3's GrammarCheck should flag such
                // grammars as author bugs.
            }
            Some(ActiveSink::Top(t)) => {
                // Top-level result: latest wins (there should be exactly
                // one; a subsequent one is unusual but harmless).
                t.tree = Some(tree);
            }
            None => unreachable!("sink stack must not be empty during parse"),
        }
    }

    fn contribute_field(&mut self, name: &str, productions: Vec<Production>) {
        if productions.is_empty() {
            return;
        }
        let all_text = productions
            .iter()
            .all(|p| matches!(p, Production::Text(..)));
        let all_tree = productions
            .iter()
            .all(|p| matches!(p, Production::Tree(..)));

        let Some(ActiveSink::Node(node_sink)) = self.sink_stack.last_mut() else {
            // Field outside a Node — silently ignored at runtime.
            return;
        };

        if all_text {
            let joined: String = productions
                .iter()
                .filter_map(|p| match p {
                    Production::Text(t, _) => Some(t.as_str()),
                    _ => None,
                })
                .collect();
            node_sink
                .fields
                .push((name.to_string(), RawValue::Text(joined)));
            return;
        }
        if all_tree {
            let trees: Vec<ParseTree> = productions
                .into_iter()
                .filter_map(|p| match p {
                    Production::Tree(t) => Some(t),
                    _ => None,
                })
                .collect();
            if let Some(slot) = node_sink.children.iter_mut().find(|(n, _)| n == name) {
                slot.1.extend(trees);
            } else {
                node_sink.children.push((name.to_string(), trees));
            }
            return;
        }
        // Mixed: keep tree productions, drop texts (grammar bug — G-3
        // GrammarCheck will flag).
        let trees: Vec<ParseTree> = productions
            .into_iter()
            .filter_map(|p| match p {
                Production::Tree(t) => Some(t),
                _ => None,
            })
            .collect();
        if trees.is_empty() {
            return;
        }
        if let Some(slot) = node_sink.children.iter_mut().find(|(n, _)| n == name) {
            slot.1.extend(trees);
        } else {
            node_sink.children.push((name.to_string(), trees));
        }
    }

    // -----------------------------------------------------------------------
    // Farthest-failure helpers
    // -----------------------------------------------------------------------

    fn expected(&mut self, what: impl Into<String>) {
        if self.pos > self.farthest_pos {
            self.farthest_pos = self.pos;
            self.farthest_expected.clear();
            self.farthest_expected.insert(what.into());
        } else if self.pos == self.farthest_pos {
            self.farthest_expected.insert(what.into());
        }
    }

    fn expected_diagnostic(&self) -> Diagnostic {
        let expected: Vec<String> = self.farthest_expected.iter().cloned().collect();
        let expected_msg = if expected.is_empty() {
            "<unknown>".to_string()
        } else {
            expected
                .iter()
                .map(|e| format!("`{e}`"))
                .collect::<Vec<_>>()
                .join(" | ")
        };
        let end = self.input.len().min(self.farthest_pos + 1);
        let got_msg = if self.farthest_pos >= self.input.len() {
            "end of input".to_string()
        } else {
            let bytes = self.input.as_bytes();
            // Grab a small snippet — up to 8 bytes — to help the reader.
            let snip_end = self.input.len().min(self.farthest_pos + 8);
            let snip =
                std::str::from_utf8(&bytes[self.farthest_pos..snip_end]).unwrap_or("<non-utf8>");
            format!("`{}`", snip)
        };
        Diagnostic::error(
            codes::UNEXPECTED,
            format!(
                "expected {expected_msg} at byte {}, got {got_msg}",
                self.farthest_pos
            ),
        )
        .with_span(Some(Span::new(self.farthest_pos, end)))
    }

    // -----------------------------------------------------------------------
    // PEG dispatch
    // -----------------------------------------------------------------------

    fn run_peg(&mut self, peg: &'g Peg) -> Result<(), ()> {
        match peg {
            Peg::Rule { body, .. } => self.run_peg(body),
            Peg::Seq { items, .. } => {
                for item in items {
                    self.run_peg(item)?;
                }
                Ok(())
            }
            Peg::Choice { alts, .. } => self.run_choice(alts),
            Peg::Repeat { body, min, max, .. } => self.run_repeat(body, *min, *max),
            Peg::RuleRef { name, .. } => self.run_rule_ref(name),
            Peg::Token { pat, .. } => self.match_token(pat),
            Peg::Node { variant, body, .. } => self.run_node(variant, body),
            Peg::Field { name, body, .. } => self.run_field(name, body),
            Peg::KeyedEntry {
                slot, key, value, ..
            } => self.run_keyed_entry(slot, key, value),
        }
    }

    fn run_choice(&mut self, alts: &'g [Peg]) -> Result<(), ()> {
        let start_pos = self.pos;
        let saved = self.top_sink_snapshot();
        for alt in alts {
            self.pos = start_pos;
            self.restore_top_sink(saved.clone());
            if self.fatal_error.is_some() {
                return Err(());
            }
            if self.run_peg(alt).is_ok() {
                return Ok(());
            }
            if self.fatal_error.is_some() {
                return Err(());
            }
        }
        self.pos = start_pos;
        self.restore_top_sink(saved);
        Err(())
    }

    fn run_repeat(&mut self, body: &'g Peg, min: u32, max: Option<u32>) -> Result<(), ()> {
        let mut count: u32 = 0;
        loop {
            if let Some(mx) = max
                && count >= mx
            {
                break;
            }
            let saved_pos = self.pos;
            let saved_sink = self.top_sink_snapshot();
            match self.run_peg(body) {
                Ok(()) => {
                    if self.pos == saved_pos {
                        // Nullable-body iteration — break rather than
                        // hang. GrammarCheck should reject grammars that
                        // permit this, so the interpreter's job is
                        // termination, not diagnosis.
                        if count < min {
                            self.fatal_error = Some(
                                Diagnostic::error(
                                    codes::NULLABLE_REPEAT,
                                    "repeat body succeeded without consuming input".to_string(),
                                )
                                .with_span(Some(Span::new(saved_pos, saved_pos))),
                            );
                            return Err(());
                        }
                        break;
                    }
                    count += 1;
                }
                Err(()) => {
                    if self.fatal_error.is_some() {
                        return Err(());
                    }
                    self.pos = saved_pos;
                    self.restore_top_sink(saved_sink);
                    break;
                }
            }
        }
        if count < min { Err(()) } else { Ok(()) }
    }

    fn run_rule_ref(&mut self, name: &str) -> Result<(), ()> {
        let Some(&rule) = self.rules_by_name.get(name) else {
            let candidates: Vec<&str> = self.rules_by_name.keys().copied().collect();
            let base = format!("reference to undefined rule `{name}`");
            let msg = match crate::BuiltinLevenshteinSuggester.enrich_unknown(name, &candidates) {
                Some(hint) => format!("{base} ({hint})"),
                None => base,
            };
            self.fatal_error = Some(
                Diagnostic::error(codes::UNKNOWN_RULE, msg)
                    .with_span(Some(Span::new(self.pos, self.pos))),
            );
            return Err(());
        };
        // Look up by pointer so we keep the &'g lifetime attached.
        let rule_name: &'g str = self
            .rules_by_name
            .keys()
            .copied()
            .find(|k| *k == name)
            .expect("just found");
        // Left-recursion guard: rule re-entered at the same position
        // without any progress.
        if self
            .call_stack
            .iter()
            .any(|(n, p)| *n == rule_name && *p == self.pos)
        {
            self.fatal_error = Some(
                Diagnostic::error(
                    codes::LEFT_RECURSION,
                    format!(
                        "left recursion detected: rule `{name}` re-entered at byte {}",
                        self.pos
                    ),
                )
                .with_span(Some(Span::new(self.pos, self.pos))),
            );
            return Err(());
        }
        self.call_stack.push((rule_name, self.pos));
        let r = self.run_peg(rule);
        self.call_stack.pop();
        r
    }

    fn run_node(&mut self, variant: &str, body: &'g Peg) -> Result<(), ()> {
        let start_pos = self.pos;
        self.sink_stack.push(ActiveSink::Node(NodeSink::default()));
        let body_result = self.run_peg(body);
        let node_sink = match self.sink_stack.pop() {
            Some(ActiveSink::Node(s)) => s,
            _ => unreachable!("balanced push/pop of NodeSink"),
        };
        body_result?;
        let end_pos = self.pos;
        // Keyed entries arrive in source order; `ParseTree` requires
        // ascending key order, and `check_conformance` enforces it.
        // Sorting here — rather than asking every grammar author to
        // write their maps pre-sorted — is what makes source order a
        // surface detail, exactly as it is for the JSON bridge.
        let mut keyed_children = node_sink.keyed_children;
        for (_, entries) in &mut keyed_children {
            entries.sort_by(|(a, _), (b, _)| a.cmp(b));
        }

        let tree = ParseTree {
            variant: variant.to_string(),
            fields: node_sink.fields,
            children: node_sink.children,
            keyed_children,
            allows: Vec::new(),
            span: Some(Span::new(start_pos, end_pos)),
        };
        self.contribute_tree(tree);
        Ok(())
    }

    fn run_field(&mut self, name: &str, body: &'g Peg) -> Result<(), ()> {
        self.sink_stack
            .push(ActiveSink::Field(FieldSink::default()));
        let body_result = self.run_peg(body);
        let field_sink = match self.sink_stack.pop() {
            Some(ActiveSink::Field(s)) => s,
            _ => unreachable!("balanced push/pop of FieldSink"),
        };
        body_result?;
        self.contribute_field(name, field_sink.productions);
        Ok(())
    }

    /// Runs one keyed entry: `key` into its own sink, then `value` into
    /// another, then pairs them onto the enclosing Node's keyed half.
    ///
    /// The two halves are captured separately rather than in one sink
    /// because a single `FieldSink` would leave "which production was
    /// the key" to positional luck. Failure of either half fails the
    /// entry: a pair missing its key cannot be stored, and storing the
    /// value under a fabricated key would invent data.
    fn run_keyed_entry(&mut self, slot: &str, key: &'g Peg, value: &'g Peg) -> Result<(), ()> {
        let key_text = {
            self.sink_stack
                .push(ActiveSink::Field(FieldSink::default()));
            let result = self.run_peg(key);
            let sink = match self.sink_stack.pop() {
                Some(ActiveSink::Field(s)) => s,
                _ => unreachable!("balanced push/pop of FieldSink"),
            };
            result?;
            // A key half that matched without producing anything is a
            // grammar bug (typically a nullable key production). Every
            // such entry would key on the empty string and collide
            // with its siblings, so fail instead — this is the check
            // the `is_empty()` guard exists for. A production that is
            // *present* but empty (`""` via `%str`) is a different
            // thing: it is a key the AST and the JSON front-end can
            // both hold, so the text syntax accepts it too.
            if sink.productions.is_empty() {
                self.expected("a text production for the keyed-entry key");
                return Err(());
            }
            let mut text = String::new();
            for production in &sink.productions {
                match production {
                    Production::Text(t, _) => text.push_str(t),
                    // A tree where the key belongs is a grammar bug of
                    // the same family — there is no text to key on.
                    Production::Tree(_) => {
                        self.expected("a text production for the keyed-entry key");
                        return Err(());
                    }
                }
            }
            text
        };

        self.sink_stack
            .push(ActiveSink::Field(FieldSink::default()));
        let value_result = self.run_peg(value);
        let value_sink = match self.sink_stack.pop() {
            Some(ActiveSink::Field(s)) => s,
            _ => unreachable!("balanced push/pop of FieldSink"),
        };
        value_result?;

        let mut trees = value_sink.productions.into_iter().filter_map(|p| match p {
            Production::Tree(t) => Some(t),
            // Syntactic noise from the value's own brackets, dropped
            // the same way `contribute_field`'s mixed arm drops it.
            Production::Text(..) => None,
        });
        let Some(tree) = trees.next() else {
            self.expected("a subtree production for the keyed-entry value");
            return Err(());
        };
        if trees.next().is_some() {
            self.expected("exactly one subtree for the keyed-entry value");
            return Err(());
        }

        let Some(ActiveSink::Node(node_sink)) = self.sink_stack.last_mut() else {
            // KeyedEntry outside a Node — silently ignored at runtime,
            // matching `contribute_field`'s handling of the same
            // grammar bug.
            return Ok(());
        };
        if let Some(existing) = node_sink.keyed_children.iter_mut().find(|(n, _)| n == slot) {
            existing.1.push((key_text, tree));
        } else {
            node_sink
                .keyed_children
                .push((slot.to_string(), vec![(key_text, tree)]));
        }
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Token matching
    // -----------------------------------------------------------------------

    fn match_token(&mut self, pat: &str) -> Result<(), ()> {
        if pat != "%ws" {
            self.skip_ws();
        }
        let start = self.pos;
        if pat == "%str" {
            // Special-cased because the contributed production is the
            // decoded inner content, not the matched source slice.
            return match self.match_str() {
                Some(decoded) => {
                    let end = self.pos;
                    self.contribute_text(decoded, Span::new(start, end));
                    Ok(())
                }
                None => {
                    self.expected(pat);
                    self.pos = start;
                    Err(())
                }
            };
        }
        if pat == "%str_raw" {
            // Same match as %str, but the contributed production is the
            // raw source slice (quotes + escape sequences preserved).
            // Used by the built-in `Vec<String>` production so the
            // captured field text is JSON-parseable directly.
            return match self.match_str() {
                Some(_) => {
                    let end = self.pos;
                    let text = self.input[start..end].to_string();
                    self.contribute_text(text, Span::new(start, end));
                    Ok(())
                }
                None => {
                    self.expected(pat);
                    self.pos = start;
                    Err(())
                }
            };
        }
        let ok = if pat == "%ident" {
            self.match_ident()
        } else if pat == "%int" {
            self.match_int()
        } else if pat == "%ws" {
            self.match_ws_required()
        } else if let Some(word) = pat.strip_prefix("%kw:") {
            self.match_keyword(word)
        } else {
            self.match_literal(pat)
        };
        if ok {
            let end = self.pos;
            let text = self.input[start..end].to_string();
            self.contribute_text(text, Span::new(start, end));
            Ok(())
        } else {
            // Restore pos (in case skip_ws advanced but match failed —
            // farthest-failure position is the *post-skip* position,
            // which is the semantic failure spot).
            self.expected(pat);
            self.pos = start;
            Err(())
        }
    }

    fn skip_ws(&mut self) {
        let bytes = self.input.as_bytes();
        while let Some(&c) = bytes.get(self.pos) {
            if matches!(c, b' ' | b'\t' | b'\n' | b'\r') {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn match_ident(&mut self) -> bool {
        let bytes = self.input.as_bytes();
        match bytes.get(self.pos) {
            Some(&c) if is_ident_start(c) => self.pos += 1,
            _ => return false,
        }
        while let Some(&c) = bytes.get(self.pos) {
            if is_ident_cont(c) {
                self.pos += 1;
            } else {
                break;
            }
        }
        true
    }

    fn match_int(&mut self) -> bool {
        let bytes = self.input.as_bytes();
        let mut p = self.pos;
        if bytes.get(p) == Some(&b'-') {
            p += 1;
        }
        let digit_start = p;
        while let Some(&c) = bytes.get(p) {
            if c.is_ascii_digit() {
                p += 1;
            } else {
                break;
            }
        }
        if p > digit_start {
            self.pos = p;
            true
        } else {
            false
        }
    }

    /// Matches a double-quoted string literal and returns the decoded
    /// inner content. `None` on no opening quote, an unterminated
    /// literal, or an unknown escape.
    fn match_str(&mut self) -> Option<String> {
        let rest = &self.input[self.pos..];
        let mut chars = rest.char_indices();
        match chars.next() {
            Some((_, '"')) => {}
            _ => return None,
        }
        let mut out = String::new();
        while let Some((i, c)) = chars.next() {
            match c {
                '"' => {
                    self.pos += i + 1;
                    return Some(out);
                }
                '\\' => match chars.next() {
                    Some((_, '"')) => out.push('"'),
                    Some((_, '\\')) => out.push('\\'),
                    Some((_, 'n')) => out.push('\n'),
                    Some((_, 't')) => out.push('\t'),
                    Some((_, 'r')) => out.push('\r'),
                    _ => return None,
                },
                other => out.push(other),
            }
        }
        None
    }

    fn match_ws_required(&mut self) -> bool {
        let start = self.pos;
        let bytes = self.input.as_bytes();
        while let Some(&c) = bytes.get(self.pos) {
            if matches!(c, b' ' | b'\t' | b'\n' | b'\r') {
                self.pos += 1;
            } else {
                break;
            }
        }
        self.pos > start
    }

    fn match_literal(&mut self, s: &str) -> bool {
        let bytes = self.input.as_bytes();
        let end = self.pos + s.len();
        if end > bytes.len() {
            return false;
        }
        if &bytes[self.pos..end] != s.as_bytes() {
            return false;
        }
        self.pos = end;
        true
    }

    fn match_keyword(&mut self, word: &str) -> bool {
        let saved = self.pos;
        if !self.match_literal(word) {
            return false;
        }
        // Word-boundary guard: the byte after must not be a word char.
        if let Some(&next) = self.input.as_bytes().get(self.pos)
            && is_ident_cont(next)
        {
            self.pos = saved;
            return false;
        }
        true
    }
}

fn is_ident_start(c: u8) -> bool {
    c.is_ascii_alphabetic() || c == b'_'
}

fn is_ident_cont(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_'
}

// ---------------------------------------------------------------------------
// Convenience constructors (grammar authors build Peg values by hand
// until G-4's meta-grammar; these helpers cut boilerplate).
// ---------------------------------------------------------------------------

use dsl_kit_core::IdGen;

/// Builds a [`Peg::Rule`] node with a fresh id.
pub fn rule(ids: &IdGen, name: impl Into<String>, body: Peg) -> Peg {
    Peg::Rule {
        id: ids.node(),
        name: name.into(),
        body: Box::new(body),
    }
}

/// Builds a [`Peg::Seq`] node with a fresh id.
pub fn seq(ids: &IdGen, items: Vec<Peg>) -> Peg {
    Peg::Seq {
        id: ids.node(),
        items,
    }
}

/// Builds a [`Peg::Choice`] node with a fresh id.
pub fn choice(ids: &IdGen, alts: Vec<Peg>) -> Peg {
    Peg::Choice {
        id: ids.node(),
        alts,
    }
}

/// Builds a [`Peg::Repeat`] node with a fresh id.
pub fn repeat(ids: &IdGen, body: Peg, min: u32, max: Option<u32>) -> Peg {
    Peg::Repeat {
        id: ids.node(),
        body: Box::new(body),
        min,
        max,
    }
}

/// Builds a [`Peg::RuleRef`] node with a fresh id.
pub fn rule_ref(ids: &IdGen, name: impl Into<String>) -> Peg {
    Peg::RuleRef {
        id: ids.node(),
        name: name.into(),
    }
}

/// Builds a [`Peg::Token`] node with a fresh id.
pub fn token(ids: &IdGen, pat: impl Into<String>) -> Peg {
    Peg::Token {
        id: ids.node(),
        pat: pat.into(),
    }
}

/// Builds a [`Peg::Node`] capture node with a fresh id.
pub fn node(ids: &IdGen, variant: impl Into<String>, body: Peg) -> Peg {
    Peg::Node {
        id: ids.node(),
        variant: variant.into(),
        body: Box::new(body),
    }
}

/// Builds a [`Peg::Field`] capture node with a fresh id.
pub fn field(ids: &IdGen, name: impl Into<String>, body: Peg) -> Peg {
    Peg::Field {
        id: ids.node(),
        name: name.into(),
        body: Box::new(body),
    }
}

/// Builds a [`Peg::KeyedEntry`] capture node with a fresh id.
///
/// `key` should produce text (e.g. `token(ids, "%str")`) and `value`
/// exactly one subtree (e.g. `rule_ref(ids, "node")`).
pub fn keyed_entry(ids: &IdGen, slot: impl Into<String>, key: Peg, value: Peg) -> Peg {
    Peg::KeyedEntry {
        id: ids.node(),
        slot: slot.into(),
        key: Box::new(key),
        value: Box::new(value),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use dsl_kit_core::IdGen;
    use dsl_kit_schema::DslSchema;

    // -- schema shape --

    #[test]
    fn peg_schema_lists_all_variants() {
        let s = Peg::schema();
        assert_eq!(s.name, "Peg");
        let names: Vec<&str> = s.variants.iter().map(|v| v.name.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "Rule",
                "Seq",
                "Choice",
                "Repeat",
                "RuleRef",
                "Token",
                "Node",
                "Field",
                "KeyedEntry"
            ]
        );
        // `KeyedEntry`'s two `Box<Peg>` halves are both child slots;
        // `slot` is the only payload field. Pins the derive's view of
        // the newest variant alongside the older `Repeat` check below.
        let keyed = s.variant("KeyedEntry").unwrap();
        let keyed_children: Vec<&str> = keyed.children.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(keyed_children, vec!["key", "value"]);
        let keyed_fields: Vec<&str> = keyed.fields.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(keyed_fields, vec!["slot"]);

        let repeat = s.variant("Repeat").unwrap();
        // body -> one child; min / max -> fields.
        assert_eq!(repeat.children.len(), 1);
        assert_eq!(repeat.children[0].name, "body");
        let field_names: Vec<&str> = repeat.fields.iter().map(|f| f.name.as_str()).collect();
        assert!(field_names.contains(&"min"));
        assert!(field_names.contains(&"max"));
    }

    // -- Token matching --

    fn parse_one(g: &Grammar, input: &str) -> Result<ParseTree, BuildError> {
        g.parse(input)
    }

    fn one_rule_grammar(ids: &IdGen, start: &str, body: Peg) -> Grammar {
        Grammar::new(vec![rule(ids, start, body)], start)
    }

    // -- KeyedEntry primitive (hand-built grammars) --
    //
    // The generated grammars in `schema_gen` only ever build keyed
    // entries in one shape, so the primitive's own contract — what it
    // does with a malformed key half, a value half that yields the
    // wrong number of trees, or an entry outside a Node — is only
    // reachable from grammars written by hand, as below.

    /// `{ key: <leaf> ... }`-style grammar over a single keyed slot,
    /// with the key production supplied by the caller so the failure
    /// branches can be driven individually.
    fn keyed_grammar(ids: &IdGen, key: Peg, value: Peg) -> Grammar {
        let entry = keyed_entry(ids, "entries", key, value);
        one_rule_grammar(
            ids,
            "start",
            node(
                ids,
                "Env",
                seq(
                    ids,
                    vec![
                        token(ids, "{"),
                        repeat(
                            ids,
                            seq(ids, vec![entry, repeat(ids, token(ids, ","), 0, Some(1))]),
                            0,
                            None,
                        ),
                        token(ids, "}"),
                    ],
                ),
            ),
        )
    }

    /// A leaf value production: `: Lit(<int>)` wrapped in its own Node.
    fn keyed_leaf_value(ids: &IdGen) -> Peg {
        seq(
            ids,
            vec![
                token(ids, ":"),
                node(ids, "Lit", field(ids, "value", token(ids, "%int"))),
            ],
        )
    }

    #[test]
    fn keyed_entry_pairs_key_with_subtree_and_sorts() {
        let ids = IdGen::new();
        let g = keyed_grammar(&ids, token(&ids, "%ident"), keyed_leaf_value(&ids));
        let tree = parse_one(&g, "{ b: 2, a: 1 }").unwrap();
        let entries = tree.keyed_child_slot("entries").expect("slot bound");
        let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
        assert_eq!(keys, ["a", "b"], "Node emission sorts by key");
        // Values travelled with their own keys, not just in order.
        let values: Vec<&RawValue> = entries
            .iter()
            .map(|(_, t)| t.field("value").expect("leaf payload"))
            .collect();
        assert_eq!(values[0], &RawValue::Text("1".into()));
        assert_eq!(values[1], &RawValue::Text("2".into()));
    }

    #[test]
    fn keyed_entry_accepts_an_empty_string_key() {
        let ids = IdGen::new();
        // `""` is a key the AST and the JSON bridge can both hold, so
        // the text side accepts it rather than leaving a `BTreeMap`
        // value with no spelling.
        let g = keyed_grammar(&ids, token(&ids, "%str"), keyed_leaf_value(&ids));
        let tree = parse_one(&g, r#"{ "": 1 }"#).unwrap();
        let entries = tree.keyed_child_slot("entries").expect("slot bound");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].0, "");
    }

    #[test]
    fn keyed_entry_rejects_a_key_half_that_produces_nothing() {
        let ids = IdGen::new();
        // A nullable key half — here an optional identifier that is
        // absent — succeeds while contributing no production, so there
        // is no text to key on. Every such entry would land on `""`
        // and collide with its siblings, which is what separates this
        // case from a genuinely empty `""` key (accepted above).
        let g = keyed_grammar(
            &ids,
            repeat(&ids, token(&ids, "%ident"), 0, Some(1)),
            keyed_leaf_value(&ids),
        );
        let err = parse_one(&g, "{ : 1 }").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);
    }

    #[test]
    fn keyed_entry_rejects_a_tree_where_the_key_belongs() {
        let ids = IdGen::new();
        let g = keyed_grammar(
            &ids,
            node(&ids, "Lit", field(&ids, "value", token(&ids, "%int"))),
            keyed_leaf_value(&ids),
        );
        let err = parse_one(&g, "{ 1: 2 }").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);
    }

    #[test]
    fn keyed_entry_rejects_a_value_half_without_exactly_one_tree() {
        let ids = IdGen::new();

        // Zero trees: the value is a bare token, so nothing to store.
        let none = keyed_grammar(
            &ids,
            token(&ids, "%ident"),
            seq(&ids, vec![token(&ids, ":"), token(&ids, "%int")]),
        );
        assert!(parse_one(&none, "{ a: 1 }").is_err());

        // Two trees: ambiguous — which one is the entry's value?
        let leaf = |ids: &IdGen| node(ids, "Lit", field(ids, "value", token(ids, "%int")));
        let two = keyed_grammar(
            &ids,
            token(&ids, "%ident"),
            seq(&ids, vec![token(&ids, ":"), leaf(&ids), leaf(&ids)]),
        );
        assert!(parse_one(&two, "{ a: 1 2 }").is_err());
    }

    #[test]
    fn keyed_entry_survives_backtracking_without_leaking_entries() {
        let ids = IdGen::new();
        // The first alternative parses one entry and then demands a
        // `;` the input does not have, so it fails *after* writing to
        // the enclosing Node's keyed half. If the sink snapshot did
        // not cover `keyed_children`, the abandoned entry would still
        // be there when the second alternative succeeds.
        let entry_then_semi = seq(
            &ids,
            vec![
                keyed_entry(
                    &ids,
                    "entries",
                    token(&ids, "%ident"),
                    keyed_leaf_value(&ids),
                ),
                token(&ids, ";"),
            ],
        );
        let entry_then_end = seq(
            &ids,
            vec![
                keyed_entry(
                    &ids,
                    "entries",
                    token(&ids, "%ident"),
                    keyed_leaf_value(&ids),
                ),
                token(&ids, "}"),
            ],
        );
        let g = one_rule_grammar(
            &ids,
            "start",
            node(
                &ids,
                "Env",
                seq(
                    &ids,
                    vec![
                        token(&ids, "{"),
                        choice(&ids, vec![entry_then_semi, entry_then_end]),
                    ],
                ),
            ),
        );

        let tree = parse_one(&g, "{ a: 1 }").unwrap();
        let entries = tree.keyed_child_slot("entries").expect("slot bound");
        assert_eq!(
            entries.len(),
            1,
            "the failed alternative's entry must be rolled back, not kept: {entries:?}"
        );
        assert_eq!(entries[0].0, "a");
    }

    #[test]
    fn keyed_entry_outside_a_node_drops_the_entry() {
        let ids = IdGen::new();
        // No enclosing Node scope, so there is nowhere to bind the
        // pair. Documented as a silent drop, matching how a stray
        // `Field` behaves; pinned here so the behaviour is a decision
        // rather than an accident.
        let g = one_rule_grammar(
            &ids,
            "start",
            seq(
                &ids,
                vec![
                    keyed_entry(
                        &ids,
                        "entries",
                        token(&ids, "%ident"),
                        keyed_leaf_value(&ids),
                    ),
                    node(&ids, "Env", token(&ids, "!")),
                ],
            ),
        );
        let tree = parse_one(&g, "a: 1 !").unwrap();
        assert_eq!(tree.variant, "Env");
        assert!(
            tree.keyed_children.is_empty(),
            "a keyed entry with no enclosing Node has nowhere to land: {:?}",
            tree.keyed_children
        );
    }

    #[test]
    fn literal_token_and_wrap_node() {
        let ids = IdGen::new();
        // start = Node "K" { Field "kw" "let" }
        let g = one_rule_grammar(
            &ids,
            "start",
            node(&ids, "K", field(&ids, "kw", token(&ids, "let"))),
        );
        let tree = parse_one(&g, "let").unwrap();
        assert_eq!(tree.variant, "K");
        assert_eq!(tree.fields.len(), 1);
        assert_eq!(tree.fields[0].0, "kw");
        match &tree.fields[0].1 {
            RawValue::Text(t) => assert_eq!(t, "let"),
            _ => panic!("expected text"),
        }
    }

    #[test]
    fn keyword_guard_blocks_prefix_match() {
        let ids = IdGen::new();
        // Plain literal `"let"` would greedily eat the prefix of
        // "letme"; `%kw:let` applies the word-boundary guard.
        let g = one_rule_grammar(&ids, "s", node(&ids, "K", token(&ids, "%kw:let")));
        let err = parse_one(&g, "letme").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);

        // And the same pattern DOES match when the boundary is honoured.
        let g2 = one_rule_grammar(&ids, "s", node(&ids, "K", token(&ids, "%kw:let")));
        assert!(parse_one(&g2, "let ").is_ok());
    }

    #[test]
    fn plain_literal_has_no_word_boundary_guard() {
        let ids = IdGen::new();
        // Plain "a" matches even when followed by another word char —
        // it's the grammar author's job to sequence more tokens after.
        let g = one_rule_grammar(&ids, "s", node(&ids, "K", token(&ids, "a")));
        let err = parse_one(&g, "ab").unwrap_err();
        // The literal matched; trailing "b" tripped the EOF check.
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);
        assert!(
            err.diagnostics[0].message.contains("trailing"),
            "{}",
            err.diagnostics[0].message
        );
    }

    #[test]
    fn ident_and_int_classes() {
        let ids = IdGen::new();
        let g = one_rule_grammar(
            &ids,
            "s",
            node(&ids, "Var", field(&ids, "name", token(&ids, "%ident"))),
        );
        let t = parse_one(&g, "foo_bar1").unwrap();
        assert_eq!(t.variant, "Var");
        match &t.fields[0].1 {
            RawValue::Text(v) => assert_eq!(v, "foo_bar1"),
            _ => panic!(),
        }

        let g2 = one_rule_grammar(
            &ids,
            "s",
            node(&ids, "N", field(&ids, "v", token(&ids, "%int"))),
        );
        let t2 = parse_one(&g2, "-42").unwrap();
        match &t2.fields[0].1 {
            RawValue::Text(v) => assert_eq!(v, "-42"),
            _ => panic!(),
        }
    }

    // -- Whitespace --

    #[test]
    fn implicit_ws_skip_before_tokens_and_at_boundaries() {
        let ids = IdGen::new();
        // Node "P" { Field "a" %int Field "b" %int }
        let body = seq(
            &ids,
            vec![
                field(&ids, "a", token(&ids, "%int")),
                field(&ids, "b", token(&ids, "%int")),
            ],
        );
        let g = one_rule_grammar(&ids, "s", node(&ids, "P", body));
        let t = parse_one(&g, "  3   7 ").unwrap();
        assert_eq!(t.fields.len(), 2);
        assert_eq!(t.fields[0].0, "a");
        assert_eq!(t.fields[1].0, "b");
    }

    // -- PEG semantics (parser-design §3.5) --

    #[test]
    fn choice_commits_on_first_match() {
        let ids = IdGen::new();
        // Choice("a" -> A | "ab" -> B). Input "ab" — PEG commits to
        // first alt, "a" matches (leaves "b" behind), then EOF check
        // fails on the trailing "b".
        let alt_a = node(&ids, "A", token(&ids, "a"));
        let alt_ab = node(&ids, "B", token(&ids, "ab"));
        let g = one_rule_grammar(&ids, "s", choice(&ids, vec![alt_a, alt_ab]));
        let err = parse_one(&g, "ab").unwrap_err();
        // Should complain about trailing "b", not attempt the second
        // alt.
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);
        assert!(
            err.diagnostics[0].message.contains("byte 1"),
            "{}",
            err.diagnostics[0].message
        );
    }

    #[test]
    fn failed_alt_restores_position() {
        let ids = IdGen::new();
        // Choice("abc" | "a") on "ab": first fails (partial), position
        // must restore, second succeeds on "a"; trailing "b" then fails
        // EOF. Confirms no partial-consume leak.
        let alt_abc = node(&ids, "L", token(&ids, "abc"));
        let alt_a = node(&ids, "S", token(&ids, "a"));
        let g = one_rule_grammar(&ids, "s", choice(&ids, vec![alt_abc, alt_a]));
        let err = parse_one(&g, "ab").unwrap_err();
        // Trailing "b" at byte 1.
        assert!(
            err.diagnostics[0].message.contains("byte 1"),
            "{}",
            err.diagnostics[0].message
        );
    }

    #[test]
    fn repeat_is_greedy_and_no_backtrack_into_completed() {
        let ids = IdGen::new();
        // Seq( Repeat("a", 0..*), "a" ). Repeat eats all a's greedily;
        // trailing "a" required by the Seq item then fails. If Repeat
        // gave back one iteration, we'd succeed — the test proves it
        // does not.
        let g = one_rule_grammar(
            &ids,
            "s",
            node(
                &ids,
                "N",
                seq(
                    &ids,
                    vec![repeat(&ids, token(&ids, "a"), 0, None), token(&ids, "a")],
                ),
            ),
        );
        let err = parse_one(&g, "aaa").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNEXPECTED);
    }

    #[test]
    fn repeat_min_enforced() {
        let ids = IdGen::new();
        let g = one_rule_grammar(
            &ids,
            "s",
            node(&ids, "N", repeat(&ids, token(&ids, "a"), 2, None)),
        );
        // Only one "a" — Repeat min=2 fails.
        assert!(parse_one(&g, "a").is_err());
        // Two "a"s — succeeds.
        assert!(parse_one(&g, "aa").is_ok());
    }

    // -- Farthest failure --

    #[test]
    fn farthest_failure_carries_position_and_expected_set() {
        let ids = IdGen::new();
        // Seq("let", "x", "="). On input "let x !": we match "let"
        // (0..3), skip ws to 4, match "x" (4..5), skip ws to 6, expect
        // "=" at 6 but get "!". Farthest-failure position = 6, expected
        // = ["="].
        let g = one_rule_grammar(
            &ids,
            "s",
            node(
                &ids,
                "N",
                seq(
                    &ids,
                    vec![token(&ids, "let"), token(&ids, "x"), token(&ids, "=")],
                ),
            ),
        );
        let err = parse_one(&g, "let x !").unwrap_err();
        let msg = &err.diagnostics[0].message;
        assert!(msg.contains("byte 6"), "{msg}");
        assert!(msg.contains("`=`"), "{msg}");
    }

    // -- Termination guards --

    #[test]
    fn left_recursion_is_detected_at_runtime() {
        let ids = IdGen::new();
        // r <- r "a" — direct left recursion. Should trip the guard
        // rather than hang.
        let r = rule(
            &ids,
            "r",
            seq(&ids, vec![rule_ref(&ids, "r"), token(&ids, "a")]),
        );
        let g = Grammar::new(vec![r], "r");
        let err = g.parse("aaa").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::LEFT_RECURSION);
    }

    #[test]
    fn unknown_rule_ref_is_diagnosed() {
        let ids = IdGen::new();
        let r = rule(&ids, "start", rule_ref(&ids, "missing"));
        let g = Grammar::new(vec![r], "start");
        let err = g.parse("").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_RULE);
    }

    #[test]
    fn unknown_rule_ref_suggests_declared_rule() {
        // A typo of a declared rule name should surface the correct
        // name via the built-in Levenshtein suggester.
        let ids = IdGen::new();
        let start = rule(&ids, "start", rule_ref(&ids, "helo"));
        let target = rule(&ids, "hello", token(&ids, "hi"));
        let g = Grammar::new(vec![start, target], "start");
        let err = g.parse("hi").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_RULE);
        assert!(
            err.diagnostics[0].message.contains("did you mean")
                && err.diagnostics[0].message.contains("hello"),
            "expected hint, got: {}",
            err.diagnostics[0].message
        );
    }

    #[test]
    fn unknown_start_rule_is_diagnosed() {
        let ids = IdGen::new();
        let r = rule(&ids, "other", token(&ids, "x"));
        let g = Grammar::new(vec![r], "start");
        let err = g.parse("x").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_RULE);
    }

    #[test]
    fn unknown_start_rule_suggests_declared_rule() {
        let ids = IdGen::new();
        let r = rule(&ids, "start", token(&ids, "x"));
        let g = Grammar::new(vec![r], "strat");
        let err = g.parse("x").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_RULE);
        assert!(
            err.diagnostics[0].message.contains("did you mean")
                && err.diagnostics[0].message.contains("start"),
            "expected hint, got: {}",
            err.diagnostics[0].message
        );
    }

    #[test]
    fn nullable_repeat_body_below_min_is_rejected() {
        let ids = IdGen::new();
        // Repeat body is a Field with no productive body — matches
        // empty. min=1 forces a failure rather than a hang.
        let empty_body = seq(&ids, vec![]);
        let g = one_rule_grammar(
            &ids,
            "s",
            node(&ids, "N", repeat(&ids, empty_body, 1, None)),
        );
        let err = g.parse("").unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::NULLABLE_REPEAT);
    }
}