#![warn(missing_docs)]
use dsl_kit_core::{IdGen, NodeId, Suggester, Suggestion};
use dsl_kit_schema::{ChildSchema, Multiplicity, NodeSchema, VariantSchema};
use serde_json::{Value, json};
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt;
pub mod allow;
pub mod dump;
pub mod example_gen;
pub mod grammar_check;
pub mod import;
pub mod peg;
pub mod schema_gen;
pub mod serde_bridge;
pub use dump::{
DslDump, dump_canonical_json, dump_canonical_json_with, dump_child_many, dump_child_map,
dump_child_one, dump_child_optional, dump_field, dump_field_optional, dump_scalar_map,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl Span {
pub const fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum RawValue {
Text(String),
Json(Value),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParseTree {
pub variant: String,
pub fields: Vec<(String, RawValue)>,
pub children: Vec<(String, Vec<ParseTree>)>,
pub keyed_children: Vec<(String, Vec<(String, ParseTree)>)>,
pub allows: Vec<String>,
pub span: Option<Span>,
}
impl ParseTree {
pub fn new(variant: impl Into<String>) -> Self {
Self {
variant: variant.into(),
fields: Vec::new(),
children: Vec::new(),
keyed_children: Vec::new(),
allows: Vec::new(),
span: None,
}
}
pub fn field(&self, name: &str) -> Option<&RawValue> {
self.fields.iter().find(|(n, _)| n == name).map(|(_, v)| v)
}
pub fn child_slot(&self, name: &str) -> Option<&[ParseTree]> {
self.children
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_slice())
}
pub fn keyed_child_slot(&self, name: &str) -> Option<&[(String, ParseTree)]> {
self.keyed_children
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_slice())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Error,
Warning,
Info,
}
impl Severity {
pub const fn as_str(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Location {
Span(Span),
Node(NodeId),
None,
}
impl Location {
pub fn to_json(&self) -> Value {
match self {
Location::Span(Span { start, end }) => {
json!({ "kind": "span", "start": start, "end": end })
}
Location::Node(id) => json!({ "kind": "node", "id": id.0 }),
Location::None => Value::Null,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
pub severity: Severity,
pub code: String,
pub message: String,
pub location: Location,
}
impl Diagnostic {
pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
severity: Severity::Error,
code: code.into(),
message: message.into(),
location: Location::None,
}
}
pub fn with_span(mut self, span: Option<Span>) -> Self {
if let Some(span) = span {
self.location = Location::Span(span);
}
self
}
pub fn with_node(mut self, id: NodeId) -> Self {
self.location = Location::Node(id);
self
}
pub fn to_json(&self) -> Value {
json!({
"severity": self.severity.as_str(),
"code": self.code,
"message": self.message,
"location": self.location.to_json(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildError {
pub diagnostics: Vec<Diagnostic>,
}
impl BuildError {
pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
assert!(
!diagnostics.is_empty(),
"BuildError requires at least one diagnostic"
);
Self { diagnostics }
}
pub fn single(diag: Diagnostic) -> Self {
Self {
diagnostics: vec![diag],
}
}
pub fn to_json(&self) -> Value {
Value::Array(self.diagnostics.iter().map(Diagnostic::to_json).collect())
}
}
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"build failed with {} diagnostic(s):",
self.diagnostics.len()
)?;
for d in &self.diagnostics {
write!(f, "\n [{}] {}: {}", d.severity.as_str(), d.code, d.message)?;
}
Ok(())
}
}
impl std::error::Error for BuildError {}
pub trait DslBuild: Sized {
fn from_parse_tree(tree: &ParseTree, ids: &IdGen) -> Result<Self, BuildError>;
}
pub mod codes {
pub const UNKNOWN_VARIANT: &str = "dsl_kit::parse::unknown_variant";
pub const MISSING_FIELD: &str = "dsl_kit::parse::missing_field";
pub const UNKNOWN_FIELD: &str = "dsl_kit::parse::unknown_field";
pub const UNKNOWN_CHILD: &str = "dsl_kit::parse::unknown_child";
pub const ARITY_ONE: &str = "dsl_kit::parse::arity_one";
pub const ARITY_OPTIONAL: &str = "dsl_kit::parse::arity_optional";
pub const ARITY_NON_EMPTY: &str = "dsl_kit::parse::arity_non_empty";
pub const FIELD_AS_CHILD: &str = "dsl_kit::parse::field_as_child";
pub const CHILD_AS_FIELD: &str = "dsl_kit::parse::child_as_field";
pub const DUPLICATE_FIELD: &str = "dsl_kit::parse::duplicate_field";
pub const DUPLICATE_CHILD: &str = "dsl_kit::parse::duplicate_child";
pub const FIELD_TYPE: &str = "dsl_kit::parse::field_type";
pub const DUPLICATE_KEY: &str = "dsl_kit::parse::duplicate_key";
pub const KEYED_SLOT_SHAPE: &str = "dsl_kit::parse::keyed_slot_shape";
pub const KEYED_SLOT_UNSORTED: &str = "dsl_kit::parse::keyed_slot_unsorted";
pub const UNKNOWN_MULTIPLICITY: &str = "dsl_kit::parse::unknown_multiplicity";
}
pub fn check_conformance(tree: &ParseTree, schema: &NodeSchema) -> Vec<Diagnostic> {
check_conformance_with(tree, schema, &BuiltinLevenshteinSuggester)
}
pub fn check_conformance_with(
tree: &ParseTree,
schema: &NodeSchema,
suggester: &dyn Suggester,
) -> Vec<Diagnostic> {
let mut out = Vec::new();
if tree.variant == import::IMPORT_VARIANT {
out.push(
Diagnostic::error(
import::import_codes::UNEXPANDED,
format!(
"unexpanded `{}` placeholder — run the document through \
`import::load_json_str` / `import::load_json_value` before conformance",
import::IMPORT_VARIANT
),
)
.with_span(tree.span),
);
return out;
}
if tree.variant == allow::ALLOW_VARIANT {
out.push(
Diagnostic::error(
allow::codes::UNCOLLAPSED,
format!(
"un-collapsed `{}` wrapper — run the tree through \
`allow::collapse` (every text parse already does) before conformance",
allow::ALLOW_VARIANT
),
)
.with_span(tree.span),
);
return out;
}
let Some(variant) = schema.variant(&tree.variant) else {
let msg = format_unknown_variant(&tree.variant, schema, suggester);
out.push(Diagnostic::error(codes::UNKNOWN_VARIANT, msg).with_span(tree.span));
return out;
};
check_fields(tree, variant, &mut out, suggester);
check_children(tree, variant, &mut out, suggester);
out
}
pub(crate) fn format_unknown_variant(
query: &str,
schema: &NodeSchema,
suggester: &dyn Suggester,
) -> String {
let names: Vec<&str> = schema.variants.iter().map(|v| v.name.as_str()).collect();
let base = format!("unknown variant `{}` for `{}`", query, schema.name);
match suggester.enrich_unknown(query, &names) {
Some(hint) => format!("{base} ({hint})"),
None => base,
}
}
pub(crate) fn format_unknown_slot(
kind: &str,
query: &str,
variant_name: &str,
all_candidates: &[&str],
missing_candidates: &[&str],
suggester: &dyn Suggester,
) -> String {
let base = format!("unknown {kind} `{query}` on variant `{variant_name}`");
let sugs = suggester.suggest(query, all_candidates);
if sugs.is_empty() {
return base;
}
let joined = sugs
.iter()
.take(3)
.map(|s| {
if missing_candidates.contains(&s.candidate) {
format!("`{}` (missing)", s.candidate)
} else {
format!("`{}`", s.candidate)
}
})
.collect::<Vec<_>>()
.join(", ");
format!("{base} (did you mean: {joined})")
}
fn check_fields(
tree: &ParseTree,
variant: &VariantSchema,
out: &mut Vec<Diagnostic>,
suggester: &dyn Suggester,
) {
for i in 0..tree.fields.len() {
let (name, _) = &tree.fields[i];
if tree.fields[..i].iter().any(|(n, _)| n == name) {
out.push(
Diagnostic::error(
codes::DUPLICATE_FIELD,
format!(
"field `{}` appears more than once on variant `{}`",
name, variant.name
),
)
.with_span(tree.span),
);
}
}
for f in &variant.fields {
if f.optional {
continue;
}
if tree.field(&f.name).is_none() {
out.push(
Diagnostic::error(
codes::MISSING_FIELD,
format!(
"variant `{}` is missing required field `{}` (type `{}`)",
variant.name, f.name, f.ty
),
)
.with_span(tree.span),
);
}
}
let missing = missing_slot_names(tree, variant);
let all_slots = all_slot_names(variant);
for (name, _) in &tree.fields {
if variant.fields.iter().any(|f| &f.name == name) {
continue;
}
if variant.children.iter().any(|c| &c.name == name) {
out.push(
Diagnostic::error(
codes::CHILD_AS_FIELD,
format!(
"`{}` on variant `{}` is a child slot, not a payload field \
(move it under `children`)",
name, variant.name
),
)
.with_span(tree.span),
);
} else {
let msg = format_unknown_slot(
"field",
name,
&variant.name,
&all_slots,
&missing,
suggester,
);
out.push(Diagnostic::error(codes::UNKNOWN_FIELD, msg).with_span(tree.span));
}
}
}
fn check_children(
tree: &ParseTree,
variant: &VariantSchema,
out: &mut Vec<Diagnostic>,
suggester: &dyn Suggester,
) {
let mut seen: Vec<&str> = Vec::new();
for name in slot_names_in_tree(tree) {
if seen.contains(&name) {
out.push(
Diagnostic::error(
codes::DUPLICATE_CHILD,
format!(
"child slot `{}` appears more than once on variant `{}`",
name, variant.name
),
)
.with_span(tree.span),
);
} else {
seen.push(name);
}
}
for c in &variant.children {
let positional = tree.child_slot(&c.name);
let keyed = tree.keyed_child_slot(&c.name);
let count = positional.map(<[ParseTree]>::len).unwrap_or(0);
let is_map = c.multiplicity == Multiplicity::Map;
let wrong_half = if is_map {
positional.is_some()
} else {
keyed.is_some()
};
if wrong_half {
out.push(diag_keying(variant, c, is_map, tree.span));
}
let only_in_wrong_half = wrong_half
&& if is_map {
keyed.is_none()
} else {
positional.is_none()
};
if only_in_wrong_half {
continue;
}
match c.multiplicity {
Multiplicity::One => {
if count != 1 {
out.push(diag_arity(codes::ARITY_ONE, variant, c, count, tree.span));
}
}
Multiplicity::Optional => {
if count > 1 {
out.push(diag_arity(
codes::ARITY_OPTIONAL,
variant,
c,
count,
tree.span,
));
}
}
Multiplicity::Many => {
if c.non_empty && count == 0 {
out.push(
Diagnostic::error(
codes::ARITY_NON_EMPTY,
format!(
"child slot `{}` on variant `{}` is declared non-empty \
but carries no children",
c.name, variant.name
),
)
.with_span(tree.span),
);
}
}
Multiplicity::Map => {
if c.non_empty && keyed.is_none_or(<[(String, ParseTree)]>::is_empty) {
out.push(
Diagnostic::error(
codes::ARITY_NON_EMPTY,
format!(
"keyed child slot `{}` on variant `{}` is declared \
non-empty but carries no entries",
c.name, variant.name
),
)
.with_span(tree.span),
);
}
let entries = keyed.unwrap_or(&[]);
for pair in entries.windows(2) {
let (lhs, rhs) = (&pair[0].0, &pair[1].0);
match lhs.cmp(rhs) {
Ordering::Equal => out.push(
Diagnostic::error(
codes::DUPLICATE_KEY,
format!(
"keyed child slot `{}` on variant `{}` carries key \
`{}` more than once",
c.name, variant.name, rhs
),
)
.with_span(tree.span),
),
Ordering::Greater => out.push(
Diagnostic::error(
codes::KEYED_SLOT_UNSORTED,
format!(
"keyed child slot `{}` on variant `{}` is not sorted by \
key (`{}` precedes `{}`); front-ends must emit keyed \
entries in key order",
c.name, variant.name, lhs, rhs
),
)
.with_span(tree.span),
),
Ordering::Less => {}
}
}
}
_ => {
out.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)",
c.name, variant.name
),
)
.with_span(tree.span),
);
}
}
}
let missing = missing_slot_names(tree, variant);
let all_slots = all_slot_names(variant);
for name in slot_names_in_tree(tree) {
if variant.children.iter().any(|c| c.name == name) {
continue;
}
if variant.fields.iter().any(|f| f.name == name) {
out.push(
Diagnostic::error(
codes::FIELD_AS_CHILD,
format!(
"`{}` on variant `{}` is a payload field, not a child slot \
(move it under `fields`)",
name, variant.name
),
)
.with_span(tree.span),
);
} else {
let msg = format_unknown_slot(
"child slot",
name,
&variant.name,
&all_slots,
&missing,
suggester,
);
out.push(Diagnostic::error(codes::UNKNOWN_CHILD, msg).with_span(tree.span));
}
}
}
fn slot_names_in_tree(tree: &ParseTree) -> impl Iterator<Item = &str> {
tree.children
.iter()
.map(|(n, _)| n.as_str())
.chain(tree.keyed_children.iter().map(|(n, _)| n.as_str()))
}
fn diag_keying(
variant: &VariantSchema,
child: &ChildSchema,
positional_seen: bool,
span: Option<Span>,
) -> Diagnostic {
let msg = if positional_seen {
format!(
"child slot `{}` on variant `{}` declares Multiplicity::Map — its children \
must be supplied as keyed entries, not as a positional list",
child.name, variant.name
)
} else {
format!(
"child slot `{}` on variant `{}` is positional ({}) — its children must be \
supplied as a plain list, not as keyed entries",
child.name,
variant.name,
child.multiplicity.as_str()
)
};
Diagnostic::error(codes::KEYED_SLOT_SHAPE, msg).with_span(span)
}
pub(crate) fn all_slot_names(variant: &VariantSchema) -> Vec<&str> {
variant
.fields
.iter()
.map(|f| f.name.as_str())
.chain(variant.children.iter().map(|c| c.name.as_str()))
.collect()
}
pub(crate) fn missing_slot_names<'a>(tree: &ParseTree, variant: &'a VariantSchema) -> Vec<&'a str> {
let mut out = Vec::new();
for f in &variant.fields {
if f.optional {
continue;
}
if tree.field(&f.name).is_none() {
out.push(f.name.as_str());
}
}
for c in &variant.children {
let positional = tree
.child_slot(&c.name)
.map(<[ParseTree]>::len)
.unwrap_or(0);
let keyed = tree
.keyed_child_slot(&c.name)
.map(<[(String, ParseTree)]>::len)
.unwrap_or(0);
if positional + keyed == 0 {
out.push(c.name.as_str());
}
}
out
}
fn diag_arity(
code: &'static str,
variant: &VariantSchema,
child: &ChildSchema,
count: usize,
span: Option<Span>,
) -> Diagnostic {
let expected = match child.multiplicity {
Multiplicity::One => "exactly one child",
Multiplicity::Optional => "at most one child",
Multiplicity::Many => "zero or more children",
Multiplicity::Map => "any number of keyed children",
_ => "a shape this build of dsl-kit-parse does not recognise",
};
Diagnostic::error(
code,
format!(
"child slot `{}` on variant `{}` expects {} but got {}",
child.name, variant.name, expected, count
),
)
.with_span(span)
}
pub(crate) struct BuiltinLevenshteinSuggester;
impl Suggester for BuiltinLevenshteinSuggester {
fn suggest<'a>(&self, query: &str, candidates: &'a [&str]) -> Vec<Suggestion<'a>> {
let cutoff = query.chars().count().max(1);
let mut scored: Vec<(usize, &'a str)> = candidates
.iter()
.map(|c| (levenshtein(query, c), *c))
.filter(|(d, _)| *d <= cutoff)
.collect();
scored.sort_by(|(da, na), (db, nb)| da.cmp(db).then_with(|| na.cmp(nb)));
scored.truncate(3);
scored
.into_iter()
.map(|(d, name)| Suggestion {
candidate: name,
score: normalise_edit(d, query, name),
})
.collect()
}
}
fn normalise_edit(distance: usize, a: &str, b: &str) -> f64 {
let max_len = a.chars().count().max(b.chars().count());
if max_len == 0 {
return 1.0;
}
1.0 - (distance as f64 / max_len as f64)
}
fn levenshtein(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let (m, n) = (a.len(), b.len());
if m == 0 {
return n;
}
if n == 0 {
return m;
}
let mut prev: Vec<usize> = (0..=n).collect();
let mut curr: Vec<usize> = vec![0; n + 1];
for i in 1..=m {
curr[0] = i;
for j in 1..=n {
let cost = if a[i - 1].eq_ignore_ascii_case(&b[j - 1]) {
0
} else {
1
};
curr[j] = (curr[j - 1] + 1).min(prev[j] + 1).min(prev[j - 1] + cost);
}
std::mem::swap(&mut prev, &mut curr);
}
prev[n]
}
pub fn build_field<T>(tree: &ParseTree, name: &str) -> Result<T, BuildError>
where
T: serde::de::DeserializeOwned + std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
match tree.field(name) {
Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
BuildError::single(
Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
.with_span(tree.span),
)
}),
Some(RawValue::Text(s)) => s.parse::<T>().map_err(|e| {
BuildError::single(
Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
.with_span(tree.span),
)
}),
None => Err(BuildError::single(
Diagnostic::error(
codes::MISSING_FIELD,
format!("missing required field `{name}`"),
)
.with_span(tree.span),
)),
}
}
pub fn build_field_optional<T>(tree: &ParseTree, name: &str) -> Result<Option<T>, BuildError>
where
T: serde::de::DeserializeOwned + std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Display,
{
match tree.field(name) {
None => Ok(None),
Some(RawValue::Json(Value::Null)) => Ok(None),
Some(RawValue::Text(s)) if s == "none" => Ok(None),
Some(_) => build_field::<T>(tree, name).map(Some),
}
}
pub fn build_field_vec<T>(tree: &ParseTree, name: &str) -> Result<Vec<T>, BuildError>
where
T: serde::de::DeserializeOwned,
{
match tree.field(name) {
None => Ok(Vec::new()),
Some(RawValue::Json(Value::Null)) => Ok(Vec::new()),
Some(RawValue::Json(v)) => serde_json::from_value(v.clone()).map_err(|e| {
BuildError::single(
Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
.with_span(tree.span),
)
}),
Some(RawValue::Text(s)) => {
let trimmed = s.trim();
if trimmed.is_empty() {
return Ok(Vec::new());
}
serde_json::from_str(trimmed).map_err(|e| {
BuildError::single(
Diagnostic::error(codes::FIELD_TYPE, format!("field `{name}`: {e}"))
.with_span(tree.span),
)
})
}
}
}
pub fn field_text<'t>(tree: &'t ParseTree, name: &str) -> Result<&'t str, BuildError> {
match tree.field(name) {
Some(RawValue::Text(s)) => Ok(s),
Some(RawValue::Json(_)) => Err(BuildError::single(
Diagnostic::error(
codes::FIELD_TYPE,
format!("field `{name}`: expected a text production, found JSON"),
)
.with_span(tree.span),
)),
None => Err(BuildError::single(
Diagnostic::error(
codes::MISSING_FIELD,
format!("missing required field `{name}`"),
)
.with_span(tree.span),
)),
}
}
pub fn build_child_one<T: DslBuild>(
tree: &ParseTree,
name: &str,
ids: &IdGen,
) -> Result<T, BuildError> {
let slot = tree.child_slot(name).unwrap_or(&[]);
if slot.len() != 1 {
return Err(BuildError::single(
Diagnostic::error(
codes::ARITY_ONE,
format!(
"child slot `{name}` expects exactly one child but got {}",
slot.len()
),
)
.with_span(tree.span),
));
}
T::from_parse_tree(&slot[0], ids)
}
pub fn build_child_optional<T: DslBuild>(
tree: &ParseTree,
name: &str,
ids: &IdGen,
) -> Result<Option<T>, BuildError> {
let slot = tree.child_slot(name).unwrap_or(&[]);
match slot.len() {
0 => Ok(None),
1 => Ok(Some(T::from_parse_tree(&slot[0], ids)?)),
n => Err(BuildError::single(
Diagnostic::error(
codes::ARITY_OPTIONAL,
format!("child slot `{name}` expects at most one child but got {n}"),
)
.with_span(tree.span),
)),
}
}
pub fn build_child_many<T: DslBuild>(
tree: &ParseTree,
name: &str,
ids: &IdGen,
) -> Result<Vec<T>, BuildError> {
let slot = tree.child_slot(name).unwrap_or(&[]);
let mut out = Vec::with_capacity(slot.len());
let mut diags = Vec::new();
for child in slot {
match T::from_parse_tree(child, ids) {
Ok(v) => out.push(v),
Err(mut e) => diags.append(&mut e.diagnostics),
}
}
if diags.is_empty() {
Ok(out)
} else {
Err(BuildError::new(diags))
}
}
pub fn build_scalar_map<V>(tree: &ParseTree, name: &str) -> Result<BTreeMap<String, V>, BuildError>
where
V: serde::de::DeserializeOwned + std::str::FromStr,
<V as std::str::FromStr>::Err: std::fmt::Display,
{
let slot = tree.keyed_child_slot(name).unwrap_or(&[]);
let mut out = BTreeMap::new();
let mut diags = Vec::new();
for (key, entry) in slot {
match build_field::<V>(entry, "value") {
Ok(v) => {
if out.insert(key.clone(), v).is_some() {
diags.push(
Diagnostic::error(
codes::DUPLICATE_KEY,
format!("keyed child slot `{name}` carries key `{key}` more than once"),
)
.with_span(tree.span),
);
}
}
Err(mut e) => diags.append(&mut e.diagnostics),
}
}
if diags.is_empty() {
Ok(out)
} else {
Err(BuildError::new(diags))
}
}
pub fn build_child_map<T: DslBuild>(
tree: &ParseTree,
name: &str,
ids: &IdGen,
) -> Result<BTreeMap<String, T>, BuildError> {
let slot = tree.keyed_child_slot(name).unwrap_or(&[]);
let mut out = BTreeMap::new();
let mut diags = Vec::new();
for (key, child) in slot {
match T::from_parse_tree(child, ids) {
Ok(v) => {
if out.insert(key.clone(), v).is_some() {
diags.push(
Diagnostic::error(
codes::DUPLICATE_KEY,
format!("keyed child slot `{name}` carries key `{key}` more than once"),
)
.with_span(tree.span),
);
}
}
Err(mut e) => diags.append(&mut e.diagnostics),
}
}
if diags.is_empty() {
Ok(out)
} else {
Err(BuildError::new(diags))
}
}
#[cfg(test)]
mod tests {
use super::*;
use dsl_kit_schema::{
ChildSchema, ChildValueShape, FieldSchema, Multiplicity, NodeSchema, VariantSchema,
};
fn schema_add_lit() -> 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,
scalar_shorthands: vec![],
non_empty: false,
},
ChildSchema {
name: "rhs".into(),
multiplicity: Multiplicity::One,
value_shape: ChildValueShape::Recursive,
scalar_shorthands: vec![],
non_empty: false,
},
],
},
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,
scalar_shorthands: vec![],
non_empty: false,
},
ChildSchema {
name: "body".into(),
multiplicity: Multiplicity::One,
value_shape: ChildValueShape::Recursive,
scalar_shorthands: vec![],
non_empty: false,
},
],
},
],
}
}
fn lit(v: i64) -> ParseTree {
let mut t = ParseTree::new("Lit");
t.fields.push(("value".into(), RawValue::Json(json!(v))));
t
}
#[test]
fn ok_lit() {
let schema = schema_add_lit();
assert!(check_conformance(&lit(1), &schema).is_empty());
}
#[test]
fn ok_add_with_two_children() {
let schema = schema_add_lit();
let mut add = ParseTree::new("Add");
add.children.push(("lhs".into(), vec![lit(1)]));
add.children.push(("rhs".into(), vec![lit(2)]));
assert!(check_conformance(&add, &schema).is_empty());
}
#[test]
fn unknown_variant_lists_candidates() {
let schema = schema_add_lit();
let tree = ParseTree::new("Aad"); let diags = check_conformance(&tree, &schema);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
assert!(
diags[0].message.contains("Add"),
"expected Add to appear as a candidate; got: {}",
diags[0].message
);
}
#[test]
fn unknown_variant_uses_injected_suggester() {
use dsl_kit_fuzzy::FuzzySuggester;
let schema = schema_add_lit();
let tree = ParseTree::new("Adx"); let suggester = FuzzySuggester::default();
let diags = check_conformance_with(&tree, &schema, &suggester);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::UNKNOWN_VARIANT);
assert!(
diags[0].message.contains("did you mean") && diags[0].message.contains("Add"),
"expected FuzzySuggester to surface `Add`; got: {}",
diags[0].message
);
}
#[test]
fn unknown_field_suggests_declared_field() {
let schema = NodeSchema {
name: "Cfg".into(),
variants: vec![VariantSchema {
name: "Load".into(),
fields: vec![
FieldSchema {
name: "target".into(),
ty: "String".into(),
optional: false,
},
FieldSchema {
name: "count".into(),
ty: "u32".into(),
optional: false,
},
],
children: vec![],
}],
};
let mut tree = ParseTree::new("Load");
tree.fields
.push(("taget".into(), RawValue::Json(json!("a"))));
tree.fields.push(("count".into(), RawValue::Json(json!(1))));
let diags = check_conformance(&tree, &schema);
let unknown = diags
.iter()
.find(|d| d.code == codes::UNKNOWN_FIELD)
.expect("expected an UNKNOWN_FIELD diagnostic for `taget`");
assert!(
unknown.message.contains("did you mean") && unknown.message.contains("target"),
"expected `target` in the hint, got: {}",
unknown.message
);
assert!(
unknown.message.contains("(missing)"),
"expected `(missing)` pair-hint since `target` is a required field \
not present on the tree; got: {}",
unknown.message
);
}
#[test]
fn unknown_child_suggests_declared_child() {
let schema = schema_add_lit();
let mut add = ParseTree::new("Add");
add.children.push(("lsh".into(), vec![lit(1)]));
add.children.push(("rhs".into(), vec![lit(2)]));
let diags = check_conformance(&add, &schema);
let unknown = diags
.iter()
.find(|d| d.code == codes::UNKNOWN_CHILD)
.expect("expected an UNKNOWN_CHILD diagnostic for `lsh`");
assert!(
unknown.message.contains("did you mean") && unknown.message.contains("lhs"),
"expected `lhs` in the hint, got: {}",
unknown.message
);
assert!(
unknown.message.contains("(missing)"),
"expected `(missing)` pair-hint on the `lhs` suggestion since \
the `lhs` slot is required but absent; got: {}",
unknown.message
);
}
#[test]
fn missing_field_is_reported() {
let schema = schema_add_lit();
let tree = ParseTree::new("Lit"); let diags = check_conformance(&tree, &schema);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::MISSING_FIELD);
assert!(diags[0].message.contains("value"));
}
#[test]
fn optional_field_absent_is_conformant() {
let schema = NodeSchema {
name: "Meta".into(),
variants: vec![VariantSchema {
name: "Row".into(),
fields: vec![
FieldSchema::required("id", "u32"),
FieldSchema::optional("description", "Option<String>"),
FieldSchema::optional("tags", "Vec<String>"),
],
children: vec![],
}],
};
let mut tree = ParseTree::new("Row");
tree.fields.push(("id".into(), RawValue::Json(json!(1))));
let diags = check_conformance(&tree, &schema);
assert!(
diags.is_empty(),
"optional fields absent should be clean: {diags:?}",
);
}
#[test]
fn optional_field_absence_does_not_shadow_required_missing() {
let schema = NodeSchema {
name: "Meta".into(),
variants: vec![VariantSchema {
name: "Row".into(),
fields: vec![
FieldSchema::required("id", "u32"),
FieldSchema::optional("description", "Option<String>"),
],
children: vec![],
}],
};
let tree = ParseTree::new("Row"); let diags = check_conformance(&tree, &schema);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::MISSING_FIELD);
assert!(
diags[0].message.contains("id"),
"only `id` is reported missing; got: {}",
diags[0].message,
);
}
#[test]
fn field_schema_to_json_omits_optional_when_false() {
let required = FieldSchema::required("id", "u32").to_json();
assert_eq!(required, json!({ "name": "id", "type": "u32" }));
assert!(
required.get("optional").is_none(),
"required field omits the optional key entirely (pre-0.3 layout)",
);
let opt = FieldSchema::optional("description", "Option<String>").to_json();
assert_eq!(
opt,
json!({ "name": "description", "type": "Option<String>", "optional": true }),
);
}
#[test]
fn build_field_optional_covers_every_absence_shape() {
let mut t = ParseTree::new("Row");
assert_eq!(
build_field_optional::<String>(&t, "description").unwrap(),
None,
);
t.fields
.push(("description".into(), RawValue::Json(Value::Null)));
assert_eq!(
build_field_optional::<String>(&t, "description").unwrap(),
None,
);
let mut t2 = ParseTree::new("Row");
t2.fields
.push(("description".into(), RawValue::Text("none".into())));
assert_eq!(
build_field_optional::<String>(&t2, "description").unwrap(),
None,
);
let mut t3 = ParseTree::new("Row");
t3.fields
.push(("description".into(), RawValue::Json(json!("hi"))));
assert_eq!(
build_field_optional::<String>(&t3, "description").unwrap(),
Some("hi".to_string()),
);
}
#[test]
fn build_field_vec_covers_every_shape() {
let t = ParseTree::new("Row");
assert_eq!(
build_field_vec::<String>(&t, "tags").unwrap(),
Vec::<String>::new()
);
let mut t2 = ParseTree::new("Row");
t2.fields.push(("tags".into(), RawValue::Json(Value::Null)));
assert_eq!(
build_field_vec::<String>(&t2, "tags").unwrap(),
Vec::<String>::new(),
);
let mut t3 = ParseTree::new("Row");
t3.fields
.push(("tags".into(), RawValue::Json(json!(["a", "b"]))));
assert_eq!(
build_field_vec::<String>(&t3, "tags").unwrap(),
vec!["a".to_string(), "b".to_string()],
);
let mut t4 = ParseTree::new("Row");
t4.fields
.push(("tags".into(), RawValue::Text(r#"["a", "b"]"#.into())));
assert_eq!(
build_field_vec::<String>(&t4, "tags").unwrap(),
vec!["a".to_string(), "b".to_string()],
);
let mut t5 = ParseTree::new("Row");
t5.fields.push(("tags".into(), RawValue::Text("[]".into())));
assert_eq!(
build_field_vec::<String>(&t5, "tags").unwrap(),
Vec::<String>::new(),
);
}
#[test]
fn unknown_field_is_reported() {
let schema = schema_add_lit();
let mut tree = lit(3);
tree.fields.push(("extra".into(), RawValue::Json(json!(0))));
let diags = check_conformance(&tree, &schema);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::UNKNOWN_FIELD);
}
#[test]
fn field_and_child_slot_swapped_reports_structural_codes() {
let schema = schema_add_lit();
let mut swap1 = ParseTree::new("Add");
swap1.fields.push(("lhs".into(), RawValue::Json(json!(0))));
swap1.children.push(("rhs".into(), vec![lit(1)]));
let diags = check_conformance(&swap1, &schema);
assert!(diags.iter().any(|d| d.code == codes::CHILD_AS_FIELD));
assert!(diags.iter().any(|d| d.code == codes::ARITY_ONE));
let mut swap2 = ParseTree::new("Let");
swap2
.children
.push(("name".into(), vec![ParseTree::new("Lit")]));
swap2.children.push(("value".into(), vec![lit(1)]));
swap2.children.push(("body".into(), vec![lit(2)]));
let diags = check_conformance(&swap2, &schema);
assert!(diags.iter().any(|d| d.code == codes::FIELD_AS_CHILD));
assert!(diags.iter().any(|d| d.code == codes::MISSING_FIELD));
}
#[test]
fn arity_one_reports_wrong_count() {
let schema = schema_add_lit();
let mut add = ParseTree::new("Add");
add.children.push(("lhs".into(), vec![lit(1), lit(2)])); add.children.push(("rhs".into(), vec![lit(3)]));
let diags = check_conformance(&add, &schema);
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].code, codes::ARITY_ONE);
assert!(diags[0].message.contains("lhs"));
}
#[test]
fn duplicate_field_and_child_reported() {
let schema = schema_add_lit();
let mut t = ParseTree::new("Lit");
t.fields.push(("value".into(), RawValue::Json(json!(1))));
t.fields.push(("value".into(), RawValue::Json(json!(2))));
let diags = check_conformance(&t, &schema);
assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_FIELD));
let mut a = ParseTree::new("Add");
a.children.push(("lhs".into(), vec![lit(1)]));
a.children.push(("lhs".into(), vec![lit(2)]));
a.children.push(("rhs".into(), vec![lit(3)]));
let diags = check_conformance(&a, &schema);
assert!(diags.iter().any(|d| d.code == codes::DUPLICATE_CHILD));
}
#[test]
fn diagnostic_json_shape() {
let diag = Diagnostic::error("x::y", "boom").with_span(Some(Span::new(3, 7)));
let v = diag.to_json();
assert_eq!(v["severity"], "error");
assert_eq!(v["code"], "x::y");
assert_eq!(v["message"], "boom");
assert_eq!(v["location"]["kind"], "span");
assert_eq!(v["location"]["start"], 3);
assert_eq!(v["location"]["end"], 7);
}
#[test]
fn build_error_display_lists_all() {
let err = BuildError::new(vec![
Diagnostic::error("a::b", "one"),
Diagnostic::error("c::d", "two"),
]);
let s = format!("{err}");
assert!(s.contains("a::b: one"));
assert!(s.contains("c::d: two"));
}
}