1#![warn(missing_docs)]
30
31use dsl_kit_core::{IdGen, NodeId, Suggester, Suggestion};
32use dsl_kit_schema::{ChildSchema, Multiplicity, NodeSchema, VariantSchema};
33use serde_json::{Value, json};
34use std::fmt;
35
36pub mod example_gen;
37pub mod grammar_check;
38pub mod peg;
39pub mod schema_gen;
40pub mod serde_bridge;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Span {
53 pub start: usize,
55 pub end: usize,
57}
58
59impl Span {
60 pub const fn new(start: usize, end: usize) -> Self {
62 Self { start, end }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq)]
80pub enum RawValue {
81 Text(String),
83 Json(Value),
85}
86
87#[derive(Debug, Clone, PartialEq)]
99pub struct ParseTree {
100 pub variant: String,
103 pub fields: Vec<(String, RawValue)>,
105 pub children: Vec<(String, Vec<ParseTree>)>,
109 pub span: Option<Span>,
111}
112
113impl ParseTree {
114 pub fn new(variant: impl Into<String>) -> Self {
116 Self {
117 variant: variant.into(),
118 fields: Vec::new(),
119 children: Vec::new(),
120 span: None,
121 }
122 }
123
124 pub fn field(&self, name: &str) -> Option<&RawValue> {
126 self.fields.iter().find(|(n, _)| n == name).map(|(_, v)| v)
127 }
128
129 pub fn child_slot(&self, name: &str) -> Option<&[ParseTree]> {
131 self.children
132 .iter()
133 .find(|(n, _)| n == name)
134 .map(|(_, v)| v.as_slice())
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Severity {
148 Error,
150 Warning,
152 Info,
154}
155
156impl Severity {
157 pub const fn as_str(self) -> &'static str {
159 match self {
160 Severity::Error => "error",
161 Severity::Warning => "warning",
162 Severity::Info => "info",
163 }
164 }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum Location {
176 Span(Span),
178 Node(NodeId),
180 None,
182}
183
184impl Location {
185 pub fn to_json(&self) -> Value {
192 match self {
193 Location::Span(Span { start, end }) => {
194 json!({ "kind": "span", "start": start, "end": end })
195 }
196 Location::Node(id) => json!({ "kind": "node", "id": id.0 }),
197 Location::None => Value::Null,
198 }
199 }
200}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct Diagnostic {
212 pub severity: Severity,
214 pub code: String,
216 pub message: String,
218 pub location: Location,
220}
221
222impl Diagnostic {
223 pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
225 Self {
226 severity: Severity::Error,
227 code: code.into(),
228 message: message.into(),
229 location: Location::None,
230 }
231 }
232
233 pub fn with_span(mut self, span: Option<Span>) -> Self {
235 if let Some(span) = span {
236 self.location = Location::Span(span);
237 }
238 self
239 }
240
241 pub fn with_node(mut self, id: NodeId) -> Self {
243 self.location = Location::Node(id);
244 self
245 }
246
247 pub fn to_json(&self) -> Value {
259 json!({
260 "severity": self.severity.as_str(),
261 "code": self.code,
262 "message": self.message,
263 "location": self.location.to_json(),
264 })
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct BuildError {
279 pub diagnostics: Vec<Diagnostic>,
282}
283
284impl BuildError {
285 pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
292 assert!(
293 !diagnostics.is_empty(),
294 "BuildError requires at least one diagnostic"
295 );
296 Self { diagnostics }
297 }
298
299 pub fn single(diag: Diagnostic) -> Self {
301 Self {
302 diagnostics: vec![diag],
303 }
304 }
305
306 pub fn to_json(&self) -> Value {
309 Value::Array(self.diagnostics.iter().map(Diagnostic::to_json).collect())
310 }
311}
312
313impl fmt::Display for BuildError {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(
316 f,
317 "build failed with {} diagnostic(s):",
318 self.diagnostics.len()
319 )?;
320 for d in &self.diagnostics {
321 write!(f, "\n [{}] {}: {}", d.severity.as_str(), d.code, d.message)?;
322 }
323 Ok(())
324 }
325}
326
327impl std::error::Error for BuildError {}
328
329pub trait DslBuild: Sized {
340 fn from_parse_tree(tree: &ParseTree, ids: &IdGen) -> Result<Self, BuildError>;
350}
351
352pub mod codes {
362 pub const UNKNOWN_VARIANT: &str = "dsl_kit::parse::unknown_variant";
366 pub const MISSING_FIELD: &str = "dsl_kit::parse::missing_field";
368 pub const UNKNOWN_FIELD: &str = "dsl_kit::parse::unknown_field";
370 pub const UNKNOWN_CHILD: &str = "dsl_kit::parse::unknown_child";
372 pub const ARITY_ONE: &str = "dsl_kit::parse::arity_one";
375 pub const ARITY_OPTIONAL: &str = "dsl_kit::parse::arity_optional";
378 pub const FIELD_AS_CHILD: &str = "dsl_kit::parse::field_as_child";
380 pub const CHILD_AS_FIELD: &str = "dsl_kit::parse::child_as_field";
382 pub const DUPLICATE_FIELD: &str = "dsl_kit::parse::duplicate_field";
384 pub const DUPLICATE_CHILD: &str = "dsl_kit::parse::duplicate_child";
386 pub const FIELD_TYPE: &str = "dsl_kit::parse::field_type";
389}
390
391pub fn check_conformance(tree: &ParseTree, schema: &NodeSchema) -> Vec<Diagnostic> {
419 check_conformance_with(tree, schema, &BuiltinLevenshteinSuggester)
420}
421
422pub fn check_conformance_with(
432 tree: &ParseTree,
433 schema: &NodeSchema,
434 suggester: &dyn Suggester,
435) -> Vec<Diagnostic> {
436 let mut out = Vec::new();
437
438 let Some(variant) = schema.variant(&tree.variant) else {
439 let msg = format_unknown_variant(&tree.variant, schema, suggester);
440 out.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg).with_span(tree.span));
441 return out;
442 };
443
444 check_fields(tree, variant, &mut out, suggester);
445 check_children(tree, variant, &mut out, suggester);
446 out
447}
448
449pub(crate) fn format_unknown_variant(
453 query: &str,
454 schema: &NodeSchema,
455 suggester: &dyn Suggester,
456) -> String {
457 let names: Vec<&str> = schema.variants.iter().map(|v| v.name.as_str()).collect();
458 let base = format!("unknown variant `{}` for `{}`", query, schema.name);
459 match suggester.enrich_unknown(query, &names) {
460 Some(hint) => format!("{base} ({hint})"),
461 None => base,
462 }
463}
464
465pub(crate) fn format_unknown_slot(
475 kind: &str,
476 query: &str,
477 variant_name: &str,
478 all_candidates: &[&str],
479 missing_candidates: &[&str],
480 suggester: &dyn Suggester,
481) -> String {
482 let base = format!("unknown {kind} `{query}` on variant `{variant_name}`");
483 let sugs = suggester.suggest(query, all_candidates);
484 if sugs.is_empty() {
485 return base;
486 }
487 let joined = sugs
488 .iter()
489 .take(3)
490 .map(|s| {
491 if missing_candidates.contains(&s.candidate) {
492 format!("`{}` (missing)", s.candidate)
493 } else {
494 format!("`{}`", s.candidate)
495 }
496 })
497 .collect::<Vec<_>>()
498 .join(", ");
499 format!("{base} (did you mean: {joined})")
500}
501
502fn check_fields(
503 tree: &ParseTree,
504 variant: &VariantSchema,
505 out: &mut Vec<Diagnostic>,
506 suggester: &dyn Suggester,
507) {
508 for i in 0..tree.fields.len() {
510 let (name, _) = &tree.fields[i];
511 if tree.fields[..i].iter().any(|(n, _)| n == name) {
512 out.push(
513 Diagnostic::error(
514 codes::DUPLICATE_FIELD,
515 format!(
516 "field `{}` appears more than once on variant `{}`",
517 name, variant.name
518 ),
519 )
520 .with_span(tree.span),
521 );
522 }
523 }
524
525 for f in &variant.fields {
531 if f.optional {
532 continue;
533 }
534 if tree.field(&f.name).is_none() {
535 out.push(
536 Diagnostic::error(
537 codes::MISSING_FIELD,
538 format!(
539 "variant `{}` is missing required field `{}` (type `{}`)",
540 variant.name, f.name, f.ty
541 ),
542 )
543 .with_span(tree.span),
544 );
545 }
546 }
547
548 let missing = missing_slot_names(tree, variant);
552 let all_slots = all_slot_names(variant);
553
554 for (name, _) in &tree.fields {
556 if variant.fields.iter().any(|f| &f.name == name) {
557 continue;
558 }
559 if variant.children.iter().any(|c| &c.name == name) {
561 out.push(
562 Diagnostic::error(
563 codes::CHILD_AS_FIELD,
564 format!(
565 "`{}` on variant `{}` is a child slot, not a payload field \
566 (move it under `children`)",
567 name, variant.name
568 ),
569 )
570 .with_span(tree.span),
571 );
572 } else {
573 let msg = format_unknown_slot(
574 "field",
575 name,
576 &variant.name,
577 &all_slots,
578 &missing,
579 suggester,
580 );
581 out.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg).with_span(tree.span));
582 }
583 }
584}
585
586fn check_children(
587 tree: &ParseTree,
588 variant: &VariantSchema,
589 out: &mut Vec<Diagnostic>,
590 suggester: &dyn Suggester,
591) {
592 for i in 0..tree.children.len() {
594 let (name, _) = &tree.children[i];
595 if tree.children[..i].iter().any(|(n, _)| n == name) {
596 out.push(
597 Diagnostic::error(
598 codes::DUPLICATE_CHILD,
599 format!(
600 "child slot `{}` appears more than once on variant `{}`",
601 name, variant.name
602 ),
603 )
604 .with_span(tree.span),
605 );
606 }
607 }
608
609 for c in &variant.children {
611 let count = tree
612 .child_slot(&c.name)
613 .map(<[ParseTree]>::len)
614 .unwrap_or(0);
615 match c.multiplicity {
616 Multiplicity::One => {
617 if count != 1 {
618 out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
619 }
620 }
621 Multiplicity::Optional => {
622 if count > 1 {
623 out.push(diag_arity(
624 codes::ARITY_OPTIONAL,
625 variant,
626 c,
627 count,
628 tree.span,
629 ));
630 }
631 }
632 Multiplicity::Many => {
633 }
635 }
636 }
637
638 let missing = missing_slot_names(tree, variant);
641 let all_slots = all_slot_names(variant);
642
643 for (name, _) in &tree.children {
645 if variant.children.iter().any(|c| &c.name == name) {
646 continue;
647 }
648 if variant.fields.iter().any(|f| &f.name == name) {
649 out.push(
650 Diagnostic::error(
651 codes::FIELD_AS_CHILD,
652 format!(
653 "`{}` on variant `{}` is a payload field, not a child slot \
654 (move it under `fields`)",
655 name, variant.name
656 ),
657 )
658 .with_span(tree.span),
659 );
660 } else {
661 let msg = format_unknown_slot(
662 "child slot",
663 name,
664 &variant.name,
665 &all_slots,
666 &missing,
667 suggester,
668 );
669 out.push(Diagnostic::error(codes::UNKNOWN_CHILD, msg).with_span(tree.span));
670 }
671 }
672}
673
674pub(crate) fn all_slot_names(variant: &VariantSchema) -> Vec<&str> {
678 variant
679 .fields
680 .iter()
681 .map(|f| f.name.as_str())
682 .chain(variant.children.iter().map(|c| c.name.as_str()))
683 .collect()
684}
685
686pub(crate) fn missing_slot_names<'a>(tree: &ParseTree, variant: &'a VariantSchema) -> Vec<&'a str> {
691 let mut out = Vec::new();
692 for f in &variant.fields {
693 if f.optional {
697 continue;
698 }
699 if tree.field(&f.name).is_none() {
700 out.push(f.name.as_str());
701 }
702 }
703 for c in &variant.children {
704 let count = tree
705 .child_slot(&c.name)
706 .map(<[ParseTree]>::len)
707 .unwrap_or(0);
708 if count == 0 {
709 out.push(c.name.as_str());
710 }
711 }
712 out
713}
714
715fn diag_arity(
716 code: &'static str,
717 variant: &VariantSchema,
718 child: &ChildSchema,
719 count: usize,
720 span: Option<Span>,
721) -> Diagnostic {
722 let expected = match child.multiplicity {
723 Multiplicity::One => "exactly one child",
724 Multiplicity::Optional => "at most one child",
725 Multiplicity::Many => "zero or more children",
726 };
727 Diagnostic::error(
728 code,
729 format!(
730 "child slot `{}` on variant `{}` expects {} but got {}",
731 child.name, variant.name, expected, count
732 ),
733 )
734 .with_span(span)
735}
736
737pub(crate) struct BuiltinLevenshteinSuggester;
749
750impl Suggester for BuiltinLevenshteinSuggester {
751 fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
752 let cutoff = query.chars().count().max(1);
753 let mut scored: Vec<(usize, &'a str)> = candidates
754 .iter()
755 .map(|c| (levenshtein(query, c), *c))
756 .filter(|(d, _)| *d <= cutoff)
757 .collect();
758 scored.sort_by(|(da, na), (db, nb)| da.cmp(db).then_with(|| na.cmp(nb)));
759 scored.truncate(3);
760 scored
761 .into_iter()
762 .map(|(d, name)| Suggestion {
763 candidate: name,
764 score: normalise_edit(d, query, name),
765 })
766 .collect()
767 }
768}
769
770fn normalise_edit(distance: usize, a: &str, b: &str) -> f64 {
771 let max_len = a.chars().count().max(b.chars().count());
772 if max_len == 0 {
773 return 1.0;
774 }
775 1.0 - (distance as f64 / max_len as f64)
776}
777
778fn levenshtein(a: &str, b: &str) -> usize {
779 let a: Vec<char> = a.chars().collect();
780 let b: Vec<char> = b.chars().collect();
781 let (m, n) = (a.len(), b.len());
782 if m == 0 {
783 return n;
784 }
785 if n == 0 {
786 return m;
787 }
788 let mut prev: Vec<usize> = (0..=n).collect();
789 let mut curr: Vec<usize> = vec![0; n + 1];
790 for i in 1..=m {
791 curr[0] = i;
792 for j in 1..=n {
793 let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
794 0
795 } else {
796 1
797 };
798 curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
799 }
800 std::mem::swap(&mut prev, &mut curr);
801 }
802 prev[n]
803}
804
805pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
824where
825 T: serde::de::DeserializeOwned + std::str::FromStr,
826 <T as std::str::FromStr>::Err: std::fmt::Display,
827{
828 match tree.field(name) {
829 Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
830 BuildError::single(
831 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
832 .with_span(tree.span),
833 )
834 }),
835 Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
836 BuildError::single(
837 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
838 .with_span(tree.span),
839 )
840 }),
841 None => Err(BuildError::single(
842 Diagnostic::error(
843 codes::MISSING_FIELD,
844 format!("missing required field `{name}`"),
845 )
846 .with_span(tree.span),
847 )),
848 }
849}
850
851pub fn build_field_optional<T>(tree: &ParseTree, name: &str) -> Result<Option<T>, BuildError>
870where
871 T: serde::de::DeserializeOwned + std::str::FromStr,
872 <T as std::str::FromStr>::Err: std::fmt::Display,
873{
874 match tree.field(name) {
875 None => Ok(None),
876 Some(RawValue::Json(Value::Null)) => Ok(None),
877 Some(RawValue::Text(s)) if s == "none" => Ok(None),
878 Some(_) => build_field::<T>(tree, name).map(Some),
879 }
880}
881
882pub fn build_field_vec<T>(tree: &ParseTree, name: &str) -> Result<Vec<T>, BuildError>
906where
907 T: serde::de::DeserializeOwned,
908{
909 match tree.field(name) {
910 None => Ok(Vec::new()),
911 Some(RawValue::Json(Value::Null)) => Ok(Vec::new()),
912 Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
913 BuildError::single(
914 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
915 .with_span(tree.span),
916 )
917 }),
918 Some(RawValue::Text(s)) => {
919 let trimmed = s.trim();
920 if trimmed.is_empty() {
921 return Ok(Vec::new());
922 }
923 serde_json::from_str(trimmed).map_err(|e| {
924 BuildError::single(
925 Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
926 .with_span(tree.span),
927 )
928 })
929 }
930 }
931}
932
933pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
942 match tree.field(name) {
943 Some(RawValue::Text(s)) => Ok(s),
944 Some(RawValue::Json(_)) => Err(BuildError::single(
945 Diagnostic::error(
946 codes::FIELD_TYPE,
947 format!("field `{name}`: expected a text production, found JSON"),
948 )
949 .with_span(tree.span),
950 )),
951 None => Err(BuildError::single(
952 Diagnostic::error(
953 codes::MISSING_FIELD,
954 format!("missing required field `{name}`"),
955 )
956 .with_span(tree.span),
957 )),
958 }
959}
960
961pub fn build_child_one<T: DslBuild>(
967 tree: &ParseTree,
968 name: &str,
969 ids: &IdGen,
970) -> Result<T, BuildError> {
971 let slot = tree.child_slot(name).unwrap_or(&[]);
972 if slot.len() != 1 {
973 return Err(BuildError::single(
974 Diagnostic::error(
975 codes::ARITY_ONE,
976 format!(
977 "child slot `{name}` expects exactly one child but got {}",
978 slot.len()
979 ),
980 )
981 .with_span(tree.span),
982 ));
983 }
984 T::from_parse_tree(&slot[0], ids)
985}
986
987pub fn build_child_optional<T: DslBuild>(
992 tree: &ParseTree,
993 name: &str,
994 ids: &IdGen,
995) -> Result<Option<T>, BuildError> {
996 let slot = tree.child_slot(name).unwrap_or(&[]);
997 match slot.len() {
998 0 => Ok(None),
999 1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
1000 n => Err(BuildError::single(
1001 Diagnostic::error(
1002 codes::ARITY_OPTIONAL,
1003 format!("child slot `{name}` expects at most one child but got {n}"),
1004 )
1005 .with_span(tree.span),
1006 )),
1007 }
1008}
1009
1010pub fn build_child_many<T: DslBuild>(
1016 tree: &ParseTree,
1017 name: &str,
1018 ids: &IdGen,
1019) -> Result<Vec<T>, BuildError> {
1020 let slot = tree.child_slot(name).unwrap_or(&[]);
1021 let mut out = Vec::with_capacity(slot.len());
1022 let mut diags = Vec::new();
1023 for child in slot {
1024 match T::from_parse_tree(child, ids) {
1025 Ok(v) => out.push(v),
1026 Err(mut e) => diags.append(&mut e.diagnostics),
1027 }
1028 }
1029 if diags.is_empty() {
1030 Ok(out)
1031 } else {
1032 Err(BuildError::new(diags))
1033 }
1034}
1035
1036#[cfg(test)]
1041mod tests {
1042 use super::*;
1043 use dsl_kit_schema::{ChildSchema, FieldSchema, Multiplicity, NodeSchema, VariantSchema};
1044
1045 fn schema_add_lit() -> NodeSchema {
1046 NodeSchema {
1047 name: "Expr".into(),
1048 variants: vec![
1049 VariantSchema {
1050 name: "Lit".into(),
1051 fields: vec![FieldSchema {
1052 name: "value".into(),
1053 ty: "i64".into(),
1054 optional: false,
1055 }],
1056 children: vec![],
1057 },
1058 VariantSchema {
1059 name: "Add".into(),
1060 fields: vec![],
1061 children: vec![
1062 ChildSchema {
1063 name: "lhs".into(),
1064 multiplicity: Multiplicity::One,
1065 },
1066 ChildSchema {
1067 name: "rhs".into(),
1068 multiplicity: Multiplicity::One,
1069 },
1070 ],
1071 },
1072 VariantSchema {
1073 name: "Let".into(),
1074 fields: vec![FieldSchema {
1075 name: "name".into(),
1076 ty: "String".into(),
1077 optional: false,
1078 }],
1079 children: vec![
1080 ChildSchema {
1081 name: "value".into(),
1082 multiplicity: Multiplicity::One,
1083 },
1084 ChildSchema {
1085 name: "body".into(),
1086 multiplicity: Multiplicity::One,
1087 },
1088 ],
1089 },
1090 ],
1091 }
1092 }
1093
1094 fn lit(v: i64) -> ParseTree {
1095 let mut t = ParseTree::new("Lit");
1096 t.fields.push(("value".into(), RawValue::Json(json!(v))));
1097 t
1098 }
1099
1100 #[test]
1101 fn ok_lit() {
1102 let schema = schema_add_lit();
1103 assert!(check_conformance(&lit(1), &schema).is_empty());
1104 }
1105
1106 #[test]
1107 fn ok_add_with_two_children() {
1108 let schema = schema_add_lit();
1109 let mut add = ParseTree::new("Add");
1110 add.children.push(("lhs".into(), vec![lit(1)]));
1111 add.children.push(("rhs".into(), vec![lit(2)]));
1112 assert!(check_conformance(&add, &schema).is_empty());
1113 }
1114
1115 #[test]
1116 fn unknown_variant_lists_candidates() {
1117 let schema = schema_add_lit();
1118 let tree = ParseTree::new("Aad"); let diags = check_conformance(&tree, &schema);
1120 assert_eq!(diags.len(), 1);
1121 assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1122 assert!(
1123 diags[0].message.contains("Add"),
1124 "expected Add to appear as a candidate; got: {}",
1125 diags[0].message
1126 );
1127 }
1128
1129 #[test]
1130 fn unknown_variant_uses_injected_suggester() {
1131 use dsl_kit_fuzzy::FuzzySuggester;
1132
1133 let schema = schema_add_lit();
1134 let tree = ParseTree::new("Adx"); let suggester = FuzzySuggester::default();
1136 let diags = check_conformance_with(&tree, &schema, &suggester);
1137 assert_eq!(diags.len(), 1);
1138 assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
1139 assert!(
1140 diags[0].message.contains("did you mean") && diags[0].message.contains("Add"),
1141 "expected FuzzySuggester to surface `Add`; got: {}",
1142 diags[0].message
1143 );
1144 }
1145
1146 #[test]
1147 fn unknown_field_suggests_declared_field() {
1148 let schema = NodeSchema {
1151 name: "Cfg".into(),
1152 variants: vec![VariantSchema {
1153 name: "Load".into(),
1154 fields: vec![
1155 FieldSchema {
1156 name: "target".into(),
1157 ty: "String".into(),
1158 optional: false,
1159 },
1160 FieldSchema {
1161 name: "count".into(),
1162 ty: "u32".into(),
1163 optional: false,
1164 },
1165 ],
1166 children: vec![],
1167 }],
1168 };
1169 let mut tree = ParseTree::new("Load");
1170 tree.fields
1171 .push(("taget".into(), RawValue::Json(json!("a"))));
1172 tree.fields.push(("count".into(), RawValue::Json(json!(1))));
1173 let diags = check_conformance(&tree, &schema);
1174
1175 let unknown = diags
1176 .iter()
1177 .find(|d| d.code == codes::UNKNOWN_FIELD)
1178 .expect("expected an UNKNOWN_FIELD diagnostic for `taget`");
1179 assert!(
1180 unknown.message.contains("did you mean") && unknown.message.contains("target"),
1181 "expected `target` in the hint, got: {}",
1182 unknown.message
1183 );
1184 assert!(
1185 unknown.message.contains("(missing)"),
1186 "expected `(missing)` pair-hint since `target` is a required field \
1187 not present on the tree; got: {}",
1188 unknown.message
1189 );
1190 }
1191
1192 #[test]
1193 fn unknown_child_suggests_declared_child() {
1194 let schema = schema_add_lit();
1195 let mut add = ParseTree::new("Add");
1196 add.children.push(("lsh".into(), vec![lit(1)]));
1199 add.children.push(("rhs".into(), vec![lit(2)]));
1200 let diags = check_conformance(&add, &schema);
1201
1202 let unknown = diags
1203 .iter()
1204 .find(|d| d.code == codes::UNKNOWN_CHILD)
1205 .expect("expected an UNKNOWN_CHILD diagnostic for `lsh`");
1206 assert!(
1207 unknown.message.contains("did you mean") && unknown.message.contains("lhs"),
1208 "expected `lhs` in the hint, got: {}",
1209 unknown.message
1210 );
1211 assert!(
1212 unknown.message.contains("(missing)"),
1213 "expected `(missing)` pair-hint on the `lhs` suggestion since \
1214 the `lhs` slot is required but absent; got: {}",
1215 unknown.message
1216 );
1217 }
1218
1219 #[test]
1220 fn missing_field_is_reported() {
1221 let schema = schema_add_lit();
1222 let tree = ParseTree::new("Lit"); let diags = check_conformance(&tree, &schema);
1224 assert_eq!(diags.len(), 1);
1225 assert_eq!(diags[0].code, codes::MISSING_FIELD);
1226 assert!(diags[0].message.contains("value"));
1227 }
1228
1229 #[test]
1231 fn optional_field_absent_is_conformant() {
1232 let schema = NodeSchema {
1233 name: "Meta".into(),
1234 variants: vec![VariantSchema {
1235 name: "Row".into(),
1236 fields: vec![
1237 FieldSchema::required("id", "u32"),
1238 FieldSchema::optional("description", "Option<String>"),
1239 FieldSchema::optional("tags", "Vec<String>"),
1240 ],
1241 children: vec![],
1242 }],
1243 };
1244 let mut tree = ParseTree::new("Row");
1245 tree.fields.push(("id".into(), RawValue::Json(json!(1))));
1246 let diags = check_conformance(&tree, &schema);
1248 assert!(
1249 diags.is_empty(),
1250 "optional fields absent should be clean: {diags:?}",
1251 );
1252 }
1253
1254 #[test]
1257 fn optional_field_absence_does_not_shadow_required_missing() {
1258 let schema = NodeSchema {
1259 name: "Meta".into(),
1260 variants: vec![VariantSchema {
1261 name: "Row".into(),
1262 fields: vec![
1263 FieldSchema::required("id", "u32"),
1264 FieldSchema::optional("description", "Option<String>"),
1265 ],
1266 children: vec![],
1267 }],
1268 };
1269 let tree = ParseTree::new("Row"); let diags = check_conformance(&tree, &schema);
1271 assert_eq!(diags.len(), 1);
1272 assert_eq!(diags[0].code, codes::MISSING_FIELD);
1273 assert!(
1274 diags[0].message.contains("id"),
1275 "only `id` is reported missing; got: {}",
1276 diags[0].message,
1277 );
1278 }
1279
1280 #[test]
1284 fn field_schema_to_json_omits_optional_when_false() {
1285 let required = FieldSchema::required("id", "u32").to_json();
1286 assert_eq!(required, json!({ "name": "id", "type": "u32" }));
1287 assert!(
1288 required.get("optional").is_none(),
1289 "required field omits the optional key entirely (pre-0.3 layout)",
1290 );
1291 let opt = FieldSchema::optional("description", "Option<String>").to_json();
1292 assert_eq!(
1293 opt,
1294 json!({ "name": "description", "type": "Option<String>", "optional": true }),
1295 );
1296 }
1297
1298 #[test]
1302 fn build_field_optional_covers_every_absence_shape() {
1303 let mut t = ParseTree::new("Row");
1304 assert_eq!(
1306 build_field_optional::<String>(&t, "description").unwrap(),
1307 None,
1308 );
1309 t.fields
1311 .push(("description".into(), RawValue::Json(Value::Null)));
1312 assert_eq!(
1313 build_field_optional::<String>(&t, "description").unwrap(),
1314 None,
1315 );
1316 let mut t2 = ParseTree::new("Row");
1318 t2.fields
1319 .push(("description".into(), RawValue::Text("none".into())));
1320 assert_eq!(
1321 build_field_optional::<String>(&t2, "description").unwrap(),
1322 None,
1323 );
1324 let mut t3 = ParseTree::new("Row");
1326 t3.fields
1327 .push(("description".into(), RawValue::Json(json!("hi"))));
1328 assert_eq!(
1329 build_field_optional::<String>(&t3, "description").unwrap(),
1330 Some("hi".to_string()),
1331 );
1332 }
1333
1334 #[test]
1338 fn build_field_vec_covers_every_shape() {
1339 let t = ParseTree::new("Row");
1341 assert_eq!(
1342 build_field_vec::<String>(&t, "tags").unwrap(),
1343 Vec::<String>::new()
1344 );
1345 let mut t2 = ParseTree::new("Row");
1347 t2.fields.push(("tags".into(), RawValue::Json(Value::Null)));
1348 assert_eq!(
1349 build_field_vec::<String>(&t2, "tags").unwrap(),
1350 Vec::<String>::new(),
1351 );
1352 let mut t3 = ParseTree::new("Row");
1354 t3.fields
1355 .push(("tags".into(), RawValue::Json(json!(["a", "b"]))));
1356 assert_eq!(
1357 build_field_vec::<String>(&t3, "tags").unwrap(),
1358 vec!["a".to_string(), "b".to_string()],
1359 );
1360 let mut t4 = ParseTree::new("Row");
1362 t4.fields
1363 .push(("tags".into(), RawValue::Text(r#"["a", "b"]"#.into())));
1364 assert_eq!(
1365 build_field_vec::<String>(&t4, "tags").unwrap(),
1366 vec!["a".to_string(), "b".to_string()],
1367 );
1368 let mut t5 = ParseTree::new("Row");
1370 t5.fields.push(("tags".into(), RawValue::Text("[]".into())));
1371 assert_eq!(
1372 build_field_vec::<String>(&t5, "tags").unwrap(),
1373 Vec::<String>::new(),
1374 );
1375 }
1376
1377 #[test]
1378 fn unknown_field_is_reported() {
1379 let schema = schema_add_lit();
1380 let mut tree = lit(3);
1381 tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
1382 let diags = check_conformance(&tree, &schema);
1383 assert_eq!(diags.len(), 1);
1384 assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
1385 }
1386
1387 #[test]
1388 fn field_and_child_slot_swapped_reports_structural_codes() {
1389 let schema = schema_add_lit();
1390
1391 let mut swap1 = ParseTree::new("Add");
1393 swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
1394 swap1.children.push(("rhs".into(), vec![lit(1)]));
1395 let diags = check_conformance(&swap1, &schema);
1398 assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
1399 assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
1400
1401 let mut swap2 = ParseTree::new("Let");
1403 swap2
1404 .children
1405 .push(("name".into(), vec![ParseTree::new("Lit")]));
1406 swap2.children.push(("value".into(), vec![lit(1)]));
1407 swap2.children.push(("body".into(), vec![lit(2)]));
1408 let diags = check_conformance(&swap2, &schema);
1409 assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
1410 assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
1411 }
1412
1413 #[test]
1414 fn arity_one_reports_wrong_count() {
1415 let schema = schema_add_lit();
1416 let mut add = ParseTree::new("Add");
1417 add.children.push(("lhs".into(), vec![lit(1), lit(2)])); add.children.push(("rhs".into(), vec![lit(3)]));
1419 let diags = check_conformance(&add, &schema);
1420 assert_eq!(diags.len(), 1);
1421 assert_eq!(diags[0].code, codes::ARITY_ONE);
1422 assert!(diags[0].message.contains("lhs"));
1423 }
1424
1425 #[test]
1426 fn duplicate_field_and_child_reported() {
1427 let schema = schema_add_lit();
1428 let mut t = ParseTree::new("Lit");
1429 t.fields.push(("value".into(), RawValue::Json(json!(1))));
1430 t.fields.push(("value".into(), RawValue::Json(json!(2))));
1431 let diags = check_conformance(&t, &schema);
1432 assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
1433
1434 let mut a = ParseTree::new("Add");
1435 a.children.push(("lhs".into(), vec![lit(1)]));
1436 a.children.push(("lhs".into(), vec![lit(2)]));
1437 a.children.push(("rhs".into(), vec![lit(3)]));
1438 let diags = check_conformance(&a, &schema);
1439 assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
1440 }
1441
1442 #[test]
1443 fn diagnostic_json_shape() {
1444 let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
1445 let v = diag.to_json();
1446 assert_eq!(v["severity"], "error");
1447 assert_eq!(v["code"], "x::y");
1448 assert_eq!(v["message"], "boom");
1449 assert_eq!(v["location"]["kind"], "span");
1450 assert_eq!(v["location"]["start"], 3);
1451 assert_eq!(v["location"]["end"], 7);
1452 }
1453
1454 #[test]
1455 fn build_error_display_lists_all() {
1456 let err = BuildError::new(vec![
1457 Diagnostic::error("a::b", "one"),
1458 Diagnostic::error("c::d", "two"),
1459 ]);
1460 let s = format!("{err}");
1461 assert!(s.contains("a::b: one"));
1462 assert!(s.contains("c::d: two"));
1463 }
1464}