dsl_kit_parse/lib.rs
1//! Parser trunk for `dsl-kit` DSLs.
2//!
3//! Two front-ends (serde bridge in G-1b, PEG interpreter in G-2) will
4//! both feed a single [`ParseTree`] shape. One consumer,
5//! `#[derive(DslBuild)]` (G-1c), converts a validated tree into a
6//! typed AST value using the caller's [`IdGen`] to mint fresh
7//! [`NodeId`]s.
8//!
9//! This module (G-1a) lands the central data types and the schema
10//! conformance checker that both front-ends run against. All feedback
11//! flows through one [`Diagnostic`] envelope so the consumer AI sees a
12//! single dialect across parsing, conformance, lint, and debugger.
13//!
14//! ## Architecture (layers)
15//!
16//! - [`ParseTree`] — untyped trunk. Variant name + field payloads +
17//! named child slots (positional lists, plus keyed entries for
18//! [`Multiplicity::Map`] slots) + usage-site lint suppressions
19//! ([`allow`]) + optional source [`Span`].
20//! - [`RawValue`] — per-field payload representation. `Text` keeps the
21//! PEG front-end's matched source text; `Json` keeps the serde
22//! front-end's typed value with no stringify round-trip.
23//! - [`check_conformance`] — validates a tree against a
24//! [`NodeSchema`] and returns diagnostics.
25//! - [`Diagnostic`] / [`Severity`] / [`Location`] — the shared
26//! envelope shape.
27//! - [`DslBuild`] — trait consumed by the derive to build a typed AST.
28//! - [`BuildError`] — non-empty diagnostic bag returned on build
29//! failure.
30
31#![warn(missing_docs)]
32
33use dsl_kit_core::{IdGen, NodeId, Suggester, Suggestion};
34use dsl_kit_schema::{ChildSchema, Multiplicity, NodeSchema, VariantSchema};
35use serde_json::{Value, json};
36use std::cmp::Ordering;
37use std::collections::BTreeMap;
38use std::fmt;
39
40pub mod allow;
41pub mod example_gen;
42pub mod grammar_check;
43pub mod import;
44pub mod peg;
45pub mod schema_gen;
46pub mod serde_bridge;
47
48// ---------------------------------------------------------------------------
49// Span
50// ---------------------------------------------------------------------------
51
52/// Byte-offset range into the parser input.
53///
54/// The PEG front-end fills this in as it consumes input; the serde
55/// front-end leaves it `None` because JSON payloads have no meaningful
56/// source position after deserialization.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct Span {
59 /// Inclusive start byte offset.
60 pub start: usize,
61 /// Exclusive end byte offset.
62 pub end: usize,
63}
64
65impl Span {
66 /// Constructs a new [`Span`].
67 pub const fn new(start: usize, end: usize) -> Self {
68 Self { start, end }
69 }
70}
71
72// ---------------------------------------------------------------------------
73// RawValue
74// ---------------------------------------------------------------------------
75
76/// Per-field payload representation carried by [`ParseTree`].
77///
78/// The two arms correspond to the two front-ends:
79///
80/// - [`RawValue::Text`] is the matched source text a PEG rule produced;
81/// the [`DslBuild`] consumer converts it via `FromStr`.
82/// - [`RawValue::Json`] is a typed value straight from serde; the
83/// consumer converts it via serde deserialization. Nested payloads
84/// like `Option<u32>` never take a stringify → reparse detour.
85#[derive(Debug, Clone, PartialEq)]
86pub enum RawValue {
87 /// Matched source text (PEG front-end).
88 Text(String),
89 /// Typed value (serde front-end).
90 Json(Value),
91}
92
93// ---------------------------------------------------------------------------
94// ParseTree
95// ---------------------------------------------------------------------------
96
97/// Untyped parse trunk, produced by any front-end and consumed by
98/// [`DslBuild`].
99///
100/// The shape deliberately mirrors [`NodeSchema`] / [`VariantSchema`]:
101/// `variant` picks a variant by name; `fields` carries non-recursive
102/// payload; `children` carries named **positional** child slots each
103/// holding an ordered list of subtrees; `keyed_children` carries named
104/// **keyed** child slots ([`Multiplicity::Map`]) holding `(key,
105/// subtree)` pairs.
106///
107/// A given slot name lives in exactly one of the two child vectors —
108/// whichever one its schema [`Multiplicity`] calls for. Putting it in
109/// the wrong one is a [`codes::KEYED_SLOT_SHAPE`] diagnostic at
110/// conformance time rather than a silent drop.
111#[derive(Debug, Clone, PartialEq)]
112pub struct ParseTree {
113 /// Variant name — must match a [`VariantSchema::name`] at
114 /// conformance time.
115 pub variant: String,
116 /// Non-recursive payload fields, keyed by field name.
117 pub fields: Vec<(String, RawValue)>,
118 /// Positional child slots, keyed by slot name. Each slot's inner
119 /// [`Vec`] holds zero-or-more trees per the child's
120 /// [`Multiplicity`] ([`One`](Multiplicity::One) /
121 /// [`Optional`](Multiplicity::Optional) /
122 /// [`Many`](Multiplicity::Many)).
123 pub children: Vec<(String, Vec<ParseTree>)>,
124 /// Keyed child slots ([`Multiplicity::Map`]), by slot name. Each
125 /// slot holds `(key, subtree)` pairs.
126 ///
127 /// Front-ends must emit the pairs **sorted by key**, so that two
128 /// front-ends handed the same document produce equal entries. The
129 /// JSON bridge sorts on ingest; hand-built trees that do not are
130 /// rejected at conformance time with
131 /// [`codes::KEYED_SLOT_UNSORTED`] rather than quietly compared
132 /// unequal later.
133 ///
134 /// One shape is *not* pinned across front-ends: an **empty** map
135 /// may arrive either as a present-but-empty slot or as no slot at
136 /// all, depending on how the front-end spells emptiness (the JSON
137 /// bridge records the key it saw; the PEG interpreter has nothing
138 /// to record). Both mean the same thing everywhere it matters —
139 /// [`check_conformance`] accepts both and
140 /// [`build_child_map`] yields an empty map from both — so
141 /// consumers should read a slot through
142 /// [`ParseTree::keyed_child_slot`] rather than testing for its
143 /// presence. The positional [`ParseTree::children`] half has
144 /// carried the same asymmetry since it existed.
145 ///
146 /// Duplicate keys within one slot are representable (the storage
147 /// is a [`Vec`], not a map) precisely so they can be *diagnosed* —
148 /// [`codes::DUPLICATE_KEY`] — instead of one entry silently
149 /// winning.
150 pub keyed_children: Vec<(String, Vec<(String, ParseTree)>)>,
151 /// Lint rule names this node suppresses at its own usage site,
152 /// verbatim in the order the document wrote them.
153 ///
154 /// Filled in by the front-end from the reserved
155 /// [`allow::ALLOW_KEY`] (`$allow`) spelling — a document concern,
156 /// not a schema one. [`check_conformance`] ignores the vector
157 /// entirely: an annotation neither satisfies nor violates a
158 /// [`NodeSchema`]. The build (`#[derive(DslBuild)]`) carries it
159 /// across to the typed AST as a
160 /// [`dsl_kit_core::AllowTable`] entry keyed on the minted
161 /// [`NodeId`], which is where a linter reads it.
162 ///
163 /// Empty is the overwhelmingly common case and means "no
164 /// suppression here".
165 pub allows: Vec<String>,
166 /// Source-range span, if the front-end tracks it.
167 pub span: Option<Span>,
168}
169
170impl ParseTree {
171 /// Constructs a new [`ParseTree`] with no fields, children, or span.
172 pub fn new(variant: impl Into<String>) -> Self {
173 Self {
174 variant: variant.into(),
175 fields: Vec::new(),
176 children: Vec::new(),
177 keyed_children: Vec::new(),
178 allows: Vec::new(),
179 span: None,
180 }
181 }
182
183 /// Looks up a payload field by name.
184 pub fn field(&self, name: &str) -> Option<&RawValue> {
185 self.fields.iter().find(|(n, _)| n == name).map(|(_, v)| v)
186 }
187
188 /// Looks up a positional child slot by name.
189 pub fn child_slot(&self, name: &str) -> Option<&[ParseTree]> {
190 self.children
191 .iter()
192 .find(|(n, _)| n == name)
193 .map(|(_, v)| v.as_slice())
194 }
195
196 /// Looks up a keyed child slot ([`Multiplicity::Map`]) by name.
197 ///
198 /// Returns the slot's `(key, subtree)` pairs in the order the
199 /// front-end emitted them. For a tree that passed
200 /// [`check_conformance`] that order is ascending by key; on an
201 /// unchecked tree it is whatever the producer wrote.
202 pub fn keyed_child_slot(&self, name: &str) -> Option<&[(String, ParseTree)]> {
203 self.keyed_children
204 .iter()
205 .find(|(n, _)| n == name)
206 .map(|(_, v)| v.as_slice())
207 }
208}
209
210// ---------------------------------------------------------------------------
211// Diagnostic envelope
212// ---------------------------------------------------------------------------
213
214/// Severity level of a [`Diagnostic`].
215///
216/// Matches the shape used by `dsl-kit-lint` so consumers speak one
217/// dialect across parse / conformance / lint / debugger.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum Severity {
220 /// Blocks build. Multiple errors may be collected before returning.
221 Error,
222 /// Non-blocking warning.
223 Warning,
224 /// Advisory note.
225 Info,
226}
227
228impl Severity {
229 /// Returns the wire-format string used by [`Diagnostic::to_json`].
230 pub const fn as_str(self) -> &'static str {
231 match self {
232 Severity::Error => "error",
233 Severity::Warning => "warning",
234 Severity::Info => "info",
235 }
236 }
237}
238
239/// Where a [`Diagnostic`] points into the consumer's material.
240///
241/// [`Location::Span`] is the parse-time answer (byte range into the
242/// input text); [`Location::Node`] is the post-build answer
243/// ([`NodeId`] into the typed AST); [`Location::None`] is for
244/// diagnostics without a natural anchor point (e.g. "missing top-level
245/// variant").
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum Location {
248 /// Source-text range.
249 Span(Span),
250 /// AST node identity.
251 Node(NodeId),
252 /// No anchor point.
253 None,
254}
255
256impl Location {
257 /// Renders the location as the JSON value used by
258 /// [`Diagnostic::to_json`].
259 ///
260 /// - `Location::Span { start, end }` → `{ "kind": "span", "start": N, "end": M }`
261 /// - `Location::Node(id)` → `{ "kind": "node", "id": N }`
262 /// - `Location::None` → JSON `null`
263 pub fn to_json(&self) -> Value {
264 match self {
265 Location::Span(Span { start, end }) => {
266 json!({ "kind": "span", "start": start, "end": end })
267 }
268 Location::Node(id) => json!({ "kind": "node", "id": id.0 }),
269 Location::None => Value::Null,
270 }
271 }
272}
273
274/// One diagnostic in the unified envelope shared across parse,
275/// conformance, lint, and debugger feedback.
276///
277/// The consumer AI is expected to read a single JSON dialect regardless
278/// of which subsystem produced the diagnostic: `{ severity, code,
279/// message, location }`. `code` is a stable machine-friendly slug
280/// (e.g. `"dsl_kit::parse::unknown_variant"`); `message` is the human
281/// (or AI) readable one-liner.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct Diagnostic {
284 /// Severity level.
285 pub severity: Severity,
286 /// Stable machine slug.
287 pub code: String,
288 /// One-line human / AI readable description.
289 pub message: String,
290 /// Anchor point (or [`Location::None`]).
291 pub location: Location,
292}
293
294impl Diagnostic {
295 /// Constructs an [`Severity::Error`] diagnostic.
296 pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
297 Self {
298 severity: Severity::Error,
299 code: code.into(),
300 message: message.into(),
301 location: Location::None,
302 }
303 }
304
305 /// Attaches a source [`Span`] as the location.
306 pub fn with_span(mut self, span: Option<Span>) -> Self {
307 if let Some(span) = span {
308 self.location = Location::Span(span);
309 }
310 self
311 }
312
313 /// Attaches an AST [`NodeId`] as the location.
314 pub fn with_node(mut self, id: NodeId) -> Self {
315 self.location = Location::Node(id);
316 self
317 }
318
319 /// Renders the diagnostic as a JSON value.
320 ///
321 /// Layout:
322 /// ```json
323 /// {
324 /// "severity": "error",
325 /// "code": "dsl_kit::parse::unknown_variant",
326 /// "message": "unknown variant `Foo` (candidates: Add, Mul, Lit)",
327 /// "location": { "kind": "span", "start": 0, "end": 3 }
328 /// }
329 /// ```
330 pub fn to_json(&self) -> Value {
331 json!({
332 "severity": self.severity.as_str(),
333 "code": self.code,
334 "message": self.message,
335 "location": self.location.to_json(),
336 })
337 }
338}
339
340// ---------------------------------------------------------------------------
341// BuildError
342// ---------------------------------------------------------------------------
343
344/// Non-empty diagnostic bag returned by [`DslBuild::from_parse_tree`]
345/// and [`check_conformance`] callers.
346///
347/// Multiple diagnostics are collected before failing so the consumer
348/// AI sees every problem in one round-trip.
349#[derive(Debug, Clone, PartialEq, Eq)]
350pub struct BuildError {
351 /// The diagnostics (at least one is guaranteed by
352 /// [`BuildError::new`]).
353 pub diagnostics: Vec<Diagnostic>,
354}
355
356impl BuildError {
357 /// Wraps a non-empty vector of diagnostics.
358 ///
359 /// # Panics
360 ///
361 /// Panics if `diagnostics` is empty — a [`BuildError`] with no
362 /// diagnostics is meaningless.
363 pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
364 assert!(
365 !diagnostics.is_empty(),
366 "BuildError requires at least one diagnostic"
367 );
368 Self { diagnostics }
369 }
370
371 /// Convenience constructor for a single-diagnostic error.
372 pub fn single(diag: Diagnostic) -> Self {
373 Self {
374 diagnostics: vec![diag],
375 }
376 }
377
378 /// Renders the whole bag as a JSON array of
379 /// [`Diagnostic::to_json`] entries.
380 pub fn to_json(&self) -> Value {
381 Value::Array(self.diagnostics.iter().map(Diagnostic::to_json).collect())
382 }
383}
384
385impl fmt::Display for BuildError {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 write!(
388 f,
389 "build failed with {} diagnostic(s):",
390 self.diagnostics.len()
391 )?;
392 for d in &self.diagnostics {
393 write!(f, "\n [{}] {}: {}", d.severity.as_str(), d.code, d.message)?;
394 }
395 Ok(())
396 }
397}
398
399impl std::error::Error for BuildError {}
400
401// ---------------------------------------------------------------------------
402// DslBuild
403// ---------------------------------------------------------------------------
404
405/// Contract for building a typed AST value from a validated
406/// [`ParseTree`].
407///
408/// Implemented via `#[derive(DslBuild)]` in `dsl-kit-macros` (G-1c);
409/// hand-written impls are fine for shapes the derive cannot express
410/// (mixed tuple variants, generics, cross-type recursion, etc.).
411pub trait DslBuild: Sized {
412 /// Builds a typed value from `tree`, minting fresh [`NodeId`]s from
413 /// `ids`.
414 ///
415 /// Implementations should call [`check_conformance`] against
416 /// `Self::schema()` before dispatching per-variant so that shape
417 /// mismatches surface as diagnostics rather than panics or ad-hoc
418 /// errors. `RawValue::Text` payloads convert through `FromStr`;
419 /// `RawValue::Json` payloads convert through
420 /// `serde_json::from_value`.
421 fn from_parse_tree(tree: &ParseTree, ids: &IdGen) -> Result<Self, BuildError>;
422}
423
424// ---------------------------------------------------------------------------
425// Schema conformance
426// ---------------------------------------------------------------------------
427
428/// Diagnostic codes emitted by [`check_conformance`].
429///
430/// Exposed as a module of `pub const &str` slugs so downstream tools
431/// (lint UIs, doc generators) can reference them without matching on
432/// string literals.
433pub mod codes {
434 /// Tree's `variant` did not match any
435 /// [`VariantSchema`](dsl_kit_schema::VariantSchema) in the
436 /// [`NodeSchema`](dsl_kit_schema::NodeSchema).
437 pub const UNKNOWN_VARIANT: &str = "dsl_kit::parse::unknown_variant";
438 /// A field required by the schema is absent from the tree.
439 pub const MISSING_FIELD: &str = "dsl_kit::parse::missing_field";
440 /// The tree carries a field the schema does not declare.
441 pub const UNKNOWN_FIELD: &str = "dsl_kit::parse::unknown_field";
442 /// The tree references a child slot the schema does not declare.
443 pub const UNKNOWN_CHILD: &str = "dsl_kit::parse::unknown_child";
444 /// A [`crate::Multiplicity::One`] slot did not carry exactly one
445 /// child.
446 pub const ARITY_ONE: &str = "dsl_kit::parse::arity_one";
447 /// A [`crate::Multiplicity::Optional`] slot carried more than one
448 /// child.
449 pub const ARITY_OPTIONAL: &str = "dsl_kit::parse::arity_optional";
450 /// A collection slot declared non-empty
451 /// ([`ChildSchema::non_empty`](dsl_kit_schema::ChildSchema::non_empty))
452 /// carried no elements. Declared-constraint violation, not a
453 /// heuristic — plain `Many` / `Map` slots keep their
454 /// zero-or-more contract.
455 pub const ARITY_NON_EMPTY: &str = "dsl_kit::parse::arity_non_empty";
456 /// A payload field appeared under `children` (structural mismatch).
457 pub const FIELD_AS_CHILD: &str = "dsl_kit::parse::field_as_child";
458 /// A child slot appeared under `fields` (structural mismatch).
459 pub const CHILD_AS_FIELD: &str = "dsl_kit::parse::child_as_field";
460 /// A field name appeared more than once.
461 pub const DUPLICATE_FIELD: &str = "dsl_kit::parse::duplicate_field";
462 /// A child slot name appeared more than once.
463 pub const DUPLICATE_CHILD: &str = "dsl_kit::parse::duplicate_child";
464 /// A payload field's value could not be converted to the target
465 /// Rust type (serde deserialization failure or `FromStr` failure).
466 pub const FIELD_TYPE: &str = "dsl_kit::parse::field_type";
467 /// A keyed child slot ([`crate::Multiplicity::Map`]) carried the
468 /// same key more than once. The map the consumer asked for cannot
469 /// hold both, and picking a winner silently would make the parse
470 /// lossy — so the duplicate is an error at conformance time and at
471 /// [`crate::build_child_map`] time.
472 pub const DUPLICATE_KEY: &str = "dsl_kit::parse::duplicate_key";
473 /// A child slot was placed in the wrong half of the tree: a slot
474 /// declared [`crate::Multiplicity::Map`] appeared under
475 /// [`ParseTree::children`] (positional), or a slot declared
476 /// `One` / `Optional` / `Many` appeared under
477 /// [`ParseTree::keyed_children`].
478 pub const KEYED_SLOT_SHAPE: &str = "dsl_kit::parse::keyed_slot_shape";
479 /// A keyed child slot's entries were not in ascending key order.
480 /// [`ParseTree::keyed_children`] documents sorted-by-key as the
481 /// canonical form so that two front-ends producing the same
482 /// document produce equal trees; this is that contract enforced
483 /// rather than assumed. The JSON bridge sorts on ingest, so this
484 /// fires only for hand-built or hand-rolled front-end trees.
485 pub const KEYED_SLOT_UNSORTED: &str = "dsl_kit::parse::keyed_slot_unsorted";
486 /// A child slot's multiplicity is a variant this build of
487 /// `dsl-kit-parse` does not recognise. Emitted from the catch-all
488 /// arm required by [`crate::Multiplicity`]'s `#[non_exhaustive]`
489 /// contract when a future variant is added to the schema crate
490 /// ahead of parse-side support. Not reachable in practice within
491 /// the workspace (both crates are versioned in lockstep) but held
492 /// as a first-class diagnostic so out-of-workspace consumers see a
493 /// stable slug rather than a panic.
494 pub const UNKNOWN_MULTIPLICITY: &str = "dsl_kit::parse::unknown_multiplicity";
495}
496
497/// Validates `tree` against `schema` shallowly (this level only).
498///
499/// The check is intentionally single-level — the recursion is the
500/// caller's job (typically `DslBuild::from_parse_tree` for each child
501/// slot). Every mismatch produces a [`Diagnostic`]; the returned
502/// vector is empty when the tree matches.
503///
504/// Checks performed:
505///
506/// - variant name matches one of `schema.variants` (else
507/// [`codes::UNKNOWN_VARIANT`] with nearest candidates in the
508/// message);
509/// - every declared field is present exactly once
510/// ([`codes::MISSING_FIELD`], [`codes::DUPLICATE_FIELD`]);
511/// - no undeclared field is present ([`codes::UNKNOWN_FIELD`],
512/// or [`codes::CHILD_AS_FIELD`] when the extra name is actually a
513/// declared child slot);
514/// - every declared child slot is present exactly once
515/// ([`codes::DUPLICATE_CHILD`]) and honours its [`Multiplicity`]
516/// ([`codes::ARITY_ONE`], [`codes::ARITY_OPTIONAL`]) plus any
517/// declared non-emptiness ([`codes::ARITY_NON_EMPTY`]);
518/// - every child slot sits in the half its [`Multiplicity`] calls for
519/// — keyed slots under [`ParseTree::keyed_children`], positional
520/// ones under [`ParseTree::children`] ([`codes::KEYED_SLOT_SHAPE`]);
521/// - a keyed slot carries each key at most once
522/// ([`codes::DUPLICATE_KEY`]) and in ascending key order
523/// ([`codes::KEYED_SLOT_UNSORTED`]);
524/// - no undeclared child slot is present ([`codes::UNKNOWN_CHILD`],
525/// or [`codes::FIELD_AS_CHILD`] when the extra name is actually a
526/// declared payload field).
527///
528/// [`Multiplicity::Many`] and [`Multiplicity::Map`] accept
529/// zero-or-more children on their own: emptiness is a domain-level
530/// judgment, not a shape error, so an undeclared collection slot that
531/// came up empty is accepted here without a diagnostic. Declaring the
532/// constraint changes that — a slot marked
533/// [`non_empty`](dsl_kit_schema::ChildSchema::non_empty) (written
534/// `#[dsl_schema(non_empty)]`) is checked at this level and reported
535/// as an error ([`codes::ARITY_NON_EMPTY`]). The `no-empty-child-slots`
536/// lint rule reads the same declaration and reports at `Error` too; it
537/// is the backstop for typed ASTs hand-built without passing through a
538/// front-end, where this check never runs.
539pub fn check_conformance(tree: &ParseTree, schema: &NodeSchema) -> Vec<Diagnostic> {
540 check_conformance_with(tree, schema, &BuiltinLevenshteinSuggester)
541}
542
543/// Variant of [`check_conformance`] that routes `did you mean X?`
544/// hints through a caller-supplied [`Suggester`].
545///
546/// The free function [`check_conformance`] delegates here with a
547/// crate-private [`Suggester`] backed by the same Levenshtein
548/// algorithm the crate has always shipped, so existing callers see no
549/// behavioural change. Reach for this variant when you want to plug
550/// in a different similarity algorithm (e.g. `dsl-kit-fuzzy`'s
551/// `FuzzySuggester` with Jaro-Winkler) at a specific call site.
552pub fn check_conformance_with(
553 tree: &ParseTree,
554 schema: &NodeSchema,
555 suggester: &dyn Suggester,
556) -> Vec<Diagnostic> {
557 let mut out = Vec::new();
558
559 if tree.variant == import::IMPORT_VARIANT {
560 out.push(
561 Diagnostic::error(
562 import::import_codes::UNEXPANDED,
563 format!(
564 "unexpanded `{}` placeholder — run the document through \
565 `import::load_json_str` / `import::load_json_value` before conformance",
566 import::IMPORT_VARIANT
567 ),
568 )
569 .with_span(tree.span),
570 );
571 return out;
572 }
573
574 if tree.variant == allow::ALLOW_VARIANT {
575 out.push(
576 Diagnostic::error(
577 allow::codes::UNCOLLAPSED,
578 format!(
579 "un-collapsed `{}` wrapper — run the tree through \
580 `allow::collapse` (every text parse already does) before conformance",
581 allow::ALLOW_VARIANT
582 ),
583 )
584 .with_span(tree.span),
585 );
586 return out;
587 }
588
589 let Some(variant) = schema.variant(&tree.variant) else {
590 let msg = format_unknown_variant(&tree.variant, schema, suggester);
591 out.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg).with_span(tree.span));
592 return out;
593 };
594
595 check_fields(tree, variant, &mut out, suggester);
596 check_children(tree, variant, &mut out, suggester);
597 out
598}
599
600/// Shared formatter for the `UNKNOWN_VARIANT` diagnostic message,
601/// used by both [`check_conformance_with`] and the serde bridge so the
602/// wording stays consistent across front-ends.
603pub(crate) fn format_unknown_variant(
604 query: &str,
605 schema: &NodeSchema,
606 suggester: &dyn Suggester,
607) -> String {
608 let names: Vec<&str> = schema.variants.iter().map(|v| v.name.as_str()).collect();
609 let base = format!("unknown variant `{}` for `{}`", query, schema.name);
610 match suggester.enrich_unknown(query, &names) {
611 Some(hint) => format!("{base} ({hint})"),
612 None => base,
613 }
614}
615
616/// Shared formatter for `UNKNOWN_FIELD` and `UNKNOWN_CHILD` messages.
617///
618/// `kind` is `"field"` or `"child slot"`. `all_candidates` should
619/// include both declared field names and declared child slot names so
620/// a `did you mean` hint can point at either. `missing_candidates`
621/// carries the slot names that are declared but currently absent from
622/// the tree; suggestions that appear in this set are marked
623/// `(missing)` — the "pair hint" that makes payloads like
624/// `taget` → `target` (missing) diagnose themselves at a glance.
625pub(crate) fn format_unknown_slot(
626 kind: &str,
627 query: &str,
628 variant_name: &str,
629 all_candidates: &[&str],
630 missing_candidates: &[&str],
631 suggester: &dyn Suggester,
632) -> String {
633 let base = format!("unknown {kind} `{query}` on variant `{variant_name}`");
634 let sugs = suggester.suggest(query, all_candidates);
635 if sugs.is_empty() {
636 return base;
637 }
638 let joined = sugs
639 .iter()
640 .take(3)
641 .map(|s| {
642 if missing_candidates.contains(&s.candidate) {
643 format!("`{}` (missing)", s.candidate)
644 } else {
645 format!("`{}`", s.candidate)
646 }
647 })
648 .collect::<Vec<_>>()
649 .join(", ");
650 format!("{base} (did you mean: {joined})")
651}
652
653fn check_fields(
654 tree: &ParseTree,
655 variant: &VariantSchema,
656 out: &mut Vec<Diagnostic>,
657 suggester: &dyn Suggester,
658) {
659 // Duplicate field names.
660 for i in 0..tree.fields.len() {
661 let (name, _) = &tree.fields[i];
662 if tree.fields[..i].iter().any(|(n, _)| n == name) {
663 out.push(
664 Diagnostic::error(
665 codes::DUPLICATE_FIELD,
666 format!(
667 "field `{}` appears more than once on variant `{}`",
668 name, variant.name
669 ),
670 )
671 .with_span(tree.span),
672 );
673 }
674 }
675
676 // Missing declared fields. Optional fields (typically `Option<T>`
677 // / `Vec<T>` payloads recognised by `#[derive(DslSchema)]`) are
678 // skipped — their absence is a valid shape and the build layer's
679 // `build_field_optional` / `build_field_vec` helpers supply the
680 // default (`None` / empty vec).
681 for f in &variant.fields {
682 if f.optional {
683 continue;
684 }
685 if tree.field(&f.name).is_none() {
686 out.push(
687 Diagnostic::error(
688 codes::MISSING_FIELD,
689 format!(
690 "variant `{}` is missing required field `{}` (type `{}`)",
691 variant.name, f.name, f.ty
692 ),
693 )
694 .with_span(tree.span),
695 );
696 }
697 }
698
699 // Precompute the "missing-so-far" set once: slot names that are
700 // declared but currently absent from `tree`. Used as the pair-hint
701 // marker on UNKNOWN_FIELD suggestions.
702 let missing = missing_slot_names(tree, variant);
703 let all_slots = all_slot_names(variant);
704
705 // Unknown fields.
706 for (name, _) in &tree.fields {
707 if variant.fields.iter().any(|f| &f.name == name) {
708 continue;
709 }
710 // If it names a declared child slot, that's a structural mix-up.
711 if variant.children.iter().any(|c| &c.name == name) {
712 out.push(
713 Diagnostic::error(
714 codes::CHILD_AS_FIELD,
715 format!(
716 "`{}` on variant `{}` is a child slot, not a payload field \
717 (move it under `children`)",
718 name, variant.name
719 ),
720 )
721 .with_span(tree.span),
722 );
723 } else {
724 let msg = format_unknown_slot(
725 "field",
726 name,
727 &variant.name,
728 &all_slots,
729 &missing,
730 suggester,
731 );
732 out.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg).with_span(tree.span));
733 }
734 }
735}
736
737fn check_children(
738 tree: &ParseTree,
739 variant: &VariantSchema,
740 out: &mut Vec<Diagnostic>,
741 suggester: &dyn Suggester,
742) {
743 // Duplicate child slot names. The two child vectors share one
744 // namespace — a slot appearing once positionally and once keyed is
745 // a duplicate, not two independent slots — so the scan walks them
746 // as a single sequence.
747 let mut seen: Vec<&str> = Vec::new();
748 for name in slot_names_in_tree(tree) {
749 if seen.contains(&name) {
750 out.push(
751 Diagnostic::error(
752 codes::DUPLICATE_CHILD,
753 format!(
754 "child slot `{}` appears more than once on variant `{}`",
755 name, variant.name
756 ),
757 )
758 .with_span(tree.span),
759 );
760 } else {
761 seen.push(name);
762 }
763 }
764
765 // Declared children: keying + arity check.
766 for c in &variant.children {
767 let positional = tree.child_slot(&c.name);
768 let keyed = tree.keyed_child_slot(&c.name);
769 let count = positional.map(<[ParseTree]>::len).unwrap_or(0);
770
771 // Keying mismatch: the slot exists, but in the half the schema
772 // did not ask for.
773 let is_map = c.multiplicity == Multiplicity::Map;
774 let wrong_half = if is_map {
775 positional.is_some()
776 } else {
777 keyed.is_some()
778 };
779 if wrong_half {
780 out.push(diag_keying(variant, c, is_map, tree.span));
781 }
782
783 // When the slot's *only* occurrence sits in the wrong half,
784 // skip the shape check below: it reads the right half, finds
785 // it empty, and would report "expects exactly one child but
786 // got 0" about a tree that supplied exactly one child. The
787 // keying diagnostic already says what went wrong; a second,
788 // untrue one only misdirects. A slot present in *both* halves
789 // still gets checked — `DUPLICATE_CHILD` covers the collision
790 // and the shape verdict on the right half stays meaningful.
791 let only_in_wrong_half = wrong_half
792 && if is_map {
793 keyed.is_none()
794 } else {
795 positional.is_none()
796 };
797 if only_in_wrong_half {
798 continue;
799 }
800
801 match c.multiplicity {
802 Multiplicity::One => {
803 if count != 1 {
804 out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
805 }
806 }
807 Multiplicity::Optional => {
808 if count > 1 {
809 out.push(diag_arity(
810 codes::ARITY_OPTIONAL,
811 variant,
812 c,
813 count,
814 tree.span,
815 ));
816 }
817 }
818 Multiplicity::Many => {
819 // Zero is fine at the shape level — unless the schema
820 // *declares* otherwise. An absent slot and a
821 // present-but-empty slot both count as empty (the two
822 // spellings mean the same thing everywhere else).
823 if c.non_empty && count == 0 {
824 out.push(
825 Diagnostic::error(
826 codes::ARITY_NON_EMPTY,
827 format!(
828 "child slot `{}` on variant `{}` is declared non-empty \
829 but carries no children",
830 c.name, variant.name
831 ),
832 )
833 .with_span(tree.span),
834 );
835 }
836 }
837 Multiplicity::Map => {
838 // Zero-or-more keyed entries is fine at the shape
839 // level (same as `Many`) — unless declared non-empty,
840 // mirroring the `Many` arm above; what a map *cannot*
841 // carry either way is the same key twice.
842 if c.non_empty && keyed.is_none_or(<[(String, ParseTree)]>::is_empty) {
843 out.push(
844 Diagnostic::error(
845 codes::ARITY_NON_EMPTY,
846 format!(
847 "keyed child slot `{}` on variant `{}` is declared \
848 non-empty but carries no entries",
849 c.name, variant.name
850 ),
851 )
852 .with_span(tree.span),
853 );
854 }
855 //
856 // Walking adjacent pairs checks that in one linear
857 // pass — and the same pass verifies the sorted-by-key
858 // order [`ParseTree::keyed_children`] documents, so
859 // that contract is enforced rather than trusted. A
860 // front-end that emits out of order finds out here
861 // instead of shipping trees that compare unequal to
862 // every other front-end's for the same document.
863 let entries = keyed.unwrap_or(&[]);
864 for pair in entries.windows(2) {
865 let (lhs, rhs) = (&pair[0].0, &pair[1].0);
866 match lhs.cmp(rhs) {
867 Ordering::Equal => out.push(
868 Diagnostic::error(
869 codes::DUPLICATE_KEY,
870 format!(
871 "keyed child slot `{}` on variant `{}` carries key \
872 `{}` more than once",
873 c.name, variant.name, rhs
874 ),
875 )
876 .with_span(tree.span),
877 ),
878 Ordering::Greater => out.push(
879 Diagnostic::error(
880 codes::KEYED_SLOT_UNSORTED,
881 format!(
882 "keyed child slot `{}` on variant `{}` is not sorted by \
883 key (`{}` precedes `{}`); front-ends must emit keyed \
884 entries in key order",
885 c.name, variant.name, lhs, rhs
886 ),
887 )
888 .with_span(tree.span),
889 ),
890 Ordering::Less => {}
891 }
892 }
893 }
894 // `#[non_exhaustive]` catch-all: emitted when a future
895 // Multiplicity variant lands in dsl-kit-schema before this
896 // arm has been extended to handle it. Not reachable inside
897 // the workspace (both crates are versioned together) but
898 // required by the type contract and useful for
899 // out-of-workspace consumers pinned to an older parse.
900 _ => {
901 out.push(
902 Diagnostic::error(
903 codes::UNKNOWN_MULTIPLICITY,
904 format!(
905 "child slot `{}` on variant `{}` uses an unrecognised \
906 Multiplicity variant (upgrade dsl-kit-parse to a version \
907 that knows about it)",
908 c.name, variant.name
909 ),
910 )
911 .with_span(tree.span),
912 );
913 }
914 }
915 }
916
917 // Same pair-hint precomputation as check_fields, sharing the
918 // "declared but currently absent" set across both diagnostics.
919 let missing = missing_slot_names(tree, variant);
920 let all_slots = all_slot_names(variant);
921
922 // Unknown child slots — both halves, since an undeclared name is
923 // equally unknown whether it arrived keyed or positional.
924 for name in slot_names_in_tree(tree) {
925 if variant.children.iter().any(|c| c.name == name) {
926 continue;
927 }
928 if variant.fields.iter().any(|f| f.name == name) {
929 out.push(
930 Diagnostic::error(
931 codes::FIELD_AS_CHILD,
932 format!(
933 "`{}` on variant `{}` is a payload field, not a child slot \
934 (move it under `fields`)",
935 name, variant.name
936 ),
937 )
938 .with_span(tree.span),
939 );
940 } else {
941 let msg = format_unknown_slot(
942 "child slot",
943 name,
944 &variant.name,
945 &all_slots,
946 &missing,
947 suggester,
948 );
949 out.push(Diagnostic::error(codes::UNKNOWN_CHILD, msg).with_span(tree.span));
950 }
951 }
952}
953
954/// Every child slot name present on `tree`, positional slots first
955/// then keyed ones. The two vectors share a single namespace, so both
956/// the duplicate scan and the unknown-slot scan walk this sequence
957/// rather than either vector alone.
958fn slot_names_in_tree(tree: &ParseTree) -> impl Iterator<Item = &str> {
959 tree.children
960 .iter()
961 .map(|(n, _)| n.as_str())
962 .chain(tree.keyed_children.iter().map(|(n, _)| n.as_str()))
963}
964
965/// Builds the [`codes::KEYED_SLOT_SHAPE`] diagnostic. `positional_seen`
966/// distinguishes the two directions: `true` = a `Map`-declared slot
967/// arrived under [`ParseTree::children`], `false` = a positional slot
968/// arrived under [`ParseTree::keyed_children`].
969fn diag_keying(
970 variant: &VariantSchema,
971 child: &ChildSchema,
972 positional_seen: bool,
973 span: Option<Span>,
974) -> Diagnostic {
975 let msg = if positional_seen {
976 format!(
977 "child slot `{}` on variant `{}` declares Multiplicity::Map — its children \
978 must be supplied as keyed entries, not as a positional list",
979 child.name, variant.name
980 )
981 } else {
982 format!(
983 "child slot `{}` on variant `{}` is positional ({}) — its children must be \
984 supplied as a plain list, not as keyed entries",
985 child.name,
986 variant.name,
987 child.multiplicity.as_str()
988 )
989 };
990 Diagnostic::error(codes::KEYED_SLOT_SHAPE, msg).with_span(span)
991}
992
993/// Names of every declared payload field and child slot on
994/// `variant`, in that order. Used as the `all_candidates` slice for
995/// [`format_unknown_slot`].
996pub(crate) fn all_slot_names(variant: &VariantSchema) -> Vec<&str> {
997 variant
998 .fields
999 .iter()
1000 .map(|f| f.name.as_str())
1001 .chain(variant.children.iter().map(|c| c.name.as_str()))
1002 .collect()
1003}
1004
1005/// Names of declared slots that are **not** currently present on
1006/// `tree`. Includes fields with no matching entry in `tree.fields`
1007/// and children whose slot has zero occurrences on the tree. Feeds
1008/// [`format_unknown_slot`]'s `(missing)` pair-hint marker.
1009pub(crate) fn missing_slot_names<'a>(tree: &ParseTree, variant: &'a VariantSchema) -> Vec<&'a str> {
1010 let mut out = Vec::new();
1011 for f in &variant.fields {
1012 // Optional fields are never "missing" for pair-hint purposes:
1013 // their absence is a valid shape, so pointing at them from an
1014 // unknown-slot suggestion would misdirect the reader.
1015 if f.optional {
1016 continue;
1017 }
1018 if tree.field(&f.name).is_none() {
1019 out.push(f.name.as_str());
1020 }
1021 }
1022 for c in &variant.children {
1023 // A slot counts as present when it carries entries in either
1024 // half — a keyed slot supplied positionally (or vice versa)
1025 // already earns its own `KEYED_SLOT_SHAPE` diagnostic, and
1026 // listing it as "missing" on top of that would misdirect.
1027 let positional = tree
1028 .child_slot(&c.name)
1029 .map(<[ParseTree]>::len)
1030 .unwrap_or(0);
1031 let keyed = tree
1032 .keyed_child_slot(&c.name)
1033 .map(<[(String, ParseTree)]>::len)
1034 .unwrap_or(0);
1035 if positional + keyed == 0 {
1036 out.push(c.name.as_str());
1037 }
1038 }
1039 out
1040}
1041
1042fn diag_arity(
1043 code: &'static str,
1044 variant: &VariantSchema,
1045 child: &ChildSchema,
1046 count: usize,
1047 span: Option<Span>,
1048) -> Diagnostic {
1049 let expected = match child.multiplicity {
1050 Multiplicity::One => "exactly one child",
1051 Multiplicity::Optional => "at most one child",
1052 Multiplicity::Many => "zero or more children",
1053 // `Map` never enters `diag_arity` in practice — keyed slots
1054 // accept zero-or-more entries, so `check_children` has no
1055 // arity complaint to raise for them (only `DUPLICATE_KEY`).
1056 // Kept explicit (rather than folded into the `_` arm) so a
1057 // future change that routes Map through here gets a Map-shaped
1058 // label instead of the generic "unknown multiplicity" fallback.
1059 Multiplicity::Map => "any number of keyed children",
1060 // `#[non_exhaustive]` catch-all — see the sibling arm in
1061 // `check_children` for the versioning rationale.
1062 _ => "a shape this build of dsl-kit-parse does not recognise",
1063 };
1064 Diagnostic::error(
1065 code,
1066 format!(
1067 "child slot `{}` on variant `{}` expects {} but got {}",
1068 child.name, variant.name, expected, count
1069 ),
1070 )
1071 .with_span(span)
1072}
1073
1074// ---------------------------------------------------------------------------
1075// Built-in Suggester (case-insensitive Levenshtein, cutoff = max(query.len, 1))
1076// ---------------------------------------------------------------------------
1077
1078/// Default [`Suggester`] used by [`check_conformance`] and the serde
1079/// bridge when no explicit suggester is supplied.
1080///
1081/// Backed by an ASCII-case-insensitive Levenshtein edit distance with
1082/// cutoff `max(query.len(), 1)` — the same behaviour the crate has
1083/// shipped since Round 1, kept internal so the parser does not need
1084/// to depend on the plugin crate.
1085pub(crate) struct BuiltinLevenshteinSuggester;
1086
1087impl Suggester for BuiltinLevenshteinSuggester {
1088 fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
1089 let cutoff = query.chars().count().max(1);
1090 let mut scored: Vec<(usize, &'a str)> = candidates
1091 .iter()
1092 .map(|c| (levenshtein(query, c), *c))
1093 .filter(|(d, _)| *d <= cutoff)
1094 .collect();
1095 scored.sort_by(|(da, na), (db, nb)| da.cmp(db).then_with(|| na.cmp(nb)));
1096 scored.truncate(3);
1097 scored
1098 .into_iter()
1099 .map(|(d, name)| Suggestion {
1100 candidate: name,
1101 score: normalise_edit(d, query, name),
1102 })
1103 .collect()
1104 }
1105}
1106
1107fn normalise_edit(distance: usize, a: &str, b: &str) -> f64 {
1108 let max_len = a.chars().count().max(b.chars().count());
1109 if max_len == 0 {
1110 return 1.0;
1111 }
1112 1.0 - (distance as f64 / max_len as f64)
1113}
1114
1115fn levenshtein(a: &str, b: &str) -> usize {
1116 let a: Vec<char> = a.chars().collect();
1117 let b: Vec<char> = b.chars().collect();
1118 let (m, n) = (a.len(), b.len());
1119 if m == 0 {
1120 return n;
1121 }
1122 if n == 0 {
1123 return m;
1124 }
1125 let mut prev: Vec<usize> = (0..=n).collect();
1126 let mut curr: Vec<usize> = vec![0; n + 1];
1127 for i in 1..=m {
1128 curr[0] = i;
1129 for j in 1..=n {
1130 let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
1131 0
1132 } else {
1133 1
1134 };
1135 curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
1136 }
1137 std::mem::swap(&mut prev, &mut curr);
1138 }
1139 prev[n]
1140}
1141
1142// ---------------------------------------------------------------------------
1143// Build helpers (used by #[derive(DslBuild)] code emission)
1144// ---------------------------------------------------------------------------
1145
1146/// Extracts a payload field into `T`.
1147///
1148/// Dispatches on the field's [`RawValue`] arm:
1149///
1150/// - [`RawValue::Json`] → `serde_json::from_value::<T>`.
1151/// - [`RawValue::Text`] → `T::from_str` (G-2: PEG front-end path).
1152///
1153/// This means the derive works with either front-end unchanged — the
1154/// front-end picks the payload representation, the derive is agnostic.
1155/// `T` must therefore satisfy both bounds; every primitive the kit
1156/// currently uses (`String`, `i64`, `u32`, `bool`, `f64`) does.
1157///
1158/// This helper is intended for use by `#[derive(DslBuild)]`-generated
1159/// code but is usable directly by hand-written [`DslBuild`] impls.
1160pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
1161where
1162 T: serde::de::DeserializeOwned + std::str::FromStr,
1163 <T as std::str::FromStr>::Err: std::fmt::Display,
1164{
1165 match tree.field(name) {
1166 Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
1167 BuildError::single(
1168 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
1169 .with_span(tree.span),
1170 )
1171 }),
1172 Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
1173 BuildError::single(
1174 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
1175 .with_span(tree.span),
1176 )
1177 }),
1178 None => Err(BuildError::single(
1179 Diagnostic::error(
1180 codes::MISSING_FIELD,
1181 format!("missing required field `{name}`"),
1182 )
1183 .with_span(tree.span),
1184 )),
1185 }
1186}
1187
1188/// Extracts an optional payload field into `Option<T>`.
1189///
1190/// Companion to [`build_field`] for fields whose Rust type is
1191/// `Option<T>` — the `#[derive(DslBuild)]` default path routes here
1192/// automatically for payload `Option<T>` types (see the derive docs).
1193///
1194/// Resolution rules:
1195///
1196/// - Absent field → `Ok(None)` (this is the "AI-emit omits noise"
1197/// contract — schema-level `optional: true` skips the
1198/// `MISSING_FIELD` diagnostic so absence reaches here).
1199/// - [`RawValue::Json`] with a `null` value → `Ok(None)`.
1200/// - [`RawValue::Text`] whose text is the literal `"none"` (the
1201/// canonical-syntax keyword produced by `schema_gen`) → `Ok(None)`.
1202/// - Any other value → delegate to [`build_field`], wrap in `Some`.
1203///
1204/// `T` must satisfy the same `DeserializeOwned + FromStr` bounds as
1205/// [`build_field`] because the delegate path uses it.
1206pub fn build_field_optional<T>(tree: &ParseTree, name: &str) -> Result<Option<T>, BuildError>
1207where
1208 T: serde::de::DeserializeOwned + std::str::FromStr,
1209 <T as std::str::FromStr>::Err: std::fmt::Display,
1210{
1211 match tree.field(name) {
1212 None => Ok(None),
1213 Some(RawValue::Json(Value::Null)) => Ok(None),
1214 Some(RawValue::Text(s)) if s == "none" => Ok(None),
1215 Some(_) => build_field::<T>(tree, name).map(Some),
1216 }
1217}
1218
1219/// Extracts a payload field into `Vec<T>`.
1220///
1221/// Companion to [`build_field`] for fields whose Rust type is
1222/// `Vec<T>` — the `#[derive(DslBuild)]` default path routes here
1223/// automatically for payload `Vec<T>` types (see the derive docs).
1224///
1225/// Resolution rules:
1226///
1227/// - Absent field → `Ok(vec![])` (schema-level `optional: true` skips
1228/// the `MISSING_FIELD` diagnostic; missing = empty list).
1229/// - [`RawValue::Json`] with a `null` value → `Ok(vec![])`.
1230/// - [`RawValue::Json`] with an array → `serde_json::from_value`
1231/// over the whole array.
1232/// - [`RawValue::Text`] whose trimmed body is empty → `Ok(vec![])`.
1233/// - [`RawValue::Text`] otherwise → parse the text as a JSON array
1234/// (`serde_json::from_str::<Vec<T>>`). The canonical-syntax
1235/// production for `Vec<String>` (`[ "a", "b" ]`) is JSON-parsable
1236/// as-is; hand-authored value productions that follow the same
1237/// bracketed shape work unchanged.
1238///
1239/// `T` must implement `serde::de::DeserializeOwned` — no `FromStr`
1240/// bound is needed because the text path routes through
1241/// `serde_json::from_str` rather than element-wise parsing.
1242pub fn build_field_vec<T>(tree: &ParseTree, name: &str) -> Result<Vec<T>, BuildError>
1243where
1244 T: serde::de::DeserializeOwned,
1245{
1246 match tree.field(name) {
1247 None => Ok(Vec::new()),
1248 Some(RawValue::Json(Value::Null)) => Ok(Vec::new()),
1249 Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
1250 BuildError::single(
1251 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
1252 .with_span(tree.span),
1253 )
1254 }),
1255 Some(RawValue::Text(s)) => {
1256 let trimmed = s.trim();
1257 if trimmed.is_empty() {
1258 return Ok(Vec::new());
1259 }
1260 serde_json::from_str(trimmed).map_err(|e| {
1261 BuildError::single(
1262 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
1263 .with_span(tree.span),
1264 )
1265 })
1266 }
1267 }
1268}
1269
1270/// Extracts a payload field's raw text production.
1271///
1272/// Convenience for `#[dsl_build(with = ...)]` converter functions,
1273/// which typically match on the spelling the grammar (often a
1274/// `schema_gen::SyntaxOverrides` value production) captured. Errors
1275/// mirror [`build_field`]: [`codes::MISSING_FIELD`] when absent,
1276/// [`codes::FIELD_TYPE`] when the field carries a
1277/// [`RawValue::Json`] payload instead of text.
1278pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
1279 match tree.field(name) {
1280 Some(RawValue::Text(s)) => Ok(s),
1281 Some(RawValue::Json(_)) => Err(BuildError::single(
1282 Diagnostic::error(
1283 codes::FIELD_TYPE,
1284 format!("field `{name}`: expected a text production, found JSON"),
1285 )
1286 .with_span(tree.span),
1287 )),
1288 None => Err(BuildError::single(
1289 Diagnostic::error(
1290 codes::MISSING_FIELD,
1291 format!("missing required field `{name}`"),
1292 )
1293 .with_span(tree.span),
1294 )),
1295 }
1296}
1297
1298/// Builds the single child of a [`Multiplicity::One`] slot.
1299///
1300/// Returns [`codes::ARITY_ONE`] if the slot is absent or holds more
1301/// than one subtree. Errors from the recursive
1302/// [`DslBuild::from_parse_tree`] call bubble up as-is.
1303pub fn build_child_one<T: DslBuild>(
1304 tree: &ParseTree,
1305 name: &str,
1306 ids: &IdGen,
1307) -> Result<T, BuildError> {
1308 let slot = tree.child_slot(name).unwrap_or(&[]);
1309 if slot.len() != 1 {
1310 return Err(BuildError::single(
1311 Diagnostic::error(
1312 codes::ARITY_ONE,
1313 format!(
1314 "child slot `{name}` expects exactly one child but got {}",
1315 slot.len()
1316 ),
1317 )
1318 .with_span(tree.span),
1319 ));
1320 }
1321 T::from_parse_tree(&slot[0], ids)
1322}
1323
1324/// Builds the (optional) child of a [`Multiplicity::Optional`] slot.
1325///
1326/// Returns [`codes::ARITY_OPTIONAL`] if the slot holds more than one
1327/// subtree. Missing / empty slots yield `Ok(None)`.
1328pub fn build_child_optional<T: DslBuild>(
1329 tree: &ParseTree,
1330 name: &str,
1331 ids: &IdGen,
1332) -> Result<Option<T>, BuildError> {
1333 let slot = tree.child_slot(name).unwrap_or(&[]);
1334 match slot.len() {
1335 0 => Ok(None),
1336 1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
1337 n => Err(BuildError::single(
1338 Diagnostic::error(
1339 codes::ARITY_OPTIONAL,
1340 format!("child slot `{name}` expects at most one child but got {n}"),
1341 )
1342 .with_span(tree.span),
1343 )),
1344 }
1345}
1346
1347/// Builds every child of a [`Multiplicity::Many`] slot.
1348///
1349/// Diagnostics from individual children are collected across the whole
1350/// slot before returning, so a partially-broken batch surfaces every
1351/// bad subtree at once rather than the first-encountered one.
1352pub fn build_child_many<T: DslBuild>(
1353 tree: &ParseTree,
1354 name: &str,
1355 ids: &IdGen,
1356) -> Result<Vec<T>, BuildError> {
1357 let slot = tree.child_slot(name).unwrap_or(&[]);
1358 let mut out = Vec::with_capacity(slot.len());
1359 let mut diags = Vec::new();
1360 for child in slot {
1361 match T::from_parse_tree(child, ids) {
1362 Ok(v) => out.push(v),
1363 Err(mut e) => diags.append(&mut e.diagnostics),
1364 }
1365 }
1366 if diags.is_empty() {
1367 Ok(out)
1368 } else {
1369 Err(BuildError::new(diags))
1370 }
1371}
1372
1373/// Builds every entry of a scalar-valued [`Multiplicity::Map`] slot
1374/// (Shape 1 of the tracking issue) into a [`BTreeMap`] keyed by the
1375/// front-end's keys.
1376///
1377/// Each entry in the tree's [`ParseTree::keyed_children`] slot is
1378/// expected to be a leaf [`ParseTree`] whose single payload field is
1379/// named `"value"` — the front-end wraps every scalar value in that
1380/// canonical shape. The convention gives `build_scalar_map` a stable
1381/// spot to fetch the payload from without the derive having to know
1382/// about the wrapping.
1383///
1384/// Like [`build_child_map`], duplicate keys emit a
1385/// [`codes::DUPLICATE_KEY`] diagnostic rather than a silent
1386/// last-one-wins overwrite. Missing `"value"` fields inside an entry
1387/// surface as [`codes::MISSING_FIELD`] and payload type errors as
1388/// [`codes::FIELD_TYPE`] — the same envelope as [`build_field`].
1389///
1390/// `V` must satisfy `serde::de::DeserializeOwned + FromStr` so both
1391/// front-ends (JSON payload / PEG text) can convert values without
1392/// element-wise divergence.
1393pub fn build_scalar_map<V>(tree: &ParseTree, name: &str) -> Result<BTreeMap<String, V>, BuildError>
1394where
1395 V: serde::de::DeserializeOwned + std::str::FromStr,
1396 <V as std::str::FromStr>::Err: std::fmt::Display,
1397{
1398 let slot = tree.keyed_child_slot(name).unwrap_or(&[]);
1399 let mut out = BTreeMap::new();
1400 let mut diags = Vec::new();
1401 for (key, entry) in slot {
1402 match build_field::<V>(entry, "value") {
1403 Ok(v) => {
1404 if out.insert(key.clone(), v).is_some() {
1405 diags.push(
1406 Diagnostic::error(
1407 codes::DUPLICATE_KEY,
1408 format!("keyed child slot `{name}` carries key `{key}` more than once"),
1409 )
1410 .with_span(tree.span),
1411 );
1412 }
1413 }
1414 Err(mut e) => diags.append(&mut e.diagnostics),
1415 }
1416 }
1417 if diags.is_empty() {
1418 Ok(out)
1419 } else {
1420 Err(BuildError::new(diags))
1421 }
1422}
1423
1424/// Builds every entry of a [`Multiplicity::Map`] slot into a
1425/// [`BTreeMap`] keyed by the front-end's keys.
1426///
1427/// [`BTreeMap`] rather than `HashMap` on purpose: the consumer's
1428/// iteration order is part of the observable AST (walks, re-emission,
1429/// canonical text), so it has to be deterministic. The derive
1430/// recognises `BTreeMap<String, T>` for the same reason.
1431///
1432/// Like [`build_child_many`], diagnostics from individual entries are
1433/// collected across the whole slot before returning. A key appearing
1434/// twice is a [`codes::DUPLICATE_KEY`] error rather than a silent
1435/// last-one-wins overwrite — the parse would otherwise drop a subtree
1436/// the author wrote.
1437pub fn build_child_map<T: DslBuild>(
1438 tree: &ParseTree,
1439 name: &str,
1440 ids: &IdGen,
1441) -> Result<BTreeMap<String, T>, BuildError> {
1442 let slot = tree.keyed_child_slot(name).unwrap_or(&[]);
1443 let mut out = BTreeMap::new();
1444 let mut diags = Vec::new();
1445 for (key, child) in slot {
1446 match T::from_parse_tree(child, ids) {
1447 Ok(v) => {
1448 if out.insert(key.clone(), v).is_some() {
1449 diags.push(
1450 Diagnostic::error(
1451 codes::DUPLICATE_KEY,
1452 format!("keyed child slot `{name}` carries key `{key}` more than once"),
1453 )
1454 .with_span(tree.span),
1455 );
1456 }
1457 }
1458 Err(mut e) => diags.append(&mut e.diagnostics),
1459 }
1460 }
1461 if diags.is_empty() {
1462 Ok(out)
1463 } else {
1464 Err(BuildError::new(diags))
1465 }
1466}
1467
1468// ---------------------------------------------------------------------------
1469// Tests
1470// ---------------------------------------------------------------------------
1471
1472#[cfg(test)]
1473mod tests {
1474 use super::*;
1475 use dsl_kit_schema::{
1476 ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, VariantSchema,
1477 };
1478
1479 fn schema_add_lit() -> NodeSchema {
1480 NodeSchema {
1481 name: "Expr".into(),
1482 variants: vec![
1483 VariantSchema {
1484 name: "Lit".into(),
1485 fields: vec![FieldSchema {
1486 name: "value".into(),
1487 ty: "i64".into(),
1488 optional: false,
1489 }],
1490 children: vec![],
1491 },
1492 VariantSchema {
1493 name: "Add".into(),
1494 fields: vec![],
1495 children: vec![
1496 ChildSchema {
1497 name: "lhs".into(),
1498 multiplicity: Multiplicity::One,
1499 value_shape: ChildValueShape::Recursive,
1500 scalar_shorthands: vec![],
1501 non_empty: false,
1502 },
1503 ChildSchema {
1504 name: "rhs".into(),
1505 multiplicity: Multiplicity::One,
1506 value_shape: ChildValueShape::Recursive,
1507 scalar_shorthands: vec![],
1508 non_empty: false,
1509 },
1510 ],
1511 },
1512 VariantSchema {
1513 name: "Let".into(),
1514 fields: vec![FieldSchema {
1515 name: "name".into(),
1516 ty: "String".into(),
1517 optional: false,
1518 }],
1519 children: vec![
1520 ChildSchema {
1521 name: "value".into(),
1522 multiplicity: Multiplicity::One,
1523 value_shape: ChildValueShape::Recursive,
1524 scalar_shorthands: vec![],
1525 non_empty: false,
1526 },
1527 ChildSchema {
1528 name: "body".into(),
1529 multiplicity: Multiplicity::One,
1530 value_shape: ChildValueShape::Recursive,
1531 scalar_shorthands: vec![],
1532 non_empty: false,
1533 },
1534 ],
1535 },
1536 ],
1537 }
1538 }
1539
1540 fn lit(v: i64) -> ParseTree {
1541 let mut t = ParseTree::new("Lit");
1542 t.fields.push(("value".into(), RawValue::Json(json!(v))));
1543 t
1544 }
1545
1546 #[test]
1547 fn ok_lit() {
1548 let schema = schema_add_lit();
1549 assert!(check_conformance(&lit(1), &schema).is_empty());
1550 }
1551
1552 #[test]
1553 fn ok_add_with_two_children() {
1554 let schema = schema_add_lit();
1555 let mut add = ParseTree::new("Add");
1556 add.children.push(("lhs".into(), vec![lit(1)]));
1557 add.children.push(("rhs".into(), vec![lit(2)]));
1558 assert!(check_conformance(&add, &schema).is_empty());
1559 }
1560
1561 #[test]
1562 fn unknown_variant_lists_candidates() {
1563 let schema = schema_add_lit();
1564 let tree = ParseTree::new("Aad"); // typo of Add
1565 let diags = check_conformance(&tree, &schema);
1566 assert_eq!(diags.len(), 1);
1567 assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1568 assert!(
1569 diags[0].message.contains("Add"),
1570 "expected Add to appear as a candidate; got: {}",
1571 diags[0].message
1572 );
1573 }
1574
1575 #[test]
1576 fn unknown_variant_uses_injected_suggester() {
1577 use dsl_kit_fuzzy::FuzzySuggester;
1578
1579 let schema = schema_add_lit();
1580 let tree = ParseTree::new("Adx"); // Jaro-Winkler prefix bias picks "Add"
1581 let suggester = FuzzySuggester::default();
1582 let diags = check_conformance_with(&tree, &schema, &suggester);
1583 assert_eq!(diags.len(), 1);
1584 assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1585 assert!(
1586 diags[0].message.contains("did you mean") && diags[0].message.contains("Add"),
1587 "expected FuzzySuggester to surface `Add`; got: {}",
1588 diags[0].message
1589 );
1590 }
1591
1592 #[test]
1593 fn unknown_field_suggests_declared_field() {
1594 // The design's canonical example: `taget` should surface `target`
1595 // as a `did you mean` hint on the UNKNOWN_FIELD diagnostic.
1596 let schema = NodeSchema {
1597 name: "Cfg".into(),
1598 variants: vec![VariantSchema {
1599 name: "Load".into(),
1600 fields: vec![
1601 FieldSchema {
1602 name: "target".into(),
1603 ty: "String".into(),
1604 optional: false,
1605 },
1606 FieldSchema {
1607 name: "count".into(),
1608 ty: "u32".into(),
1609 optional: false,
1610 },
1611 ],
1612 children: vec![],
1613 }],
1614 };
1615 let mut tree = ParseTree::new("Load");
1616 tree.fields
1617 .push(("taget".into(), RawValue::Json(json!("a"))));
1618 tree.fields.push(("count".into(), RawValue::Json(json!(1))));
1619 let diags = check_conformance(&tree, &schema);
1620
1621 let unknown = diags
1622 .iter()
1623 .find(|d| d.code == codes::UNKNOWN_FIELD)
1624 .expect("expected an UNKNOWN_FIELD diagnostic for `taget`");
1625 assert!(
1626 unknown.message.contains("did you mean") && unknown.message.contains("target"),
1627 "expected `target` in the hint, got: {}",
1628 unknown.message
1629 );
1630 assert!(
1631 unknown.message.contains("(missing)"),
1632 "expected `(missing)` pair-hint since `target` is a required field \
1633 not present on the tree; got: {}",
1634 unknown.message
1635 );
1636 }
1637
1638 #[test]
1639 fn unknown_child_suggests_declared_child() {
1640 let schema = schema_add_lit();
1641 let mut add = ParseTree::new("Add");
1642 // `lsh` is a typo of `lhs`; `rhs` is present so only `lhs`
1643 // remains in the missing set.
1644 add.children.push(("lsh".into(), vec![lit(1)]));
1645 add.children.push(("rhs".into(), vec![lit(2)]));
1646 let diags = check_conformance(&add, &schema);
1647
1648 let unknown = diags
1649 .iter()
1650 .find(|d| d.code == codes::UNKNOWN_CHILD)
1651 .expect("expected an UNKNOWN_CHILD diagnostic for `lsh`");
1652 assert!(
1653 unknown.message.contains("did you mean") && unknown.message.contains("lhs"),
1654 "expected `lhs` in the hint, got: {}",
1655 unknown.message
1656 );
1657 assert!(
1658 unknown.message.contains("(missing)"),
1659 "expected `(missing)` pair-hint on the `lhs` suggestion since \
1660 the `lhs` slot is required but absent; got: {}",
1661 unknown.message
1662 );
1663 }
1664
1665 #[test]
1666 fn missing_field_is_reported() {
1667 let schema = schema_add_lit();
1668 let tree = ParseTree::new("Lit"); // no "value"
1669 let diags = check_conformance(&tree, &schema);
1670 assert_eq!(diags.len(), 1);
1671 assert_eq!(diags[0].code, codes::MISSING_FIELD);
1672 assert!(diags[0].message.contains("value"));
1673 }
1674
1675 /// Layer 1: absent optional field does NOT trigger `MISSING_FIELD`.
1676 #[test]
1677 fn optional_field_absent_is_conformant() {
1678 let schema = NodeSchema {
1679 name: "Meta".into(),
1680 variants: vec![VariantSchema {
1681 name: "Row".into(),
1682 fields: vec![
1683 FieldSchema::required("id", "u32"),
1684 FieldSchema::optional("description", "Option<String>"),
1685 FieldSchema::optional("tags", "Vec<String>"),
1686 ],
1687 children: vec![],
1688 }],
1689 };
1690 let mut tree = ParseTree::new("Row");
1691 tree.fields.push(("id".into(), RawValue::Json(json!(1))));
1692 // description + tags are absent — must not report MISSING_FIELD.
1693 let diags = check_conformance(&tree, &schema);
1694 assert!(
1695 diags.is_empty(),
1696 "optional fields absent should be clean: {diags:?}",
1697 );
1698 }
1699
1700 /// Layer 1 negative: absent REQUIRED field alongside absent
1701 /// optional fields still reports only the required one.
1702 #[test]
1703 fn optional_field_absence_does_not_shadow_required_missing() {
1704 let schema = NodeSchema {
1705 name: "Meta".into(),
1706 variants: vec![VariantSchema {
1707 name: "Row".into(),
1708 fields: vec![
1709 FieldSchema::required("id", "u32"),
1710 FieldSchema::optional("description", "Option<String>"),
1711 ],
1712 children: vec![],
1713 }],
1714 };
1715 let tree = ParseTree::new("Row"); // absent id + absent description
1716 let diags = check_conformance(&tree, &schema);
1717 assert_eq!(diags.len(), 1);
1718 assert_eq!(diags[0].code, codes::MISSING_FIELD);
1719 assert!(
1720 diags[0].message.contains("id"),
1721 "only `id` is reported missing; got: {}",
1722 diags[0].message,
1723 );
1724 }
1725
1726 /// Layer 1 wire contract: `to_json` emits `optional: true` only
1727 /// when the field is optional, preserving the pre-0.3 layout for
1728 /// required fields.
1729 #[test]
1730 fn field_schema_to_json_omits_optional_when_false() {
1731 let required = FieldSchema::required("id", "u32").to_json();
1732 assert_eq!(required, json!({ "name": "id", "type": "u32" }));
1733 assert!(
1734 required.get("optional").is_none(),
1735 "required field omits the optional key entirely (pre-0.3 layout)",
1736 );
1737 let opt = FieldSchema::optional("description", "Option<String>").to_json();
1738 assert_eq!(
1739 opt,
1740 json!({ "name": "description", "type": "Option<String>", "optional": true }),
1741 );
1742 }
1743
1744 /// Layer 2: `build_field_optional` returns `None` for every
1745 /// canonical form of absence: missing field, JSON null, canonical
1746 /// `none` keyword. Present values flow through `build_field`.
1747 #[test]
1748 fn build_field_optional_covers_every_absence_shape() {
1749 let mut t = ParseTree::new("Row");
1750 // Absent field.
1751 assert_eq!(
1752 build_field_optional::<String>(&t, "description").unwrap(),
1753 None,
1754 );
1755 // JSON null.
1756 t.fields
1757 .push(("description".into(), RawValue::Json(Value::Null)));
1758 assert_eq!(
1759 build_field_optional::<String>(&t, "description").unwrap(),
1760 None,
1761 );
1762 // Canonical "none" keyword (Text path).
1763 let mut t2 = ParseTree::new("Row");
1764 t2.fields
1765 .push(("description".into(), RawValue::Text("none".into())));
1766 assert_eq!(
1767 build_field_optional::<String>(&t2, "description").unwrap(),
1768 None,
1769 );
1770 // Present JSON string.
1771 let mut t3 = ParseTree::new("Row");
1772 t3.fields
1773 .push(("description".into(), RawValue::Json(json!("hi"))));
1774 assert_eq!(
1775 build_field_optional::<String>(&t3, "description").unwrap(),
1776 Some("hi".to_string()),
1777 );
1778 }
1779
1780 /// Layer 2: `build_field_vec` defaults to empty on absence, parses
1781 /// JSON arrays natively, and parses canonical bracketed text
1782 /// productions via `serde_json::from_str`.
1783 #[test]
1784 fn build_field_vec_covers_every_shape() {
1785 // Absent → empty.
1786 let t = ParseTree::new("Row");
1787 assert_eq!(
1788 build_field_vec::<String>(&t, "tags").unwrap(),
1789 Vec::<String>::new()
1790 );
1791 // JSON null → empty.
1792 let mut t2 = ParseTree::new("Row");
1793 t2.fields.push(("tags".into(), RawValue::Json(Value::Null)));
1794 assert_eq!(
1795 build_field_vec::<String>(&t2, "tags").unwrap(),
1796 Vec::<String>::new(),
1797 );
1798 // JSON array.
1799 let mut t3 = ParseTree::new("Row");
1800 t3.fields
1801 .push(("tags".into(), RawValue::Json(json!(["a", "b"]))));
1802 assert_eq!(
1803 build_field_vec::<String>(&t3, "tags").unwrap(),
1804 vec!["a".to_string(), "b".to_string()],
1805 );
1806 // Canonical bracketed text (JSON-parsable as-is).
1807 let mut t4 = ParseTree::new("Row");
1808 t4.fields
1809 .push(("tags".into(), RawValue::Text(r#"["a", "b"]"#.into())));
1810 assert_eq!(
1811 build_field_vec::<String>(&t4, "tags").unwrap(),
1812 vec!["a".to_string(), "b".to_string()],
1813 );
1814 // Empty bracketed text.
1815 let mut t5 = ParseTree::new("Row");
1816 t5.fields.push(("tags".into(), RawValue::Text("[]".into())));
1817 assert_eq!(
1818 build_field_vec::<String>(&t5, "tags").unwrap(),
1819 Vec::<String>::new(),
1820 );
1821 }
1822
1823 #[test]
1824 fn unknown_field_is_reported() {
1825 let schema = schema_add_lit();
1826 let mut tree = lit(3);
1827 tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
1828 let diags = check_conformance(&tree, &schema);
1829 assert_eq!(diags.len(), 1);
1830 assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
1831 }
1832
1833 #[test]
1834 fn field_and_child_slot_swapped_reports_structural_codes() {
1835 let schema = schema_add_lit();
1836
1837 // A child slot placed under fields.
1838 let mut swap1 = ParseTree::new("Add");
1839 swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
1840 swap1.children.push(("rhs".into(), vec![lit(1)]));
1841 // Missing lhs child (arity_one) + child-as-field structural swap
1842 // → two diagnostics.
1843 let diags = check_conformance(&swap1, &schema);
1844 assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
1845 assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
1846
1847 // A payload field placed under children.
1848 let mut swap2 = ParseTree::new("Let");
1849 swap2
1850 .children
1851 .push(("name".into(), vec![ParseTree::new("Lit")]));
1852 swap2.children.push(("value".into(), vec![lit(1)]));
1853 swap2.children.push(("body".into(), vec![lit(2)]));
1854 let diags = check_conformance(&swap2, &schema);
1855 assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
1856 assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
1857 }
1858
1859 #[test]
1860 fn arity_one_reports_wrong_count() {
1861 let schema = schema_add_lit();
1862 let mut add = ParseTree::new("Add");
1863 add.children.push(("lhs".into(), vec![lit(1), lit(2)])); // two, not one
1864 add.children.push(("rhs".into(), vec![lit(3)]));
1865 let diags = check_conformance(&add, &schema);
1866 assert_eq!(diags.len(), 1);
1867 assert_eq!(diags[0].code, codes::ARITY_ONE);
1868 assert!(diags[0].message.contains("lhs"));
1869 }
1870
1871 #[test]
1872 fn duplicate_field_and_child_reported() {
1873 let schema = schema_add_lit();
1874 let mut t = ParseTree::new("Lit");
1875 t.fields.push(("value".into(), RawValue::Json(json!(1))));
1876 t.fields.push(("value".into(), RawValue::Json(json!(2))));
1877 let diags = check_conformance(&t, &schema);
1878 assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
1879
1880 let mut a = ParseTree::new("Add");
1881 a.children.push(("lhs".into(), vec![lit(1)]));
1882 a.children.push(("lhs".into(), vec![lit(2)]));
1883 a.children.push(("rhs".into(), vec![lit(3)]));
1884 let diags = check_conformance(&a, &schema);
1885 assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
1886 }
1887
1888 #[test]
1889 fn diagnostic_json_shape() {
1890 let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
1891 let v = diag.to_json();
1892 assert_eq!(v["severity"], "error");
1893 assert_eq!(v["code"], "x::y");
1894 assert_eq!(v["message"], "boom");
1895 assert_eq!(v["location"]["kind"], "span");
1896 assert_eq!(v["location"]["start"], 3);
1897 assert_eq!(v["location"]["end"], 7);
1898 }
1899
1900 #[test]
1901 fn build_error_display_lists_all() {
1902 let err = BuildError::new(vec![
1903 Diagnostic::error("a::b", "one"),
1904 Diagnostic::error("c::d", "two"),
1905 ]);
1906 let s = format!("{err}");
1907 assert!(s.contains("a::b: one"));
1908 assert!(s.contains("c::d: two"));
1909 }
1910}