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};
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    let mut out = Vec::new();
420
421    let Some(variant) = schema.variant(&tree.variant) else {
422        let candidates = nearest_candidates(&tree.variant, &schema.variants, 3);
423        let msg = if candidates.is_empty() {
424            format!("unknown variant `{}` for `{}`", tree.variant, schema.name)
425        } else {
426            format!(
427                "unknown variant `{}` for `{}` (did you mean: {})",
428                tree.variant,
429                schema.name,
430                candidates.join(", ")
431            )
432        };
433        out.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg).with_span(tree.span));
434        return out;
435    };
436
437    check_fields(tree, variant, &mut out);
438    check_children(tree, variant, &mut out);
439    out
440}
441
442fn check_fields(tree: &ParseTree, variant: &VariantSchema, out: &mut Vec<Diagnostic>) {
443    // Duplicate field names.
444    for i in 0..tree.fields.len() {
445        let (name, _) = &tree.fields[i];
446        if tree.fields[..i].iter().any(|(n, _)| n == name) {
447            out.push(
448                Diagnostic::error(
449                    codes::DUPLICATE_FIELD,
450                    format!(
451                        "field `{}` appears more than once on variant `{}`",
452                        name, variant.name
453                    ),
454                )
455                .with_span(tree.span),
456            );
457        }
458    }
459
460    // Missing declared fields.
461    for f in &variant.fields {
462        if tree.field(&f.name).is_none() {
463            out.push(
464                Diagnostic::error(
465                    codes::MISSING_FIELD,
466                    format!(
467                        "variant `{}` is missing required field `{}` (type `{}`)",
468                        variant.name, f.name, f.ty
469                    ),
470                )
471                .with_span(tree.span),
472            );
473        }
474    }
475
476    // Unknown fields.
477    for (name, _) in &tree.fields {
478        if variant.fields.iter().any(|f| &f.name == name) {
479            continue;
480        }
481        // If it names a declared child slot, that's a structural mix-up.
482        if variant.children.iter().any(|c| &c.name == name) {
483            out.push(
484                Diagnostic::error(
485                    codes::CHILD_AS_FIELD,
486                    format!(
487                        "`{}` on variant `{}` is a child slot, not a payload field \
488                         (move it under `children`)",
489                        name, variant.name
490                    ),
491                )
492                .with_span(tree.span),
493            );
494        } else {
495            out.push(
496                Diagnostic::error(
497                    codes::UNKNOWN_FIELD,
498                    format!("unknown field `{}` on variant `{}`", name, variant.name),
499                )
500                .with_span(tree.span),
501            );
502        }
503    }
504}
505
506fn check_children(tree: &ParseTree, variant: &VariantSchema, out: &mut Vec<Diagnostic>) {
507    // Duplicate child slot names.
508    for i in 0..tree.children.len() {
509        let (name, _) = &tree.children[i];
510        if tree.children[..i].iter().any(|(n, _)| n == name) {
511            out.push(
512                Diagnostic::error(
513                    codes::DUPLICATE_CHILD,
514                    format!(
515                        "child slot `{}` appears more than once on variant `{}`",
516                        name, variant.name
517                    ),
518                )
519                .with_span(tree.span),
520            );
521        }
522    }
523
524    // Declared children: arity check.
525    for c in &variant.children {
526        let count = tree
527            .child_slot(&c.name)
528            .map(<[ParseTree]>::len)
529            .unwrap_or(0);
530        match c.multiplicity {
531            Multiplicity::One => {
532                if count != 1 {
533                    out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
534                }
535            }
536            Multiplicity::Optional => {
537                if count > 1 {
538                    out.push(diag_arity(
539                        codes::ARITY_OPTIONAL,
540                        variant,
541                        c,
542                        count,
543                        tree.span,
544                    ));
545                }
546            }
547            Multiplicity::Many => {
548                // Zero is fine at the shape level.
549            }
550        }
551    }
552
553    // Unknown child slots.
554    for (name, _) in &tree.children {
555        if variant.children.iter().any(|c| &c.name == name) {
556            continue;
557        }
558        if variant.fields.iter().any(|f| &f.name == name) {
559            out.push(
560                Diagnostic::error(
561                    codes::FIELD_AS_CHILD,
562                    format!(
563                        "`{}` on variant `{}` is a payload field, not a child slot \
564                         (move it under `fields`)",
565                        name, variant.name
566                    ),
567                )
568                .with_span(tree.span),
569            );
570        } else {
571            out.push(
572                Diagnostic::error(
573                    codes::UNKNOWN_CHILD,
574                    format!(
575                        "unknown child slot `{}` on variant `{}`",
576                        name, variant.name
577                    ),
578                )
579                .with_span(tree.span),
580            );
581        }
582    }
583}
584
585fn diag_arity(
586    code: &'static str,
587    variant: &VariantSchema,
588    child: &ChildSchema,
589    count: usize,
590    span: Option<Span>,
591) -> Diagnostic {
592    let expected = match child.multiplicity {
593        Multiplicity::One => "exactly one child",
594        Multiplicity::Optional => "at most one child",
595        Multiplicity::Many => "zero or more children",
596    };
597    Diagnostic::error(
598        code,
599        format!(
600            "child slot `{}` on variant `{}` expects {} but got {}",
601            child.name, variant.name, expected, count
602        ),
603    )
604    .with_span(span)
605}
606
607// ---------------------------------------------------------------------------
608// Nearest-candidate suggestions (small Levenshtein)
609// ---------------------------------------------------------------------------
610
611pub(crate) fn nearest_candidates(query: &str, variants: &[VariantSchema], k: usize) -> Vec<String> {
612    let mut scored: Vec<(usize, &str)> = variants
613        .iter()
614        .map(|v| (levenshtein(query, &v.name), v.name.as_str()))
615        .collect();
616    scored.sort_by_key(|(d, name)| (*d, name.to_string()));
617    let cutoff = query.len().max(1);
618    scored
619        .into_iter()
620        .filter(|(d, _)| *d <= cutoff)
621        .take(k)
622        .map(|(_, n)| n.to_string())
623        .collect()
624}
625
626fn levenshtein(a: &str, b: &str) -> usize {
627    let a: Vec<char> = a.chars().collect();
628    let b: Vec<char> = b.chars().collect();
629    let (m, n) = (a.len(), b.len());
630    if m == 0 {
631        return n;
632    }
633    if n == 0 {
634        return m;
635    }
636    let mut prev: Vec<usize> = (0..=n).collect();
637    let mut curr: Vec<usize> = vec![0; n + 1];
638    for i in 1..=m {
639        curr[0] = i;
640        for j in 1..=n {
641            let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
642                0
643            } else {
644                1
645            };
646            curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
647        }
648        std::mem::swap(&mut prev, &mut curr);
649    }
650    prev[n]
651}
652
653// ---------------------------------------------------------------------------
654// Build helpers (used by #[derive(DslBuild)] code emission)
655// ---------------------------------------------------------------------------
656
657/// Extracts a payload field into `T`.
658///
659/// Dispatches on the field's [`RawValue`] arm:
660///
661/// - [`RawValue::Json`] → `serde_json::from_value::<T>`.
662/// - [`RawValue::Text`] → `T::from_str` (G-2: PEG front-end path).
663///
664/// This means the derive works with either front-end unchanged — the
665/// front-end picks the payload representation, the derive is agnostic.
666/// `T` must therefore satisfy both bounds; every primitive the kit
667/// currently uses (`String`, `i64`, `u32`, `bool`, `f64`) does.
668///
669/// This helper is intended for use by `#[derive(DslBuild)]`-generated
670/// code but is usable directly by hand-written [`DslBuild`] impls.
671pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
672where
673    T: serde::de::DeserializeOwned + std::str::FromStr,
674    <T as std::str::FromStr>::Err: std::fmt::Display,
675{
676    match tree.field(name) {
677        Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
678            BuildError::single(
679                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
680                    .with_span(tree.span),
681            )
682        }),
683        Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
684            BuildError::single(
685                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
686                    .with_span(tree.span),
687            )
688        }),
689        None => Err(BuildError::single(
690            Diagnostic::error(
691                codes::MISSING_FIELD,
692                format!("missing required field `{name}`"),
693            )
694            .with_span(tree.span),
695        )),
696    }
697}
698
699/// Extracts a payload field's raw text production.
700///
701/// Convenience for `#[dsl_build(with = ...)]` converter functions,
702/// which typically match on the spelling the grammar (often a
703/// `schema_gen::SyntaxOverrides` value production) captured. Errors
704/// mirror [`build_field`]: [`codes::MISSING_FIELD`] when absent,
705/// [`codes::FIELD_TYPE`] when the field carries a
706/// [`RawValue::Json`] payload instead of text.
707pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
708    match tree.field(name) {
709        Some(RawValue::Text(s)) => Ok(s),
710        Some(RawValue::Json(_)) => Err(BuildError::single(
711            Diagnostic::error(
712                codes::FIELD_TYPE,
713                format!("field `{name}`: expected a text production, found JSON"),
714            )
715            .with_span(tree.span),
716        )),
717        None => Err(BuildError::single(
718            Diagnostic::error(
719                codes::MISSING_FIELD,
720                format!("missing required field `{name}`"),
721            )
722            .with_span(tree.span),
723        )),
724    }
725}
726
727/// Builds the single child of a [`Multiplicity::One`] slot.
728///
729/// Returns [`codes::ARITY_ONE`] if the slot is absent or holds more
730/// than one subtree. Errors from the recursive
731/// [`DslBuild::from_parse_tree`] call bubble up as-is.
732pub fn build_child_one<T: DslBuild>(
733    tree: &ParseTree,
734    name: &str,
735    ids: &IdGen,
736) -> Result<T, BuildError> {
737    let slot = tree.child_slot(name).unwrap_or(&[]);
738    if slot.len() != 1 {
739        return Err(BuildError::single(
740            Diagnostic::error(
741                codes::ARITY_ONE,
742                format!(
743                    "child slot `{name}` expects exactly one child but got {}",
744                    slot.len()
745                ),
746            )
747            .with_span(tree.span),
748        ));
749    }
750    T::from_parse_tree(&slot[0], ids)
751}
752
753/// Builds the (optional) child of a [`Multiplicity::Optional`] slot.
754///
755/// Returns [`codes::ARITY_OPTIONAL`] if the slot holds more than one
756/// subtree. Missing / empty slots yield `Ok(None)`.
757pub fn build_child_optional<T: DslBuild>(
758    tree: &ParseTree,
759    name: &str,
760    ids: &IdGen,
761) -> Result<Option<T>, BuildError> {
762    let slot = tree.child_slot(name).unwrap_or(&[]);
763    match slot.len() {
764        0 => Ok(None),
765        1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
766        n => Err(BuildError::single(
767            Diagnostic::error(
768                codes::ARITY_OPTIONAL,
769                format!("child slot `{name}` expects at most one child but got {n}"),
770            )
771            .with_span(tree.span),
772        )),
773    }
774}
775
776/// Builds every child of a [`Multiplicity::Many`] slot.
777///
778/// Diagnostics from individual children are collected across the whole
779/// slot before returning, so a partially-broken batch surfaces every
780/// bad subtree at once rather than the first-encountered one.
781pub fn build_child_many<T: DslBuild>(
782    tree: &ParseTree,
783    name: &str,
784    ids: &IdGen,
785) -> Result<Vec<T>, BuildError> {
786    let slot = tree.child_slot(name).unwrap_or(&[]);
787    let mut out = Vec::with_capacity(slot.len());
788    let mut diags = Vec::new();
789    for child in slot {
790        match T::from_parse_tree(child, ids) {
791            Ok(v) => out.push(v),
792            Err(mut e) => diags.append(&mut e.diagnostics),
793        }
794    }
795    if diags.is_empty() {
796        Ok(out)
797    } else {
798        Err(BuildError::new(diags))
799    }
800}
801
802// ---------------------------------------------------------------------------
803// Tests
804// ---------------------------------------------------------------------------
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809    use dsl_kit_schema::{ChildSchema, FieldSchema, Multiplicity, NodeSchema, VariantSchema};
810
811    fn schema_add_lit() -> NodeSchema {
812        NodeSchema {
813            name: "Expr".into(),
814            variants: vec![
815                VariantSchema {
816                    name: "Lit".into(),
817                    fields: vec![FieldSchema {
818                        name: "value".into(),
819                        ty: "i64".into(),
820                    }],
821                    children: vec![],
822                },
823                VariantSchema {
824                    name: "Add".into(),
825                    fields: vec![],
826                    children: vec![
827                        ChildSchema {
828                            name: "lhs".into(),
829                            multiplicity: Multiplicity::One,
830                        },
831                        ChildSchema {
832                            name: "rhs".into(),
833                            multiplicity: Multiplicity::One,
834                        },
835                    ],
836                },
837                VariantSchema {
838                    name: "Let".into(),
839                    fields: vec![FieldSchema {
840                        name: "name".into(),
841                        ty: "String".into(),
842                    }],
843                    children: vec![
844                        ChildSchema {
845                            name: "value".into(),
846                            multiplicity: Multiplicity::One,
847                        },
848                        ChildSchema {
849                            name: "body".into(),
850                            multiplicity: Multiplicity::One,
851                        },
852                    ],
853                },
854            ],
855        }
856    }
857
858    fn lit(v: i64) -> ParseTree {
859        let mut t = ParseTree::new("Lit");
860        t.fields.push(("value".into(), RawValue::Json(json!(v))));
861        t
862    }
863
864    #[test]
865    fn ok_lit() {
866        let schema = schema_add_lit();
867        assert!(check_conformance(&lit(1), &schema).is_empty());
868    }
869
870    #[test]
871    fn ok_add_with_two_children() {
872        let schema = schema_add_lit();
873        let mut add = ParseTree::new("Add");
874        add.children.push(("lhs".into(), vec![lit(1)]));
875        add.children.push(("rhs".into(), vec![lit(2)]));
876        assert!(check_conformance(&add, &schema).is_empty());
877    }
878
879    #[test]
880    fn unknown_variant_lists_candidates() {
881        let schema = schema_add_lit();
882        let tree = ParseTree::new("Aad"); // typo of Add
883        let diags = check_conformance(&tree, &schema);
884        assert_eq!(diags.len(), 1);
885        assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
886        assert!(
887            diags[0].message.contains("Add"),
888            "expected Add to appear as a candidate; got: {}",
889            diags[0].message
890        );
891    }
892
893    #[test]
894    fn missing_field_is_reported() {
895        let schema = schema_add_lit();
896        let tree = ParseTree::new("Lit"); // no "value"
897        let diags = check_conformance(&tree, &schema);
898        assert_eq!(diags.len(), 1);
899        assert_eq!(diags[0].code, codes::MISSING_FIELD);
900        assert!(diags[0].message.contains("value"));
901    }
902
903    #[test]
904    fn unknown_field_is_reported() {
905        let schema = schema_add_lit();
906        let mut tree = lit(3);
907        tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
908        let diags = check_conformance(&tree, &schema);
909        assert_eq!(diags.len(), 1);
910        assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
911    }
912
913    #[test]
914    fn field_and_child_slot_swapped_reports_structural_codes() {
915        let schema = schema_add_lit();
916
917        // A child slot placed under fields.
918        let mut swap1 = ParseTree::new("Add");
919        swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
920        swap1.children.push(("rhs".into(), vec![lit(1)]));
921        // Missing lhs child (arity_one) + child-as-field structural swap
922        // → two diagnostics.
923        let diags = check_conformance(&swap1, &schema);
924        assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
925        assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
926
927        // A payload field placed under children.
928        let mut swap2 = ParseTree::new("Let");
929        swap2
930            .children
931            .push(("name".into(), vec![ParseTree::new("Lit")]));
932        swap2.children.push(("value".into(), vec![lit(1)]));
933        swap2.children.push(("body".into(), vec![lit(2)]));
934        let diags = check_conformance(&swap2, &schema);
935        assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
936        assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
937    }
938
939    #[test]
940    fn arity_one_reports_wrong_count() {
941        let schema = schema_add_lit();
942        let mut add = ParseTree::new("Add");
943        add.children.push(("lhs".into(), vec![lit(1), lit(2)])); // two, not one
944        add.children.push(("rhs".into(), vec![lit(3)]));
945        let diags = check_conformance(&add, &schema);
946        assert_eq!(diags.len(), 1);
947        assert_eq!(diags[0].code, codes::ARITY_ONE);
948        assert!(diags[0].message.contains("lhs"));
949    }
950
951    #[test]
952    fn duplicate_field_and_child_reported() {
953        let schema = schema_add_lit();
954        let mut t = ParseTree::new("Lit");
955        t.fields.push(("value".into(), RawValue::Json(json!(1))));
956        t.fields.push(("value".into(), RawValue::Json(json!(2))));
957        let diags = check_conformance(&t, &schema);
958        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
959
960        let mut a = ParseTree::new("Add");
961        a.children.push(("lhs".into(), vec![lit(1)]));
962        a.children.push(("lhs".into(), vec![lit(2)]));
963        a.children.push(("rhs".into(), vec![lit(3)]));
964        let diags = check_conformance(&a, &schema);
965        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
966    }
967
968    #[test]
969    fn diagnostic_json_shape() {
970        let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
971        let v = diag.to_json();
972        assert_eq!(v["severity"], "error");
973        assert_eq!(v["code"], "x::y");
974        assert_eq!(v["message"], "boom");
975        assert_eq!(v["location"]["kind"], "span");
976        assert_eq!(v["location"]["start"], 3);
977        assert_eq!(v["location"]["end"], 7);
978    }
979
980    #[test]
981    fn build_error_display_lists_all() {
982        let err = BuildError::new(vec![
983            Diagnostic::error("a::b", "one"),
984            Diagnostic::error("c::d", "two"),
985        ]);
986        let s = format!("{err}");
987        assert!(s.contains("a::b: one"));
988        assert!(s.contains("c::d: two"));
989    }
990}