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