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.
526    for f in &variant.fields {
527        if tree.field(&f.name).is_none() {
528            out.push(
529                Diagnostic::error(
530                    codes::MISSING_FIELD,
531                    format!(
532                        "variant `{}` is missing required field `{}` (type `{}`)",
533                        variant.name, f.name, f.ty
534                    ),
535                )
536                .with_span(tree.span),
537            );
538        }
539    }
540
541    // Precompute the "missing-so-far" set once: slot names that are
542    // declared but currently absent from `tree`. Used as the pair-hint
543    // marker on UNKNOWN_FIELD suggestions.
544    let missing = missing_slot_names(tree, variant);
545    let all_slots = all_slot_names(variant);
546
547    // Unknown fields.
548    for (name, _) in &tree.fields {
549        if variant.fields.iter().any(|f| &f.name == name) {
550            continue;
551        }
552        // If it names a declared child slot, that's a structural mix-up.
553        if variant.children.iter().any(|c| &c.name == name) {
554            out.push(
555                Diagnostic::error(
556                    codes::CHILD_AS_FIELD,
557                    format!(
558                        "`{}` on variant `{}` is a child slot, not a payload field \
559                         (move it under `children`)",
560                        name, variant.name
561                    ),
562                )
563                .with_span(tree.span),
564            );
565        } else {
566            let msg = format_unknown_slot(
567                "field",
568                name,
569                &variant.name,
570                &all_slots,
571                &missing,
572                suggester,
573            );
574            out.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg).with_span(tree.span));
575        }
576    }
577}
578
579fn check_children(
580    tree: &ParseTree,
581    variant: &VariantSchema,
582    out: &mut Vec<Diagnostic>,
583    suggester: &dyn Suggester,
584) {
585    // Duplicate child slot names.
586    for i in 0..tree.children.len() {
587        let (name, _) = &tree.children[i];
588        if tree.children[..i].iter().any(|(n, _)| n == name) {
589            out.push(
590                Diagnostic::error(
591                    codes::DUPLICATE_CHILD,
592                    format!(
593                        "child slot `{}` appears more than once on variant `{}`",
594                        name, variant.name
595                    ),
596                )
597                .with_span(tree.span),
598            );
599        }
600    }
601
602    // Declared children: arity check.
603    for c in &variant.children {
604        let count = tree
605            .child_slot(&c.name)
606            .map(<[ParseTree]>::len)
607            .unwrap_or(0);
608        match c.multiplicity {
609            Multiplicity::One => {
610                if count != 1 {
611                    out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
612                }
613            }
614            Multiplicity::Optional => {
615                if count > 1 {
616                    out.push(diag_arity(
617                        codes::ARITY_OPTIONAL,
618                        variant,
619                        c,
620                        count,
621                        tree.span,
622                    ));
623                }
624            }
625            Multiplicity::Many => {
626                // Zero is fine at the shape level.
627            }
628        }
629    }
630
631    // Same pair-hint precomputation as check_fields, sharing the
632    // "declared but currently absent" set across both diagnostics.
633    let missing = missing_slot_names(tree, variant);
634    let all_slots = all_slot_names(variant);
635
636    // Unknown child slots.
637    for (name, _) in &tree.children {
638        if variant.children.iter().any(|c| &c.name == name) {
639            continue;
640        }
641        if variant.fields.iter().any(|f| &f.name == name) {
642            out.push(
643                Diagnostic::error(
644                    codes::FIELD_AS_CHILD,
645                    format!(
646                        "`{}` on variant `{}` is a payload field, not a child slot \
647                         (move it under `fields`)",
648                        name, variant.name
649                    ),
650                )
651                .with_span(tree.span),
652            );
653        } else {
654            let msg = format_unknown_slot(
655                "child slot",
656                name,
657                &variant.name,
658                &all_slots,
659                &missing,
660                suggester,
661            );
662            out.push(Diagnostic::error(codes::UNKNOWN_CHILD, msg).with_span(tree.span));
663        }
664    }
665}
666
667/// Names of every declared payload field and child slot on
668/// `variant`, in that order. Used as the `all_candidates` slice for
669/// [`format_unknown_slot`].
670pub(crate) fn all_slot_names(variant: &VariantSchema) -> Vec<&str> {
671    variant
672        .fields
673        .iter()
674        .map(|f| f.name.as_str())
675        .chain(variant.children.iter().map(|c| c.name.as_str()))
676        .collect()
677}
678
679/// Names of declared slots that are **not** currently present on
680/// `tree`. Includes fields with no matching entry in `tree.fields`
681/// and children whose slot has zero occurrences on the tree. Feeds
682/// [`format_unknown_slot`]'s `(missing)` pair-hint marker.
683pub(crate) fn missing_slot_names<'a>(tree: &ParseTree, variant: &'a VariantSchema) -> Vec<&'a str> {
684    let mut out = Vec::new();
685    for f in &variant.fields {
686        if tree.field(&f.name).is_none() {
687            out.push(f.name.as_str());
688        }
689    }
690    for c in &variant.children {
691        let count = tree
692            .child_slot(&c.name)
693            .map(<[ParseTree]>::len)
694            .unwrap_or(0);
695        if count == 0 {
696            out.push(c.name.as_str());
697        }
698    }
699    out
700}
701
702fn diag_arity(
703    code: &'static str,
704    variant: &VariantSchema,
705    child: &ChildSchema,
706    count: usize,
707    span: Option<Span>,
708) -> Diagnostic {
709    let expected = match child.multiplicity {
710        Multiplicity::One => "exactly one child",
711        Multiplicity::Optional => "at most one child",
712        Multiplicity::Many => "zero or more children",
713    };
714    Diagnostic::error(
715        code,
716        format!(
717            "child slot `{}` on variant `{}` expects {} but got {}",
718            child.name, variant.name, expected, count
719        ),
720    )
721    .with_span(span)
722}
723
724// ---------------------------------------------------------------------------
725// Built-in Suggester (case-insensitive Levenshtein, cutoff = max(query.len, 1))
726// ---------------------------------------------------------------------------
727
728/// Default [`Suggester`] used by [`check_conformance`] and the serde
729/// bridge when no explicit suggester is supplied.
730///
731/// Backed by an ASCII-case-insensitive Levenshtein edit distance with
732/// cutoff `max(query.len(), 1)` — the same behaviour the crate has
733/// shipped since Round 1, kept internal so the parser does not need
734/// to depend on the plugin crate.
735pub(crate) struct BuiltinLevenshteinSuggester;
736
737impl Suggester for BuiltinLevenshteinSuggester {
738    fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
739        let cutoff = query.chars().count().max(1);
740        let mut scored: Vec<(usize, &'a str)> = candidates
741            .iter()
742            .map(|c| (levenshtein(query, c), *c))
743            .filter(|(d, _)| *d <= cutoff)
744            .collect();
745        scored.sort_by(|(da, na), (db, nb)| da.cmp(db).then_with(|| na.cmp(nb)));
746        scored.truncate(3);
747        scored
748            .into_iter()
749            .map(|(d, name)| Suggestion {
750                candidate: name,
751                score: normalise_edit(d, query, name),
752            })
753            .collect()
754    }
755}
756
757fn normalise_edit(distance: usize, a: &str, b: &str) -> f64 {
758    let max_len = a.chars().count().max(b.chars().count());
759    if max_len == 0 {
760        return 1.0;
761    }
762    1.0 - (distance as f64 / max_len as f64)
763}
764
765fn levenshtein(a: &str, b: &str) -> usize {
766    let a: Vec<char> = a.chars().collect();
767    let b: Vec<char> = b.chars().collect();
768    let (m, n) = (a.len(), b.len());
769    if m == 0 {
770        return n;
771    }
772    if n == 0 {
773        return m;
774    }
775    let mut prev: Vec<usize> = (0..=n).collect();
776    let mut curr: Vec<usize> = vec![0; n + 1];
777    for i in 1..=m {
778        curr[0] = i;
779        for j in 1..=n {
780            let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
781                0
782            } else {
783                1
784            };
785            curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
786        }
787        std::mem::swap(&mut prev, &mut curr);
788    }
789    prev[n]
790}
791
792// ---------------------------------------------------------------------------
793// Build helpers (used by #[derive(DslBuild)] code emission)
794// ---------------------------------------------------------------------------
795
796/// Extracts a payload field into `T`.
797///
798/// Dispatches on the field's [`RawValue`] arm:
799///
800/// - [`RawValue::Json`] → `serde_json::from_value::<T>`.
801/// - [`RawValue::Text`] → `T::from_str` (G-2: PEG front-end path).
802///
803/// This means the derive works with either front-end unchanged — the
804/// front-end picks the payload representation, the derive is agnostic.
805/// `T` must therefore satisfy both bounds; every primitive the kit
806/// currently uses (`String`, `i64`, `u32`, `bool`, `f64`) does.
807///
808/// This helper is intended for use by `#[derive(DslBuild)]`-generated
809/// code but is usable directly by hand-written [`DslBuild`] impls.
810pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
811where
812    T: serde::de::DeserializeOwned + std::str::FromStr,
813    <T as std::str::FromStr>::Err: std::fmt::Display,
814{
815    match tree.field(name) {
816        Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
817            BuildError::single(
818                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
819                    .with_span(tree.span),
820            )
821        }),
822        Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
823            BuildError::single(
824                Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
825                    .with_span(tree.span),
826            )
827        }),
828        None => Err(BuildError::single(
829            Diagnostic::error(
830                codes::MISSING_FIELD,
831                format!("missing required field `{name}`"),
832            )
833            .with_span(tree.span),
834        )),
835    }
836}
837
838/// Extracts a payload field's raw text production.
839///
840/// Convenience for `#[dsl_build(with = ...)]` converter functions,
841/// which typically match on the spelling the grammar (often a
842/// `schema_gen::SyntaxOverrides` value production) captured. Errors
843/// mirror [`build_field`]: [`codes::MISSING_FIELD`] when absent,
844/// [`codes::FIELD_TYPE`] when the field carries a
845/// [`RawValue::Json`] payload instead of text.
846pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
847    match tree.field(name) {
848        Some(RawValue::Text(s)) => Ok(s),
849        Some(RawValue::Json(_)) => Err(BuildError::single(
850            Diagnostic::error(
851                codes::FIELD_TYPE,
852                format!("field `{name}`: expected a text production, found JSON"),
853            )
854            .with_span(tree.span),
855        )),
856        None => Err(BuildError::single(
857            Diagnostic::error(
858                codes::MISSING_FIELD,
859                format!("missing required field `{name}`"),
860            )
861            .with_span(tree.span),
862        )),
863    }
864}
865
866/// Builds the single child of a [`Multiplicity::One`] slot.
867///
868/// Returns [`codes::ARITY_ONE`] if the slot is absent or holds more
869/// than one subtree. Errors from the recursive
870/// [`DslBuild::from_parse_tree`] call bubble up as-is.
871pub fn build_child_one<T: DslBuild>(
872    tree: &ParseTree,
873    name: &str,
874    ids: &IdGen,
875) -> Result<T, BuildError> {
876    let slot = tree.child_slot(name).unwrap_or(&[]);
877    if slot.len() != 1 {
878        return Err(BuildError::single(
879            Diagnostic::error(
880                codes::ARITY_ONE,
881                format!(
882                    "child slot `{name}` expects exactly one child but got {}",
883                    slot.len()
884                ),
885            )
886            .with_span(tree.span),
887        ));
888    }
889    T::from_parse_tree(&slot[0], ids)
890}
891
892/// Builds the (optional) child of a [`Multiplicity::Optional`] slot.
893///
894/// Returns [`codes::ARITY_OPTIONAL`] if the slot holds more than one
895/// subtree. Missing / empty slots yield `Ok(None)`.
896pub fn build_child_optional<T: DslBuild>(
897    tree: &ParseTree,
898    name: &str,
899    ids: &IdGen,
900) -> Result<Option<T>, BuildError> {
901    let slot = tree.child_slot(name).unwrap_or(&[]);
902    match slot.len() {
903        0 => Ok(None),
904        1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
905        n => Err(BuildError::single(
906            Diagnostic::error(
907                codes::ARITY_OPTIONAL,
908                format!("child slot `{name}` expects at most one child but got {n}"),
909            )
910            .with_span(tree.span),
911        )),
912    }
913}
914
915/// Builds every child of a [`Multiplicity::Many`] slot.
916///
917/// Diagnostics from individual children are collected across the whole
918/// slot before returning, so a partially-broken batch surfaces every
919/// bad subtree at once rather than the first-encountered one.
920pub fn build_child_many<T: DslBuild>(
921    tree: &ParseTree,
922    name: &str,
923    ids: &IdGen,
924) -> Result<Vec<T>, BuildError> {
925    let slot = tree.child_slot(name).unwrap_or(&[]);
926    let mut out = Vec::with_capacity(slot.len());
927    let mut diags = Vec::new();
928    for child in slot {
929        match T::from_parse_tree(child, ids) {
930            Ok(v) => out.push(v),
931            Err(mut e) => diags.append(&mut e.diagnostics),
932        }
933    }
934    if diags.is_empty() {
935        Ok(out)
936    } else {
937        Err(BuildError::new(diags))
938    }
939}
940
941// ---------------------------------------------------------------------------
942// Tests
943// ---------------------------------------------------------------------------
944
945#[cfg(test)]
946mod tests {
947    use super::*;
948    use dsl_kit_schema::{ChildSchema, FieldSchema, Multiplicity, NodeSchema, VariantSchema};
949
950    fn schema_add_lit() -> NodeSchema {
951        NodeSchema {
952            name: "Expr".into(),
953            variants: vec![
954                VariantSchema {
955                    name: "Lit".into(),
956                    fields: vec![FieldSchema {
957                        name: "value".into(),
958                        ty: "i64".into(),
959                    }],
960                    children: vec![],
961                },
962                VariantSchema {
963                    name: "Add".into(),
964                    fields: vec![],
965                    children: vec![
966                        ChildSchema {
967                            name: "lhs".into(),
968                            multiplicity: Multiplicity::One,
969                        },
970                        ChildSchema {
971                            name: "rhs".into(),
972                            multiplicity: Multiplicity::One,
973                        },
974                    ],
975                },
976                VariantSchema {
977                    name: "Let".into(),
978                    fields: vec![FieldSchema {
979                        name: "name".into(),
980                        ty: "String".into(),
981                    }],
982                    children: vec![
983                        ChildSchema {
984                            name: "value".into(),
985                            multiplicity: Multiplicity::One,
986                        },
987                        ChildSchema {
988                            name: "body".into(),
989                            multiplicity: Multiplicity::One,
990                        },
991                    ],
992                },
993            ],
994        }
995    }
996
997    fn lit(v: i64) -> ParseTree {
998        let mut t = ParseTree::new("Lit");
999        t.fields.push(("value".into(), RawValue::Json(json!(v))));
1000        t
1001    }
1002
1003    #[test]
1004    fn ok_lit() {
1005        let schema = schema_add_lit();
1006        assert!(check_conformance(&lit(1), &schema).is_empty());
1007    }
1008
1009    #[test]
1010    fn ok_add_with_two_children() {
1011        let schema = schema_add_lit();
1012        let mut add = ParseTree::new("Add");
1013        add.children.push(("lhs".into(), vec![lit(1)]));
1014        add.children.push(("rhs".into(), vec![lit(2)]));
1015        assert!(check_conformance(&add, &schema).is_empty());
1016    }
1017
1018    #[test]
1019    fn unknown_variant_lists_candidates() {
1020        let schema = schema_add_lit();
1021        let tree = ParseTree::new("Aad"); // typo of Add
1022        let diags = check_conformance(&tree, &schema);
1023        assert_eq!(diags.len(), 1);
1024        assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1025        assert!(
1026            diags[0].message.contains("Add"),
1027            "expected Add to appear as a candidate; got: {}",
1028            diags[0].message
1029        );
1030    }
1031
1032    #[test]
1033    fn unknown_variant_uses_injected_suggester() {
1034        use dsl_kit_fuzzy::FuzzySuggester;
1035
1036        let schema = schema_add_lit();
1037        let tree = ParseTree::new("Adx"); // Jaro-Winkler prefix bias picks "Add"
1038        let suggester = FuzzySuggester::default();
1039        let diags = check_conformance_with(&tree, &schema, &suggester);
1040        assert_eq!(diags.len(), 1);
1041        assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1042        assert!(
1043            diags[0].message.contains("did you mean") && diags[0].message.contains("Add"),
1044            "expected FuzzySuggester to surface `Add`; got: {}",
1045            diags[0].message
1046        );
1047    }
1048
1049    #[test]
1050    fn unknown_field_suggests_declared_field() {
1051        // The design's canonical example: `taget` should surface `target`
1052        // as a `did you mean` hint on the UNKNOWN_FIELD diagnostic.
1053        let schema = NodeSchema {
1054            name: "Cfg".into(),
1055            variants: vec![VariantSchema {
1056                name: "Load".into(),
1057                fields: vec![
1058                    FieldSchema {
1059                        name: "target".into(),
1060                        ty: "String".into(),
1061                    },
1062                    FieldSchema {
1063                        name: "count".into(),
1064                        ty: "u32".into(),
1065                    },
1066                ],
1067                children: vec![],
1068            }],
1069        };
1070        let mut tree = ParseTree::new("Load");
1071        tree.fields
1072            .push(("taget".into(), RawValue::Json(json!("a"))));
1073        tree.fields.push(("count".into(), RawValue::Json(json!(1))));
1074        let diags = check_conformance(&tree, &schema);
1075
1076        let unknown = diags
1077            .iter()
1078            .find(|d| d.code == codes::UNKNOWN_FIELD)
1079            .expect("expected an UNKNOWN_FIELD diagnostic for `taget`");
1080        assert!(
1081            unknown.message.contains("did you mean") && unknown.message.contains("target"),
1082            "expected `target` in the hint, got: {}",
1083            unknown.message
1084        );
1085        assert!(
1086            unknown.message.contains("(missing)"),
1087            "expected `(missing)` pair-hint since `target` is a required field \
1088             not present on the tree; got: {}",
1089            unknown.message
1090        );
1091    }
1092
1093    #[test]
1094    fn unknown_child_suggests_declared_child() {
1095        let schema = schema_add_lit();
1096        let mut add = ParseTree::new("Add");
1097        // `lsh` is a typo of `lhs`; `rhs` is present so only `lhs`
1098        // remains in the missing set.
1099        add.children.push(("lsh".into(), vec![lit(1)]));
1100        add.children.push(("rhs".into(), vec![lit(2)]));
1101        let diags = check_conformance(&add, &schema);
1102
1103        let unknown = diags
1104            .iter()
1105            .find(|d| d.code == codes::UNKNOWN_CHILD)
1106            .expect("expected an UNKNOWN_CHILD diagnostic for `lsh`");
1107        assert!(
1108            unknown.message.contains("did you mean") && unknown.message.contains("lhs"),
1109            "expected `lhs` in the hint, got: {}",
1110            unknown.message
1111        );
1112        assert!(
1113            unknown.message.contains("(missing)"),
1114            "expected `(missing)` pair-hint on the `lhs` suggestion since \
1115             the `lhs` slot is required but absent; got: {}",
1116            unknown.message
1117        );
1118    }
1119
1120    #[test]
1121    fn missing_field_is_reported() {
1122        let schema = schema_add_lit();
1123        let tree = ParseTree::new("Lit"); // no "value"
1124        let diags = check_conformance(&tree, &schema);
1125        assert_eq!(diags.len(), 1);
1126        assert_eq!(diags[0].code, codes::MISSING_FIELD);
1127        assert!(diags[0].message.contains("value"));
1128    }
1129
1130    #[test]
1131    fn unknown_field_is_reported() {
1132        let schema = schema_add_lit();
1133        let mut tree = lit(3);
1134        tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
1135        let diags = check_conformance(&tree, &schema);
1136        assert_eq!(diags.len(), 1);
1137        assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
1138    }
1139
1140    #[test]
1141    fn field_and_child_slot_swapped_reports_structural_codes() {
1142        let schema = schema_add_lit();
1143
1144        // A child slot placed under fields.
1145        let mut swap1 = ParseTree::new("Add");
1146        swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
1147        swap1.children.push(("rhs".into(), vec![lit(1)]));
1148        // Missing lhs child (arity_one) + child-as-field structural swap
1149        // → two diagnostics.
1150        let diags = check_conformance(&swap1, &schema);
1151        assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
1152        assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
1153
1154        // A payload field placed under children.
1155        let mut swap2 = ParseTree::new("Let");
1156        swap2
1157            .children
1158            .push(("name".into(), vec![ParseTree::new("Lit")]));
1159        swap2.children.push(("value".into(), vec![lit(1)]));
1160        swap2.children.push(("body".into(), vec![lit(2)]));
1161        let diags = check_conformance(&swap2, &schema);
1162        assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
1163        assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
1164    }
1165
1166    #[test]
1167    fn arity_one_reports_wrong_count() {
1168        let schema = schema_add_lit();
1169        let mut add = ParseTree::new("Add");
1170        add.children.push(("lhs".into(), vec![lit(1), lit(2)])); // two, not one
1171        add.children.push(("rhs".into(), vec![lit(3)]));
1172        let diags = check_conformance(&add, &schema);
1173        assert_eq!(diags.len(), 1);
1174        assert_eq!(diags[0].code, codes::ARITY_ONE);
1175        assert!(diags[0].message.contains("lhs"));
1176    }
1177
1178    #[test]
1179    fn duplicate_field_and_child_reported() {
1180        let schema = schema_add_lit();
1181        let mut t = ParseTree::new("Lit");
1182        t.fields.push(("value".into(), RawValue::Json(json!(1))));
1183        t.fields.push(("value".into(), RawValue::Json(json!(2))));
1184        let diags = check_conformance(&t, &schema);
1185        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
1186
1187        let mut a = ParseTree::new("Add");
1188        a.children.push(("lhs".into(), vec![lit(1)]));
1189        a.children.push(("lhs".into(), vec![lit(2)]));
1190        a.children.push(("rhs".into(), vec![lit(3)]));
1191        let diags = check_conformance(&a, &schema);
1192        assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
1193    }
1194
1195    #[test]
1196    fn diagnostic_json_shape() {
1197        let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
1198        let v = diag.to_json();
1199        assert_eq!(v["severity"], "error");
1200        assert_eq!(v["code"], "x::y");
1201        assert_eq!(v["message"], "boom");
1202        assert_eq!(v["location"]["kind"], "span");
1203        assert_eq!(v["location"]["start"], 3);
1204        assert_eq!(v["location"]["end"], 7);
1205    }
1206
1207    #[test]
1208    fn build_error_display_lists_all() {
1209        let err = BuildError::new(vec![
1210            Diagnostic::error("a::b", "one"),
1211            Diagnostic::error("c::d", "two"),
1212        ]);
1213        let s = format!("{err}");
1214        assert!(s.contains("a::b: one"));
1215        assert!(s.contains("c::d: two"));
1216    }
1217}