use std::cmp::Reverse;
use crate::codes::{
SHAPE_MISSING_FIELD, SHAPE_MISSING_TAG, SHAPE_NO_FORM, SHAPE_NOT_INTEGER, SHAPE_NOT_ONE_OF,
SHAPE_OUT_OF_RANGE, SHAPE_REPEATED_FIELD, SHAPE_TOO_DEEP, SHAPE_TOO_FEW, SHAPE_TOO_LONG,
SHAPE_TOO_MANY, SHAPE_TOO_SHORT, SHAPE_UNKNOWN_FIELD, SHAPE_UNKNOWN_TAG, SHAPE_WRONG_TYPE,
};
use crate::diagnostic::{Code, Diagnostic};
use crate::path::{Path, Segment};
use crate::read::MAX_DEPTH;
use crate::schema::{Additional, Definition, Format, Schema, SchemaId, Types};
use crate::tree::{Node, NumberKind, Span, Value};
use crate::write::quote;
#[derive(Clone, Debug)]
pub struct Finding {
pub diagnostic: Diagnostic,
pub schema: Option<SchemaId>,
pub parent: Option<SchemaId>,
}
impl Finding {
#[must_use]
pub const fn bare(diagnostic: Diagnostic) -> Self {
Self {
diagnostic,
schema: None,
parent: None,
}
}
}
#[derive(Clone, Debug)]
pub struct CheckOptions<'a> {
pub incomplete: &'a [Path],
pub limit: usize,
}
impl Default for CheckOptions<'_> {
fn default() -> Self {
Self {
incomplete: &[],
limit: crate::diagnostic::Collector::DEFAULT_CAPACITY,
}
}
}
const SHOWN_VALUES: usize = 16;
const TRIAL_VISITS_PER_NODE: usize = 16;
#[must_use]
pub fn check(
schema: &Schema,
tree: &Node,
root: &Path,
options: &CheckOptions<'_>,
) -> Vec<Finding> {
let mut walker = Walker {
schema,
incomplete: options.incomplete,
trial_budget: tree.count().saturating_mul(TRIAL_VISITS_PER_NODE) + 1_000,
trials: 0,
depth: 0,
};
let mut out = Vec::new();
let context = Context {
definition: schema.definition_of(schema.root()),
parent: None,
};
walker.walk(
schema.root(),
tree,
&mut root.clone(),
context,
&mut out,
options.limit,
);
out
}
#[derive(Clone, Copy)]
struct Context<'s> {
definition: Option<&'s Definition>,
parent: Option<SchemaId>,
}
struct Walker<'s, 'o> {
schema: &'s Schema,
incomplete: &'o [Path],
trial_budget: usize,
trials: usize,
depth: usize,
}
struct Problem<'a> {
code: &'static Code,
id: SchemaId,
path: Path,
span: Option<Span>,
message: String,
data: Vec<(&'a str, Node)>,
}
fn article(name: &str) -> &'static str {
if name.starts_with(['a', 'e', 'i', 'o', 'u']) {
"an"
} else {
"a"
}
}
fn list_values<'n>(values: impl IntoIterator<Item = &'n Node>) -> String {
let values: Vec<String> = values.into_iter().map(written).collect();
if values.len() > SHOWN_VALUES {
format!(
"{}, ... ({} in all)",
values[..SHOWN_VALUES].join(", "),
values.len()
)
} else {
values.join(", ")
}
}
#[must_use]
pub fn written(node: &Node) -> String {
let text = match &node.value {
Value::Text(text) => quote(text),
Value::Number(number) => number.text().to_owned(),
_ => crate::write::json(node, &Path::root("value")).0,
};
if text.len() > 60 {
let mut end = 57;
while !text.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &text[..end])
} else {
text
}
}
#[must_use]
pub fn type_words(types: Types) -> String {
let mut names = types.names();
if names.contains(&"number") {
names.retain(|name| *name != "integer");
}
let words: Vec<String> = names
.iter()
.map(|name| match *name {
"null" => "null".to_owned(),
name => format!("{} {name}", article(name)),
})
.collect();
match words.len() {
0 => "nothing".to_owned(),
1 => words[0].clone(),
_ => format!(
"{} or {}",
words[..words.len() - 1].join(", "),
words[words.len() - 1]
),
}
}
impl<'s> Walker<'s, '_> {
fn name(context: &Context<'_>) -> String {
context.definition.map_or_else(
|| "this object".to_owned(),
|definition| definition.name.clone(),
)
}
fn push(out: &mut Vec<Finding>, context: &Context<'s>, problem: Problem<'_>) {
let mut diagnostic =
Diagnostic::new(problem.code, problem.path, sentence(problem.message)).at(problem.span);
if !problem.data.is_empty() {
diagnostic = diagnostic.data(Node::map(problem.data));
}
if let Some(definition) = context.definition {
diagnostic = diagnostic.reference(definition.topic.clone(), definition.name.clone());
}
out.push(Finding {
diagnostic,
schema: Some(problem.id),
parent: context.parent,
});
}
fn is_incomplete(&self, path: &Path) -> bool {
self.incomplete.contains(path)
}
fn spend(&mut self) -> bool {
if self.trials == 0 {
return true;
}
if self.trial_budget == 0 {
return false;
}
self.trial_budget -= 1;
true
}
fn walk(
&mut self,
id: SchemaId,
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) {
if out.len() >= cap || !self.spend() {
return;
}
let schema = self.schema;
let rule = schema.node(id);
if rule.never {
Self::push(
out,
&context,
Problem {
code: &SHAPE_NO_FORM,
id,
path: path.clone(),
span: node.span,
message: "No value is allowed here.".into(),
data: vec![],
},
);
return;
}
if let Some(target) = rule.reference {
let inner = Context {
definition: schema
.node(target)
.definition
.as_ref()
.or(context.definition),
parent: context.parent,
};
let before = out.len();
self.walk(target, node, path, inner, out, cap);
if out.len() > before || rule.is_bare_reference() {
return;
}
}
if let Some(constant) = &rule.constant
&& !constant.same_value(node)
{
Self::not_one_of(
out,
&context,
id,
node,
path,
std::slice::from_ref(constant).iter(),
);
return;
}
if let Some(choices) = &rule.choices
&& !choices.iter().any(|choice| choice.same_value(node))
{
Self::not_one_of(out, &context, id, node, path, choices.iter());
return;
}
if !rule.forms.is_empty() && self.union(id, node, path, context, out, cap) {
return;
}
if let Some(types) = rule.types
&& !types.admits(node)
{
Self::push(
out,
&context,
Problem {
code: &SHAPE_WRONG_TYPE,
id,
path: path.clone(),
span: node.span,
message: format!(
"Expected {} but found {}.",
type_words(types),
type_words(Types::of(node))
),
data: vec![
("expected", Node::from(types.names())),
("found", Node::text(node.kind_name())),
],
},
);
return;
}
match &node.value {
Value::Number(_) => self.number(id, node, path, &context, out),
Value::Text(text) => self.text(id, text, node, path, &context, out),
Value::List(items) => {
if self.enter(id, node, path, &context, out) {
self.list(id, items, node, path, context, out, cap);
self.depth -= 1;
}
}
Value::Map(_) => {
if self.enter(id, node, path, &context, out) {
self.map(id, node, path, context, out, cap);
self.depth -= 1;
}
}
Value::Null | Value::Bool(_) => {}
}
}
fn enter(
&mut self,
id: SchemaId,
node: &Node,
path: &Path,
context: &Context<'s>,
out: &mut Vec<Finding>,
) -> bool {
if self.depth >= MAX_DEPTH {
Self::push(
out,
context,
Problem {
code: &SHAPE_TOO_DEEP,
id,
path: path.clone(),
span: node.span,
message: format!(
"Arrays and objects nest deeper than {MAX_DEPTH} levels here."
),
data: vec![("maximum", Node::from(MAX_DEPTH))],
},
);
return false;
}
self.depth += 1;
true
}
fn not_one_of<'n>(
out: &mut Vec<Finding>,
context: &Context<'s>,
id: SchemaId,
node: &Node,
path: &Path,
allowed: impl Iterator<Item = &'n Node> + Clone,
) {
let list: Vec<Node> = allowed.clone().cloned().collect();
let message = if list.len() == 1 {
format!(
"Expected {} but found {}.",
written(&list[0]),
written(node)
)
} else {
format!("{} is not one of {}.", written(node), list_values(allowed))
};
Self::push(
out,
context,
Problem {
code: &SHAPE_NOT_ONE_OF,
id,
path: path.clone(),
span: node.span,
message,
data: vec![
("allowed", Node::list(list)),
("found", node.clone().without_spans()),
],
},
);
}
fn union(
&mut self,
id: SchemaId,
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) -> bool {
let schema = self.schema;
let rule = schema.node(id);
match schema.constant_match(id, node) {
Some(true) => return false,
Some(false) => {
let constants: Vec<Node> = schema
.constants(id)
.unwrap_or_default()
.into_iter()
.cloned()
.collect();
Self::not_one_of(out, &context, id, node, path, constants.iter());
return true;
}
None => {}
}
if let Some(tag) = &rule.tag {
return self.tagged(id, tag, node, path, context, out, cap);
}
let admits = |form: &SchemaId| schema.types(*form).admits(node);
if rule.partial_tag.is_none() {
let mut admitted = rule.forms.iter().filter(|form| admits(form));
if let (Some(only), None) = (admitted.next(), admitted.next()) {
let before = out.len();
self.walk(*only, node, path, context, out, cap);
return out.len() > before;
}
}
let mut candidates: Vec<SchemaId> = rule.forms.iter().copied().filter(admits).collect();
if let Some(tag) = &rule.partial_tag
&& matches!(node.value, Value::Map(_))
{
let has_tag =
|form: &SchemaId| schema.node(schema.resolve(*form)).property(tag).is_some();
if node.get(tag).is_some() {
candidates.retain(has_tag);
return self.partly_tagged(id, tag, &candidates, node, path, context, out, cap);
}
candidates.retain(|form| !has_tag(form));
if candidates.is_empty() {
let allowed: Vec<Node> = rule
.forms
.iter()
.filter_map(|form| schema.tag_value(*form, tag).cloned())
.collect();
self.missing_tag(id, tag, allowed, node, path, &context, out);
return true;
}
}
match candidates.as_slice() {
[] => {
let types = schema.types(id);
Self::push(
out,
&context,
Problem {
code: &SHAPE_WRONG_TYPE,
id,
path: path.clone(),
span: node.span,
message: format!(
"Expected {} but found {}.",
type_words(types),
type_words(Types::of(node))
),
data: vec![
("expected", Node::from(types.names())),
("found", Node::text(node.kind_name())),
],
},
);
true
}
[only] => {
let before = out.len();
self.walk(*only, node, path, context, out, cap);
out.len() > before
}
several => self.untagged(id, several, node, path, context, out, cap),
}
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn tagged(
&mut self,
id: SchemaId,
tag: &str,
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) -> bool {
let schema = self.schema;
let forms = &schema.node(id).forms;
if matches!(node.value, Value::Map(_)) && node.get(tag).is_some() {
return self.tagged_among(id, tag, forms, node, path, context, out, cap);
}
let allowed: Vec<Node> = forms
.iter()
.filter_map(|form| schema.tag_value(*form, tag).cloned())
.collect();
if !matches!(node.value, Value::Map(_)) {
let types = schema.types(id);
if types.admits(node) {
return false;
}
Self::push(
out,
&context,
Problem {
code: &SHAPE_WRONG_TYPE,
id,
path: path.clone(),
span: node.span,
message: format!(
"Expected {} but found {}.",
type_words(types),
type_words(Types::of(node))
),
data: vec![
("expected", Node::from(types.names())),
("found", Node::text(node.kind_name())),
],
},
);
return true;
}
self.missing_tag(id, tag, allowed, node, path, &context, out);
true
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn missing_tag(
&self,
id: SchemaId,
tag: &str,
allowed: Vec<Node>,
node: &Node,
path: &Path,
context: &Context<'s>,
out: &mut Vec<Finding>,
) {
if self.is_incomplete(path) {
return;
}
let name = Self::name(context);
Self::push(
out,
context,
Problem {
code: &SHAPE_MISSING_TAG,
id,
path: path.clone(),
span: node.span,
message: format!(
"{name} needs the field {} naming its kind: {}.",
quote(tag),
list_values(&allowed)
),
data: vec![("tag", Node::text(tag)), ("allowed", Node::list(allowed))],
},
);
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn tagged_among(
&mut self,
id: SchemaId,
tag: &str,
forms: &[SchemaId],
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) -> bool {
let schema = self.schema;
let Some(value) = node.get(tag) else {
return false;
};
let allowed: Vec<Node> = forms
.iter()
.filter_map(|form| schema.tag_value(*form, tag).cloned())
.collect();
let name = Self::name(&context);
if let Some(form) = forms.iter().find(|form| {
schema
.tag_value(**form, tag)
.is_some_and(|known| known.same_value(value))
}) {
let inner = Context {
definition: schema.definition_of(*form).or(context.definition),
parent: context.parent,
};
let before = out.len();
self.walk(*form, node, path, inner, out, cap);
return out.len() > before;
}
Self::push(
out,
&context,
Problem {
code: &SHAPE_UNKNOWN_TAG,
id,
path: path.key(tag),
span: value.span,
message: format!(
"{} is not a kind of {name}; its {} is one of {}.",
written(value),
quote(tag),
list_values(&allowed)
),
data: vec![
("tag", Node::text(tag)),
("allowed", Node::list(allowed)),
("found", value.clone().without_spans()),
],
},
);
true
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn partly_tagged(
&mut self,
id: SchemaId,
tag: &str,
forms: &[SchemaId],
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) -> bool {
let schema = self.schema;
let (closed, open): (Vec<SchemaId>, Vec<SchemaId>) = forms
.iter()
.partition(|form| schema.tag_value(**form, tag).is_some());
if open.is_empty() {
return self.tagged_among(id, tag, forms, node, path, context, out, cap);
}
let Some(value) = node.get(tag) else {
return false;
};
let matching = closed.iter().find(|form| {
schema
.tag_value(**form, tag)
.is_some_and(|known| known.same_value(value))
});
let mut found = None;
if let Some(form) = matching {
let inner = Context {
definition: schema.definition_of(*form).or(context.definition),
parent: context.parent,
};
let mut tried = Vec::new();
self.walk(
*form,
node,
path,
inner,
&mut tried,
cap.saturating_sub(out.len()).max(1),
);
if tried.is_empty() {
return false;
}
found = Some(tried);
}
self.trials += 1;
for form in &open {
let inner = Context {
definition: schema.definition_of(*form).or(context.definition),
parent: context.parent,
};
let mut tried = Vec::new();
self.walk(*form, node, path, inner, &mut tried, 1);
if tried.is_empty() && self.trial_budget > 0 {
self.trials -= 1;
return false;
}
}
self.trials -= 1;
if let Some(found) = found {
out.extend(found);
return true;
}
let allowed: Vec<Node> = closed
.iter()
.filter_map(|form| schema.tag_value(*form, tag).cloned())
.collect();
let name = Self::name(&context);
Self::push(
out,
&context,
Problem {
code: &SHAPE_UNKNOWN_TAG,
id,
path: path.key(tag),
span: value.span,
message: format!(
"{} is not a kind of {name}; its {} is one of {}.",
written(value),
quote(tag),
list_values(&allowed)
),
data: vec![
("tag", Node::text(tag)),
("allowed", Node::list(allowed)),
("found", value.clone().without_spans()),
],
},
);
true
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn untagged(
&mut self,
id: SchemaId,
forms: &[SchemaId],
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) -> bool {
let mut best: Option<Vec<Finding>> = None;
let mut tie = false;
self.trials += 1;
let mut exhausted = false;
for form in forms {
let limit = best
.as_ref()
.map_or(cap.saturating_sub(out.len()), |known| known.len() + 1);
let mut tried = Vec::new();
let inner = Context {
definition: self.schema.definition_of(*form).or(context.definition),
parent: context.parent,
};
self.walk(*form, node, path, inner, &mut tried, limit.max(1));
if self.trial_budget == 0 {
exhausted = true;
break;
}
if tried.is_empty() {
self.trials -= 1;
return false;
}
let fit = |found: &[Finding]| (Reverse(found.len()), deepest(found));
match &best {
Some(known) if fit(&tried) < fit(known) => {}
Some(known) if fit(&tried) == fit(known) => tie = true,
_ => {
best = Some(tried);
tie = false;
}
}
}
self.trials -= 1;
match best {
Some(found) if !tie && !exhausted => out.extend(found),
_ => {
let name = Self::name(&context);
Self::push(
out,
&context,
Problem {
code: &SHAPE_NO_FORM,
id,
path: path.clone(),
span: node.span,
message: format!(
"The value fits none of the {} forms {name} takes.",
forms.len()
),
data: vec![("forms", Node::from(forms.len()))],
},
);
}
}
true
}
fn number(
&self,
id: SchemaId,
node: &Node,
path: &Path,
context: &Context<'s>,
out: &mut Vec<Finding>,
) {
let rule = self.schema.node(id);
let Some(number) = node.as_number() else {
return;
};
if number.kind() == NumberKind::NotFinite {
return;
}
let types = rule.types.unwrap_or_default();
let integer_only = types.contains(Types::INTEGER) && !types.contains(Types::NUMBER);
let out_of_range = |message: String, data: Vec<(&'static str, Node)>| Problem {
code: &SHAPE_OUT_OF_RANGE,
id,
path: path.clone(),
span: node.span,
message,
data,
};
if integer_only || rule.format.and_then(Format::integer_range).is_some() {
let Some(value) = number.as_i128() else {
if number.kind() == NumberKind::Decimal {
let mut data = vec![("found", Node::text(number.text()))];
if let Some(whole) = number.whole() {
data.push(("whole", Node::text(whole.to_string())));
}
Self::push(
out,
context,
Problem {
code: &SHAPE_NOT_INTEGER,
id,
path: path.clone(),
span: node.span,
message: format!("Expected an integer but found {}.", number.text()),
data,
},
);
} else {
Self::push(
out,
context,
out_of_range(
format!("{} is too large an integer.", number.text()),
vec![("found", Node::text(number.text()))],
),
);
}
return;
};
let (low, high) = integer_bounds(rule);
if value < low || value > high {
let range = integer_range_words(low, high);
let mut data = vec![("found", Node::text(number.text()))];
if low != i128::MIN {
data.push(("minimum", Node::text(low.to_string())));
}
if high != i128::MAX {
data.push(("maximum", Node::text(high.to_string())));
}
Self::push(
out,
context,
out_of_range(format!("{} is outside {range}.", number.text()), data),
);
}
return;
}
let mut value = number.as_f64();
if rule.format == Some(Format::Float) {
#[expect(
clippy::cast_possible_truncation,
reason = "the engine reads this value as 32 bits"
)]
{
value = f64::from(value as f32);
}
}
let below = rule.minimum.is_some_and(|minimum| value < minimum);
let above = rule.maximum.is_some_and(|maximum| value > maximum);
if below || above {
let range = float_range_words(rule.minimum, rule.maximum);
let mut data = vec![("found", Node::number(number.clone()))];
if let Some(minimum) = rule.minimum {
data.push(("minimum", Node::float(minimum)));
}
if let Some(maximum) = rule.maximum {
data.push(("maximum", Node::float(maximum)));
}
Self::push(
out,
context,
out_of_range(format!("{} is outside {range}.", number.text()), data),
);
}
}
fn text(
&self,
id: SchemaId,
text: &str,
node: &Node,
path: &Path,
context: &Context<'s>,
out: &mut Vec<Finding>,
) {
let rule = self.schema.node(id);
let length = text.chars().count();
if let Some(minimum) = rule.min_length
&& length < minimum
{
let message = if minimum == 1 {
"The string must not be empty.".to_owned()
} else {
format!("The string has {length} characters; at least {minimum} are needed.")
};
Self::push(
out,
context,
Problem {
code: &SHAPE_TOO_SHORT,
id,
path: path.clone(),
span: node.span,
message,
data: vec![
("minimum", Node::from(minimum)),
("found", Node::from(length)),
],
},
);
} else if let Some(maximum) = rule.max_length
&& length > maximum
{
Self::push(
out,
context,
Problem {
code: &SHAPE_TOO_LONG,
id,
path: path.clone(),
span: node.span,
message: format!(
"The string has {length} characters; at most {maximum} are allowed."
),
data: vec![
("maximum", Node::from(maximum)),
("found", Node::from(length)),
],
},
);
}
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn list(
&mut self,
id: SchemaId,
items: &[Node],
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) {
let schema = self.schema;
let rule = schema.node(id);
if let Some(minimum) = rule.min_items
&& items.len() < minimum
&& !self.is_incomplete(path)
{
Self::push(
out,
&context,
Problem {
code: &SHAPE_TOO_FEW,
id,
path: path.clone(),
span: node.span,
message: format!("{} items where at least {minimum} are needed.", items.len()),
data: vec![
("minimum", Node::from(minimum)),
("found", Node::from(items.len())),
],
},
);
}
if let Some(maximum) = rule.max_items
&& items.len() > maximum
{
Self::push(
out,
&context,
Problem {
code: &SHAPE_TOO_MANY,
id,
path: path.clone(),
span: node.span,
message: format!("{} items where at most {maximum} are allowed.", items.len()),
data: vec![
("maximum", Node::from(maximum)),
("found", Node::from(items.len())),
],
},
);
}
for (index, item) in items.iter().enumerate() {
if out.len() >= cap {
return;
}
let item_rule = rule
.prefix_items
.get(index)
.copied()
.map(Additional::Schema)
.or(rule.items);
match item_rule {
Some(Additional::Schema(item_id)) => {
let inner = Context {
definition: context.definition,
parent: Some(id),
};
path.push(Segment::Index(index));
self.walk(item_id, item, path, inner, out, cap);
path.pop();
}
Some(Additional::Denied) => {
Self::push(
out,
&context,
Problem {
code: &SHAPE_TOO_MANY,
id,
path: path.index(index),
span: item.span,
message: format!(
"{} items where at most {} are allowed.",
items.len(),
rule.prefix_items.len()
),
data: vec![
("maximum", Node::from(rule.prefix_items.len())),
("found", Node::from(items.len())),
],
},
);
return;
}
Some(Additional::Allowed) | None => {}
}
}
}
fn map(
&mut self,
id: SchemaId,
node: &Node,
path: &mut Path,
context: Context<'s>,
out: &mut Vec<Finding>,
cap: usize,
) {
let schema = self.schema;
let rule = schema.node(id);
let Some(entries) = node.as_map() else {
return;
};
let name = Self::name(&context);
if let Some(maximum) = rule.max_properties
&& entries.len() > maximum
{
Self::push(
out,
&context,
Problem {
code: &SHAPE_TOO_MANY,
id,
path: path.clone(),
span: node.span,
message: format!(
"{} fields where at most {maximum} are allowed.",
entries.len()
),
data: vec![
("maximum", Node::from(maximum)),
("found", Node::from(entries.len())),
],
},
);
}
for (index, entry) in entries.iter().enumerate() {
if out.len() >= cap {
return;
}
let property = rule.property(&entry.key);
if property.is_some()
&& entries[index + 1..]
.iter()
.any(|later| later.key == entry.key)
{
Self::push(
out,
&context,
Problem {
code: &SHAPE_REPEATED_FIELD,
id,
path: path.key(entry.key.clone()),
span: entry.key_span.or(entry.value.span),
message: format!(
"The field {} is given more than once.",
quote(&entry.key)
),
data: vec![("field", Node::text(entry.key.clone()))],
},
);
continue;
}
let value_rule = property.map(Additional::Schema).or(rule.additional);
match value_rule {
Some(Additional::Schema(value_id)) => {
let inner = Context {
definition: context.definition,
parent: Some(id),
};
path.push(Segment::Key(entry.key.clone()));
self.walk(value_id, &entry.value, path, inner, out, cap);
path.pop();
}
Some(Additional::Denied) => {
Self::push(
out,
&context,
Problem {
code: &SHAPE_UNKNOWN_FIELD,
id,
path: path.key(entry.key.clone()),
span: entry.key_span.or(entry.value.span),
message: format!("{name} has no field {}.", quote(&entry.key)),
data: vec![("field", Node::text(entry.key.clone()))],
},
);
}
Some(Additional::Allowed) | None => {}
}
}
if !self.is_incomplete(path) {
Self::required(id, rule, node, path, &context, &name, out, cap);
}
}
#[expect(
clippy::too_many_arguments,
reason = "the walk's state, passed down unchanged"
)]
fn required(
id: SchemaId,
rule: &crate::schema::SchemaNode,
node: &Node,
path: &Path,
context: &Context<'s>,
name: &str,
out: &mut Vec<Finding>,
cap: usize,
) {
for field in &rule.required {
if out.len() >= cap {
return;
}
if node.get(field).is_none() {
Self::push(
out,
context,
Problem {
code: &SHAPE_MISSING_FIELD,
id,
path: path.clone(),
span: node.span,
message: format!("{name} lacks the required field {}.", quote(field)),
data: vec![("field", Node::text(field.clone()))],
},
);
}
}
}
}
fn sentence(message: String) -> String {
let mut chars = message.chars();
match chars.next() {
Some(first) if first.is_lowercase() => first.to_uppercase().chain(chars).collect(),
_ => message,
}
}
fn deepest(found: &[Finding]) -> usize {
found
.iter()
.map(|finding| finding.diagnostic.path.segments().len())
.max()
.unwrap_or(0)
}
fn integer_bounds(rule: &crate::schema::SchemaNode) -> (i128, i128) {
let (mut low, mut high) = rule
.format
.and_then(Format::integer_range)
.unwrap_or((i128::MIN, i128::MAX));
#[expect(
clippy::cast_possible_truncation,
reason = "a schema bound is a small whole number"
)]
{
if let Some(minimum) = rule.minimum {
low = low.max(minimum.ceil() as i128);
}
if let Some(maximum) = rule.maximum {
high = high.min(maximum.floor() as i128);
}
}
(low, high)
}
fn integer_range_words(low: i128, high: i128) -> String {
match (low == i128::MIN, high == i128::MAX) {
(false, false) => format!("{low}..={high}"),
(false, true) => format!("the integers from {low}"),
(true, false) => format!("the integers up to {high}"),
(true, true) => "the integers".to_owned(),
}
}
#[must_use]
pub fn float_range_words(minimum: Option<f64>, maximum: Option<f64>) -> String {
let show = |value: f64| {
crate::tree::Number::float(value)
.text()
.trim_end_matches(".0")
.to_owned()
};
match (minimum, maximum) {
(Some(low), Some(high)) => format!("{}..={}", show(low), show(high)),
(Some(low), None) => format!("at least {}", show(low)),
(None, Some(high)) => format!("at most {}", show(high)),
(None, None) => "any number".to_owned(),
}
}
#[cfg(test)]
#[path = "shape_tests.rs"]
mod tests;