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 + optional source [`Span`].
18//! - [`RawValue`] — per-field payload representation. `Text` keeps the
19//!   PEG front-end's matched source text; `Json` keeps the serde
20//!   front-end's typed value with no stringify round-trip.
21//! - [`check_conformance`] — validates a tree against a
22//!   [`NodeSchema`] and returns diagnostics.
23//! - [`Diagnostic`] / [`Severity`] / [`Location`] — the shared
24//!   envelope shape.
25//! - [`DslBuild`] — trait consumed by the derive to build a typed AST.
26//! - [`BuildError`] — non-empty diagnostic bag returned on build
27//!   failure.
28
29#![warn(missing_docs)]
30
31use dsl_kit_core::{IdGen, NodeId, Suggester, Suggestion};
32use dsl_kit_schema::{ChildSchema, Multiplicity, NodeSchema, VariantSchema};
33use serde_json::{Value, json};
34use std::fmt;
35
36pub mod example_gen;
37pub mod grammar_check;
38pub mod peg;
39pub mod schema_gen;
40pub mod serde_bridge;
41
42// ---------------------------------------------------------------------------
43// Span
44// ---------------------------------------------------------------------------
45
46/// Byte-offset range into the parser input.
47///
48/// The PEG front-end fills this in as it consumes input; the serde
49/// front-end leaves it `None` because JSON payloads have no meaningful
50/// source position after deserialization.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Span {
53    /// Inclusive start byte offset.
54    pub start: usize,
55    /// Exclusive end byte offset.
56    pub end: usize,
57}
58
59impl Span {
60    /// Constructs a new [`Span`].
61    pub const fn new(start: usize, end: usize) -> Self {
62        Self { start, end }
63    }
64}
65
66// ---------------------------------------------------------------------------
67// RawValue
68// ---------------------------------------------------------------------------
69
70/// Per-field payload representation carried by [`ParseTree`].
71///
72/// The two arms correspond to the two front-ends:
73///
74/// - [`RawValue::Text`] is the matched source text a PEG rule produced;
75///   the [`DslBuild`] consumer converts it via `FromStr`.
76/// - [`RawValue::Json`] is a typed value straight from serde; the
77///   consumer converts it via serde deserialization. Nested payloads
78///   like `Option<u32>` never take a stringify → reparse detour.
79#[derive(Debug, Clone, PartialEq)]
80pub enum RawValue {
81    /// Matched source text (PEG front-end).
82    Text(String),
83    /// Typed value (serde front-end).
84    Json(Value),
85}
86
87// ---------------------------------------------------------------------------
88// ParseTree
89// ---------------------------------------------------------------------------
90
91/// Untyped parse trunk, produced by any front-end and consumed by
92/// [`DslBuild`].
93///
94/// The shape deliberately mirrors [`NodeSchema`] / [`VariantSchema`]:
95/// `variant` picks a variant by name; `fields` carries non-recursive
96/// payload; `children` carries named child slots each holding an
97/// ordered list of subtrees (matching the schema's [`Multiplicity`]).
98#[derive(Debug, Clone, PartialEq)]
99pub struct ParseTree {
100    /// Variant name — must match a [`VariantSchema::name`] at
101    /// conformance time.
102    pub variant: String,
103    /// Non-recursive payload fields, keyed by field name.
104    pub fields: Vec<(String, RawValue)>,
105    /// Recursive child slots, keyed by slot name. Each slot's inner
106    /// [`Vec`] holds zero-or-more trees per the child's
107    /// [`Multiplicity`].
108    pub children: Vec<(String, Vec<ParseTree>)>,
109    /// Source-range span, if the front-end tracks it.
110    pub span: Option<Span>,
111}
112
113impl ParseTree {
114    /// Constructs a new [`ParseTree`] with no fields, children, or span.
115    pub fn new(variant: impl Into<String>) -> Self {
116        Self {
117            variant: variant.into(),
118            fields: Vec::new(),
119            children: Vec::new(),
120            span: None,
121        }
122    }
123
124    /// Looks up a payload field by name.
125    pub fn field(&self, name: &str) -> Option<&RawValue> {
126        self.fields.iter().find(|(n, _)| n == name).map(|(_, v)| v)
127    }
128
129    /// Looks up a child slot by name.
130    pub fn child_slot(&self, name: &str) -> Option<&[ParseTree]> {
131        self.children
132            .iter()
133            .find(|(n, _)| n == name)
134            .map(|(_, v)| v.as_slice())
135    }
136}
137
138// ---------------------------------------------------------------------------
139// Diagnostic envelope
140// ---------------------------------------------------------------------------
141
142/// Severity level of a [`Diagnostic`].
143///
144/// Matches the shape used by `dsl-kit-lint` so consumers speak one
145/// dialect across parse / conformance / lint / debugger.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Severity {
148    /// Blocks build. Multiple errors may be collected before returning.
149    Error,
150    /// Non-blocking warning.
151    Warning,
152    /// Advisory note.
153    Info,
154}
155
156impl Severity {
157    /// Returns the wire-format string used by [`Diagnostic::to_json`].
158    pub const fn as_str(self) -> &'static str {
159        match self {
160            Severity::Error => "error",
161            Severity::Warning => "warning",
162            Severity::Info => "info",
163        }
164    }
165}
166
167/// Where a [`Diagnostic`] points into the consumer's material.
168///
169/// [`Location::Span`] is the parse-time answer (byte range into the
170/// input text); [`Location::Node`] is the post-build answer
171/// ([`NodeId`] into the typed AST); [`Location::None`] is for
172/// diagnostics without a natural anchor point (e.g. "missing top-level
173/// variant").
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum Location {
176    /// Source-text range.
177    Span(Span),
178    /// AST node identity.
179    Node(NodeId),
180    /// No anchor point.
181    None,
182}
183
184impl Location {
185    /// Renders the location as the JSON value used by
186    /// [`Diagnostic::to_json`].
187    ///
188    /// - `Location::Span { start, end }` → `{ "kind": "span", "start": N, "end": M }`
189    /// - `Location::Node(id)`           → `{ "kind": "node", "id": N }`
190    /// - `Location::None`               → JSON `null`
191    pub fn to_json(&self) -> Value {
192        match self {
193            Location::Span(Span { start, end }) => {
194                json!({ "kind": "span", "start": start, "end": end })
195            }
196            Location::Node(id) => json!({ "kind": "node", "id": id.0 }),
197            Location::None => Value::Null,
198        }
199    }
200}
201
202/// One diagnostic in the unified envelope shared across parse,
203/// conformance, lint, and debugger feedback.
204///
205/// The consumer AI is expected to read a single JSON dialect regardless
206/// of which subsystem produced the diagnostic: `{ severity, code,
207/// message, location }`. `code` is a stable machine-friendly slug
208/// (e.g. `"dsl_kit::parse::unknown_variant"`); `message` is the human
209/// (or AI) readable one-liner.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct Diagnostic {
212    /// Severity level.
213    pub severity: Severity,
214    /// Stable machine slug.
215    pub code: String,
216    /// One-line human / AI readable description.
217    pub message: String,
218    /// Anchor point (or [`Location::None`]).
219    pub location: Location,
220}
221
222impl Diagnostic {
223    /// Constructs an [`Severity::Error`] diagnostic.
224    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
225        Self {
226            severity: Severity::Error,
227            code: code.into(),
228            message: message.into(),
229            location: Location::None,
230        }
231    }
232
233    /// Attaches a source [`Span`] as the location.
234    pub fn with_span(mut self, span: Option<Span>) -> Self {
235        if let Some(span) = span {
236            self.location = Location::Span(span);
237        }
238        self
239    }
240
241    /// Attaches an AST [`NodeId`] as the location.
242    pub fn with_node(mut self, id: NodeId) -> Self {
243        self.location = Location::Node(id);
244        self
245    }
246
247    /// Renders the diagnostic as a JSON value.
248    ///
249    /// Layout:
250    /// ```json
251    /// {
252    ///   "severity": "error",
253    ///   "code": "dsl_kit::parse::unknown_variant",
254    ///   "message": "unknown variant `Foo` (candidates: Add, Mul, Lit)",
255    ///   "location": { "kind": "span", "start": 0, "end": 3 }
256    /// }
257    /// ```
258    pub fn to_json(&self) -> Value {
259        json!({
260            "severity": self.severity.as_str(),
261            "code": self.code,
262            "message": self.message,
263            "location": self.location.to_json(),
264        })
265    }
266}
267
268// ---------------------------------------------------------------------------
269// BuildError
270// ---------------------------------------------------------------------------
271
272/// Non-empty diagnostic bag returned by [`DslBuild::from_parse_tree`]
273/// and [`check_conformance`] callers.
274///
275/// Multiple diagnostics are collected before failing so the consumer
276/// AI sees every problem in one round-trip.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct BuildError {
279    /// The diagnostics (at least one is guaranteed by
280    /// [`BuildError::new`]).
281    pub diagnostics: Vec<Diagnostic>,
282}
283
284impl BuildError {
285    /// Wraps a non-empty vector of diagnostics.
286    ///
287    /// # Panics
288    ///
289    /// Panics if `diagnostics` is empty — a [`BuildError`] with no
290    /// diagnostics is meaningless.
291    pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
292        assert!(
293            !diagnostics.is_empty(),
294            "BuildError requires at least one diagnostic"
295        );
296        Self { diagnostics }
297    }
298
299    /// Convenience constructor for a single-diagnostic error.
300    pub fn single(diag: Diagnostic) -> Self {
301        Self {
302            diagnostics: vec![diag],
303        }
304    }
305
306    /// Renders the whole bag as a JSON array of
307    /// [`Diagnostic::to_json`] entries.
308    pub fn to_json(&self) -> Value {
309        Value::Array(self.diagnostics.iter().map(Diagnostic::to_json).collect())
310    }
311}
312
313impl fmt::Display for BuildError {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        write!(
316            f,
317            "build failed with {} diagnostic(s):",
318            self.diagnostics.len()
319        )?;
320        for d in &self.diagnostics {
321            write!(f, "\n  [{}] {}: {}", d.severity.as_str(), d.code, d.message)?;
322        }
323        Ok(())
324    }
325}
326
327impl std::error::Error for BuildError {}
328
329// ---------------------------------------------------------------------------
330// DslBuild
331// ---------------------------------------------------------------------------
332
333/// Contract for building a typed AST value from a validated
334/// [`ParseTree`].
335///
336/// Implemented via `#[derive(DslBuild)]` in `dsl-kit-macros` (G-1c);
337/// hand-written impls are fine for shapes the derive cannot express
338/// (mixed tuple variants, generics, cross-type recursion, etc.).
339pub trait DslBuild: Sized {
340    /// Builds a typed value from `tree`, minting fresh [`NodeId`]s from
341    /// `ids`.
342    ///
343    /// Implementations should call [`check_conformance`] against
344    /// `Self::schema()` before dispatching per-variant so that shape
345    /// mismatches surface as diagnostics rather than panics or ad-hoc
346    /// errors. `RawValue::Text` payloads convert through `FromStr`;
347    /// `RawValue::Json` payloads convert through
348    /// `serde_json::from_value`.
349    fn from_parse_tree(tree: &ParseTree, ids: &IdGen) -> Result<Self, BuildError>;
350}
351
352// ---------------------------------------------------------------------------
353// Schema conformance
354// ---------------------------------------------------------------------------
355
356/// Diagnostic codes emitted by [`check_conformance`].
357///
358/// Exposed as a module of `pub const &str` slugs so downstream tools
359/// (lint UIs, doc generators) can reference them without matching on
360/// string literals.
361pub mod codes {
362    /// Tree's `variant` did not match any
363    /// [`VariantSchema`](dsl_kit_schema::VariantSchema) in the
364    /// [`NodeSchema`](dsl_kit_schema::NodeSchema).
365    pub const UNKNOWN_VARIANT: &str = "dsl_kit::parse::unknown_variant";
366    /// A field required by the schema is absent from the tree.
367    pub const MISSING_FIELD: &str = "dsl_kit::parse::missing_field";
368    /// The tree carries a field the schema does not declare.
369    pub const UNKNOWN_FIELD: &str = "dsl_kit::parse::unknown_field";
370    /// The tree references a child slot the schema does not declare.
371    pub const UNKNOWN_CHILD: &str = "dsl_kit::parse::unknown_child";
372    /// A [`crate::Multiplicity::One`] slot did not carry exactly one
373    /// child.
374    pub const ARITY_ONE: &str = "dsl_kit::parse::arity_one";
375    /// A [`crate::Multiplicity::Optional`] slot carried more than one
376    /// child.
377    pub const ARITY_OPTIONAL: &str = "dsl_kit::parse::arity_optional";
378    /// A payload field appeared under `children` (structural mismatch).
379    pub const FIELD_AS_CHILD: &str = "dsl_kit::parse::field_as_child";
380    /// A child slot appeared under `fields` (structural mismatch).
381    pub const CHILD_AS_FIELD: &str = "dsl_kit::parse::child_as_field";
382    /// A field name appeared more than once.
383    pub const DUPLICATE_FIELD: &str = "dsl_kit::parse::duplicate_field";
384    /// A child slot name appeared more than once.
385    pub const DUPLICATE_CHILD: &str = "dsl_kit::parse::duplicate_child";
386    /// A payload field's value could not be converted to the target
387    /// Rust type (serde deserialization failure or `FromStr` failure).
388    pub const FIELD_TYPE: &str = "dsl_kit::parse::field_type";
389}
390
391/// Validates `tree` against `schema` shallowly (this level only).
392///
393/// The check is intentionally single-level — the recursion is the
394/// caller's job (typically `DslBuild::from_parse_tree` for each child
395/// slot). Every mismatch produces a [`Diagnostic`]; the returned
396/// vector is empty when the tree matches.
397///
398/// Checks performed:
399///
400/// - variant name matches one of `schema.variants` (else
401///   [`codes::UNKNOWN_VARIANT`] with nearest candidates in the
402///   message);
403/// - every declared field is present exactly once
404///   ([`codes::MISSING_FIELD`], [`codes::DUPLICATE_FIELD`]);
405/// - no undeclared field is present ([`codes::UNKNOWN_FIELD`],
406///   or [`codes::CHILD_AS_FIELD`] when the extra name is actually a
407///   declared child slot);
408/// - every declared child slot is present exactly once
409///   ([`codes::DUPLICATE_CHILD`]) and honours its [`Multiplicity`]
410///   ([`codes::ARITY_ONE`], [`codes::ARITY_OPTIONAL`]);
411/// - no undeclared child slot is present ([`codes::UNKNOWN_CHILD`],
412///   or [`codes::FIELD_AS_CHILD`] when the extra name is actually a
413///   declared payload field).
414///
415/// [`Multiplicity::Many`] accepts zero-or-more children — the
416/// `NoEmptyManyChildren` lint rule is the place to complain about
417/// domain-level emptiness.
418pub fn check_conformance(tree: &ParseTree, schema: &NodeSchema) -> Vec<Diagnostic> {
419    check_conformance_with(tree, schema, &BuiltinLevenshteinSuggester)
420}
421
422/// Variant of [`check_conformance`] that routes `did you mean X?`
423/// hints through a caller-supplied [`Suggester`].
424///
425/// The free function [`check_conformance`] delegates here with a
426/// crate-private [`Suggester`] backed by the same Levenshtein
427/// algorithm the crate has always shipped, so existing callers see no
428/// behavioural change. Reach for this variant when you want to plug
429/// in a different similarity algorithm (e.g. `dsl-kit-fuzzy`'s
430/// `FuzzySuggester` with Jaro-Winkler) at a specific call site.
431pub fn check_conformance_with(
432    tree: &ParseTree,
433    schema: &NodeSchema,
434    suggester: &dyn Suggester,
435) -> Vec<Diagnostic> {
436    let mut out = Vec::new();
437
438    let Some(variant) = schema.variant(&tree.variant) else {
439        let msg = format_unknown_variant(&tree.variant, schema, suggester);
440        out.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg).with_span(tree.span));
441        return out;
442    };
443
444    check_fields(tree, variant, &mut out, suggester);
445    check_children(tree, variant, &mut out, suggester);
446    out
447}
448
449/// Shared formatter for the `UNKNOWN_VARIANT` diagnostic message,
450/// used by both [`check_conformance_with`] and the serde bridge so the
451/// wording stays consistent across front-ends.
452pub(crate) fn format_unknown_variant(
453    query: &str,
454    schema: &NodeSchema,
455    suggester: &dyn Suggester,
456) -> String {
457    let names: Vec<&str> = schema.variants.iter().map(|v| v.name.as_str()).collect();
458    let base = format!("unknown variant `{}` for `{}`", query, schema.name);
459    match suggester.enrich_unknown(query, &names) {
460        Some(hint) => format!("{base} ({hint})"),
461        None => base,
462    }
463}
464
465/// Shared formatter for `UNKNOWN_FIELD` and `UNKNOWN_CHILD` messages.
466///
467/// `kind` is `"field"` or `"child slot"`. `all_candidates` should
468/// include both declared field names and declared child slot names so
469/// a `did you mean` hint can point at either. `missing_candidates`
470/// carries the slot names that are declared but currently absent from
471/// the tree; suggestions that appear in this set are marked
472/// `(missing)` — the "pair hint" that makes payloads like
473/// `taget` → `target` (missing) diagnose themselves at a glance.
474pub(crate) fn format_unknown_slot(
475    kind: &str,
476    query: &str,
477    variant_name: &str,
478    all_candidates: &[&str],
479    missing_candidates: &[&str],
480    suggester: &dyn Suggester,
481) -> String {
482    let base = format!("unknown {kind} `{query}` on variant `{variant_name}`");
483    let sugs = suggester.suggest(query, all_candidates);
484    if sugs.is_empty() {
485        return base;
486    }
487    let joined = sugs
488        .iter()
489        .take(3)
490        .map(|s| {
491            if missing_candidates.contains(&s.candidate) {
492                format!("`{}` (missing)", s.candidate)
493            } else {
494                format!("`{}`", s.candidate)
495            }
496        })
497        .collect::<Vec<_>>()
498        .join(", ");
499    format!("{base} (did you mean: {joined})")
500}
501
502fn check_fields(
503    tree: &ParseTree,
504    variant: &VariantSchema,
505    out: &mut Vec<Diagnostic>,
506    suggester: &dyn Suggester,
507) {
508    // Duplicate field names.
509    for i in 0..tree.fields.len() {
510        let (name, _) = &tree.fields[i];
511        if tree.fields[..i].iter().any(|(n, _)| n == name) {
512            out.push(
513                Diagnostic::error(
514                    codes::DUPLICATE_FIELD,
515                    format!(
516                        "field `{}` appears more than once on variant `{}`",
517                        name, variant.name
518                    ),
519                )
520                .with_span(tree.span),
521            );
522        }
523    }
524
525    // Missing declared fields. Optional fields (typically `Option<T>`
526    // / `Vec<T>` payloads recognised by `#[derive(DslSchema)]`) are
527    // skipped — their absence is a valid shape and the build layer's
528    // `build_field_optional` / `build_field_vec` helpers supply the
529    // default (`None` / empty vec).
530    for f in &variant.fields {
531        if f.optional {
532            continue;
533        }
534        if tree.field(&f.name).is_none() {
535            out.push(
536                Diagnostic::error(
537                    codes::MISSING_FIELD,
538                    format!(
539                        "variant `{}` is missing required field `{}` (type `{}`)",
540                        variant.name, f.name, f.ty
541                    ),
542                )
543                .with_span(tree.span),
544            );
545        }
546    }
547
548    // Precompute the "missing-so-far" set once: slot names that are
549    // declared but currently absent from `tree`. Used as the pair-hint
550    // marker on UNKNOWN_FIELD suggestions.
551    let missing = missing_slot_names(tree, variant);
552    let all_slots = all_slot_names(variant);
553
554    // Unknown fields.
555    for (name, _) in &tree.fields {
556        if variant.fields.iter().any(|f| &f.name == name) {
557            continue;
558        }
559        // If it names a declared child slot, that's a structural mix-up.
560        if variant.children.iter().any(|c| &c.name == name) {
561            out.push(
562                Diagnostic::error(
563                    codes::CHILD_AS_FIELD,
564                    format!(
565                        "`{}` on variant `{}` is a child slot, not a payload field \
566                         (move it under `children`)",
567                        name, variant.name
568                    ),
569                )
570                .with_span(tree.span),
571            );
572        } else {
573            let msg = format_unknown_slot(
574                "field",
575                name,
576                &variant.name,
577                &all_slots,
578                &missing,
579                suggester,
580            );
581            out.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg).with_span(tree.span));
582        }
583    }
584}
585
586fn check_children(
587    tree: &ParseTree,
588    variant: &VariantSchema,
589    out: &mut Vec<Diagnostic>,
590    suggester: &dyn Suggester,
591) {
592    // Duplicate child slot names.
593    for i in 0..tree.children.len() {
594        let (name, _) = &tree.children[i];
595        if tree.children[..i].iter().any(|(n, _)| n == name) {
596            out.push(
597                Diagnostic::error(
598                    codes::DUPLICATE_CHILD,
599                    format!(
600                        "child slot `{}` appears more than once on variant `{}`",
601                        name, variant.name
602                    ),
603                )
604                .with_span(tree.span),
605            );
606        }
607    }
608
609    // Declared children: arity check.
610    for c in &variant.children {
611        let count = tree
612            .child_slot(&c.name)
613            .map(<[ParseTree]>::len)
614            .unwrap_or(0);
615        match c.multiplicity {
616            Multiplicity::One => {
617                if count != 1 {
618                    out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
619                }
620            }
621            Multiplicity::Optional => {
622                if count > 1 {
623                    out.push(diag_arity(
624                        codes::ARITY_OPTIONAL,
625                        variant,
626                        c,
627                        count,
628                        tree.span,
629                    ));
630                }
631            }
632            Multiplicity::Many => {
633                // Zero is fine at the shape level.
634            }
635        }
636    }
637
638    // Same pair-hint precomputation as check_fields, sharing the
639    // "declared but currently absent" set across both diagnostics.
640    let missing = missing_slot_names(tree, variant);
641    let all_slots = all_slot_names(variant);
642
643    // Unknown child slots.
644    for (name, _) in &tree.children {
645        if variant.children.iter().any(|c| &c.name == name) {
646            continue;
647        }
648        if variant.fields.iter().any(|f| &f.name == name) {
649            out.push(
650                Diagnostic::error(
651                    codes::FIELD_AS_CHILD,
652                    format!(
653                        "`{}` on variant `{}` is a payload field, not a child slot \
654                         (move it under `fields`)",
655                        name, variant.name
656                    ),
657                )
658                .with_span(tree.span),
659            );
660        } else {
661            let msg = format_unknown_slot(
662                "child slot",
663                name,
664                &variant.name,
665                &all_slots,
666                &missing,
667                suggester,
668            );
669            out.push(Diagnostic::error(codes::UNKNOWN_CHILD, msg).with_span(tree.span));
670        }
671    }
672}
673
674/// Names of every declared payload field and child slot on
675/// `variant`, in that order. Used as the `all_candidates` slice for
676/// [`format_unknown_slot`].
677pub(crate) fn all_slot_names(variant: &VariantSchema) -> Vec<&str> {
678    variant
679        .fields
680        .iter()
681        .map(|f| f.name.as_str())
682        .chain(variant.children.iter().map(|c| c.name.as_str()))
683        .collect()
684}
685
686/// Names of declared slots that are **not** currently present on
687/// `tree`. Includes fields with no matching entry in `tree.fields`
688/// and children whose slot has zero occurrences on the tree. Feeds
689/// [`format_unknown_slot`]'s `(missing)` pair-hint marker.
690pub(crate) fn missing_slot_names<'a>(tree: &ParseTree, variant: &'a VariantSchema) -> Vec<&'a str> {
691    let mut out = Vec::new();
692    for f in &variant.fields {
693        // Optional fields are never "missing" for pair-hint purposes:
694        // their absence is a valid shape, so pointing at them from an
695        // unknown-slot suggestion would misdirect the reader.
696        if f.optional {
697            continue;
698        }
699        if tree.field(&f.name).is_none() {
700            out.push(f.name.as_str());
701        }
702    }
703    for c in &variant.children {
704        let count = tree
705            .child_slot(&c.name)
706            .map(<[ParseTree]>::len)
707            .unwrap_or(0);
708        if count == 0 {
709            out.push(c.name.as_str());
710        }
711    }
712    out
713}
714
715fn diag_arity(
716    code: &'static str,
717    variant: &VariantSchema,
718    child: &ChildSchema,
719    count: usize,
720    span: Option<Span>,
721) -> Diagnostic {
722    let expected = match child.multiplicity {
723        Multiplicity::One => "exactly one child",
724        Multiplicity::Optional => "at most one child",
725        Multiplicity::Many => "zero or more children",
726    };
727    Diagnostic::error(
728        code,
729        format!(
730            "child slot `{}` on variant `{}` expects {} but got {}",
731            child.name, variant.name, expected, count
732        ),
733    )
734    .with_span(span)
735}
736
737// ---------------------------------------------------------------------------
738// Built-in Suggester (case-insensitive Levenshtein, cutoff = max(query.len, 1))
739// ---------------------------------------------------------------------------
740
741/// Default [`Suggester`] used by [`check_conformance`] and the serde
742/// bridge when no explicit suggester is supplied.
743///
744/// Backed by an ASCII-case-insensitive Levenshtein edit distance with
745/// cutoff `max(query.len(), 1)` — the same behaviour the crate has
746/// shipped since Round 1, kept internal so the parser does not need
747/// to depend on the plugin crate.
748pub(crate) struct BuiltinLevenshteinSuggester;
749
750impl Suggester for BuiltinLevenshteinSuggester {
751    fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
752        let cutoff = query.chars().count().max(1);
753        let mut scored: Vec<(usize, &'a str)> = candidates
754            .iter()
755            .map(|c| (levenshtein(query, c), *c))
756            .filter(|(d, _)| *d <= cutoff)
757            .collect();
758        scored.sort_by(|(da, na), (db, nb)| da.cmp(db).then_with(|| na.cmp(nb)));
759        scored.truncate(3);
760        scored
761            .into_iter()
762            .map(|(d, name)| Suggestion {
763                candidate: name,
764                score: normalise_edit(d, query, name),
765            })
766            .collect()
767    }
768}
769
770fn normalise_edit(distance: usize, a: &str, b: &str) -> f64 {
771    let max_len = a.chars().count().max(b.chars().count());
772    if max_len == 0 {
773        return 1.0;
774    }
775    1.0 - (distance as f64 / max_len as f64)
776}
777
778fn levenshtein(a: &str, b: &str) -> usize {
779    let a: Vec<char> = a.chars().collect();
780    let b: Vec<char> = b.chars().collect();
781    let (m, n) = (a.len(), b.len());
782    if m == 0 {
783        return n;
784    }
785    if n == 0 {
786        return m;
787    }
788    let mut prev: Vec<usize> = (0..=n).collect();
789    let mut curr: Vec<usize> = vec![0; n + 1];
790    for i in 1..=m {
791        curr[0] = i;
792        for j in 1..=n {
793            let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
794                0
795            } else {
796                1
797            };
798            curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
799        }
800        std::mem::swap(&mut prev, &mut curr);
801    }
802    prev[n]
803}
804
805// ---------------------------------------------------------------------------
806// Build helpers (used by #[derive(DslBuild)] code emission)
807// ---------------------------------------------------------------------------
808
809/// Extracts a payload field into `T`.
810///
811/// Dispatches on the field's [`RawValue`] arm:
812///
813/// - [`RawValue::Json`] → `serde_json::from_value::<T>`.
814/// - [`RawValue::Text`] → `T::from_str` (G-2: PEG front-end path).
815///
816/// This means the derive works with either front-end unchanged — the
817/// front-end picks the payload representation, the derive is agnostic.
818/// `T` must therefore satisfy both bounds; every primitive the kit
819/// currently uses (`String`, `i64`, `u32`, `bool`, `f64`) does.
820///
821/// This helper is intended for use by `#[derive(DslBuild)]`-generated
822/// code but is usable directly by hand-written [`DslBuild`] impls.
823pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
824where
825    T: serde::de::DeserializeOwned + std::str::FromStr,
826    <T as std::str::FromStr>::Err: std::fmt::Display,
827{
828    match tree.field(name) {
829        Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
830            BuildError::single(
831                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
832                    .with_span(tree.span),
833            )
834        }),
835        Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
836            BuildError::single(
837                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
838                    .with_span(tree.span),
839            )
840        }),
841        None => Err(BuildError::single(
842            Diagnostic::error(
843                codes::MISSING_FIELD,
844                format!("missing required field `{name}`"),
845            )
846            .with_span(tree.span),
847        )),
848    }
849}
850
851/// Extracts an optional payload field into `Option<T>`.
852///
853/// Companion to [`build_field`] for fields whose Rust type is
854/// `Option<T>` — the `#[derive(DslBuild)]` default path routes here
855/// automatically for payload `Option<T>` types (see the derive docs).
856///
857/// Resolution rules:
858///
859/// - Absent field → `Ok(None)` (this is the "AI-emit omits noise"
860///   contract — schema-level `optional: true` skips the
861///   `MISSING_FIELD` diagnostic so absence reaches here).
862/// - [`RawValue::Json`] with a `null` value → `Ok(None)`.
863/// - [`RawValue::Text`] whose text is the literal `"none"` (the
864///   canonical-syntax keyword produced by `schema_gen`) → `Ok(None)`.
865/// - Any other value → delegate to [`build_field`], wrap in `Some`.
866///
867/// `T` must satisfy the same `DeserializeOwned + FromStr` bounds as
868/// [`build_field`] because the delegate path uses it.
869pub fn build_field_optional<T>(tree: &ParseTree, name: &str) -> Result<Option<T>, BuildError>
870where
871    T: serde::de::DeserializeOwned + std::str::FromStr,
872    <T as std::str::FromStr>::Err: std::fmt::Display,
873{
874    match tree.field(name) {
875        None => Ok(None),
876        Some(RawValue::Json(Value::Null)) => Ok(None),
877        Some(RawValue::Text(s)) if s == "none" => Ok(None),
878        Some(_) => build_field::<T>(tree, name).map(Some),
879    }
880}
881
882/// Extracts a payload field into `Vec<T>`.
883///
884/// Companion to [`build_field`] for fields whose Rust type is
885/// `Vec<T>` — the `#[derive(DslBuild)]` default path routes here
886/// automatically for payload `Vec<T>` types (see the derive docs).
887///
888/// Resolution rules:
889///
890/// - Absent field → `Ok(vec![])` (schema-level `optional: true` skips
891///   the `MISSING_FIELD` diagnostic; missing = empty list).
892/// - [`RawValue::Json`] with a `null` value → `Ok(vec![])`.
893/// - [`RawValue::Json`] with an array → `serde_json::from_value`
894///   over the whole array.
895/// - [`RawValue::Text`] whose trimmed body is empty → `Ok(vec![])`.
896/// - [`RawValue::Text`] otherwise → parse the text as a JSON array
897///   (`serde_json::from_str::<Vec<T>>`). The canonical-syntax
898///   production for `Vec<String>` (`[ "a", "b" ]`) is JSON-parsable
899///   as-is; hand-authored value productions that follow the same
900///   bracketed shape work unchanged.
901///
902/// `T` must implement `serde::de::DeserializeOwned` — no `FromStr`
903/// bound is needed because the text path routes through
904/// `serde_json::from_str` rather than element-wise parsing.
905pub fn build_field_vec<T>(tree: &ParseTree, name: &str) -> Result<Vec<T>, BuildError>
906where
907    T: serde::de::DeserializeOwned,
908{
909    match tree.field(name) {
910        None => Ok(Vec::new()),
911        Some(RawValue::Json(Value::Null)) => Ok(Vec::new()),
912        Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
913            BuildError::single(
914                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
915                    .with_span(tree.span),
916            )
917        }),
918        Some(RawValue::Text(s)) => {
919            let trimmed = s.trim();
920            if trimmed.is_empty() {
921                return Ok(Vec::new());
922            }
923            serde_json::from_str(trimmed).map_err(|e| {
924                BuildError::single(
925                    Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
926                        .with_span(tree.span),
927                )
928            })
929        }
930    }
931}
932
933/// Extracts a payload field's raw text production.
934///
935/// Convenience for `#[dsl_build(with = ...)]` converter functions,
936/// which typically match on the spelling the grammar (often a
937/// `schema_gen::SyntaxOverrides` value production) captured. Errors
938/// mirror [`build_field`]: [`codes::MISSING_FIELD`] when absent,
939/// [`codes::FIELD_TYPE`] when the field carries a
940/// [`RawValue::Json`] payload instead of text.
941pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
942    match tree.field(name) {
943        Some(RawValue::Text(s)) => Ok(s),
944        Some(RawValue::Json(_)) => Err(BuildError::single(
945            Diagnostic::error(
946                codes::FIELD_TYPE,
947                format!("field `{name}`: expected a text production, found JSON"),
948            )
949            .with_span(tree.span),
950        )),
951        None => Err(BuildError::single(
952            Diagnostic::error(
953                codes::MISSING_FIELD,
954                format!("missing required field `{name}`"),
955            )
956            .with_span(tree.span),
957        )),
958    }
959}
960
961/// Builds the single child of a [`Multiplicity::One`] slot.
962///
963/// Returns [`codes::ARITY_ONE`] if the slot is absent or holds more
964/// than one subtree. Errors from the recursive
965/// [`DslBuild::from_parse_tree`] call bubble up as-is.
966pub fn build_child_one<T: DslBuild>(
967    tree: &ParseTree,
968    name: &str,
969    ids: &IdGen,
970) -> Result<T, BuildError> {
971    let slot = tree.child_slot(name).unwrap_or(&[]);
972    if slot.len() != 1 {
973        return Err(BuildError::single(
974            Diagnostic::error(
975                codes::ARITY_ONE,
976                format!(
977                    "child slot `{name}` expects exactly one child but got {}",
978                    slot.len()
979                ),
980            )
981            .with_span(tree.span),
982        ));
983    }
984    T::from_parse_tree(&slot[0], ids)
985}
986
987/// Builds the (optional) child of a [`Multiplicity::Optional`] slot.
988///
989/// Returns [`codes::ARITY_OPTIONAL`] if the slot holds more than one
990/// subtree. Missing / empty slots yield `Ok(None)`.
991pub fn build_child_optional<T: DslBuild>(
992    tree: &ParseTree,
993    name: &str,
994    ids: &IdGen,
995) -> Result<Option<T>, BuildError> {
996    let slot = tree.child_slot(name).unwrap_or(&[]);
997    match slot.len() {
998        0 => Ok(None),
999        1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
1000        n => Err(BuildError::single(
1001            Diagnostic::error(
1002                codes::ARITY_OPTIONAL,
1003                format!("child slot `{name}` expects at most one child but got {n}"),
1004            )
1005            .with_span(tree.span),
1006        )),
1007    }
1008}
1009
1010/// Builds every child of a [`Multiplicity::Many`] slot.
1011///
1012/// Diagnostics from individual children are collected across the whole
1013/// slot before returning, so a partially-broken batch surfaces every
1014/// bad subtree at once rather than the first-encountered one.
1015pub fn build_child_many<T: DslBuild>(
1016    tree: &ParseTree,
1017    name: &str,
1018    ids: &IdGen,
1019) -> Result<Vec<T>, BuildError> {
1020    let slot = tree.child_slot(name).unwrap_or(&[]);
1021    let mut out = Vec::with_capacity(slot.len());
1022    let mut diags = Vec::new();
1023    for child in slot {
1024        match T::from_parse_tree(child, ids) {
1025            Ok(v) => out.push(v),
1026            Err(mut e) => diags.append(&mut e.diagnostics),
1027        }
1028    }
1029    if diags.is_empty() {
1030        Ok(out)
1031    } else {
1032        Err(BuildError::new(diags))
1033    }
1034}
1035
1036// ---------------------------------------------------------------------------
1037// Tests
1038// ---------------------------------------------------------------------------
1039
1040#[cfg(test)]
1041mod tests {
1042    use super::*;
1043    use dsl_kit_schema::{ChildSchema, FieldSchema, Multiplicity, NodeSchema, VariantSchema};
1044
1045    fn schema_add_lit() -> NodeSchema {
1046        NodeSchema {
1047            name: "Expr".into(),
1048            variants: vec![
1049                VariantSchema {
1050                    name: "Lit".into(),
1051                    fields: vec![FieldSchema {
1052                        name: "value".into(),
1053                        ty: "i64".into(),
1054                        optional: false,
1055                    }],
1056                    children: vec![],
1057                },
1058                VariantSchema {
1059                    name: "Add".into(),
1060                    fields: vec![],
1061                    children: vec![
1062                        ChildSchema {
1063                            name: "lhs".into(),
1064                            multiplicity: Multiplicity::One,
1065                        },
1066                        ChildSchema {
1067                            name: "rhs".into(),
1068                            multiplicity: Multiplicity::One,
1069                        },
1070                    ],
1071                },
1072                VariantSchema {
1073                    name: "Let".into(),
1074                    fields: vec![FieldSchema {
1075                        name: "name".into(),
1076                        ty: "String".into(),
1077                        optional: false,
1078                    }],
1079                    children: vec![
1080                        ChildSchema {
1081                            name: "value".into(),
1082                            multiplicity: Multiplicity::One,
1083                        },
1084                        ChildSchema {
1085                            name: "body".into(),
1086                            multiplicity: Multiplicity::One,
1087                        },
1088                    ],
1089                },
1090            ],
1091        }
1092    }
1093
1094    fn lit(v: i64) -> ParseTree {
1095        let mut t = ParseTree::new("Lit");
1096        t.fields.push(("value".into(), RawValue::Json(json!(v))));
1097        t
1098    }
1099
1100    #[test]
1101    fn ok_lit() {
1102        let schema = schema_add_lit();
1103        assert!(check_conformance(&lit(1), &schema).is_empty());
1104    }
1105
1106    #[test]
1107    fn ok_add_with_two_children() {
1108        let schema = schema_add_lit();
1109        let mut add = ParseTree::new("Add");
1110        add.children.push(("lhs".into(), vec![lit(1)]));
1111        add.children.push(("rhs".into(), vec![lit(2)]));
1112        assert!(check_conformance(&add, &schema).is_empty());
1113    }
1114
1115    #[test]
1116    fn unknown_variant_lists_candidates() {
1117        let schema = schema_add_lit();
1118        let tree = ParseTree::new("Aad"); // typo of Add
1119        let diags = check_conformance(&tree, &schema);
1120        assert_eq!(diags.len(), 1);
1121        assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1122        assert!(
1123            diags[0].message.contains("Add"),
1124            "expected Add to appear as a candidate; got: {}",
1125            diags[0].message
1126        );
1127    }
1128
1129    #[test]
1130    fn unknown_variant_uses_injected_suggester() {
1131        use dsl_kit_fuzzy::FuzzySuggester;
1132
1133        let schema = schema_add_lit();
1134        let tree = ParseTree::new("Adx"); // Jaro-Winkler prefix bias picks "Add"
1135        let suggester = FuzzySuggester::default();
1136        let diags = check_conformance_with(&tree, &schema, &suggester);
1137        assert_eq!(diags.len(), 1);
1138        assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1139        assert!(
1140            diags[0].message.contains("did you mean") && diags[0].message.contains("Add"),
1141            "expected FuzzySuggester to surface `Add`; got: {}",
1142            diags[0].message
1143        );
1144    }
1145
1146    #[test]
1147    fn unknown_field_suggests_declared_field() {
1148        // The design's canonical example: `taget` should surface `target`
1149        // as a `did you mean` hint on the UNKNOWN_FIELD diagnostic.
1150        let schema = NodeSchema {
1151            name: "Cfg".into(),
1152            variants: vec![VariantSchema {
1153                name: "Load".into(),
1154                fields: vec![
1155                    FieldSchema {
1156                        name: "target".into(),
1157                        ty: "String".into(),
1158                        optional: false,
1159                    },
1160                    FieldSchema {
1161                        name: "count".into(),
1162                        ty: "u32".into(),
1163                        optional: false,
1164                    },
1165                ],
1166                children: vec![],
1167            }],
1168        };
1169        let mut tree = ParseTree::new("Load");
1170        tree.fields
1171            .push(("taget".into(), RawValue::Json(json!("a"))));
1172        tree.fields.push(("count".into(), RawValue::Json(json!(1))));
1173        let diags = check_conformance(&tree, &schema);
1174
1175        let unknown = diags
1176            .iter()
1177            .find(|d| d.code == codes::UNKNOWN_FIELD)
1178            .expect("expected an UNKNOWN_FIELD diagnostic for `taget`");
1179        assert!(
1180            unknown.message.contains("did you mean") && unknown.message.contains("target"),
1181            "expected `target` in the hint, got: {}",
1182            unknown.message
1183        );
1184        assert!(
1185            unknown.message.contains("(missing)"),
1186            "expected `(missing)` pair-hint since `target` is a required field \
1187             not present on the tree; got: {}",
1188            unknown.message
1189        );
1190    }
1191
1192    #[test]
1193    fn unknown_child_suggests_declared_child() {
1194        let schema = schema_add_lit();
1195        let mut add = ParseTree::new("Add");
1196        // `lsh` is a typo of `lhs`; `rhs` is present so only `lhs`
1197        // remains in the missing set.
1198        add.children.push(("lsh".into(), vec![lit(1)]));
1199        add.children.push(("rhs".into(), vec![lit(2)]));
1200        let diags = check_conformance(&add, &schema);
1201
1202        let unknown = diags
1203            .iter()
1204            .find(|d| d.code == codes::UNKNOWN_CHILD)
1205            .expect("expected an UNKNOWN_CHILD diagnostic for `lsh`");
1206        assert!(
1207            unknown.message.contains("did you mean") && unknown.message.contains("lhs"),
1208            "expected `lhs` in the hint, got: {}",
1209            unknown.message
1210        );
1211        assert!(
1212            unknown.message.contains("(missing)"),
1213            "expected `(missing)` pair-hint on the `lhs` suggestion since \
1214             the `lhs` slot is required but absent; got: {}",
1215            unknown.message
1216        );
1217    }
1218
1219    #[test]
1220    fn missing_field_is_reported() {
1221        let schema = schema_add_lit();
1222        let tree = ParseTree::new("Lit"); // no "value"
1223        let diags = check_conformance(&tree, &schema);
1224        assert_eq!(diags.len(), 1);
1225        assert_eq!(diags[0].code, codes::MISSING_FIELD);
1226        assert!(diags[0].message.contains("value"));
1227    }
1228
1229    /// Layer 1: absent optional field does NOT trigger `MISSING_FIELD`.
1230    #[test]
1231    fn optional_field_absent_is_conformant() {
1232        let schema = NodeSchema {
1233            name: "Meta".into(),
1234            variants: vec![VariantSchema {
1235                name: "Row".into(),
1236                fields: vec![
1237                    FieldSchema::required("id", "u32"),
1238                    FieldSchema::optional("description", "Option<String>"),
1239                    FieldSchema::optional("tags", "Vec<String>"),
1240                ],
1241                children: vec![],
1242            }],
1243        };
1244        let mut tree = ParseTree::new("Row");
1245        tree.fields.push(("id".into(), RawValue::Json(json!(1))));
1246        // description + tags are absent — must not report MISSING_FIELD.
1247        let diags = check_conformance(&tree, &schema);
1248        assert!(
1249            diags.is_empty(),
1250            "optional fields absent should be clean: {diags:?}",
1251        );
1252    }
1253
1254    /// Layer 1 negative: absent REQUIRED field alongside absent
1255    /// optional fields still reports only the required one.
1256    #[test]
1257    fn optional_field_absence_does_not_shadow_required_missing() {
1258        let schema = NodeSchema {
1259            name: "Meta".into(),
1260            variants: vec![VariantSchema {
1261                name: "Row".into(),
1262                fields: vec![
1263                    FieldSchema::required("id", "u32"),
1264                    FieldSchema::optional("description", "Option<String>"),
1265                ],
1266                children: vec![],
1267            }],
1268        };
1269        let tree = ParseTree::new("Row"); // absent id + absent description
1270        let diags = check_conformance(&tree, &schema);
1271        assert_eq!(diags.len(), 1);
1272        assert_eq!(diags[0].code, codes::MISSING_FIELD);
1273        assert!(
1274            diags[0].message.contains("id"),
1275            "only `id` is reported missing; got: {}",
1276            diags[0].message,
1277        );
1278    }
1279
1280    /// Layer 1 wire contract: `to_json` emits `optional: true` only
1281    /// when the field is optional, preserving the pre-0.3 layout for
1282    /// required fields.
1283    #[test]
1284    fn field_schema_to_json_omits_optional_when_false() {
1285        let required = FieldSchema::required("id", "u32").to_json();
1286        assert_eq!(required, json!({ "name": "id", "type": "u32" }));
1287        assert!(
1288            required.get("optional").is_none(),
1289            "required field omits the optional key entirely (pre-0.3 layout)",
1290        );
1291        let opt = FieldSchema::optional("description", "Option<String>").to_json();
1292        assert_eq!(
1293            opt,
1294            json!({ "name": "description", "type": "Option<String>", "optional": true }),
1295        );
1296    }
1297
1298    /// Layer 2: `build_field_optional` returns `None` for every
1299    /// canonical form of absence: missing field, JSON null, canonical
1300    /// `none` keyword. Present values flow through `build_field`.
1301    #[test]
1302    fn build_field_optional_covers_every_absence_shape() {
1303        let mut t = ParseTree::new("Row");
1304        // Absent field.
1305        assert_eq!(
1306            build_field_optional::<String>(&t, "description").unwrap(),
1307            None,
1308        );
1309        // JSON null.
1310        t.fields
1311            .push(("description".into(), RawValue::Json(Value::Null)));
1312        assert_eq!(
1313            build_field_optional::<String>(&t, "description").unwrap(),
1314            None,
1315        );
1316        // Canonical "none" keyword (Text path).
1317        let mut t2 = ParseTree::new("Row");
1318        t2.fields
1319            .push(("description".into(), RawValue::Text("none".into())));
1320        assert_eq!(
1321            build_field_optional::<String>(&t2, "description").unwrap(),
1322            None,
1323        );
1324        // Present JSON string.
1325        let mut t3 = ParseTree::new("Row");
1326        t3.fields
1327            .push(("description".into(), RawValue::Json(json!("hi"))));
1328        assert_eq!(
1329            build_field_optional::<String>(&t3, "description").unwrap(),
1330            Some("hi".to_string()),
1331        );
1332    }
1333
1334    /// Layer 2: `build_field_vec` defaults to empty on absence, parses
1335    /// JSON arrays natively, and parses canonical bracketed text
1336    /// productions via `serde_json::from_str`.
1337    #[test]
1338    fn build_field_vec_covers_every_shape() {
1339        // Absent → empty.
1340        let t = ParseTree::new("Row");
1341        assert_eq!(
1342            build_field_vec::<String>(&t, "tags").unwrap(),
1343            Vec::<String>::new()
1344        );
1345        // JSON null → empty.
1346        let mut t2 = ParseTree::new("Row");
1347        t2.fields.push(("tags".into(), RawValue::Json(Value::Null)));
1348        assert_eq!(
1349            build_field_vec::<String>(&t2, "tags").unwrap(),
1350            Vec::<String>::new(),
1351        );
1352        // JSON array.
1353        let mut t3 = ParseTree::new("Row");
1354        t3.fields
1355            .push(("tags".into(), RawValue::Json(json!(["a", "b"]))));
1356        assert_eq!(
1357            build_field_vec::<String>(&t3, "tags").unwrap(),
1358            vec!["a".to_string(), "b".to_string()],
1359        );
1360        // Canonical bracketed text (JSON-parsable as-is).
1361        let mut t4 = ParseTree::new("Row");
1362        t4.fields
1363            .push(("tags".into(), RawValue::Text(r#"["a", "b"]"#.into())));
1364        assert_eq!(
1365            build_field_vec::<String>(&t4, "tags").unwrap(),
1366            vec!["a".to_string(), "b".to_string()],
1367        );
1368        // Empty bracketed text.
1369        let mut t5 = ParseTree::new("Row");
1370        t5.fields.push(("tags".into(), RawValue::Text("[]".into())));
1371        assert_eq!(
1372            build_field_vec::<String>(&t5, "tags").unwrap(),
1373            Vec::<String>::new(),
1374        );
1375    }
1376
1377    #[test]
1378    fn unknown_field_is_reported() {
1379        let schema = schema_add_lit();
1380        let mut tree = lit(3);
1381        tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
1382        let diags = check_conformance(&tree, &schema);
1383        assert_eq!(diags.len(), 1);
1384        assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
1385    }
1386
1387    #[test]
1388    fn field_and_child_slot_swapped_reports_structural_codes() {
1389        let schema = schema_add_lit();
1390
1391        // A child slot placed under fields.
1392        let mut swap1 = ParseTree::new("Add");
1393        swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
1394        swap1.children.push(("rhs".into(), vec![lit(1)]));
1395        // Missing lhs child (arity_one) + child-as-field structural swap
1396        // → two diagnostics.
1397        let diags = check_conformance(&swap1, &schema);
1398        assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
1399        assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
1400
1401        // A payload field placed under children.
1402        let mut swap2 = ParseTree::new("Let");
1403        swap2
1404            .children
1405            .push(("name".into(), vec![ParseTree::new("Lit")]));
1406        swap2.children.push(("value".into(), vec![lit(1)]));
1407        swap2.children.push(("body".into(), vec![lit(2)]));
1408        let diags = check_conformance(&swap2, &schema);
1409        assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
1410        assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
1411    }
1412
1413    #[test]
1414    fn arity_one_reports_wrong_count() {
1415        let schema = schema_add_lit();
1416        let mut add = ParseTree::new("Add");
1417        add.children.push(("lhs".into(), vec![lit(1), lit(2)])); // two, not one
1418        add.children.push(("rhs".into(), vec![lit(3)]));
1419        let diags = check_conformance(&add, &schema);
1420        assert_eq!(diags.len(), 1);
1421        assert_eq!(diags[0].code, codes::ARITY_ONE);
1422        assert!(diags[0].message.contains("lhs"));
1423    }
1424
1425    #[test]
1426    fn duplicate_field_and_child_reported() {
1427        let schema = schema_add_lit();
1428        let mut t = ParseTree::new("Lit");
1429        t.fields.push(("value".into(), RawValue::Json(json!(1))));
1430        t.fields.push(("value".into(), RawValue::Json(json!(2))));
1431        let diags = check_conformance(&t, &schema);
1432        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
1433
1434        let mut a = ParseTree::new("Add");
1435        a.children.push(("lhs".into(), vec![lit(1)]));
1436        a.children.push(("lhs".into(), vec![lit(2)]));
1437        a.children.push(("rhs".into(), vec![lit(3)]));
1438        let diags = check_conformance(&a, &schema);
1439        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
1440    }
1441
1442    #[test]
1443    fn diagnostic_json_shape() {
1444        let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
1445        let v = diag.to_json();
1446        assert_eq!(v["severity"], "error");
1447        assert_eq!(v["code"], "x::y");
1448        assert_eq!(v["message"], "boom");
1449        assert_eq!(v["location"]["kind"], "span");
1450        assert_eq!(v["location"]["start"], 3);
1451        assert_eq!(v["location"]["end"], 7);
1452    }
1453
1454    #[test]
1455    fn build_error_display_lists_all() {
1456        let err = BuildError::new(vec![
1457            Diagnostic::error("a::b", "one"),
1458            Diagnostic::error("c::d", "two"),
1459        ]);
1460        let s = format!("{err}");
1461        assert!(s.contains("a::b: one"));
1462        assert!(s.contains("c::d: two"));
1463    }
1464}