dsl-kit-parse 0.7.0

Parser trunk for dsl-kit DSLs (ParseTree, schema conformance, serde bridge, DslBuild consumer).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
//! Serde-JSON → [`ParseTree`] bridge.
//!
//! Front-end #1 of the two mentioned in the crate root: takes a
//! [`serde_json::Value`] shaped by the **internally-tagged `"type"`**
//! convention and produces the untyped [`ParseTree`] trunk. The other
//! front-end — a PEG interpreter — lands in G-2.
//!
//! ## Convention
//!
//! An AST node is an object with a `"type"` key naming its variant.
//! The remaining keys are dispatched against the target's
//! [`NodeSchema`]:
//!
//! - keys that name a declared
//!   [`FieldSchema`](dsl_kit_schema::FieldSchema) land in
//!   [`ParseTree::fields`] wrapped as [`RawValue::Json`] — no
//!   stringify round-trip;
//! - keys that name a declared
//!   [`ChildSchema`](dsl_kit_schema::ChildSchema) land in
//!   [`ParseTree::children`], recursively parsed as nested
//!   [`ParseTree`]s. Their value shape depends on the child's
//!   [`Multiplicity`]:
//!   - `One` → a single object (the child);
//!   - `Optional` → `null` or a single object;
//!   - `Many` → an array of objects (possibly empty);
//!   - `Map` → an object mapping keys to child objects (possibly
//!     empty), landing in [`ParseTree::keyed_children`] sorted by key.
//! - keys that name neither yield an [`codes::UNKNOWN_FIELD`]
//!   diagnostic (or, when the key is a declared child slot placed as a
//!   field / vice versa, the appropriate structural code).
//!
//! Structural errors during dispatch are collected before returning so
//! that a malformed document produces one bag of diagnostics rather
//! than a chain of stop-at-first failures.
//!
//! One object shape is reserved: `{"$import": "name"}` at a node
//! position produces an import placeholder for the load phase
//! ([`crate::import`]) instead of a variant node. `$import` must be
//! the object's only key and its value a literal string; anything else
//! is a [`crate::import::import_codes::SPEC_SHAPE`] diagnostic.
//!
//! ## Example
//!
//! ```ignore
//! use dsl_kit_parse::serde_bridge::from_json_value;
//! use dsl_kit_schema::DslSchema;
//!
//! let value = serde_json::json!({
//!     "type": "Add",
//!     "lhs": { "type": "Lit", "value": 1 },
//!     "rhs": { "type": "Lit", "value": 2 },
//! });
//! let tree = from_json_value(&value, &Expr::schema()).unwrap();
//! assert_eq!(tree.variant, "Add");
//! ```

use crate::import::{self, import_codes};
use crate::{BuildError, BuiltinLevenshteinSuggester, Diagnostic, ParseTree, RawValue, codes};
use dsl_kit_core::Suggester;
use dsl_kit_schema::{ChildValueShape, Multiplicity, NodeSchema, VariantSchema};
use serde_json::Value;

/// Additional diagnostic codes emitted specifically by the serde
/// bridge (structural JSON-shape errors distinct from schema
/// conformance).
///
/// Reuses [`codes::UNKNOWN_VARIANT`] / [`codes::UNKNOWN_FIELD`] /
/// [`codes::FIELD_AS_CHILD`] / [`codes::CHILD_AS_FIELD`] where the
/// meaning is identical to conformance.
pub mod serde_codes {
    /// The document (or a nested child) was not a JSON object.
    pub const NOT_OBJECT: &str = "dsl_kit::parse::serde::not_object";
    /// The object lacks a `"type"` key.
    pub const TYPE_MISSING: &str = "dsl_kit::parse::serde::type_missing";
    /// The `"type"` key exists but is not a string.
    pub const TYPE_NOT_STRING: &str = "dsl_kit::parse::serde::type_not_string";
    /// A child slot's value shape did not match its
    /// [`Multiplicity`](dsl_kit_schema::Multiplicity) contract.
    pub const CHILD_SHAPE: &str = "dsl_kit::parse::serde::child_shape";
}

/// Parses a JSON string into a [`ParseTree`], using `schema` to
/// dispatch keys.
///
/// Convenience wrapper around [`from_json_value`] that surfaces
/// `serde_json::from_str` failures as a
/// [`serde_codes::NOT_OBJECT`]-tagged diagnostic (JSON syntax errors
/// have no `Span` mapping here — the parser's own position isn't
/// exposed by `serde_json` in a stable way).
pub fn from_json_str(input: &str, schema: &NodeSchema) -> Result<ParseTree, BuildError> {
    from_json_str_with(input, schema, &BuiltinLevenshteinSuggester)
}

/// Variant of [`from_json_str`] that routes `did you mean X?` hints
/// through a caller-supplied [`Suggester`]. See
/// [`from_json_value_with`] for the same wiring on
/// [`serde_json::Value`] inputs.
pub fn from_json_str_with(
    input: &str,
    schema: &NodeSchema,
    suggester: &dyn Suggester,
) -> Result<ParseTree, BuildError> {
    let value: Value = serde_json::from_str(input).map_err(|e| {
        BuildError::single(Diagnostic::error(
            serde_codes::NOT_OBJECT,
            format!("invalid JSON: {e}"),
        ))
    })?;
    from_json_value_with(&value, schema, suggester)
}

/// Parses a [`serde_json::Value`] into a [`ParseTree`] using `schema`
/// to dispatch each key into a payload field or a child slot.
///
/// Recurses on every child value using the same `schema` (the current
/// derive's recursion is same-type; heterogenous cross-type recursion
/// would need a resolver hook — not needed for G-1).
///
/// All diagnostics found during the walk are collected before
/// returning; a malformed document yields one [`BuildError`] with
/// every problem, not the first-encountered one.
pub fn from_json_value(value: &Value, schema: &NodeSchema) -> Result<ParseTree, BuildError> {
    from_json_value_with(value, schema, &BuiltinLevenshteinSuggester)
}

/// Variant of [`from_json_value`] that routes `did you mean X?` hints
/// through a caller-supplied [`Suggester`].
///
/// The free function [`from_json_value`] delegates here with the same
/// crate-private Levenshtein backend used by
/// [`crate::check_conformance`]. Reach for this variant to plug in a
/// different similarity algorithm (e.g. `dsl-kit-fuzzy`'s
/// `FuzzySuggester`) without touching the parse trunk contract.
pub fn from_json_value_with(
    value: &Value,
    schema: &NodeSchema,
    suggester: &dyn Suggester,
) -> Result<ParseTree, BuildError> {
    let mut diags = Vec::new();
    let tree = build_tree(value, schema, &mut diags, suggester);
    if diags.is_empty() {
        Ok(tree.unwrap_or_else(|| ParseTree::new("")))
    } else {
        Err(BuildError::new(diags))
    }
}

/// Core recursive builder. Returns `Some(tree)` when a well-shaped
/// object was found; `None` when the input was so malformed that no
/// meaningful trunk could be produced (still records diagnostics).
fn build_tree(
    value: &Value,
    schema: &NodeSchema,
    diags: &mut Vec<Diagnostic>,
    suggester: &dyn Suggester,
) -> Option<ParseTree> {
    let obj = match value {
        Value::Object(map) => map,
        _ => {
            diags.push(Diagnostic::error(
                serde_codes::NOT_OBJECT,
                format!(
                    "expected a JSON object with a `type` tag, got {}",
                    kind(value)
                ),
            ));
            return None;
        }
    };

    // `{"$import": "spec"}` at a node position becomes an import
    // placeholder for the load phase (`crate::import`). Checked before
    // the `type` dispatch so a placeholder needs no `type` key.
    if let Some(spec) = obj.get(import::IMPORT_VARIANT) {
        if obj.len() != 1 {
            diags.push(Diagnostic::error(
                import_codes::SPEC_SHAPE,
                format!(
                    "`{}` must be the object's only key ({} other key(s) present)",
                    import::IMPORT_VARIANT,
                    obj.len() - 1
                ),
            ));
            return None;
        }
        return match spec {
            Value::String(_) => {
                let mut tree = ParseTree::new(import::IMPORT_VARIANT);
                tree.fields.push((
                    import::IMPORT_SPEC_FIELD.to_string(),
                    RawValue::Json(spec.clone()),
                ));
                Some(tree)
            }
            other => {
                diags.push(Diagnostic::error(
                    import_codes::SPEC_SHAPE,
                    format!(
                        "`{}` value must be a literal string, got {}",
                        import::IMPORT_VARIANT,
                        kind(other)
                    ),
                ));
                None
            }
        };
    }

    let variant_name = match obj.get("type") {
        None => {
            diags.push(Diagnostic::error(
                serde_codes::TYPE_MISSING,
                "object is missing the `type` tag (expected a variant name)".to_string(),
            ));
            return None;
        }
        Some(Value::String(s)) => s.clone(),
        Some(other) => {
            diags.push(Diagnostic::error(
                serde_codes::TYPE_NOT_STRING,
                format!("`type` tag must be a string, got {}", kind(other)),
            ));
            return None;
        }
    };

    let variant = match schema.variant(&variant_name) {
        Some(v) => v,
        None => {
            let msg = crate::format_unknown_variant(&variant_name, schema, suggester);
            diags.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg));
            return None;
        }
    };

    let mut tree = ParseTree::new(variant_name);

    for (key, val) in obj {
        if key == "type" {
            continue;
        }
        if let Some(_field) = variant.fields.iter().find(|f| &f.name == key) {
            tree.fields.push((key.clone(), RawValue::Json(val.clone())));
        } else if let Some(child) = variant.children.iter().find(|c| &c.name == key) {
            if child.multiplicity == Multiplicity::Map {
                let entries = match &child.value_shape {
                    ChildValueShape::Scalar { .. } => {
                        build_scalar_keyed_slot(val, variant, key, diags)
                    }
                    ChildValueShape::Recursive => {
                        build_keyed_child_slot(val, variant, key, schema, diags, suggester)
                    }
                    // `#[non_exhaustive]` catch-all: a future
                    // `ChildValueShape` variant added to the schema
                    // crate before this bridge is extended lands
                    // here. Falls back to the recursive path
                    // (`build_keyed_child_slot`) so the front-end
                    // stays usable, but records the shape as
                    // unknown so the drift is visible in
                    // diagnostics rather than silent misroute.
                    _ => {
                        diags.push(Diagnostic::error(
                            codes::UNKNOWN_MULTIPLICITY,
                            format!(
                                "keyed child slot `{}` on variant `{}` declares a \
                                 ChildValueShape variant this build does not recognise \
                                 (upgrade dsl-kit-parse to a version that knows about it)",
                                key, variant.name
                            ),
                        ));
                        build_keyed_child_slot(val, variant, key, schema, diags, suggester)
                    }
                };
                tree.keyed_children.push((key.clone(), entries));
            } else {
                let subtrees = build_child_slot(
                    child.multiplicity,
                    val,
                    variant,
                    key,
                    schema,
                    diags,
                    suggester,
                );
                tree.children.push((key.clone(), subtrees));
            }
        } else {
            // Not a declared field, not a declared child — either a
            // shape mix-up (using a field name inside "children" via
            // this bridge isn't a thing, since we dispatch by name;
            // but a client may have typoed a variant slot). We only
            // have UNKNOWN_FIELD to describe "top-level key unknown"
            // in this dialect; that reads correctly here.
            let all_slots = crate::all_slot_names(variant);
            let hint = suggester.enrich_unknown(key, &all_slots);
            let msg = match hint {
                Some(h) => format!(
                    "unknown key `{}` on variant `{}` (not a declared field or child slot; {})",
                    key, variant.name, h
                ),
                None => format!(
                    "unknown key `{}` on variant `{}` (not a declared field or child slot)",
                    key, variant.name
                ),
            };
            diags.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg));
        }
    }

    Some(tree)
}

fn build_child_slot(
    m: Multiplicity,
    val: &Value,
    variant: &VariantSchema,
    slot: &str,
    schema: &NodeSchema,
    diags: &mut Vec<Diagnostic>,
    suggester: &dyn Suggester,
) -> Vec<ParseTree> {
    match m {
        Multiplicity::One => match val {
            Value::Object(_) => build_tree(val, schema, diags, suggester)
                .into_iter()
                .collect(),
            _ => {
                diags.push(Diagnostic::error(
                    serde_codes::CHILD_SHAPE,
                    format!(
                        "child slot `{}` on variant `{}` requires exactly one object, got {}",
                        slot,
                        variant.name,
                        kind(val)
                    ),
                ));
                Vec::new()
            }
        },
        Multiplicity::Optional => match val {
            Value::Null => Vec::new(),
            Value::Object(_) => build_tree(val, schema, diags, suggester)
                .into_iter()
                .collect(),
            _ => {
                diags.push(Diagnostic::error(
                    serde_codes::CHILD_SHAPE,
                    format!(
                        "child slot `{}` on variant `{}` requires null or an object, got {}",
                        slot,
                        variant.name,
                        kind(val)
                    ),
                ));
                Vec::new()
            }
        },
        Multiplicity::Many => match val {
            Value::Array(items) => items
                .iter()
                .filter_map(|item| build_tree(item, schema, diags, suggester))
                .collect(),
            _ => {
                diags.push(Diagnostic::error(
                    serde_codes::CHILD_SHAPE,
                    format!(
                        "child slot `{}` on variant `{}` requires an array of objects, got {}",
                        slot,
                        variant.name,
                        kind(val)
                    ),
                ));
                Vec::new()
            }
        },
        Multiplicity::Map => {
            // Keyed slots are routed to `build_keyed_child_slot` by
            // `build_tree` before reaching here, because their result
            // shape (`(key, tree)` pairs) does not fit this function's
            // return type. Arriving in this arm means that dispatch
            // lost sync with the schema — surface it rather than
            // silently dropping every entry.
            diags.push(Diagnostic::error(
                serde_codes::CHILD_SHAPE,
                format!(
                    "child slot `{}` on variant `{}` declares Multiplicity::Map but was \
                     routed through the positional builder",
                    slot, variant.name
                ),
            ));
            Vec::new()
        }
        // `#[non_exhaustive]` catch-all — see the sibling arm in
        // `check_children` (crate::lib.rs) for the versioning
        // rationale. Reuses the crate-level slug because the failure
        // mode ("this build of parse doesn't know about that
        // Multiplicity variant") is the same across all pipeline
        // stages.
        _ => {
            diags.push(Diagnostic::error(
                codes::UNKNOWN_MULTIPLICITY,
                format!(
                    "child slot `{}` on variant `{}` uses an unrecognised \
                     Multiplicity variant (upgrade dsl-kit-parse to a version \
                     that knows about it)",
                    slot, variant.name
                ),
            ));
            Vec::new()
        }
    }
}

/// Builds a keyed child slot ([`Multiplicity::Map`]) from a JSON
/// object mapping keys to child node objects.
///
/// The pairs are sorted by key before returning so that
/// [`ParseTree::keyed_children`] carries one canonical order
/// regardless of how the JSON was written, and regardless of whether
/// `serde_json` was built with the `preserve_order` feature (which
/// swaps its object map from a sorted `BTreeMap` to an
/// insertion-ordered one). Sorting here is what keeps the bridge on
/// the right side of the ordering contract
/// [`check_conformance`](crate::check_conformance) enforces
/// ([`crate::codes::KEYED_SLOT_UNSORTED`]) — a JSON document can
/// never trip it.
///
/// Duplicate keys cannot survive `serde_json`'s own object parsing
/// (the later one wins before the bridge ever sees the document), so
/// [`crate::codes::DUPLICATE_KEY`] is raised by hand-built trees and
/// by future non-JSON front-ends, not here.
fn build_keyed_child_slot(
    val: &Value,
    variant: &VariantSchema,
    slot: &str,
    schema: &NodeSchema,
    diags: &mut Vec<Diagnostic>,
    suggester: &dyn Suggester,
) -> Vec<(String, ParseTree)> {
    let Value::Object(map) = val else {
        diags.push(Diagnostic::error(
            serde_codes::CHILD_SHAPE,
            format!(
                "keyed child slot `{}` on variant `{}` requires an object mapping keys \
                 to child objects, got {}",
                slot,
                variant.name,
                kind(val)
            ),
        ));
        return Vec::new();
    };

    let mut out = Vec::with_capacity(map.len());
    for (key, item) in map {
        match item {
            Value::Object(_) => {
                if let Some(child) = build_tree(item, schema, diags, suggester) {
                    out.push((key.clone(), child));
                }
            }
            _ => diags.push(Diagnostic::error(
                serde_codes::CHILD_SHAPE,
                format!(
                    "keyed child slot `{}` on variant `{}`: entry `{}` requires an object, got {}",
                    slot,
                    variant.name,
                    key,
                    kind(item)
                ),
            )),
        }
    }
    out.sort_by(|(a, _), (b, _)| a.cmp(b));
    out
}

/// Builds a keyed child slot ([`Multiplicity::Map`]) whose values are
/// scalars (Shape 1 of the tracking issue). Each entry is wrapped as
/// a leaf [`ParseTree`] carrying its payload under the well-known
/// `"value"` field, so [`build_scalar_map`](crate::build_scalar_map)
/// can read it back with the same `build_field` route the rest of the
/// derive already uses.
///
/// JSON scalars land as [`RawValue::Json`] wholesale — `serde_json`
/// distinguishes strings, numbers, booleans, and null on its own, and
/// the build layer's [`build_field`](crate::build_field) delegates to
/// `serde_json::from_value` for that arm. That means a `String` /
/// `i64` / `bool` scalar type all deserialize without a stringify
/// round-trip. Nested arrays or objects on the value side are handed
/// straight through so a scalar map declared as
/// `BTreeMap<String, Vec<String>>` (still a scalar shape at the
/// schema level — the value is a payload type, not another AST) also
/// deserializes cleanly.
///
/// Sorted by key on emit, matching `build_keyed_child_slot` so both
/// arms feed [`ParseTree::keyed_children`] on the same canonical
/// ordering contract enforced by
/// [`check_conformance`](crate::check_conformance).
fn build_scalar_keyed_slot(
    val: &Value,
    variant: &VariantSchema,
    slot: &str,
    diags: &mut Vec<Diagnostic>,
) -> Vec<(String, ParseTree)> {
    let Value::Object(map) = val else {
        diags.push(Diagnostic::error(
            serde_codes::CHILD_SHAPE,
            format!(
                "scalar keyed child slot `{}` on variant `{}` requires an object mapping keys \
                 to scalar values, got {}",
                slot,
                variant.name,
                kind(val)
            ),
        ));
        return Vec::new();
    };

    let mut out = Vec::with_capacity(map.len());
    for (key, item) in map {
        let mut leaf = ParseTree::new("");
        leaf.fields
            .push(("value".into(), RawValue::Json(item.clone())));
        out.push((key.clone(), leaf));
    }
    out.sort_by(|(a, _), (b, _)| a.cmp(b));
    out
}

fn kind(v: &Value) -> &'static str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{check_conformance, codes};
    use dsl_kit_schema::{
        ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, VariantSchema,
    };
    use serde_json::json;

    fn schema() -> NodeSchema {
        NodeSchema {
            name: "Expr".into(),
            variants: vec![
                VariantSchema {
                    name: "Lit".into(),
                    fields: vec![FieldSchema {
                        name: "value".into(),
                        ty: "i64".into(),
                        optional: false,
                    }],
                    children: vec![],
                },
                VariantSchema {
                    name: "Add".into(),
                    fields: vec![],
                    children: vec![
                        ChildSchema {
                            name: "lhs".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                        },
                        ChildSchema {
                            name: "rhs".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                        },
                    ],
                },
                VariantSchema {
                    name: "Let".into(),
                    fields: vec![FieldSchema {
                        name: "name".into(),
                        ty: "String".into(),
                        optional: false,
                    }],
                    children: vec![
                        ChildSchema {
                            name: "value".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                        },
                        ChildSchema {
                            name: "body".into(),
                            multiplicity: Multiplicity::One,
                            value_shape: ChildValueShape::Recursive,
                        },
                    ],
                },
                VariantSchema {
                    name: "Group".into(),
                    fields: vec![],
                    children: vec![ChildSchema {
                        name: "items".into(),
                        multiplicity: Multiplicity::Many,
                        value_shape: ChildValueShape::Recursive,
                    }],
                },
                VariantSchema {
                    name: "Wrap".into(),
                    fields: vec![],
                    children: vec![ChildSchema {
                        name: "inner".into(),
                        multiplicity: Multiplicity::Optional,
                        value_shape: ChildValueShape::Recursive,
                    }],
                },
            ],
        }
    }

    #[test]
    fn simple_lit() {
        let tree = from_json_value(&json!({ "type": "Lit", "value": 7 }), &schema()).unwrap();
        assert_eq!(tree.variant, "Lit");
        assert_eq!(tree.fields.len(), 1);
        assert_eq!(tree.children.len(), 0);
        assert!(matches!(
            tree.field("value").unwrap(),
            RawValue::Json(v) if v.as_i64() == Some(7)
        ));
        assert!(check_conformance(&tree, &schema()).is_empty());
    }

    #[test]
    fn nested_add() {
        let value = json!({
            "type": "Add",
            "lhs": { "type": "Lit", "value": 1 },
            "rhs": { "type": "Lit", "value": 2 },
        });
        let tree = from_json_value(&value, &schema()).unwrap();
        assert_eq!(tree.variant, "Add");
        assert_eq!(tree.child_slot("lhs").unwrap().len(), 1);
        assert_eq!(tree.child_slot("rhs").unwrap().len(), 1);
        assert!(check_conformance(&tree, &schema()).is_empty());
    }

    #[test]
    fn many_slot_from_array() {
        let value = json!({
            "type": "Group",
            "items": [
                { "type": "Lit", "value": 1 },
                { "type": "Lit", "value": 2 },
                { "type": "Lit", "value": 3 },
            ],
        });
        let tree = from_json_value(&value, &schema()).unwrap();
        assert_eq!(tree.child_slot("items").unwrap().len(), 3);
    }

    #[test]
    fn optional_slot_from_null_is_empty() {
        let tree = from_json_value(&json!({ "type": "Wrap", "inner": null }), &schema()).unwrap();
        assert_eq!(tree.child_slot("inner").unwrap().len(), 0);
    }

    #[test]
    fn optional_slot_from_object_is_one() {
        let tree = from_json_value(
            &json!({ "type": "Wrap", "inner": { "type": "Lit", "value": 9 } }),
            &schema(),
        )
        .unwrap();
        assert_eq!(tree.child_slot("inner").unwrap().len(), 1);
    }

    #[test]
    fn unknown_variant_lists_candidates() {
        let err = from_json_value(&json!({ "type": "Ad" }), &schema()).unwrap_err();
        assert_eq!(err.diagnostics.len(), 1);
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_VARIANT);
        assert!(err.diagnostics[0].message.contains("Add"));
    }

    #[test]
    fn unknown_key_suggests_declared_slot() {
        // The serde-bridge front-end mirrors the check_conformance
        // pair-hint: a typo of a declared field name gets `did you
        // mean` on its UNKNOWN_FIELD diagnostic.
        let value = json!({ "type": "Lit", "vlue": 1 });
        let err = from_json_value(&value, &schema()).unwrap_err();
        let d = err
            .diagnostics
            .iter()
            .find(|d| d.code == codes::UNKNOWN_FIELD)
            .expect("expected UNKNOWN_FIELD");
        assert!(
            d.message.contains("did you mean") && d.message.contains("value"),
            "expected `value` in the hint, got: {}",
            d.message
        );
    }

    #[test]
    fn missing_type_tag_reports() {
        let err = from_json_value(&json!({ "value": 1 }), &schema()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, serde_codes::TYPE_MISSING);
    }

    #[test]
    fn type_not_string_reports() {
        let err = from_json_value(&json!({ "type": 42 }), &schema()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, serde_codes::TYPE_NOT_STRING);
    }

    #[test]
    fn non_object_at_root_reports() {
        let err = from_json_value(&json!(42), &schema()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, serde_codes::NOT_OBJECT);
    }

    #[test]
    fn many_slot_from_object_fails_shape() {
        let value = json!({
            "type": "Group",
            "items": { "type": "Lit", "value": 1 },
        });
        let err = from_json_value(&value, &schema()).unwrap_err();
        assert!(
            err.diagnostics
                .iter()
                .any(|d| d.code == serde_codes::CHILD_SHAPE)
        );
    }

    #[test]
    fn one_slot_missing_reports_via_conformance() {
        // Bridge accepts the doc; conformance catches the missing rhs.
        let value = json!({
            "type": "Add",
            "lhs": { "type": "Lit", "value": 1 },
        });
        let tree = from_json_value(&value, &schema()).unwrap();
        let diags = check_conformance(&tree, &schema());
        assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
    }

    #[test]
    fn unknown_key_reports() {
        let value = json!({ "type": "Lit", "value": 1, "extra": 2 });
        let err = from_json_value(&value, &schema()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, codes::UNKNOWN_FIELD);
    }

    #[test]
    fn multiple_errors_collected() {
        // Two Adds, each missing rhs entirely — bridge accepts, but
        // give an unknown key too so bridge sees it. Nested collection
        // proves diagnostics from recursion bubble up.
        let value = json!({
            "type": "Add",
            "lhs": { "type": "Lit", "value": 1, "bogus": 0 },
            "rhs": { "type": "Nope" },
        });
        let err = from_json_value(&value, &schema()).unwrap_err();
        // Expect: one UNKNOWN_FIELD (bogus) + one UNKNOWN_VARIANT (Nope).
        assert!(
            err.diagnostics
                .iter()
                .any(|d| d.code == codes::UNKNOWN_FIELD)
        );
        assert!(
            err.diagnostics
                .iter()
                .any(|d| d.code == codes::UNKNOWN_VARIANT)
        );
    }

    #[test]
    fn from_json_str_wraps_syntax_errors() {
        let err = from_json_str("{ not: valid }", &schema()).unwrap_err();
        assert_eq!(err.diagnostics[0].code, serde_codes::NOT_OBJECT);
    }
}