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
//! Schema-driven grammar generation (item N).
//!
//! The kit's identity axis is "write the AST in Rust, the toolchain
//! supplies the rest". [`grammar_from_schema`] converts the type-level
//! shape a `#[derive(DslSchema)]` already extracts into a working
//! [`Grammar`] for a canonical text syntax — the DSL author writes two
//! derives and gets an external-format parser for free, instead of
//! hand-authoring a grammar (in Rust or, worse, in a Bison-style JSON
//! blob nobody wants to write).
//!
//! # Canonical syntax
//!
//! One form per variant: the variant name as a keyword, followed by a
//! parenthesised, comma-separated argument list. Arguments appear in
//! schema order — payload fields first, then child slots — each spelled
//! `name: value`:
//!
//! ```text
//! Add(lhs: Lit(value: 1), rhs: Neg(body: none))
//! List(items: [Lit(value: 1), Lit(value: 2)])
//! Name(text: "hello world")
//! Unit()
//! ```
//!
//! - **`One` child** — `name: <node>`.
//! - **`Optional` child** — `name: <node>` or `name: none`. (If a
//!   variant is literally called `none`, PEG ordered choice still
//!   parses `name: none(...)` as that variant; bare `none` means
//!   absent.)
//! - **`Many` child** — `name: [<node>, <node>, ...]`, empty list
//!   allowed.
//! - **`Map` child** — `name: { <key>: <node>, <key>: <node> }`, empty
//!   map allowed. Braces (not the `Many` brackets) mark the slot as
//!   keyed, matching the JSON bridge's object spelling. A key is
//!   either a `%str` literal or a bare `%ident`, so `"a b": …` and
//!   `path: …` are both writable. Entries may be written in any
//!   order — the parser sorts them into the canonical
//!   ascending-by-key form the `ParseTree` requires.
//! - **Payload fields** — by Rust type source text:
//!   `String` → a `%str` literal; the integer types → `%int`;
//!   `bool` → `true` / `false`. Any other payload type fails
//!   generation with [`codes::UNSUPPORTED_FIELD`] — loudly, per
//!   variant, rather than silently dropping the variant from the
//!   grammar — unless a [`SyntaxOverrides`] entry supplies its value
//!   production.
//!
//! # Syntax overrides
//!
//! [`grammar_from_schema_with`] accepts a [`SyntaxOverrides`] carrying
//! value productions for payload types the built-in mapping rejects
//! (e.g. `Option<JoinPolicy>`), keyed by type source text or pinned to
//! one `(variant, field)` site. The override supplies only the value
//! [`Peg`] — the surrounding `name: value` argument shape stays
//! canonical — and its matched text becomes the field's production, so
//! the override author owns making that text consumable downstream
//! (typically `FromStr` on the field type, via
//! [`build_field`](crate::build_field)).
//!
//! # Guarantees
//!
//! The generated grammar is left-recursion-free by construction (every
//! variant rule starts with its keyword token) and contains no nullable
//! repeats; `GrammarCheck`'s `check_left_recursion` /
//! `check_nullable_repeat` / `check_schema_consistency` all pass
//! against it — the tests pin this. Trees produced by parsing satisfy
//! [`check_conformance`](crate::check_conformance) against the source
//! schema.

use std::collections::HashMap;

use crate::grammar_check;
use crate::peg::{
    Grammar, Peg, choice, field, keyed_entry, node, repeat, rule, rule_ref, seq, token,
};
use crate::{BuildError, Diagnostic};
use dsl_kit_core::IdGen;
use dsl_kit_schema::{
    ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, ScalarKind,
    ScalarShorthand, VariantSchema,
};

/// Diagnostic codes emitted by grammar generation.
pub mod codes {
    /// A payload field's Rust type has no canonical-syntax mapping.
    pub const UNSUPPORTED_FIELD: &str = "dsl_kit::schema_gen::unsupported_field";
    /// The schema declares no variants — there is nothing to parse.
    pub const EMPTY_SCHEMA: &str = "dsl_kit::schema_gen::empty_schema";
    /// A child slot's multiplicity is a variant this build of
    /// `dsl-kit-parse` does not recognise (added to the schema crate's
    /// `#[non_exhaustive]` enum ahead of parse-side support). Emitted
    /// by the pre-flight check in
    /// [`grammar_from_schema_with`] so `child_arg_peg` never sees an
    /// unknown variant.
    pub const UNKNOWN_MULTIPLICITY: &str = "dsl_kit::schema_gen::unknown_multiplicity";
    /// A keyed child slot declares a value shape the canonical text
    /// syntax has not yet grown a production for. Emitted by the
    /// pre-flight check so a scalar-valued keyed slot fails loudly
    /// at grammar-generation time rather than silently producing a
    /// grammar that expects each entry's value to be a full AST
    /// node — the shape mismatch would otherwise surface as an
    /// opaque parse failure on the DSL author's first document.
    pub const UNSUPPORTED_MAP_VALUE_SHAPE: &str =
        "dsl_kit::schema_gen::unsupported_map_value_shape";
    /// A child slot declares a [`ScalarShorthand`](dsl_kit_schema::ScalarShorthand)
    /// this build cannot honour: wrong multiplicity / value shape for
    /// a shorthand, a duplicate kind, an unknown target variant or
    /// field, a target field whose type does not match the declared
    /// kind, or a kind this build does not recognise. Emitted by the
    /// pre-flight check so an incoherent declaration fails loudly at
    /// grammar-generation time — the same declaration drives the JSON
    /// bridge, so silently dropping it here would let the two
    /// front-ends drift apart.
    pub const UNSUPPORTED_SCALAR_SHORTHAND: &str =
        "dsl_kit::schema_gen::unsupported_scalar_shorthand";
    /// A child slot declares
    /// [`non_empty`](dsl_kit_schema::ChildSchema::non_empty) on a
    /// multiplicity that has no empty collection to forbid (`One` /
    /// `Optional`). Emitted by the pre-flight check so an incoherent
    /// hand-written declaration fails loudly at grammar-generation
    /// time — the derive macro rejects the same combination at
    /// compile time.
    pub const INVALID_NON_EMPTY: &str = "dsl_kit::schema_gen::invalid_non_empty";
}

/// Integer payload types with a built-in `%int` production. Shared by
/// the payload-field mapping ([`field_value_peg`]) and the scalar
/// shorthand kind check so the two stay in step.
const INT_TYPES: &[&str] = &[
    "i8", "i16", "i32", "i64", "i128", "u8", "u16", "u32", "u64", "u128", "usize", "isize",
];

/// Name of the generated start rule.
pub const START_RULE: &str = "node";

/// A deferred value-production constructor: overrides are registered
/// before the [`IdGen`] doing the generation exists, so each entry is a
/// factory invoked with the generator's `ids` at build time.
type PegFactory = Box<dyn Fn(&IdGen) -> Peg>;

/// Value-production overrides for payload fields whose Rust type has no
/// built-in canonical-syntax mapping (see the module docs).
///
/// Two granularities, resolved most-specific-first:
///
/// 1. **Per field** ([`Self::for_field`]) — pinned to one
///    `(variant, field)` site.
/// 2. **Per type** ([`Self::for_type`]) — keyed by the field's Rust
///    type source text; whitespace is ignored, so
///    `"Option<JoinPolicy>"` matches the derive-extracted
///    `"Option < JoinPolicy >"` spelling.
///
/// A field with neither entry falls back to the built-in mapping, and
/// failing that still fails generation loudly with
/// [`codes::UNSUPPORTED_FIELD`].
///
/// The factory builds only the **value** production; the enclosing
/// `name ':' <value>` argument shape (and the `Field` sink binding the
/// matched text to the field name) stays canonical, which keeps the
/// generated grammar's `GrammarCheck` guarantees intact.
#[derive(Default)]
pub struct SyntaxOverrides {
    by_type: HashMap<String, PegFactory>,
    by_field: HashMap<(String, String), PegFactory>,
}

impl SyntaxOverrides {
    /// An empty override set (equivalent to the built-in mapping only).
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a value production for every payload field of Rust
    /// type `ty` (source-text comparison, whitespace-insensitive).
    pub fn for_type(
        mut self,
        ty: impl AsRef<str>,
        value: impl Fn(&IdGen) -> Peg + 'static,
    ) -> Self {
        self.by_type.insert(strip_ws(ty.as_ref()), Box::new(value));
        self
    }

    /// Registers a value production for the single field `field` of
    /// variant `variant`, winning over any [`Self::for_type`] entry.
    pub fn for_field(
        mut self,
        variant: impl Into<String>,
        field: impl Into<String>,
        value: impl Fn(&IdGen) -> Peg + 'static,
    ) -> Self {
        self.by_field
            .insert((variant.into(), field.into()), Box::new(value));
        self
    }

    /// Most-specific matching factory for `field` of `variant`, if any.
    fn resolve(&self, variant: &str, field: &FieldSchema) -> Option<&PegFactory> {
        self.by_field
            .get(&(variant.to_string(), field.name.clone()))
            .or_else(|| self.by_type.get(&strip_ws(&field.ty)))
    }
}

/// Whitespace-insensitive type key: `Option < JoinPolicy >` (the
/// token-stream spelling `#[derive(DslSchema)]` extracts) and
/// `Option<JoinPolicy>` (what an author writes) must compare equal.
fn strip_ws(ty: &str) -> String {
    ty.chars().filter(|c| !c.is_whitespace()).collect()
}

impl Grammar {
    /// Generates the canonical-syntax grammar for `schema`. See
    /// [`grammar_from_schema`].
    pub fn from_schema(schema: &NodeSchema, ids: &IdGen) -> Result<Grammar, BuildError> {
        grammar_from_schema(schema, ids)
    }
}

/// Generates a [`Grammar`] for the canonical named-argument syntax of
/// `schema` (see the module docs for the syntax), built-in field
/// mapping only.
///
/// Fails with one [`codes::UNSUPPORTED_FIELD`] diagnostic per
/// unmappable payload field (collected across all variants, so the
/// author sees the full list at once). To map such fields instead of
/// failing, use [`grammar_from_schema_with`].
pub fn grammar_from_schema(schema: &NodeSchema, ids: &IdGen) -> Result<Grammar, BuildError> {
    grammar_from_schema_with(schema, ids, &SyntaxOverrides::default())
}

/// [`grammar_from_schema`] with [`SyntaxOverrides`] consulted before
/// the built-in field mapping (per-field entries win over per-type
/// entries win over built-ins).
pub fn grammar_from_schema_with(
    schema: &NodeSchema,
    ids: &IdGen,
    overrides: &SyntaxOverrides,
) -> Result<Grammar, BuildError> {
    if schema.variants.is_empty() {
        return Err(BuildError::single(Diagnostic::error(
            codes::EMPTY_SCHEMA,
            format!("schema `{}` declares no variants", schema.name),
        )));
    }

    // Pre-flight: collect every diagnostic that must block rule
    // generation, then return in one shot. A single pass means an
    // author with both a bad payload type and a `Multiplicity::Map`
    // slot sees both errors on the first build instead of paying two
    // edit-compile cycles for one report.
    //
    // Grouping:
    //   - `UNSUPPORTED_FIELD` for payload types with no canonical-syntax
    //     mapping (and no `SyntaxOverrides` entry).
    //   - `UNKNOWN_MULTIPLICITY` for child slots whose multiplicity
    //     this build does not know, which is what keeps
    //     `child_arg_peg`'s catch-all arm from ever running.
    let mut pre_flight = Vec::new();
    for v in &schema.variants {
        for f in &v.fields {
            if resolved_field_value_peg(&v.name, f, ids, overrides).is_none() {
                pre_flight.push(Diagnostic::error(
                    codes::UNSUPPORTED_FIELD,
                    format!(
                        "variant `{}` field `{}`: type `{}` has no canonical-syntax \
                         mapping (supported: String, bool, the integer types; or \
                         register a `SyntaxOverrides` value production)",
                        v.name, f.name, f.ty
                    ),
                ));
            }
        }
        for c in &v.children {
            match c.multiplicity {
                // Every shape `child_arg_peg` knows how to emit.
                Multiplicity::One | Multiplicity::Optional | Multiplicity::Many => {}
                // Keyed slots come in two value shapes at derive
                // level: recursive (`BTreeMap<String, Self>` /
                // `BTreeMap<String, Box<Self>>`) and scalar
                // (`ChildValueShape::Scalar { .. }`, Shape 1 of the
                // tracking issue). Both are supported by the
                // canonical text syntax as of dsl-kit 0.7; scalar
                // values reuse the built-in payload-type mapping
                // (`field_value_peg`) — same names, same productions
                // — so any type the payload path can spell
                // (`String` / integer / `bool` / …) works in a keyed
                // slot too. A scalar value with no built-in mapping
                // is still an error here: `child_arg_peg`'s
                // downstream `.expect(...)` would panic otherwise,
                // and the DSL author needs a pointer to
                // `SyntaxOverrides` or a real bug report either way.
                Multiplicity::Map => {
                    if let ChildValueShape::Scalar { ty } = &c.value_shape {
                        let synthetic = FieldSchema {
                            name: "value".into(),
                            ty: ty.clone(),
                            optional: false,
                        };
                        if field_value_peg(&synthetic, ids).is_none() {
                            pre_flight.push(Diagnostic::error(
                                codes::UNSUPPORTED_MAP_VALUE_SHAPE,
                                format!(
                                    "variant `{}` child slot `{}`: keyed scalar value type \
                                     `{}` has no canonical-syntax mapping (supported: \
                                     String, bool, the integer types, Option<String>, \
                                     Vec<String>). Register a `SyntaxOverrides` value \
                                     production for the surrounding payload field of the \
                                     same type, or use the JSON front-end where scalar \
                                     entries are dispatched through serde",
                                    v.name, c.name, ty
                                ),
                            ));
                        }
                    }
                }
                // `#[non_exhaustive]` catch-all: a future Multiplicity
                // variant added to dsl-kit-schema before this crate is
                // updated must also be rejected here — that's what
                // keeps `child_arg_peg`'s `_ => unreachable!()` arm
                // honest.
                _ => {
                    pre_flight.push(Diagnostic::error(
                        codes::UNKNOWN_MULTIPLICITY,
                        format!(
                            "variant `{}` child slot `{}`: unrecognised Multiplicity \
                             variant (upgrade dsl-kit-parse to a version that knows about it)",
                            v.name, c.name
                        ),
                    ));
                }
            }
            pre_flight.extend(check_scalar_shorthands(schema, v, c));
            if c.non_empty && matches!(c.multiplicity, Multiplicity::One | Multiplicity::Optional) {
                pre_flight.push(Diagnostic::error(
                    codes::INVALID_NON_EMPTY,
                    format!(
                        "variant `{}` child slot `{}`: `non_empty` is only meaningful \
                         on `Many` / `Map` collection slots (`One` is inherently \
                         non-empty, `Optional` inherently permits absence)",
                        v.name, c.name
                    ),
                ));
            }
        }
    }
    if !pre_flight.is_empty() {
        return Err(BuildError::new(pre_flight));
    }

    let mut rules = Vec::with_capacity(schema.variants.len() + 1);
    rules.push(rule(
        ids,
        START_RULE,
        choice(
            ids,
            schema
                .variants
                .iter()
                .map(|v| rule_ref(ids, v.name.clone()))
                .collect(),
        ),
    ));
    for v in &schema.variants {
        rules.push(variant_rule(v, ids, overrides));
    }
    Ok(Grammar::new(rules, START_RULE))
}

/// Pre-flight validation of one slot's declared scalar shorthands.
///
/// The declaration is the single source both front-ends lower from, so
/// every way it can be incoherent is rejected here in one pass:
/// shorthands on a slot shape that has no bare-scalar position
/// (non-`One`/`Optional` multiplicity, or a non-recursive value),
/// duplicate kinds (kind dispatch must be unambiguous), an unknown
/// target variant or field, a target field whose type cannot carry the
/// kind, and a kind this build does not recognise (the schema crate's
/// `#[non_exhaustive]` escape hatch — rejecting it keeps
/// `scalar_shorthand_value_peg`'s `_` arm from ever running).
fn check_scalar_shorthands(
    schema: &NodeSchema,
    v: &VariantSchema,
    c: &ChildSchema,
) -> Vec<Diagnostic> {
    let mut diags = Vec::new();
    if c.scalar_shorthands.is_empty() {
        return diags;
    }
    let site = format!("variant `{}` child slot `{}`", v.name, c.name);
    if !matches!(c.multiplicity, Multiplicity::One | Multiplicity::Optional) {
        diags.push(Diagnostic::error(
            codes::UNSUPPORTED_SCALAR_SHORTHAND,
            format!("{site}: scalar shorthands are only supported on `One` / `Optional` slots"),
        ));
        return diags;
    }
    if !matches!(c.value_shape, ChildValueShape::Recursive) {
        diags.push(Diagnostic::error(
            codes::UNSUPPORTED_SCALAR_SHORTHAND,
            format!("{site}: scalar shorthands require a recursive value shape"),
        ));
        return diags;
    }
    let mut seen: Vec<ScalarKind> = Vec::new();
    for sh in &c.scalar_shorthands {
        if seen.contains(&sh.kind) {
            diags.push(Diagnostic::error(
                codes::UNSUPPORTED_SCALAR_SHORTHAND,
                format!(
                    "{site}: duplicate shorthand for kind `{}` — each kind may map to \
                     at most one target so dispatch stays unambiguous",
                    sh.kind.as_str()
                ),
            ));
            continue;
        }
        seen.push(sh.kind);
        let Some(target) = schema.variant(&sh.variant) else {
            diags.push(Diagnostic::error(
                codes::UNSUPPORTED_SCALAR_SHORTHAND,
                format!(
                    "{site}: shorthand target variant `{}` is not declared in schema `{}`",
                    sh.variant, schema.name
                ),
            ));
            continue;
        };
        let Some(field) = target.fields.iter().find(|f| f.name == sh.field) else {
            diags.push(Diagnostic::error(
                codes::UNSUPPORTED_SCALAR_SHORTHAND,
                format!(
                    "{site}: shorthand target variant `{}` has no payload field `{}`",
                    sh.variant, sh.field
                ),
            ));
            continue;
        };
        let ty = strip_ws(&field.ty);
        let compatible = match sh.kind {
            ScalarKind::Str => ty == "String",
            ScalarKind::Int => INT_TYPES.contains(&ty.as_str()),
            ScalarKind::Bool => ty == "bool",
            // `#[non_exhaustive]` catch-all: reject kinds this build
            // does not know rather than generating a grammar that
            // silently drops them.
            _ => {
                diags.push(Diagnostic::error(
                    codes::UNSUPPORTED_SCALAR_SHORTHAND,
                    format!(
                        "{site}: unrecognised ScalarKind (upgrade dsl-kit-parse to a \
                         version that knows about it)"
                    ),
                ));
                continue;
            }
        };
        if !compatible {
            diags.push(Diagnostic::error(
                codes::UNSUPPORTED_SCALAR_SHORTHAND,
                format!(
                    "{site}: shorthand kind `{}` cannot target `{}::{}` of type `{}`",
                    sh.kind.as_str(),
                    sh.variant,
                    sh.field,
                    field.ty
                ),
            ));
        }
    }
    diags
}

/// Builds the rule for one variant. Two shapes:
///
/// - **Strict-order** (default, variant has no optional fields):
///   `%kw:V "(" arg ("," arg)* ")"` with arguments emitted in schema
///   order (fields, then children). Preserves the pre-0.3 canonical
///   spelling for variants that never omit.
/// - **Free-order** (variant has ≥ 1 optional field): `%kw:V "(" (arg
///   ("," arg)*)? ")"` where each arg is `arg_1 | arg_2 | ...` and
///   every alternative carries its own `%kw:name` prefix. Args are
///   distinguishable by that name-keyword, so the DSL author may
///   omit any subset of optional arguments (or even all of them),
///   and `check_conformance` remains the authority on required /
///   duplicate / unknown-slot diagnostics.
fn variant_rule(v: &VariantSchema, ids: &IdGen, overrides: &SyntaxOverrides) -> Peg {
    let has_optional = v.fields.iter().any(|f| f.optional);
    let mut args: Vec<Peg> = Vec::new();
    for f in &v.fields {
        let value = resolved_field_value_peg(&v.name, f, ids, overrides)
            .expect("unsupported field types were rejected before rule generation");
        args.push(seq(
            ids,
            vec![
                token(ids, format!("%kw:{}", f.name)),
                token(ids, ":"),
                field(ids, f.name.clone(), value),
            ],
        ));
    }
    for c in &v.children {
        args.push(child_arg_peg(c, ids));
    }

    let mut items = vec![token(ids, format!("%kw:{}", v.name)), token(ids, "(")];
    if has_optional && !args.is_empty() {
        // Free-order: any of the argument shapes, comma-separated,
        // whole list optional. Each argument-slot is a Field capture
        // in its own right (built above), and the name-keyword prefix
        // keeps the alternation unambiguous at the byte level.
        let arg_choice = choice(ids, args);
        // The tail repeats `("," arg_choice)`; we rebuild arg_choice
        // per position so each Choice node gets a fresh id (Peg nodes
        // are id-unique in a grammar).
        let tail_alt = |ids: &IdGen| -> Peg {
            let mut alts: Vec<Peg> = Vec::new();
            for f in &v.fields {
                let value = resolved_field_value_peg(&v.name, f, ids, overrides)
                    .expect("unsupported field types were rejected before rule generation");
                alts.push(seq(
                    ids,
                    vec![
                        token(ids, format!("%kw:{}", f.name)),
                        token(ids, ":"),
                        field(ids, f.name.clone(), value),
                    ],
                ));
            }
            for c in &v.children {
                alts.push(child_arg_peg(c, ids));
            }
            choice(ids, alts)
        };
        let tail = repeat(ids, seq(ids, vec![token(ids, ","), tail_alt(ids)]), 0, None);
        let full = seq(ids, vec![arg_choice, tail]);
        items.push(repeat(ids, full, 0, Some(1)));
    } else {
        for (i, arg) in args.into_iter().enumerate() {
            if i > 0 {
                items.push(token(ids, ","));
            }
            items.push(arg);
        }
    }
    items.push(token(ids, ")"));

    rule(
        ids,
        v.name.clone(),
        node(ids, v.name.clone(), seq(ids, items)),
    )
}

/// Value production for a payload field: the most specific
/// [`SyntaxOverrides`] entry if registered, else the built-in mapping.
fn resolved_field_value_peg(
    variant: &str,
    f: &FieldSchema,
    ids: &IdGen,
    overrides: &SyntaxOverrides,
) -> Option<Peg> {
    match overrides.resolve(variant, f) {
        Some(factory) => Some(factory(ids)),
        None => field_value_peg(f, ids),
    }
}

/// Built-in value production for a payload field, by Rust type source
/// text. `None` when the type has no canonical-syntax mapping.
///
/// Recognised (whitespace-insensitive on the type-source spelling):
///
/// - `String` → `%str`
/// - the integer types → `%int`
/// - `bool` → `true` / `false`
/// - `Option<String>` → `none` | `%str`
/// - `Vec<String>` → `[ %str ("," %str)* ]`, empty list allowed
///
/// The last two entries realise Layer 2 of the "built-in optional
/// payload fields" contract — downstream DSLs no longer need to
/// register a [`SyntaxOverrides`] entry (nor a paired
/// `#[dsl_build(with = ...)]` converter) for these shapes.
fn field_value_peg(f: &FieldSchema, ids: &IdGen) -> Option<Peg> {
    let ty = strip_ws(&f.ty);
    if ty == "String" {
        Some(token(ids, "%str"))
    } else if INT_TYPES.contains(&ty.as_str()) {
        Some(token(ids, "%int"))
    } else if ty == "bool" {
        Some(choice(
            ids,
            vec![token(ids, "%kw:true"), token(ids, "%kw:false")],
        ))
    } else if ty == "Option<String>" {
        // Canonical spelling of an absent Option-payload; mirrors the
        // `Multiplicity::Optional` child idiom.
        Some(choice(
            ids,
            vec![token(ids, "%kw:none"), token(ids, "%str")],
        ))
    } else if ty == "Vec<String>" {
        // `[ %str_raw ("," %str_raw)* ]` with empty list allowed.
        // `%str_raw` (peg-level primitive) contributes the raw
        // source slice for each element — quotes and escapes intact —
        // so the joined field text is a JSON-compatible array literal
        // that `build_field_vec` can hand straight to
        // `serde_json::from_str`.
        let elems = seq(
            ids,
            vec![
                token(ids, "%str_raw"),
                repeat(
                    ids,
                    seq(ids, vec![token(ids, ","), token(ids, "%str_raw")]),
                    0,
                    None,
                ),
            ],
        );
        Some(seq(
            ids,
            vec![
                token(ids, "["),
                repeat(ids, elems, 0, Some(1)),
                token(ids, "]"),
            ],
        ))
    } else {
        None
    }
}

/// Value production for one declared scalar shorthand: a synthetic
/// node of the target variant whose single field captures the scalar
/// token. Structurally identical to what the explicit node spelling
/// produces, so the two spellings land on the same `ParseTree` — the
/// lowering is expressed in the grammar itself, no post-pass needed.
fn scalar_shorthand_value_peg(sh: &ScalarShorthand, ids: &IdGen) -> Peg {
    let scalar = match sh.kind {
        ScalarKind::Str => token(ids, "%str"),
        ScalarKind::Int => token(ids, "%int"),
        ScalarKind::Bool => choice(ids, vec![token(ids, "%kw:true"), token(ids, "%kw:false")]),
        // Unreachable in a generated grammar: the pre-flight check
        // (`check_scalar_shorthands`) rejects unrecognised kinds with
        // `UNSUPPORTED_SCALAR_SHORTHAND` before rule generation runs.
        _ => unreachable!(
            "pre-flight rejects unrecognised ScalarKind; child_arg_peg must not see it"
        ),
    };
    node(
        ids,
        sh.variant.clone(),
        field(ids, sh.field.clone(), scalar),
    )
}

/// Value production for a `One` / `Optional` slot: the explicit node
/// spelling, plus one alternative per declared scalar shorthand. The
/// node arm is tried first so the explicit spelling always wins;
/// a bare scalar cannot open a node production (`ident '('`), so the
/// alternatives never overlap.
fn one_slot_value_peg(c: &ChildSchema, ids: &IdGen) -> Peg {
    if c.scalar_shorthands.is_empty() {
        return rule_ref(ids, START_RULE);
    }
    let mut alts = vec![rule_ref(ids, START_RULE)];
    for sh in &c.scalar_shorthands {
        alts.push(scalar_shorthand_value_peg(sh, ids));
    }
    choice(ids, alts)
}

/// Argument production for one child slot, by multiplicity.
fn child_arg_peg(c: &ChildSchema, ids: &IdGen) -> Peg {
    let name_kw = token(ids, format!("%kw:{}", c.name));
    let colon = token(ids, ":");
    match c.multiplicity {
        Multiplicity::One => seq(
            ids,
            vec![
                name_kw,
                colon,
                field(ids, c.name.clone(), one_slot_value_peg(c, ids)),
            ],
        ),
        // `name: <node>` or `name: none`. The Field arm is tried first,
        // so a variant literally named `none` still wins when followed
        // by `(`. The bare-`none` arm sits *outside* any Field: its
        // matched text lands on the enclosing Node sink where it is
        // dropped as syntactic noise, leaving the slot absent.
        Multiplicity::Optional => seq(
            ids,
            vec![
                name_kw,
                colon,
                choice(
                    ids,
                    vec![
                        field(ids, c.name.clone(), one_slot_value_peg(c, ids)),
                        token(ids, "%kw:none"),
                    ],
                ),
            ],
        ),
        // `name: [ <node> ("," <node>)* ]`, empty list allowed. The
        // list commas live inside the Field body; the mixed-field
        // "trees win" fallback drops them as noise. A slot declared
        // `non_empty` drops the outer 0..1 wrap so the grammar itself
        // requires at least one element — which also makes the
        // synthesized minimal example carry one (example_gen walks
        // the grammar, so the constraint propagates for free).
        Multiplicity::Many => {
            let elems = seq(
                ids,
                vec![
                    rule_ref(ids, START_RULE),
                    repeat(
                        ids,
                        seq(ids, vec![token(ids, ","), rule_ref(ids, START_RULE)]),
                        0,
                        None,
                    ),
                ],
            );
            let list = if c.non_empty {
                field(ids, c.name.clone(), elems)
            } else {
                field(ids, c.name.clone(), repeat(ids, elems, 0, Some(1)))
            };
            seq(
                ids,
                vec![name_kw, colon, token(ids, "["), list, token(ids, "]")],
            )
        }
        // `name: { <key>: <node> ("," <key>: <node>)* }`, empty map
        // allowed. Braces rather than the `Many` idiom's brackets so
        // the two shapes are distinguishable at a glance, and matching
        // the JSON bridge's object spelling so a DSL reads the same
        // way in both front-ends.
        //
        // The key token is `%str | %ident`: keys are arbitrary strings
        // at the `ParseTree` level, so a quoted form has to exist, but
        // requiring quotes around every `PATH`-style key would be
        // noise. `%str` is tried first — a quoted key is unambiguous,
        // while `%ident` cannot start with `"` — and its production is
        // the decoded content, so `"a b"` and `a` both arrive as plain
        // key text.
        Multiplicity::Map => {
            //
            // The `:` separator rides on the *value* half, not the
            // key half: every token matched inside the key production
            // contributes to the key text, so a `:` there would land
            // in the key itself. On the value side it is dropped as
            // syntactic noise, the same way the `Many` list's commas
            // are.
            //
            // The value half branches on `value_shape`:
            //
            // - `Recursive` (`BTreeMap<String, Self>` /
            //   `BTreeMap<String, Box<Self>>`) → the value is a full
            //   AST node, produced by `rule_ref(START_RULE)`.
            //
            // - `Scalar { ty }` (`BTreeMap<String, String>` /
            //   `BTreeMap<String, i64>` / …) → the value is a scalar
            //   payload wrapped in a synthetic leaf `Node` whose
            //   single `Field` is named `value`. That matches the
            //   canonical entry shape the JSON bridge emits (see
            //   `serde_bridge::build_scalar_keyed_slot`) so
            //   `build_scalar_map` reads `.field("value")` from each
            //   entry regardless of front-end.
            //
            // The `_ =>` fallback keeps the recursive spelling for
            // any future `ChildValueShape` variant this build does
            // not yet know about; the pre-flight check in
            // `grammar_from_schema_with` rejects those cases with
            // `UNSUPPORTED_MAP_VALUE_SHAPE`, so `child_arg_peg` never
            // sees an unrecognised shape at run time.
            let value_prod = |ids: &IdGen| -> Peg {
                match &c.value_shape {
                    ChildValueShape::Recursive => rule_ref(ids, START_RULE),
                    ChildValueShape::Scalar { ty } => {
                        let synthetic = FieldSchema {
                            name: "value".into(),
                            ty: ty.clone(),
                            optional: false,
                        };
                        let scalar = field_value_peg(&synthetic, ids).expect(
                            "scalar-map value type rejected by pre-flight; \
                             child_arg_peg must not see it",
                        );
                        node(ids, "", field(ids, "value", scalar))
                    }
                    _ => rule_ref(ids, START_RULE),
                }
            };
            let entry = |ids: &IdGen| -> Peg {
                keyed_entry(
                    ids,
                    c.name.clone(),
                    choice(ids, vec![token(ids, "%str"), token(ids, "%ident")]),
                    seq(ids, vec![token(ids, ":"), value_prod(ids)]),
                )
            };
            let entries = seq(
                ids,
                vec![
                    entry(ids),
                    repeat(ids, seq(ids, vec![token(ids, ","), entry(ids)]), 0, None),
                ],
            );
            // A `non_empty` map drops the outer 0..1 wrap, same as
            // the `Many` arm above: the grammar requires at least one
            // entry and the synthesized minimal example follows.
            let body = if c.non_empty {
                entries
            } else {
                repeat(ids, entries, 0, Some(1))
            };
            seq(
                ids,
                vec![name_kw, colon, token(ids, "{"), body, token(ids, "}")],
            )
        }
        // `#[non_exhaustive]` catch-all: a future Multiplicity variant
        // added to dsl-kit-schema before this crate is updated would
        // land here. The pre-flight check in
        // `grammar_from_schema_with` should be extended in lockstep to
        // reject unknown variants; if that extension is missed the
        // panic here surfaces the omission loudly instead of emitting
        // a silently-wrong grammar rule.
        _ => unreachable!(
            "child_arg_peg encountered an unrecognised Multiplicity variant on slot \
             `{}` — extend the pre-flight check in grammar_from_schema_with to reject it",
            c.name
        ),
    }
}

/// Convenience: generate and immediately assert the grammar is clean
/// under `GrammarCheck` (left recursion, nullable repeats, schema
/// consistency). Intended for tests and one-shot setup paths; returns
/// the same grammar as [`grammar_from_schema`].
pub fn checked_grammar_from_schema(
    schema: &NodeSchema,
    ids: &IdGen,
) -> Result<Grammar, BuildError> {
    checked_grammar_from_schema_with(schema, ids, &SyntaxOverrides::default())
}

/// [`checked_grammar_from_schema`] with [`SyntaxOverrides`] consulted
/// before the built-in field mapping.
pub fn checked_grammar_from_schema_with(
    schema: &NodeSchema,
    ids: &IdGen,
    overrides: &SyntaxOverrides,
) -> Result<Grammar, BuildError> {
    let grammar = grammar_from_schema_with(schema, ids, overrides)?;
    let mut diags = grammar_check::check_left_recursion(&grammar);
    diags.extend(grammar_check::check_nullable_repeat(&grammar));
    diags.extend(
        grammar_check::check_schema_consistency(&grammar, schema)
            .into_iter()
            .filter(|d| d.severity == crate::Severity::Error),
    );
    if diags.is_empty() {
        Ok(grammar)
    } else {
        Err(BuildError::new(diags))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RawValue, check_conformance};
    use dsl_kit_schema::ChildValueShape;

    /// Expr-flavoured schema exercising every supported shape: int /
    /// string / bool fields, One / Optional / Many children, and a
    /// zero-argument variant.
    fn demo_schema() -> NodeSchema {
        NodeSchema {
            name: "Expr".into(),
            variants: vec![
                VariantSchema {
                    name: "Lit".into(),
                    fields: vec![FieldSchema {
                        name: "value".into(),
                        ty: "i64".into(),
                        optional: false,
                    }],
                    children: vec![],
                },
                VariantSchema {
                    name: "Name".into(),
                    fields: vec![
                        FieldSchema {
                            name: "text".into(),
                            ty: "String".into(),
                            optional: false,
                        },
                        FieldSchema {
                            name: "quoted".into(),
                            ty: "bool".into(),
                            optional: false,
                        },
                    ],
                    children: vec![],
                },
                VariantSchema {
                    name: "Add".into(),
                    fields: vec![],
                    children: vec![
                        ChildSchema {
                            name: "lhs".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                            scalar_shorthands: vec![],
                            non_empty: false,
                        },
                        ChildSchema {
                            name: "rhs".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                            scalar_shorthands: vec![],
                            non_empty: false,
                        },
                    ],
                },
                VariantSchema {
                    name: "Neg".into(),
                    fields: vec![],
                    children: vec![ChildSchema {
                        name: "body".into(),
                        multiplicity: Multiplicity::Optional,
                        value_shape: ChildValueShape::Recursive,
                        scalar_shorthands: vec![],
                        non_empty: false,
                    }],
                },
                VariantSchema {
                    name: "List".into(),
                    fields: vec![],
                    children: vec![ChildSchema {
                        name: "items".into(),
                        multiplicity: Multiplicity::Many,
                        value_shape: ChildValueShape::Recursive,
                        scalar_shorthands: vec![],
                        non_empty: false,
                    }],
                },
                VariantSchema {
                    name: "Env".into(),
                    fields: vec![],
                    children: vec![ChildSchema {
                        name: "entries".into(),
                        multiplicity: Multiplicity::Map,
                        value_shape: ChildValueShape::Recursive,
                        scalar_shorthands: vec![],
                        non_empty: false,
                    }],
                },
                VariantSchema {
                    name: "Unit".into(),
                    fields: vec![],
                    children: vec![],
                },
            ],
        }
    }

    fn demo_grammar() -> Grammar {
        checked_grammar_from_schema(&demo_schema(), &IdGen::new())
            .expect("demo schema generates a clean grammar")
    }

    /// Parse + conformance-check against the demo schema in one go.
    fn parse_ok(input: &str) -> crate::ParseTree {
        let g = demo_grammar();
        let tree = g
            .parse(input)
            .unwrap_or_else(|e| panic!("parse failed for {input:?}: {:?}", e.diagnostics));
        let diags = check_conformance(&tree, &demo_schema());
        assert!(
            diags.is_empty(),
            "conformance clean for {input:?}: {diags:?}"
        );
        tree
    }

    #[test]
    fn generated_grammar_passes_all_static_checks() {
        // checked_grammar_from_schema already runs the three checks;
        // this test pins that it succeeds for the full shape matrix.
        demo_grammar();
    }

    #[test]
    fn parses_int_field_variant() {
        let tree = parse_ok("Lit(value: -42)");
        assert_eq!(tree.variant, "Lit");
        assert_eq!(tree.field("value"), Some(&RawValue::Text("-42".into())));
    }

    #[test]
    fn parses_string_and_bool_fields_with_escapes() {
        let tree = parse_ok(r#"Name(text: "hello \"world\"\n", quoted: true)"#);
        assert_eq!(
            tree.field("text"),
            Some(&RawValue::Text("hello \"world\"\n".into()))
        );
        assert_eq!(tree.field("quoted"), Some(&RawValue::Text("true".into())));
    }

    #[test]
    fn parses_nested_one_children() {
        let tree = parse_ok("Add(lhs: Lit(value: 1), rhs: Neg(body: none))");
        let lhs = tree.child_slot("lhs").unwrap();
        assert_eq!(lhs.len(), 1);
        assert_eq!(lhs[0].variant, "Lit");
        let rhs = tree.child_slot("rhs").unwrap();
        assert_eq!(rhs[0].variant, "Neg");
    }

    #[test]
    fn optional_child_none_leaves_slot_absent() {
        let tree = parse_ok("Neg(body: none)");
        assert!(
            tree.child_slot("body").is_none(),
            "bare `none` = absent slot"
        );
    }

    #[test]
    fn optional_child_present_binds_one_tree() {
        let tree = parse_ok("Neg(body: Lit(value: 3))");
        assert_eq!(tree.child_slot("body").unwrap().len(), 1);
    }

    #[test]
    fn many_child_list_binds_in_order_and_drops_commas() {
        let tree = parse_ok("List(items: [Lit(value: 1), Lit(value: 2), Unit()])");
        let items = tree.child_slot("items").unwrap();
        let variants: Vec<&str> = items.iter().map(|t| t.variant.as_str()).collect();
        assert_eq!(variants, ["Lit", "Lit", "Unit"]);
    }

    #[test]
    fn many_child_empty_list_is_conformant() {
        let tree = parse_ok("List(items: [])");
        assert!(
            tree.child_slot("items").is_none_or(<[_]>::is_empty),
            "empty list = zero children"
        );
    }

    #[test]
    fn keyed_map_binds_entries_sorted_by_key() {
        // Written deliberately out of order, with one quoted key that
        // could not be spelled as a bare identifier: the parser is
        // responsible for landing both in canonical order.
        let tree = parse_ok(r#"Env(entries: { zeta: Unit(), "a b": Lit(value: 1) })"#);
        let entries = tree.keyed_child_slot("entries").expect("keyed slot bound");
        let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
        assert_eq!(keys, ["a b", "zeta"]);
        let variants: Vec<&str> = entries.iter().map(|(_, t)| t.variant.as_str()).collect();
        assert_eq!(variants, ["Lit", "Unit"]);
        assert!(
            tree.children.is_empty(),
            "keyed entries must not leak into the positional half: {:?}",
            tree.children
        );
    }

    #[test]
    fn keyed_map_source_order_does_not_change_the_tree() {
        let forward = parse_ok("Env(entries: { a: Unit(), b: Lit(value: 1) })");
        let reversed = parse_ok("Env(entries: { b: Lit(value: 1), a: Unit() })");
        // Spans differ (the two spellings put the subtrees at
        // different offsets), so compare the keyed payload rather than
        // the whole tree.
        let keys = |t: &crate::ParseTree| -> Vec<String> {
            t.keyed_child_slot("entries")
                .unwrap()
                .iter()
                .map(|(k, v)| format!("{k}={}", v.variant))
                .collect()
        };
        assert_eq!(keys(&forward), keys(&reversed));
    }

    #[test]
    fn keyed_map_empty_is_conformant() {
        let tree = parse_ok("Env(entries: {})");
        assert!(
            tree.keyed_child_slot("entries").is_none_or(<[_]>::is_empty),
            "empty map = zero entries"
        );
    }

    #[test]
    fn keyed_map_duplicate_key_parses_but_fails_conformance() {
        // The grammar has no reason to reject it — duplicate detection
        // is the schema's job, and `parse_ok` would hide the split, so
        // this test drives the two stages apart deliberately.
        let g = demo_grammar();
        let tree = g
            .parse("Env(entries: { k: Unit(), k: Lit(value: 1) })")
            .expect("grammar accepts a repeated key");
        let diags = check_conformance(&tree, &demo_schema());
        assert!(
            diags.iter().any(|d| d.code == crate::codes::DUPLICATE_KEY),
            "expected DUPLICATE_KEY; got {:?}",
            diags.iter().map(|d| d.code.as_str()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn zero_argument_variant_parses() {
        let tree = parse_ok("Unit()");
        assert_eq!(tree.variant, "Unit");
        assert!(tree.fields.is_empty() && tree.children.is_empty());
    }

    #[test]
    fn whitespace_and_newlines_are_tolerated() {
        let tree = parse_ok("Add(\n  lhs: Lit( value : 7 ),\n  rhs: Unit()\n)");
        assert_eq!(tree.child_slot("lhs").unwrap()[0].variant, "Lit");
    }

    #[test]
    fn unsupported_field_type_fails_generation_with_full_list() {
        let schema = NodeSchema {
            name: "Bad".into(),
            variants: vec![VariantSchema {
                name: "Par".into(),
                fields: vec![
                    FieldSchema {
                        name: "policy".into(),
                        ty: "Option<JoinPolicy>".into(),
                        optional: false,
                    },
                    FieldSchema {
                        name: "reducer".into(),
                        ty: "ReducerId".into(),
                        optional: false,
                    },
                ],
                children: vec![],
            }],
        };
        let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
        assert_eq!(err.diagnostics.len(), 2, "one diagnostic per bad field");
        assert!(
            err.diagnostics
                .iter()
                .all(|d| d.code == codes::UNSUPPORTED_FIELD)
        );
    }

    /// A scalar-valued keyed slot whose value type has a built-in
    /// canonical-syntax mapping (`String`, integer, `bool`, …)
    /// generates a grammar cleanly — the same built-in mapping the
    /// payload path already uses is reused for the keyed-entry
    /// value slot, wrapped in a synthetic leaf node carrying the
    /// `value` field so `build_scalar_map` reads it back
    /// canonically. Pins the "text syntax landed for Shape 1"
    /// contract so a regression to the pre-0.7 "loud fail" spelling
    /// is impossible to ship.
    #[test]
    fn scalar_keyed_slot_with_builtin_type_generates_grammar() {
        let schema = NodeSchema {
            name: "Cfg".into(),
            variants: vec![VariantSchema {
                name: "Env".into(),
                fields: vec![],
                children: vec![ChildSchema::scalar_map("entries", "String")],
            }],
        };
        grammar_from_schema(&schema, &IdGen::new()).expect(
            "String is a built-in scalar; the pre-flight must accept it and \
             child_arg_peg must emit a grammar rule that wraps each entry's \
             value as a `value`-field leaf",
        );
    }

    /// A scalar-valued keyed slot whose value type has no built-in
    /// mapping (and no `SyntaxOverrides` entry — `child_arg_peg`
    /// does not yet thread overrides into the keyed-entry value
    /// slot) still fails loudly at grammar-generation time with
    /// [`codes::UNSUPPORTED_MAP_VALUE_SHAPE`]. The diagnostic
    /// message points the DSL author at the JSON front-end and the
    /// override path so they never see the raw
    /// `child_arg_peg` `.expect(...)` panic downstream.
    #[test]
    fn scalar_keyed_slot_with_unmapped_type_fails_grammar_generation_loudly() {
        let schema = NodeSchema {
            name: "Cfg".into(),
            variants: vec![VariantSchema {
                name: "Env".into(),
                fields: vec![],
                children: vec![ChildSchema::scalar_map("entries", "JoinPolicy")],
            }],
        };
        let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
        assert_eq!(err.diagnostics.len(), 1);
        assert_eq!(err.diagnostics[0].code, codes::UNSUPPORTED_MAP_VALUE_SHAPE);
        assert!(
            err.diagnostics[0].message.contains("entries"),
            "diagnostic mentions the slot name: {}",
            err.diagnostics[0].message
        );
        assert!(
            err.diagnostics[0].message.contains("JoinPolicy"),
            "diagnostic mentions the scalar value type: {}",
            err.diagnostics[0].message
        );
    }

    /// Recursive keyed slots still generate cleanly — the scalar
    /// gate must not accidentally reject the pre-0.6 keyed shape.
    #[test]
    fn recursive_keyed_slot_still_generates_grammar() {
        let schema = NodeSchema {
            name: "Cfg".into(),
            variants: vec![
                VariantSchema {
                    name: "Env".into(),
                    fields: vec![],
                    children: vec![ChildSchema::recursive("entries", Multiplicity::Map)],
                },
                VariantSchema {
                    name: "Unit".into(),
                    fields: vec![],
                    children: vec![],
                },
            ],
        };
        grammar_from_schema(&schema, &IdGen::new())
            .expect("recursive keyed shape still supported end-to-end in the text front-end");
    }

    /// Flow-shaped schema whose `Par` payload fields the built-in
    /// mapping rejects — the override motivating case.
    fn par_schema() -> NodeSchema {
        NodeSchema {
            name: "Flow".into(),
            variants: vec![
                VariantSchema {
                    name: "Par".into(),
                    fields: vec![
                        FieldSchema {
                            name: "policy".into(),
                            // Token-stream spelling, as the derive extracts it.
                            ty: "Option < JoinPolicy >".into(),
                            optional: false,
                        },
                        FieldSchema {
                            name: "reducer_id".into(),
                            ty: "Option < String >".into(),
                            optional: false,
                        },
                    ],
                    children: vec![ChildSchema {
                        name: "children".into(),
                        multiplicity: Multiplicity::Many,
                        value_shape: ChildValueShape::Recursive,
                        scalar_shorthands: vec![],
                        non_empty: false,
                    }],
                },
                VariantSchema {
                    name: "Call".into(),
                    fields: vec![FieldSchema {
                        name: "label".into(),
                        ty: "String".into(),
                        optional: false,
                    }],
                    children: vec![],
                },
            ],
        }
    }

    fn par_overrides() -> SyntaxOverrides {
        SyntaxOverrides::new()
            .for_type("Option<JoinPolicy>", |ids| {
                choice(
                    ids,
                    vec![
                        token(ids, "%kw:none"),
                        token(ids, "%kw:all_failfast"),
                        token(ids, "%kw:any_failfast"),
                    ],
                )
            })
            .for_type("Option<String>", |ids| {
                choice(ids, vec![token(ids, "%kw:none"), token(ids, "%str")])
            })
    }

    #[test]
    fn type_overrides_unlock_exotic_payload_fields() {
        // Without overrides the Flow-shaped schema fails generation
        // (pinned by unsupported_field_type_fails_generation_with_full_list);
        // with them it generates check-clean and parses. Note the
        // override keys are written without whitespace while the schema
        // carries the token-stream spelling.
        let g = checked_grammar_from_schema_with(&par_schema(), &IdGen::new(), &par_overrides())
            .expect("overridden Flow schema generates a clean grammar");
        let tree = g
            .parse(
                r#"Par(policy: all_failfast, reducer_id: "reduce_all_ordered",
                     children: [Call(label: "a"), Call(label: "b")])"#,
            )
            .expect("canonical Par text parses");
        let diags = check_conformance(&tree, &par_schema());
        assert!(diags.is_empty(), "conformance clean: {diags:?}");
        assert_eq!(
            tree.field("policy"),
            Some(&RawValue::Text("all_failfast".into()))
        );
        assert_eq!(
            tree.field("reducer_id"),
            Some(&RawValue::Text("reduce_all_ordered".into()))
        );
        assert_eq!(tree.child_slot("children").unwrap().len(), 2);
    }

    #[test]
    fn field_override_wins_over_type_override() {
        // Same type in both entries; the (variant, field)-pinned one
        // must decide the syntax.
        let overrides = par_overrides().for_field("Par", "policy", |ids| token(ids, "%kw:pinned"));
        let g = checked_grammar_from_schema_with(&par_schema(), &IdGen::new(), &overrides)
            .expect("clean grammar with field-level override");
        let tree = g
            .parse(r#"Par(policy: pinned, reducer_id: none, children: [])"#)
            .expect("field-level syntax parses");
        assert_eq!(tree.field("policy"), Some(&RawValue::Text("pinned".into())));
        // The type-level spelling is no longer accepted at that site.
        assert!(
            g.parse(r#"Par(policy: all_failfast, reducer_id: none, children: [])"#)
                .is_err(),
            "type-level syntax rejected once the field is pinned"
        );
    }

    #[test]
    fn unrelated_override_leaves_builtin_mapping_and_failure_intact() {
        // An override for some other type neither rescues the
        // unsupported fields nor perturbs built-in ones. Note that
        // `Option<String>` on `reducer_id` is now a built-in mapping
        // (Layer 2 of the "built-in optional payload fields"
        // contract), so only the `Option<JoinPolicy>` field on
        // `policy` remains unmapped without a `SyntaxOverrides` entry.
        let overrides = SyntaxOverrides::new().for_type("Uuid", |ids| token(ids, "%str"));
        let err = grammar_from_schema_with(&par_schema(), &IdGen::new(), &overrides).unwrap_err();
        assert_eq!(
            err.diagnostics.len(),
            1,
            "policy is the only Par field still unmapped without overrides",
        );
        assert!(
            err.diagnostics
                .iter()
                .all(|d| d.code == codes::UNSUPPORTED_FIELD)
        );
        assert!(
            err.diagnostics[0].message.contains("policy"),
            "unmapped-field diagnostic points at `policy`",
        );
        // Built-in demo schema is unaffected by the stray entry.
        let g = checked_grammar_from_schema_with(&demo_schema(), &IdGen::new(), &overrides)
            .expect("demo schema still generates");
        assert_eq!(g.parse("Lit(value: 7)").unwrap().variant, "Lit");
    }

    /// Layer 2: `Option<String>` payload maps to `none | %str` via the
    /// built-in mapping (no `SyntaxOverrides` entry needed). Canonical
    /// text parses both spellings and both build through the derive's
    /// `build_field_optional` route.
    #[test]
    fn builtin_option_string_mapping_accepts_none_and_str() {
        let schema = NodeSchema {
            name: "Meta".into(),
            variants: vec![VariantSchema {
                name: "Row".into(),
                fields: vec![FieldSchema {
                    name: "description".into(),
                    ty: "Option<String>".into(),
                    optional: true,
                }],
                children: vec![],
            }],
        };
        let g = checked_grammar_from_schema(&schema, &IdGen::new())
            .expect("Option<String> is a built-in mapping");
        // `none` spelling.
        let t1 = g.parse(r#"Row(description: none)"#).expect("none parses");
        assert_eq!(
            t1.field("description"),
            Some(&RawValue::Text("none".into())),
        );
        // `%str` spelling.
        let t2 = g.parse(r#"Row(description: "hi")"#).expect("string parses");
        assert_eq!(t2.field("description"), Some(&RawValue::Text("hi".into())));
        // Omitted entirely (Layer 1 optional PEG wrap).
        let t3 = g.parse(r#"Row()"#).expect("omitted parses");
        assert!(t3.field("description").is_none());
        // check_conformance is clean for all three.
        for t in [&t1, &t2, &t3] {
            assert!(
                check_conformance(t, &schema).is_empty(),
                "conformance clean for {t:?}",
            );
        }
    }

    /// Layer 2: `Vec<String>` payload maps to `[ %str ("," %str)* ]`
    /// via the built-in mapping. Empty list, single item, and multi
    /// item all parse; captured text is JSON-parsable so
    /// `build_field_vec` reads it directly.
    #[test]
    fn builtin_vec_string_mapping_accepts_bracketed_list() {
        let schema = NodeSchema {
            name: "Meta".into(),
            variants: vec![VariantSchema {
                name: "Row".into(),
                fields: vec![FieldSchema {
                    name: "tags".into(),
                    ty: "Vec<String>".into(),
                    optional: true,
                }],
                children: vec![],
            }],
        };
        let g = checked_grammar_from_schema(&schema, &IdGen::new())
            .expect("Vec<String> is a built-in mapping");
        // Empty list.
        let t1 = g.parse(r#"Row(tags: [])"#).expect("empty list parses");
        assert_eq!(t1.field("tags"), Some(&RawValue::Text("[]".into())));
        // Multi item. The PEG runtime's implicit whitespace-skip
        // strips inter-token spaces from the captured text, so the
        // field carries the compact form `["a","b"]` (still valid
        // JSON — `serde_json::from_str` accepts it).
        let t2 = g
            .parse(r#"Row(tags: ["a", "b"])"#)
            .expect("two items parses");
        assert_eq!(
            t2.field("tags"),
            Some(&RawValue::Text(r#"["a","b"]"#.into())),
        );
        // Omitted.
        let t3 = g.parse(r#"Row()"#).expect("omitted parses");
        assert!(t3.field("tags").is_none());
        for t in [&t1, &t2, &t3] {
            assert!(
                check_conformance(t, &schema).is_empty(),
                "conformance clean for {t:?}",
            );
        }
    }

    #[test]
    fn empty_schema_fails_generation() {
        let schema = NodeSchema {
            name: "Void".into(),
            variants: vec![],
        };
        let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::EMPTY_SCHEMA);
    }

    #[test]
    fn parse_error_reports_expected_set() {
        let g = demo_grammar();
        let err = g.parse("Lit(value: banana)").unwrap_err();
        assert!(!err.diagnostics.is_empty());
    }
}