Skip to main content

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