dsl_kit_parse/schema_gen.rs
1//! Schema-driven grammar generation (item N).
2//!
3//! The kit's identity axis is "write the AST in Rust, the toolchain
4//! supplies the rest". [`grammar_from_schema`] converts the type-level
5//! shape a `#[derive(DslSchema)]` already extracts into a working
6//! [`Grammar`] for a canonical text syntax — the DSL author writes two
7//! derives and gets an external-format parser for free, instead of
8//! hand-authoring a grammar (in Rust or, worse, in a Bison-style JSON
9//! blob nobody wants to write).
10//!
11//! # Canonical syntax
12//!
13//! One form per variant: the variant name as a keyword, followed by a
14//! parenthesised, comma-separated argument list. Arguments appear in
15//! schema order — payload fields first, then child slots — each spelled
16//! `name: value`:
17//!
18//! ```text
19//! Add(lhs: Lit(value: 1), rhs: Neg(body: none))
20//! List(items: [Lit(value: 1), Lit(value: 2)])
21//! Name(text: "hello world")
22//! Unit()
23//! ```
24//!
25//! - **`One` child** — `name: <node>`.
26//! - **`Optional` child** — `name: <node>` or `name: none`. (If a
27//! variant is literally called `none`, PEG ordered choice still
28//! parses `name: none(...)` as that variant; bare `none` means
29//! absent.)
30//! - **`Many` child** — `name: [<node>, <node>, ...]`, empty list
31//! allowed.
32//! - **`Map` child** — `name: { <key>: <node>, <key>: <node> }`, empty
33//! map allowed. Braces (not the `Many` brackets) mark the slot as
34//! keyed, matching the JSON bridge's object spelling. A key is
35//! either a `%str` literal or a bare `%ident`, so `"a b": …` and
36//! `path: …` are both writable. Entries may be written in any
37//! order — the parser sorts them into the canonical
38//! ascending-by-key form the `ParseTree` requires.
39//! - **Payload fields** — by Rust type source text:
40//! `String` → a `%str` literal; the integer types → `%int`;
41//! `bool` → `true` / `false`. Any other payload type fails
42//! generation with [`codes::UNSUPPORTED_FIELD`] — loudly, per
43//! variant, rather than silently dropping the variant from the
44//! grammar — unless a [`SyntaxOverrides`] entry supplies its value
45//! production.
46//!
47//! # Syntax overrides
48//!
49//! [`grammar_from_schema_with`] accepts a [`SyntaxOverrides`] carrying
50//! value productions for payload types the built-in mapping rejects
51//! (e.g. `Option<JoinPolicy>`), keyed by type source text or pinned to
52//! one `(variant, field)` site. The override supplies only the value
53//! [`Peg`] — the surrounding `name: value` argument shape stays
54//! canonical — and its matched text becomes the field's production, so
55//! the override author owns making that text consumable downstream
56//! (typically `FromStr` on the field type, via
57//! [`build_field`](crate::build_field)).
58//!
59//! # Guarantees
60//!
61//! The generated grammar is left-recursion-free by construction (every
62//! variant rule starts with its keyword token) and contains no nullable
63//! repeats; `GrammarCheck`'s `check_left_recursion` /
64//! `check_nullable_repeat` / `check_schema_consistency` all pass
65//! against it — the tests pin this. Trees produced by parsing satisfy
66//! [`check_conformance`](crate::check_conformance) against the source
67//! schema.
68
69use std::collections::HashMap;
70
71use crate::grammar_check;
72use crate::peg::{
73 Grammar, Peg, choice, field, keyed_entry, node, repeat, rule, rule_ref, seq, token,
74};
75use crate::{BuildError, Diagnostic};
76use dsl_kit_core::IdGen;
77use dsl_kit_schema::{
78 ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, VariantSchema,
79};
80
81/// Diagnostic codes emitted by grammar generation.
82pub mod codes {
83 /// A payload field's Rust type has no canonical-syntax mapping.
84 pub const UNSUPPORTED_FIELD: &str = "dsl_kit::schema_gen::unsupported_field";
85 /// The schema declares no variants — there is nothing to parse.
86 pub const EMPTY_SCHEMA: &str = "dsl_kit::schema_gen::empty_schema";
87 /// A child slot's multiplicity is a variant this build of
88 /// `dsl-kit-parse` does not recognise (added to the schema crate's
89 /// `#[non_exhaustive]` enum ahead of parse-side support). Emitted
90 /// by the pre-flight check in
91 /// [`grammar_from_schema_with`] so `child_arg_peg` never sees an
92 /// unknown variant.
93 pub const UNKNOWN_MULTIPLICITY: &str = "dsl_kit::schema_gen::unknown_multiplicity";
94 /// A keyed child slot declares a value shape the canonical text
95 /// syntax has not yet grown a production for. Emitted by the
96 /// pre-flight check so a scalar-valued keyed slot fails loudly
97 /// at grammar-generation time rather than silently producing a
98 /// grammar that expects each entry's value to be a full AST
99 /// node — the shape mismatch would otherwise surface as an
100 /// opaque parse failure on the DSL author's first document.
101 pub const UNSUPPORTED_MAP_VALUE_SHAPE: &str =
102 "dsl_kit::schema_gen::unsupported_map_value_shape";
103}
104
105/// Name of the generated start rule.
106pub const START_RULE: &str = "node";
107
108/// A deferred value-production constructor: overrides are registered
109/// before the [`IdGen`] doing the generation exists, so each entry is a
110/// factory invoked with the generator's `ids` at build time.
111type PegFactory = Box<dyn Fn(&IdGen) -> Peg>;
112
113/// Value-production overrides for payload fields whose Rust type has no
114/// built-in canonical-syntax mapping (see the module docs).
115///
116/// Two granularities, resolved most-specific-first:
117///
118/// 1. **Per field** ([`Self::for_field`]) — pinned to one
119/// `(variant, field)` site.
120/// 2. **Per type** ([`Self::for_type`]) — keyed by the field's Rust
121/// type source text; whitespace is ignored, so
122/// `"Option<JoinPolicy>"` matches the derive-extracted
123/// `"Option < JoinPolicy >"` spelling.
124///
125/// A field with neither entry falls back to the built-in mapping, and
126/// failing that still fails generation loudly with
127/// [`codes::UNSUPPORTED_FIELD`].
128///
129/// The factory builds only the **value** production; the enclosing
130/// `name ':' <value>` argument shape (and the `Field` sink binding the
131/// matched text to the field name) stays canonical, which keeps the
132/// generated grammar's `GrammarCheck` guarantees intact.
133#[derive(Default)]
134pub struct SyntaxOverrides {
135 by_type: HashMap<String, PegFactory>,
136 by_field: HashMap<(String, String), PegFactory>,
137}
138
139impl SyntaxOverrides {
140 /// An empty override set (equivalent to the built-in mapping only).
141 pub fn new() -> Self {
142 Self::default()
143 }
144
145 /// Registers a value production for every payload field of Rust
146 /// type `ty` (source-text comparison, whitespace-insensitive).
147 pub fn for_type(
148 mut self,
149 ty: impl AsRef<str>,
150 value: impl Fn(&IdGen) -> Peg + 'static,
151 ) -> Self {
152 self.by_type.insert(strip_ws(ty.as_ref()), Box::new(value));
153 self
154 }
155
156 /// Registers a value production for the single field `field` of
157 /// variant `variant`, winning over any [`Self::for_type`] entry.
158 pub fn for_field(
159 mut self,
160 variant: impl Into<String>,
161 field: impl Into<String>,
162 value: impl Fn(&IdGen) -> Peg + 'static,
163 ) -> Self {
164 self.by_field
165 .insert((variant.into(), field.into()), Box::new(value));
166 self
167 }
168
169 /// Most-specific matching factory for `field` of `variant`, if any.
170 fn resolve(&self, variant: &str, field: &FieldSchema) -> Option<&PegFactory> {
171 self.by_field
172 .get(&(variant.to_string(), field.name.clone()))
173 .or_else(|| self.by_type.get(&strip_ws(&field.ty)))
174 }
175}
176
177/// Whitespace-insensitive type key: `Option < JoinPolicy >` (the
178/// token-stream spelling `#[derive(DslSchema)]` extracts) and
179/// `Option<JoinPolicy>` (what an author writes) must compare equal.
180fn strip_ws(ty: &str) -> String {
181 ty.chars().filter(|c| !c.is_whitespace()).collect()
182}
183
184impl Grammar {
185 /// Generates the canonical-syntax grammar for `schema`. See
186 /// [`grammar_from_schema`].
187 pub fn from_schema(schema: &NodeSchema, ids: &IdGen) -> Result<Grammar, BuildError> {
188 grammar_from_schema(schema, ids)
189 }
190}
191
192/// Generates a [`Grammar`] for the canonical named-argument syntax of
193/// `schema` (see the module docs for the syntax), built-in field
194/// mapping only.
195///
196/// Fails with one [`codes::UNSUPPORTED_FIELD`] diagnostic per
197/// unmappable payload field (collected across all variants, so the
198/// author sees the full list at once). To map such fields instead of
199/// failing, use [`grammar_from_schema_with`].
200pub fn grammar_from_schema(schema: &NodeSchema, ids: &IdGen) -> Result<Grammar, BuildError> {
201 grammar_from_schema_with(schema, ids, &SyntaxOverrides::default())
202}
203
204/// [`grammar_from_schema`] with [`SyntaxOverrides`] consulted before
205/// the built-in field mapping (per-field entries win over per-type
206/// entries win over built-ins).
207pub fn grammar_from_schema_with(
208 schema: &NodeSchema,
209 ids: &IdGen,
210 overrides: &SyntaxOverrides,
211) -> Result<Grammar, BuildError> {
212 if schema.variants.is_empty() {
213 return Err(BuildError::single(Diagnostic::error(
214 codes::EMPTY_SCHEMA,
215 format!("schema `{}` declares no variants", schema.name),
216 )));
217 }
218
219 // Pre-flight: collect every diagnostic that must block rule
220 // generation, then return in one shot. A single pass means an
221 // author with both a bad payload type and a `Multiplicity::Map`
222 // slot sees both errors on the first build instead of paying two
223 // edit-compile cycles for one report.
224 //
225 // Grouping:
226 // - `UNSUPPORTED_FIELD` for payload types with no canonical-syntax
227 // mapping (and no `SyntaxOverrides` entry).
228 // - `UNKNOWN_MULTIPLICITY` for child slots whose multiplicity
229 // this build does not know, which is what keeps
230 // `child_arg_peg`'s catch-all arm from ever running.
231 let mut pre_flight = Vec::new();
232 for v in &schema.variants {
233 for f in &v.fields {
234 if resolved_field_value_peg(&v.name, f, ids, overrides).is_none() {
235 pre_flight.push(Diagnostic::error(
236 codes::UNSUPPORTED_FIELD,
237 format!(
238 "variant `{}` field `{}`: type `{}` has no canonical-syntax \
239 mapping (supported: String, bool, the integer types; or \
240 register a `SyntaxOverrides` value production)",
241 v.name, f.name, f.ty
242 ),
243 ));
244 }
245 }
246 for c in &v.children {
247 match c.multiplicity {
248 // Every shape `child_arg_peg` knows how to emit.
249 Multiplicity::One | Multiplicity::Optional | Multiplicity::Many => {}
250 // Keyed slots come in two value shapes at derive
251 // level: recursive (`BTreeMap<String, Self>` /
252 // `BTreeMap<String, Box<Self>>`) and scalar
253 // (`ChildValueShape::Scalar { .. }`, Shape 1 of the
254 // tracking issue). Both are supported by the
255 // canonical text syntax as of dsl-kit 0.7; scalar
256 // values reuse the built-in payload-type mapping
257 // (`field_value_peg`) — same names, same productions
258 // — so any type the payload path can spell
259 // (`String` / integer / `bool` / …) works in a keyed
260 // slot too. A scalar value with no built-in mapping
261 // is still an error here: `child_arg_peg`'s
262 // downstream `.expect(...)` would panic otherwise,
263 // and the DSL author needs a pointer to
264 // `SyntaxOverrides` or a real bug report either way.
265 Multiplicity::Map => {
266 if let ChildValueShape::Scalar { ty } = &c.value_shape {
267 let synthetic = FieldSchema {
268 name: "value".into(),
269 ty: ty.clone(),
270 optional: false,
271 };
272 if field_value_peg(&synthetic, ids).is_none() {
273 pre_flight.push(Diagnostic::error(
274 codes::UNSUPPORTED_MAP_VALUE_SHAPE,
275 format!(
276 "variant `{}` child slot `{}`: keyed scalar value type \
277 `{}` has no canonical-syntax mapping (supported: \
278 String, bool, the integer types, Option<String>, \
279 Vec<String>). Register a `SyntaxOverrides` value \
280 production for the surrounding payload field of the \
281 same type, or use the JSON front-end where scalar \
282 entries are dispatched through serde",
283 v.name, c.name, ty
284 ),
285 ));
286 }
287 }
288 }
289 // `#[non_exhaustive]` catch-all: a future Multiplicity
290 // variant added to dsl-kit-schema before this crate is
291 // updated must also be rejected here — that's what
292 // keeps `child_arg_peg`'s `_ => unreachable!()` arm
293 // honest.
294 _ => {
295 pre_flight.push(Diagnostic::error(
296 codes::UNKNOWN_MULTIPLICITY,
297 format!(
298 "variant `{}` child slot `{}`: unrecognised Multiplicity \
299 variant (upgrade dsl-kit-parse to a version that knows about it)",
300 v.name, c.name
301 ),
302 ));
303 }
304 }
305 }
306 }
307 if !pre_flight.is_empty() {
308 return Err(BuildError::new(pre_flight));
309 }
310
311 let mut rules = Vec::with_capacity(schema.variants.len() + 1);
312 rules.push(rule(
313 ids,
314 START_RULE,
315 choice(
316 ids,
317 schema
318 .variants
319 .iter()
320 .map(|v| rule_ref(ids, v.name.clone()))
321 .collect(),
322 ),
323 ));
324 for v in &schema.variants {
325 rules.push(variant_rule(v, ids, overrides));
326 }
327 Ok(Grammar::new(rules, START_RULE))
328}
329
330/// Builds the rule for one variant. Two shapes:
331///
332/// - **Strict-order** (default, variant has no optional fields):
333/// `%kw:V "(" arg ("," arg)* ")"` with arguments emitted in schema
334/// order (fields, then children). Preserves the pre-0.3 canonical
335/// spelling for variants that never omit.
336/// - **Free-order** (variant has ≥ 1 optional field): `%kw:V "(" (arg
337/// ("," arg)*)? ")"` where each arg is `arg_1 | arg_2 | ...` and
338/// every alternative carries its own `%kw:name` prefix. Args are
339/// distinguishable by that name-keyword, so the DSL author may
340/// omit any subset of optional arguments (or even all of them),
341/// and `check_conformance` remains the authority on required /
342/// duplicate / unknown-slot diagnostics.
343fn variant_rule(v: &VariantSchema, ids: &IdGen, overrides: &SyntaxOverrides) -> Peg {
344 let has_optional = v.fields.iter().any(|f| f.optional);
345 let mut args: Vec<Peg> = Vec::new();
346 for f in &v.fields {
347 let value = resolved_field_value_peg(&v.name, f, ids, overrides)
348 .expect("unsupported field types were rejected before rule generation");
349 args.push(seq(
350 ids,
351 vec![
352 token(ids, format!("%kw:{}", f.name)),
353 token(ids, ":"),
354 field(ids, f.name.clone(), value),
355 ],
356 ));
357 }
358 for c in &v.children {
359 args.push(child_arg_peg(c, ids));
360 }
361
362 let mut items = vec![token(ids, format!("%kw:{}", v.name)), token(ids, "(")];
363 if has_optional && !args.is_empty() {
364 // Free-order: any of the argument shapes, comma-separated,
365 // whole list optional. Each argument-slot is a Field capture
366 // in its own right (built above), and the name-keyword prefix
367 // keeps the alternation unambiguous at the byte level.
368 let arg_choice = choice(ids, args);
369 // The tail repeats `("," arg_choice)`; we rebuild arg_choice
370 // per position so each Choice node gets a fresh id (Peg nodes
371 // are id-unique in a grammar).
372 let tail_alt = |ids: &IdGen| -> Peg {
373 let mut alts: Vec<Peg> = Vec::new();
374 for f in &v.fields {
375 let value = resolved_field_value_peg(&v.name, f, ids, overrides)
376 .expect("unsupported field types were rejected before rule generation");
377 alts.push(seq(
378 ids,
379 vec![
380 token(ids, format!("%kw:{}", f.name)),
381 token(ids, ":"),
382 field(ids, f.name.clone(), value),
383 ],
384 ));
385 }
386 for c in &v.children {
387 alts.push(child_arg_peg(c, ids));
388 }
389 choice(ids, alts)
390 };
391 let tail = repeat(ids, seq(ids, vec![token(ids, ","), tail_alt(ids)]), 0, None);
392 let full = seq(ids, vec![arg_choice, tail]);
393 items.push(repeat(ids, full, 0, Some(1)));
394 } else {
395 for (i, arg) in args.into_iter().enumerate() {
396 if i > 0 {
397 items.push(token(ids, ","));
398 }
399 items.push(arg);
400 }
401 }
402 items.push(token(ids, ")"));
403
404 rule(
405 ids,
406 v.name.clone(),
407 node(ids, v.name.clone(), seq(ids, items)),
408 )
409}
410
411/// Value production for a payload field: the most specific
412/// [`SyntaxOverrides`] entry if registered, else the built-in mapping.
413fn resolved_field_value_peg(
414 variant: &str,
415 f: &FieldSchema,
416 ids: &IdGen,
417 overrides: &SyntaxOverrides,
418) -> Option<Peg> {
419 match overrides.resolve(variant, f) {
420 Some(factory) => Some(factory(ids)),
421 None => field_value_peg(f, ids),
422 }
423}
424
425/// Built-in value production for a payload field, by Rust type source
426/// text. `None` when the type has no canonical-syntax mapping.
427///
428/// Recognised (whitespace-insensitive on the type-source spelling):
429///
430/// - `String` → `%str`
431/// - the integer types → `%int`
432/// - `bool` → `true` / `false`
433/// - `Option<String>` → `none` | `%str`
434/// - `Vec<String>` → `[ %str ("," %str)* ]`, empty list allowed
435///
436/// The last two entries realise Layer 2 of the "built-in optional
437/// payload fields" contract — downstream DSLs no longer need to
438/// register a [`SyntaxOverrides`] entry (nor a paired
439/// `#[dsl_build(with = ...)]` converter) for these shapes.
440fn field_value_peg(f: &FieldSchema, ids: &IdGen) -> Option<Peg> {
441 const INT_TYPES: &[&str] = &[
442 "i8", "i16", "i32", "i64", "i128", "u8", "u16", "u32", "u64", "u128", "usize", "isize",
443 ];
444 let ty = strip_ws(&f.ty);
445 if ty == "String" {
446 Some(token(ids, "%str"))
447 } else if INT_TYPES.contains(&ty.as_str()) {
448 Some(token(ids, "%int"))
449 } else if ty == "bool" {
450 Some(choice(
451 ids,
452 vec![token(ids, "%kw:true"), token(ids, "%kw:false")],
453 ))
454 } else if ty == "Option<String>" {
455 // Canonical spelling of an absent Option-payload; mirrors the
456 // `Multiplicity::Optional` child idiom.
457 Some(choice(
458 ids,
459 vec![token(ids, "%kw:none"), token(ids, "%str")],
460 ))
461 } else if ty == "Vec<String>" {
462 // `[ %str_raw ("," %str_raw)* ]` with empty list allowed.
463 // `%str_raw` (peg-level primitive) contributes the raw
464 // source slice for each element — quotes and escapes intact —
465 // so the joined field text is a JSON-compatible array literal
466 // that `build_field_vec` can hand straight to
467 // `serde_json::from_str`.
468 let elems = seq(
469 ids,
470 vec![
471 token(ids, "%str_raw"),
472 repeat(
473 ids,
474 seq(ids, vec![token(ids, ","), token(ids, "%str_raw")]),
475 0,
476 None,
477 ),
478 ],
479 );
480 Some(seq(
481 ids,
482 vec![
483 token(ids, "["),
484 repeat(ids, elems, 0, Some(1)),
485 token(ids, "]"),
486 ],
487 ))
488 } else {
489 None
490 }
491}
492
493/// Argument production for one child slot, by multiplicity.
494fn child_arg_peg(c: &ChildSchema, ids: &IdGen) -> Peg {
495 let name_kw = token(ids, format!("%kw:{}", c.name));
496 let colon = token(ids, ":");
497 match c.multiplicity {
498 Multiplicity::One => seq(
499 ids,
500 vec![
501 name_kw,
502 colon,
503 field(ids, c.name.clone(), rule_ref(ids, START_RULE)),
504 ],
505 ),
506 // `name: <node>` or `name: none`. The Field arm is tried first,
507 // so a variant literally named `none` still wins when followed
508 // by `(`. The bare-`none` arm sits *outside* any Field: its
509 // matched text lands on the enclosing Node sink where it is
510 // dropped as syntactic noise, leaving the slot absent.
511 Multiplicity::Optional => seq(
512 ids,
513 vec![
514 name_kw,
515 colon,
516 choice(
517 ids,
518 vec![
519 field(ids, c.name.clone(), rule_ref(ids, START_RULE)),
520 token(ids, "%kw:none"),
521 ],
522 ),
523 ],
524 ),
525 // `name: [ <node> ("," <node>)* ]`, empty list allowed. The
526 // list commas live inside the Field body; the mixed-field
527 // "trees win" fallback drops them as noise.
528 Multiplicity::Many => {
529 let elems = seq(
530 ids,
531 vec![
532 rule_ref(ids, START_RULE),
533 repeat(
534 ids,
535 seq(ids, vec![token(ids, ","), rule_ref(ids, START_RULE)]),
536 0,
537 None,
538 ),
539 ],
540 );
541 seq(
542 ids,
543 vec![
544 name_kw,
545 colon,
546 token(ids, "["),
547 field(ids, c.name.clone(), repeat(ids, elems, 0, Some(1))),
548 token(ids, "]"),
549 ],
550 )
551 }
552 // `name: { <key>: <node> ("," <key>: <node>)* }`, empty map
553 // allowed. Braces rather than the `Many` idiom's brackets so
554 // the two shapes are distinguishable at a glance, and matching
555 // the JSON bridge's object spelling so a DSL reads the same
556 // way in both front-ends.
557 //
558 // The key token is `%str | %ident`: keys are arbitrary strings
559 // at the `ParseTree` level, so a quoted form has to exist, but
560 // requiring quotes around every `PATH`-style key would be
561 // noise. `%str` is tried first — a quoted key is unambiguous,
562 // while `%ident` cannot start with `"` — and its production is
563 // the decoded content, so `"a b"` and `a` both arrive as plain
564 // key text.
565 Multiplicity::Map => {
566 //
567 // The `:` separator rides on the *value* half, not the
568 // key half: every token matched inside the key production
569 // contributes to the key text, so a `:` there would land
570 // in the key itself. On the value side it is dropped as
571 // syntactic noise, the same way the `Many` list's commas
572 // are.
573 //
574 // The value half branches on `value_shape`:
575 //
576 // - `Recursive` (`BTreeMap<String, Self>` /
577 // `BTreeMap<String, Box<Self>>`) → the value is a full
578 // AST node, produced by `rule_ref(START_RULE)`.
579 //
580 // - `Scalar { ty }` (`BTreeMap<String, String>` /
581 // `BTreeMap<String, i64>` / …) → the value is a scalar
582 // payload wrapped in a synthetic leaf `Node` whose
583 // single `Field` is named `value`. That matches the
584 // canonical entry shape the JSON bridge emits (see
585 // `serde_bridge::build_scalar_keyed_slot`) so
586 // `build_scalar_map` reads `.field("value")` from each
587 // entry regardless of front-end.
588 //
589 // The `_ =>` fallback keeps the recursive spelling for
590 // any future `ChildValueShape` variant this build does
591 // not yet know about; the pre-flight check in
592 // `grammar_from_schema_with` rejects those cases with
593 // `UNSUPPORTED_MAP_VALUE_SHAPE`, so `child_arg_peg` never
594 // sees an unrecognised shape at run time.
595 let value_prod = |ids: &IdGen| -> Peg {
596 match &c.value_shape {
597 ChildValueShape::Recursive => rule_ref(ids, START_RULE),
598 ChildValueShape::Scalar { ty } => {
599 let synthetic = FieldSchema {
600 name: "value".into(),
601 ty: ty.clone(),
602 optional: false,
603 };
604 let scalar = field_value_peg(&synthetic, ids).expect(
605 "scalar-map value type rejected by pre-flight; \
606 child_arg_peg must not see it",
607 );
608 node(ids, "", field(ids, "value", scalar))
609 }
610 _ => rule_ref(ids, START_RULE),
611 }
612 };
613 let entry = |ids: &IdGen| -> Peg {
614 keyed_entry(
615 ids,
616 c.name.clone(),
617 choice(ids, vec![token(ids, "%str"), token(ids, "%ident")]),
618 seq(ids, vec![token(ids, ":"), value_prod(ids)]),
619 )
620 };
621 let entries = seq(
622 ids,
623 vec![
624 entry(ids),
625 repeat(ids, seq(ids, vec![token(ids, ","), entry(ids)]), 0, None),
626 ],
627 );
628 seq(
629 ids,
630 vec![
631 name_kw,
632 colon,
633 token(ids, "{"),
634 repeat(ids, entries, 0, Some(1)),
635 token(ids, "}"),
636 ],
637 )
638 }
639 // `#[non_exhaustive]` catch-all: a future Multiplicity variant
640 // added to dsl-kit-schema before this crate is updated would
641 // land here. The pre-flight check in
642 // `grammar_from_schema_with` should be extended in lockstep to
643 // reject unknown variants; if that extension is missed the
644 // panic here surfaces the omission loudly instead of emitting
645 // a silently-wrong grammar rule.
646 _ => unreachable!(
647 "child_arg_peg encountered an unrecognised Multiplicity variant on slot \
648 `{}` — extend the pre-flight check in grammar_from_schema_with to reject it",
649 c.name
650 ),
651 }
652}
653
654/// Convenience: generate and immediately assert the grammar is clean
655/// under `GrammarCheck` (left recursion, nullable repeats, schema
656/// consistency). Intended for tests and one-shot setup paths; returns
657/// the same grammar as [`grammar_from_schema`].
658pub fn checked_grammar_from_schema(
659 schema: &NodeSchema,
660 ids: &IdGen,
661) -> Result<Grammar, BuildError> {
662 checked_grammar_from_schema_with(schema, ids, &SyntaxOverrides::default())
663}
664
665/// [`checked_grammar_from_schema`] with [`SyntaxOverrides`] consulted
666/// before the built-in field mapping.
667pub fn checked_grammar_from_schema_with(
668 schema: &NodeSchema,
669 ids: &IdGen,
670 overrides: &SyntaxOverrides,
671) -> Result<Grammar, BuildError> {
672 let grammar = grammar_from_schema_with(schema, ids, overrides)?;
673 let mut diags = grammar_check::check_left_recursion(&grammar);
674 diags.extend(grammar_check::check_nullable_repeat(&grammar));
675 diags.extend(
676 grammar_check::check_schema_consistency(&grammar, schema)
677 .into_iter()
678 .filter(|d| d.severity == crate::Severity::Error),
679 );
680 if diags.is_empty() {
681 Ok(grammar)
682 } else {
683 Err(BuildError::new(diags))
684 }
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690 use crate::{RawValue, check_conformance};
691 use dsl_kit_schema::ChildValueShape;
692
693 /// Expr-flavoured schema exercising every supported shape: int /
694 /// string / bool fields, One / Optional / Many children, and a
695 /// zero-argument variant.
696 fn demo_schema() -> NodeSchema {
697 NodeSchema {
698 name: "Expr".into(),
699 variants: vec![
700 VariantSchema {
701 name: "Lit".into(),
702 fields: vec![FieldSchema {
703 name: "value".into(),
704 ty: "i64".into(),
705 optional: false,
706 }],
707 children: vec![],
708 },
709 VariantSchema {
710 name: "Name".into(),
711 fields: vec![
712 FieldSchema {
713 name: "text".into(),
714 ty: "String".into(),
715 optional: false,
716 },
717 FieldSchema {
718 name: "quoted".into(),
719 ty: "bool".into(),
720 optional: false,
721 },
722 ],
723 children: vec![],
724 },
725 VariantSchema {
726 name: "Add".into(),
727 fields: vec![],
728 children: vec![
729 ChildSchema {
730 name: "lhs".into(),
731 multiplicity: Multiplicity::One,
732 value_shape: ChildValueShape::Recursive,
733 },
734 ChildSchema {
735 name: "rhs".into(),
736 multiplicity: Multiplicity::One,
737 value_shape: ChildValueShape::Recursive,
738 },
739 ],
740 },
741 VariantSchema {
742 name: "Neg".into(),
743 fields: vec![],
744 children: vec![ChildSchema {
745 name: "body".into(),
746 multiplicity: Multiplicity::Optional,
747 value_shape: ChildValueShape::Recursive,
748 }],
749 },
750 VariantSchema {
751 name: "List".into(),
752 fields: vec![],
753 children: vec![ChildSchema {
754 name: "items".into(),
755 multiplicity: Multiplicity::Many,
756 value_shape: ChildValueShape::Recursive,
757 }],
758 },
759 VariantSchema {
760 name: "Env".into(),
761 fields: vec![],
762 children: vec![ChildSchema {
763 name: "entries".into(),
764 multiplicity: Multiplicity::Map,
765 value_shape: ChildValueShape::Recursive,
766 }],
767 },
768 VariantSchema {
769 name: "Unit".into(),
770 fields: vec![],
771 children: vec![],
772 },
773 ],
774 }
775 }
776
777 fn demo_grammar() -> Grammar {
778 checked_grammar_from_schema(&demo_schema(), &IdGen::new())
779 .expect("demo schema generates a clean grammar")
780 }
781
782 /// Parse + conformance-check against the demo schema in one go.
783 fn parse_ok(input: &str) -> crate::ParseTree {
784 let g = demo_grammar();
785 let tree = g
786 .parse(input)
787 .unwrap_or_else(|e| panic!("parse failed for {input:?}: {:?}", e.diagnostics));
788 let diags = check_conformance(&tree, &demo_schema());
789 assert!(
790 diags.is_empty(),
791 "conformance clean for {input:?}: {diags:?}"
792 );
793 tree
794 }
795
796 #[test]
797 fn generated_grammar_passes_all_static_checks() {
798 // checked_grammar_from_schema already runs the three checks;
799 // this test pins that it succeeds for the full shape matrix.
800 demo_grammar();
801 }
802
803 #[test]
804 fn parses_int_field_variant() {
805 let tree = parse_ok("Lit(value: -42)");
806 assert_eq!(tree.variant, "Lit");
807 assert_eq!(tree.field("value"), Some(&RawValue::Text("-42".into())));
808 }
809
810 #[test]
811 fn parses_string_and_bool_fields_with_escapes() {
812 let tree = parse_ok(r#"Name(text: "hello \"world\"\n", quoted: true)"#);
813 assert_eq!(
814 tree.field("text"),
815 Some(&RawValue::Text("hello \"world\"\n".into()))
816 );
817 assert_eq!(tree.field("quoted"), Some(&RawValue::Text("true".into())));
818 }
819
820 #[test]
821 fn parses_nested_one_children() {
822 let tree = parse_ok("Add(lhs: Lit(value: 1), rhs: Neg(body: none))");
823 let lhs = tree.child_slot("lhs").unwrap();
824 assert_eq!(lhs.len(), 1);
825 assert_eq!(lhs[0].variant, "Lit");
826 let rhs = tree.child_slot("rhs").unwrap();
827 assert_eq!(rhs[0].variant, "Neg");
828 }
829
830 #[test]
831 fn optional_child_none_leaves_slot_absent() {
832 let tree = parse_ok("Neg(body: none)");
833 assert!(
834 tree.child_slot("body").is_none(),
835 "bare `none` = absent slot"
836 );
837 }
838
839 #[test]
840 fn optional_child_present_binds_one_tree() {
841 let tree = parse_ok("Neg(body: Lit(value: 3))");
842 assert_eq!(tree.child_slot("body").unwrap().len(), 1);
843 }
844
845 #[test]
846 fn many_child_list_binds_in_order_and_drops_commas() {
847 let tree = parse_ok("List(items: [Lit(value: 1), Lit(value: 2), Unit()])");
848 let items = tree.child_slot("items").unwrap();
849 let variants: Vec<&str> = items.iter().map(|t| t.variant.as_str()).collect();
850 assert_eq!(variants, ["Lit", "Lit", "Unit"]);
851 }
852
853 #[test]
854 fn many_child_empty_list_is_conformant() {
855 let tree = parse_ok("List(items: [])");
856 assert!(
857 tree.child_slot("items").is_none_or(<[_]>::is_empty),
858 "empty list = zero children"
859 );
860 }
861
862 #[test]
863 fn keyed_map_binds_entries_sorted_by_key() {
864 // Written deliberately out of order, with one quoted key that
865 // could not be spelled as a bare identifier: the parser is
866 // responsible for landing both in canonical order.
867 let tree = parse_ok(r#"Env(entries: { zeta: Unit(), "a b": Lit(value: 1) })"#);
868 let entries = tree.keyed_child_slot("entries").expect("keyed slot bound");
869 let keys: Vec<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
870 assert_eq!(keys, ["a b", "zeta"]);
871 let variants: Vec<&str> = entries.iter().map(|(_, t)| t.variant.as_str()).collect();
872 assert_eq!(variants, ["Lit", "Unit"]);
873 assert!(
874 tree.children.is_empty(),
875 "keyed entries must not leak into the positional half: {:?}",
876 tree.children
877 );
878 }
879
880 #[test]
881 fn keyed_map_source_order_does_not_change_the_tree() {
882 let forward = parse_ok("Env(entries: { a: Unit(), b: Lit(value: 1) })");
883 let reversed = parse_ok("Env(entries: { b: Lit(value: 1), a: Unit() })");
884 // Spans differ (the two spellings put the subtrees at
885 // different offsets), so compare the keyed payload rather than
886 // the whole tree.
887 let keys = |t: &crate::ParseTree| -> Vec<String> {
888 t.keyed_child_slot("entries")
889 .unwrap()
890 .iter()
891 .map(|(k, v)| format!("{k}={}", v.variant))
892 .collect()
893 };
894 assert_eq!(keys(&forward), keys(&reversed));
895 }
896
897 #[test]
898 fn keyed_map_empty_is_conformant() {
899 let tree = parse_ok("Env(entries: {})");
900 assert!(
901 tree.keyed_child_slot("entries").is_none_or(<[_]>::is_empty),
902 "empty map = zero entries"
903 );
904 }
905
906 #[test]
907 fn keyed_map_duplicate_key_parses_but_fails_conformance() {
908 // The grammar has no reason to reject it — duplicate detection
909 // is the schema's job, and `parse_ok` would hide the split, so
910 // this test drives the two stages apart deliberately.
911 let g = demo_grammar();
912 let tree = g
913 .parse("Env(entries: { k: Unit(), k: Lit(value: 1) })")
914 .expect("grammar accepts a repeated key");
915 let diags = check_conformance(&tree, &demo_schema());
916 assert!(
917 diags.iter().any(|d| d.code == crate::codes::DUPLICATE_KEY),
918 "expected DUPLICATE_KEY; got {:?}",
919 diags.iter().map(|d| d.code.as_str()).collect::<Vec<_>>()
920 );
921 }
922
923 #[test]
924 fn zero_argument_variant_parses() {
925 let tree = parse_ok("Unit()");
926 assert_eq!(tree.variant, "Unit");
927 assert!(tree.fields.is_empty() && tree.children.is_empty());
928 }
929
930 #[test]
931 fn whitespace_and_newlines_are_tolerated() {
932 let tree = parse_ok("Add(\n lhs: Lit( value : 7 ),\n rhs: Unit()\n)");
933 assert_eq!(tree.child_slot("lhs").unwrap()[0].variant, "Lit");
934 }
935
936 #[test]
937 fn unsupported_field_type_fails_generation_with_full_list() {
938 let schema = NodeSchema {
939 name: "Bad".into(),
940 variants: vec![VariantSchema {
941 name: "Par".into(),
942 fields: vec![
943 FieldSchema {
944 name: "policy".into(),
945 ty: "Option<JoinPolicy>".into(),
946 optional: false,
947 },
948 FieldSchema {
949 name: "reducer".into(),
950 ty: "ReducerId".into(),
951 optional: false,
952 },
953 ],
954 children: vec![],
955 }],
956 };
957 let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
958 assert_eq!(err.diagnostics.len(), 2, "one diagnostic per bad field");
959 assert!(
960 err.diagnostics
961 .iter()
962 .all(|d| d.code == codes::UNSUPPORTED_FIELD)
963 );
964 }
965
966 /// A scalar-valued keyed slot whose value type has a built-in
967 /// canonical-syntax mapping (`String`, integer, `bool`, …)
968 /// generates a grammar cleanly — the same built-in mapping the
969 /// payload path already uses is reused for the keyed-entry
970 /// value slot, wrapped in a synthetic leaf node carrying the
971 /// `value` field so `build_scalar_map` reads it back
972 /// canonically. Pins the "text syntax landed for Shape 1"
973 /// contract so a regression to the pre-0.7 "loud fail" spelling
974 /// is impossible to ship.
975 #[test]
976 fn scalar_keyed_slot_with_builtin_type_generates_grammar() {
977 let schema = NodeSchema {
978 name: "Cfg".into(),
979 variants: vec![VariantSchema {
980 name: "Env".into(),
981 fields: vec![],
982 children: vec![ChildSchema::scalar_map("entries", "String")],
983 }],
984 };
985 grammar_from_schema(&schema, &IdGen::new()).expect(
986 "String is a built-in scalar; the pre-flight must accept it and \
987 child_arg_peg must emit a grammar rule that wraps each entry's \
988 value as a `value`-field leaf",
989 );
990 }
991
992 /// A scalar-valued keyed slot whose value type has no built-in
993 /// mapping (and no `SyntaxOverrides` entry — `child_arg_peg`
994 /// does not yet thread overrides into the keyed-entry value
995 /// slot) still fails loudly at grammar-generation time with
996 /// [`codes::UNSUPPORTED_MAP_VALUE_SHAPE`]. The diagnostic
997 /// message points the DSL author at the JSON front-end and the
998 /// override path so they never see the raw
999 /// `child_arg_peg` `.expect(...)` panic downstream.
1000 #[test]
1001 fn scalar_keyed_slot_with_unmapped_type_fails_grammar_generation_loudly() {
1002 let schema = NodeSchema {
1003 name: "Cfg".into(),
1004 variants: vec![VariantSchema {
1005 name: "Env".into(),
1006 fields: vec![],
1007 children: vec![ChildSchema::scalar_map("entries", "JoinPolicy")],
1008 }],
1009 };
1010 let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
1011 assert_eq!(err.diagnostics.len(), 1);
1012 assert_eq!(err.diagnostics[0].code, codes::UNSUPPORTED_MAP_VALUE_SHAPE);
1013 assert!(
1014 err.diagnostics[0].message.contains("entries"),
1015 "diagnostic mentions the slot name: {}",
1016 err.diagnostics[0].message
1017 );
1018 assert!(
1019 err.diagnostics[0].message.contains("JoinPolicy"),
1020 "diagnostic mentions the scalar value type: {}",
1021 err.diagnostics[0].message
1022 );
1023 }
1024
1025 /// Recursive keyed slots still generate cleanly — the scalar
1026 /// gate must not accidentally reject the pre-0.6 keyed shape.
1027 #[test]
1028 fn recursive_keyed_slot_still_generates_grammar() {
1029 let schema = NodeSchema {
1030 name: "Cfg".into(),
1031 variants: vec![
1032 VariantSchema {
1033 name: "Env".into(),
1034 fields: vec![],
1035 children: vec![ChildSchema::recursive("entries", Multiplicity::Map)],
1036 },
1037 VariantSchema {
1038 name: "Unit".into(),
1039 fields: vec![],
1040 children: vec![],
1041 },
1042 ],
1043 };
1044 grammar_from_schema(&schema, &IdGen::new())
1045 .expect("recursive keyed shape still supported end-to-end in the text front-end");
1046 }
1047
1048 /// Flow-shaped schema whose `Par` payload fields the built-in
1049 /// mapping rejects — the override motivating case.
1050 fn par_schema() -> NodeSchema {
1051 NodeSchema {
1052 name: "Flow".into(),
1053 variants: vec![
1054 VariantSchema {
1055 name: "Par".into(),
1056 fields: vec![
1057 FieldSchema {
1058 name: "policy".into(),
1059 // Token-stream spelling, as the derive extracts it.
1060 ty: "Option < JoinPolicy >".into(),
1061 optional: false,
1062 },
1063 FieldSchema {
1064 name: "reducer_id".into(),
1065 ty: "Option < String >".into(),
1066 optional: false,
1067 },
1068 ],
1069 children: vec![ChildSchema {
1070 name: "children".into(),
1071 multiplicity: Multiplicity::Many,
1072 value_shape: ChildValueShape::Recursive,
1073 }],
1074 },
1075 VariantSchema {
1076 name: "Call".into(),
1077 fields: vec![FieldSchema {
1078 name: "label".into(),
1079 ty: "String".into(),
1080 optional: false,
1081 }],
1082 children: vec![],
1083 },
1084 ],
1085 }
1086 }
1087
1088 fn par_overrides() -> SyntaxOverrides {
1089 SyntaxOverrides::new()
1090 .for_type("Option<JoinPolicy>", |ids| {
1091 choice(
1092 ids,
1093 vec![
1094 token(ids, "%kw:none"),
1095 token(ids, "%kw:all_failfast"),
1096 token(ids, "%kw:any_failfast"),
1097 ],
1098 )
1099 })
1100 .for_type("Option<String>", |ids| {
1101 choice(ids, vec![token(ids, "%kw:none"), token(ids, "%str")])
1102 })
1103 }
1104
1105 #[test]
1106 fn type_overrides_unlock_exotic_payload_fields() {
1107 // Without overrides the Flow-shaped schema fails generation
1108 // (pinned by unsupported_field_type_fails_generation_with_full_list);
1109 // with them it generates check-clean and parses. Note the
1110 // override keys are written without whitespace while the schema
1111 // carries the token-stream spelling.
1112 let g = checked_grammar_from_schema_with(&par_schema(), &IdGen::new(), &par_overrides())
1113 .expect("overridden Flow schema generates a clean grammar");
1114 let tree = g
1115 .parse(
1116 r#"Par(policy: all_failfast, reducer_id: "reduce_all_ordered",
1117 children: [Call(label: "a"), Call(label: "b")])"#,
1118 )
1119 .expect("canonical Par text parses");
1120 let diags = check_conformance(&tree, &par_schema());
1121 assert!(diags.is_empty(), "conformance clean: {diags:?}");
1122 assert_eq!(
1123 tree.field("policy"),
1124 Some(&RawValue::Text("all_failfast".into()))
1125 );
1126 assert_eq!(
1127 tree.field("reducer_id"),
1128 Some(&RawValue::Text("reduce_all_ordered".into()))
1129 );
1130 assert_eq!(tree.child_slot("children").unwrap().len(), 2);
1131 }
1132
1133 #[test]
1134 fn field_override_wins_over_type_override() {
1135 // Same type in both entries; the (variant, field)-pinned one
1136 // must decide the syntax.
1137 let overrides = par_overrides().for_field("Par", "policy", |ids| token(ids, "%kw:pinned"));
1138 let g = checked_grammar_from_schema_with(&par_schema(), &IdGen::new(), &overrides)
1139 .expect("clean grammar with field-level override");
1140 let tree = g
1141 .parse(r#"Par(policy: pinned, reducer_id: none, children: [])"#)
1142 .expect("field-level syntax parses");
1143 assert_eq!(tree.field("policy"), Some(&RawValue::Text("pinned".into())));
1144 // The type-level spelling is no longer accepted at that site.
1145 assert!(
1146 g.parse(r#"Par(policy: all_failfast, reducer_id: none, children: [])"#)
1147 .is_err(),
1148 "type-level syntax rejected once the field is pinned"
1149 );
1150 }
1151
1152 #[test]
1153 fn unrelated_override_leaves_builtin_mapping_and_failure_intact() {
1154 // An override for some other type neither rescues the
1155 // unsupported fields nor perturbs built-in ones. Note that
1156 // `Option<String>` on `reducer_id` is now a built-in mapping
1157 // (Layer 2 of the "built-in optional payload fields"
1158 // contract), so only the `Option<JoinPolicy>` field on
1159 // `policy` remains unmapped without a `SyntaxOverrides` entry.
1160 let overrides = SyntaxOverrides::new().for_type("Uuid", |ids| token(ids, "%str"));
1161 let err = grammar_from_schema_with(&par_schema(), &IdGen::new(), &overrides).unwrap_err();
1162 assert_eq!(
1163 err.diagnostics.len(),
1164 1,
1165 "policy is the only Par field still unmapped without overrides",
1166 );
1167 assert!(
1168 err.diagnostics
1169 .iter()
1170 .all(|d| d.code == codes::UNSUPPORTED_FIELD)
1171 );
1172 assert!(
1173 err.diagnostics[0].message.contains("policy"),
1174 "unmapped-field diagnostic points at `policy`",
1175 );
1176 // Built-in demo schema is unaffected by the stray entry.
1177 let g = checked_grammar_from_schema_with(&demo_schema(), &IdGen::new(), &overrides)
1178 .expect("demo schema still generates");
1179 assert_eq!(g.parse("Lit(value: 7)").unwrap().variant, "Lit");
1180 }
1181
1182 /// Layer 2: `Option<String>` payload maps to `none | %str` via the
1183 /// built-in mapping (no `SyntaxOverrides` entry needed). Canonical
1184 /// text parses both spellings and both build through the derive's
1185 /// `build_field_optional` route.
1186 #[test]
1187 fn builtin_option_string_mapping_accepts_none_and_str() {
1188 let schema = NodeSchema {
1189 name: "Meta".into(),
1190 variants: vec![VariantSchema {
1191 name: "Row".into(),
1192 fields: vec![FieldSchema {
1193 name: "description".into(),
1194 ty: "Option<String>".into(),
1195 optional: true,
1196 }],
1197 children: vec![],
1198 }],
1199 };
1200 let g = checked_grammar_from_schema(&schema, &IdGen::new())
1201 .expect("Option<String> is a built-in mapping");
1202 // `none` spelling.
1203 let t1 = g.parse(r#"Row(description: none)"#).expect("none parses");
1204 assert_eq!(
1205 t1.field("description"),
1206 Some(&RawValue::Text("none".into())),
1207 );
1208 // `%str` spelling.
1209 let t2 = g.parse(r#"Row(description: "hi")"#).expect("string parses");
1210 assert_eq!(t2.field("description"), Some(&RawValue::Text("hi".into())));
1211 // Omitted entirely (Layer 1 optional PEG wrap).
1212 let t3 = g.parse(r#"Row()"#).expect("omitted parses");
1213 assert!(t3.field("description").is_none());
1214 // check_conformance is clean for all three.
1215 for t in [&t1, &t2, &t3] {
1216 assert!(
1217 check_conformance(t, &schema).is_empty(),
1218 "conformance clean for {t:?}",
1219 );
1220 }
1221 }
1222
1223 /// Layer 2: `Vec<String>` payload maps to `[ %str ("," %str)* ]`
1224 /// via the built-in mapping. Empty list, single item, and multi
1225 /// item all parse; captured text is JSON-parsable so
1226 /// `build_field_vec` reads it directly.
1227 #[test]
1228 fn builtin_vec_string_mapping_accepts_bracketed_list() {
1229 let schema = NodeSchema {
1230 name: "Meta".into(),
1231 variants: vec![VariantSchema {
1232 name: "Row".into(),
1233 fields: vec![FieldSchema {
1234 name: "tags".into(),
1235 ty: "Vec<String>".into(),
1236 optional: true,
1237 }],
1238 children: vec![],
1239 }],
1240 };
1241 let g = checked_grammar_from_schema(&schema, &IdGen::new())
1242 .expect("Vec<String> is a built-in mapping");
1243 // Empty list.
1244 let t1 = g.parse(r#"Row(tags: [])"#).expect("empty list parses");
1245 assert_eq!(t1.field("tags"), Some(&RawValue::Text("[]".into())));
1246 // Multi item. The PEG runtime's implicit whitespace-skip
1247 // strips inter-token spaces from the captured text, so the
1248 // field carries the compact form `["a","b"]` (still valid
1249 // JSON — `serde_json::from_str` accepts it).
1250 let t2 = g
1251 .parse(r#"Row(tags: ["a", "b"])"#)
1252 .expect("two items parses");
1253 assert_eq!(
1254 t2.field("tags"),
1255 Some(&RawValue::Text(r#"["a","b"]"#.into())),
1256 );
1257 // Omitted.
1258 let t3 = g.parse(r#"Row()"#).expect("omitted parses");
1259 assert!(t3.field("tags").is_none());
1260 for t in [&t1, &t2, &t3] {
1261 assert!(
1262 check_conformance(t, &schema).is_empty(),
1263 "conformance clean for {t:?}",
1264 );
1265 }
1266 }
1267
1268 #[test]
1269 fn empty_schema_fails_generation() {
1270 let schema = NodeSchema {
1271 name: "Void".into(),
1272 variants: vec![],
1273 };
1274 let err = grammar_from_schema(&schema, &IdGen::new()).unwrap_err();
1275 assert_eq!(err.diagnostics[0].code, codes::EMPTY_SCHEMA);
1276 }
1277
1278 #[test]
1279 fn parse_error_reports_expected_set() {
1280 let g = demo_grammar();
1281 let err = g.parse("Lit(value: banana)").unwrap_err();
1282 assert!(!err.diagnostics.is_empty());
1283 }
1284}