use crate::codes::{
SHAPE_MISSING_FIELD, SHAPE_MISSING_TAG, SHAPE_NOT_INTEGER, SHAPE_NOT_ONE_OF,
SHAPE_OUT_OF_RANGE, SHAPE_UNKNOWN_FIELD, SHAPE_UNKNOWN_TAG, SHAPE_WRONG_TYPE,
};
use crate::diagnostic::{Diagnostic, Edit, Fix};
use crate::path::{Path, Segment};
use crate::schema::{Schema, SchemaId, Types};
use crate::shape::{Finding, type_words, written};
use crate::suggest::{self, Suggestion};
use crate::tree::{Node, Number, Value};
use crate::write::quote;
#[derive(Clone, Copy, Debug)]
pub struct Context<'a> {
pub schema: Option<&'a Schema>,
pub tree: &'a Node,
pub at: Option<SchemaId>,
pub parent: Option<SchemaId>,
}
impl<'a> Context<'a> {
#[must_use]
pub fn shape(&self) -> Option<(&'a Schema, SchemaId)> {
self.schema.zip(self.at)
}
}
pub trait Advisor {
fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>);
}
impl<F: Fn(&mut Diagnostic, &Context<'_>)> Advisor for F {
fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
self(diagnostic, context);
}
}
#[derive(Clone, Copy, Debug)]
pub struct Misplacement {
pub definition: &'static str,
pub field: &'static str,
pub help: &'static str,
}
#[derive(Clone, Copy, Debug)]
pub struct Misplacements(pub &'static [Misplacement]);
impl Advisor for Misplacements {
fn advise(&self, diagnostic: &mut Diagnostic, _: &Context<'_>) {
if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) {
return;
}
let Some(definition) = diagnostic
.reference
.as_ref()
.map(|reference| reference.definition.clone())
else {
return;
};
let field = diagnostic.path.last_key().unwrap_or_default().to_owned();
if let Some(entry) = self
.0
.iter()
.find(|entry| entry.definition == definition && entry.field == field)
{
diagnostic.help.push(entry.help.to_owned());
}
}
}
#[must_use]
pub fn generic() -> Vec<&'static dyn Advisor> {
vec![
&integer_spelling,
&same_name,
&one_level_off,
&close_name,
&bare_value,
&misspelt_tag,
&missing_field,
&percent_for_fraction,
]
}
#[must_use]
pub fn run(
findings: Vec<Finding>,
schema: Option<&Schema>,
tree: &Node,
advisors: &[&dyn Advisor],
) -> Vec<Diagnostic> {
let generic = generic();
let advised: Vec<Diagnostic> = findings
.into_iter()
.map(|finding| {
let mut diagnostic = finding.diagnostic;
let context = Context {
schema,
tree,
at: finding.schema,
parent: finding.parent,
};
for advisor in advisors.iter().chain(generic.iter()) {
advisor.advise(&mut diagnostic, &context);
}
diagnostic
})
.collect();
without_renamed_missing(advised)
}
fn without_renamed_missing(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
let renamed: Vec<(Path, String)> = diagnostics
.iter()
.filter(|diagnostic| diagnostic.is(&SHAPE_UNKNOWN_FIELD))
.flat_map(|diagnostic| &diagnostic.fixes)
.flat_map(|fix| &fix.edits)
.filter_map(|edit| match edit {
Edit::RenameKey { path, to } => Some((path.parent()?, to.clone())),
_ => None,
})
.collect();
diagnostics
.into_iter()
.filter(|diagnostic| {
!(diagnostic.is(&SHAPE_MISSING_FIELD)
&& diagnostic
.datum("field")
.and_then(Node::as_str)
.is_some_and(|field| {
renamed
.iter()
.any(|(object, to)| *object == diagnostic.path && to == field)
}))
})
.collect()
}
fn property_names(schema: &Schema, id: SchemaId) -> Vec<&str> {
let mut names: Vec<&str> = Vec::new();
for object in schema.objects(id) {
for (name, _) in &schema.node(object).properties {
if !names.contains(&name.as_str()) {
names.push(name);
}
}
}
names
}
fn property(schema: &Schema, id: SchemaId, name: &str) -> Option<SchemaId> {
schema
.objects(id)
.into_iter()
.find_map(|object| schema.node(object).property(name))
}
fn field_of(diagnostic: &Diagnostic) -> Option<(Path, String)> {
let field = diagnostic.path.last_key()?.to_owned();
Some((diagnostic.path.parent()?, field))
}
pub fn misspelt_tag(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if !diagnostic.is(&SHAPE_MISSING_TAG) || diagnostic.has_advice() {
return;
}
let Some(tag) = diagnostic
.datum("tag")
.and_then(Node::as_str)
.map(str::to_owned)
else {
return;
};
let Some(entries) = context.tree.at(&diagnostic.path).and_then(Node::as_map) else {
return;
};
let keys = entries
.iter()
.map(|entry| entry.key.as_str())
.filter(|key| *key != tag);
let Suggestion::One(written) = suggest::closest(&tag, keys) else {
return;
};
diagnostic.help.push(format!(
"{} looks like {} misspelt (a guess)",
quote(written),
quote(&tag)
));
diagnostic.fixes.push(Fix::likely(
format!("rename {} to {}", quote(written), quote(&tag)),
vec![Edit::RenameKey {
path: diagnostic.path.key(written),
to: tag,
}],
));
}
pub fn integer_spelling(diagnostic: &mut Diagnostic, _: &Context<'_>) {
if !diagnostic.is(&SHAPE_NOT_INTEGER) {
return;
}
let Some(whole) = diagnostic
.datum("whole")
.and_then(Node::as_str)
.map(str::to_owned)
else {
return;
};
let Some(number) = Number::parse(&whole) else {
return;
};
diagnostic.help.push(format!(
"the value is the integer {whole}; write it without a fraction"
));
diagnostic.fixes.push(Fix::certain(
format!("write {whole}"),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: Node::number(number),
}],
));
}
pub fn same_name(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) || diagnostic.has_advice() {
return;
}
let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
else {
return;
};
let names = property_names(schema, at);
let matches: Vec<&str> = names
.iter()
.copied()
.filter(|name| suggest::same_name(name, &field))
.collect();
let [name] = matches.as_slice() else {
return;
};
diagnostic
.help
.push(format!("the field is spelt {}", quote(name)));
let taken = context
.tree
.at(&object)
.and_then(|node| node.get(name))
.is_some();
if taken {
diagnostic.help.push(format!(
"{} is already given; remove one of the two",
quote(name)
));
} else {
diagnostic.fixes.push(Fix::certain(
format!("rename {} to {}", quote(&field), quote(name)),
vec![Edit::RenameKey {
path: diagnostic.path.clone(),
to: (*name).to_owned(),
}],
));
}
}
pub fn one_level_off(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if !diagnostic.is(&SHAPE_UNKNOWN_FIELD) || diagnostic.has_advice() {
return;
}
let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
else {
return;
};
let children: Vec<&str> = property_names(schema, at)
.into_iter()
.filter(|child| {
property(schema, at, child)
.is_some_and(|child_id| property(schema, child_id, &field).is_some())
})
.collect();
if let [child] = children.as_slice() {
diagnostic.help.push(format!(
"{} is a field of {}, one level down",
quote(&field),
quote(child)
));
let child_path = object.key(*child);
let to = child_path.key(field.clone());
let mut edits = Vec::new();
match context.tree.at(&child_path) {
Some(node) if node.get(&field).is_some() => return,
Some(node) if matches!(node.value, Value::Map(_)) => {}
Some(_) => return,
None => edits.push(Edit::Insert {
path: child_path,
value: Node::map(Vec::<(String, Node)>::new()),
}),
}
edits.push(Edit::Move {
from: diagnostic.path.clone(),
to,
});
diagnostic.fixes.push(Fix::likely(
format!("move {} into {}", quote(&field), quote(child)),
edits,
));
return;
}
let Some(parent) = context.parent else {
return;
};
if property(schema, parent, &field).is_none() || !matches!(object.last(), Some(Segment::Key(_)))
{
return;
}
let Some(above) = object.parent() else {
return;
};
diagnostic
.help
.push(format!("{} is a field of the object above", quote(&field)));
if context
.tree
.at(&above)
.and_then(|node| node.get(&field))
.is_none()
{
diagnostic.fixes.push(Fix::likely(
format!("move {} up one level", quote(&field)),
vec![Edit::Move {
from: diagnostic.path.clone(),
to: above.key(field),
}],
));
}
}
pub fn close_name(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if diagnostic.has_advice() {
return;
}
if diagnostic.is(&SHAPE_UNKNOWN_FIELD) {
let (Some((schema, at)), Some((object, field))) = (context.shape(), field_of(diagnostic))
else {
return;
};
let present = context.tree.at(&object);
let names: Vec<&str> = property_names(schema, at)
.into_iter()
.filter(|name| present.and_then(|node| node.get(name)).is_none())
.collect();
match suggest::closest(&field, names.iter().copied()) {
Suggestion::One(name) => {
diagnostic
.help
.push(format!("did you mean {}?", quote(name)));
diagnostic.fixes.push(Fix::likely(
format!("rename {} to {}", quote(&field), quote(name)),
vec![Edit::RenameKey {
path: diagnostic.path.clone(),
to: name.to_owned(),
}],
));
}
Suggestion::Several(list) => diagnostic.help.push(format!(
"did you mean one of {}?",
suggest::listed(list, suggest::MAX_CANDIDATES)
)),
Suggestion::None => {
let all = property_names(schema, at);
if !all.is_empty() {
let owner = diagnostic.reference.as_ref().map_or_else(
|| "this object".to_owned(),
|reference| reference.definition.clone(),
);
diagnostic.help.push(format!(
"{owner} has the fields {}",
suggest::listed(all, 24)
));
}
}
}
return;
}
if !(diagnostic.is(&SHAPE_UNKNOWN_TAG) || diagnostic.is(&SHAPE_NOT_ONE_OF)) {
return;
}
let Some(found) = diagnostic
.datum("found")
.and_then(Node::as_str)
.map(str::to_owned)
else {
return;
};
let allowed: Vec<String> = diagnostic
.datum("allowed")
.and_then(Node::as_list)
.unwrap_or_default()
.iter()
.filter_map(|value| value.as_str().map(str::to_owned))
.collect();
match suggest::closest(&found, allowed.iter().map(String::as_str)) {
Suggestion::One(name) => {
diagnostic
.help
.push(format!("did you mean {}?", quote(name)));
diagnostic.fixes.push(Fix::likely(
format!("write {}", quote(name)),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: Node::text(name),
}],
));
}
Suggestion::Several(list) => diagnostic.help.push(format!(
"did you mean one of {}?",
suggest::listed(list, suggest::MAX_CANDIDATES)
)),
Suggestion::None => {}
}
}
fn tagged_unions(schema: &Schema, id: SchemaId) -> Vec<(String, Vec<SchemaId>)> {
let mut unions = Vec::new();
for candidate in std::iter::once(schema.resolve(id)).chain(schema.non_null_forms(id)) {
let node = schema.node(candidate);
if let Some(tag) = &node.tag
&& !unions
.iter()
.any(|(_, forms): &(String, Vec<SchemaId>)| *forms == node.forms)
{
unions.push((tag.clone(), node.forms.clone()));
}
}
unions
}
pub fn bare_value(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if !diagnostic.is(&SHAPE_WRONG_TYPE) || diagnostic.has_advice() {
return;
}
let Some((schema, at)) = context.shape() else {
return;
};
let Some(value) = context.tree.at(&diagnostic.path) else {
return;
};
if matches!(value.value, Value::Map(_) | Value::Null) {
return;
}
let mut wraps = Vec::new();
for (tag, forms) in tagged_unions(schema, at) {
for form in forms {
let form = schema.resolve(form);
let node = schema.node(form);
let Some(tag_value) = schema.tag_value(form, &tag) else {
continue;
};
let others: Vec<&(String, SchemaId)> = node
.properties
.iter()
.filter(|(name, _)| *name != tag)
.collect();
let fits: Vec<&&(String, SchemaId)> = others
.iter()
.filter(|(_, property)| schema.types(*property).admits(value))
.collect();
let required_ok = node
.required
.iter()
.all(|name| *name == tag || fits.first().is_some_and(|(fit, _)| fit == name));
if let [(name, property)] = fits.as_slice()
&& required_ok
{
let exact = schema.types(*property).intersects(Types::of(value));
wraps.push((
exact,
Node::map([
(tag.clone(), tag_value.clone()),
(name.clone(), value.clone().without_spans()),
]),
));
}
}
}
if wraps.len() > 1 {
wraps.retain(|(exact, _)| *exact);
}
let [(_, wrapped)] = wraps.as_slice() else {
return;
};
diagnostic.help.push(format!(
"a bare value is written in its tagged form here: {}",
written(wrapped)
));
diagnostic.fixes.push(Fix::likely(
format!("write {}", written(wrapped)),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: wrapped.clone(),
}],
));
}
pub fn missing_field(diagnostic: &mut Diagnostic, context: &Context<'_>) {
if !diagnostic.is(&SHAPE_MISSING_FIELD) || diagnostic.has_advice() {
return;
}
let Some((schema, at)) = context.shape() else {
return;
};
let Some(field) = diagnostic
.datum("field")
.and_then(Node::as_str)
.map(str::to_owned)
else {
return;
};
let Some(property) = property(schema, at, &field) else {
return;
};
diagnostic.help.push(format!(
"{} takes {}",
quote(&field),
describe(schema, property)
));
if let Some(smallest) = smallest(schema, property, 0) {
diagnostic
.help
.push(format!("its smallest form is {}", written(&smallest)));
}
}
pub fn percent_for_fraction(diagnostic: &mut Diagnostic, _: &Context<'_>) {
if !diagnostic.is(&SHAPE_OUT_OF_RANGE) || diagnostic.has_advice() {
return;
}
let number = |key| {
diagnostic
.datum(key)
.and_then(Node::as_number)
.map(Number::as_f64)
};
let (Some(found), Some(minimum), Some(maximum)) =
(number("found"), number("minimum"), number("maximum"))
else {
return;
};
if minimum < 0.0 || (maximum - 1.0).abs() > f64::EPSILON || found <= 1.0 || found > 100.0 {
return;
}
let fraction = Node::float(found / 100.0);
diagnostic.help.push(format!(
"the range is a fraction; if {} is a percentage, write {}",
written(&Node::float(found)),
written(&fraction)
));
diagnostic.fixes.push(Fix::likely(
format!("write {}", written(&fraction)),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: fraction,
}],
));
}
#[must_use]
pub fn describe(schema: &Schema, id: SchemaId) -> String {
if let Some(definition) = schema.definition_of(id) {
return format!("a {}", definition.name);
}
if let Some(constants) = schema.constants(id) {
let values: Vec<String> = constants.iter().map(|value| written(value)).collect();
return format!("one of {}", values.join(", "));
}
let forms = schema.non_null_forms(id);
if let [only] = forms.as_slice()
&& *only != schema.resolve(id)
{
return format!("{} or null", describe(schema, *only));
}
let node = schema.node(schema.resolve(id));
let mut words = type_words(schema.types(id));
if let Some(format) = node.format {
words = format!("{words} ({})", format.name());
}
words
}
#[must_use]
pub fn smallest(schema: &Schema, id: SchemaId, depth: usize) -> Option<Node> {
if depth > 6 {
return None;
}
let id = schema.resolve(id);
let node = schema.node(id);
if let Some(constant) = &node.constant {
return Some(constant.clone());
}
if let Some(choices) = &node.choices {
return choices.first().cloned();
}
if let Some(default) = &node.default {
return Some(default.clone());
}
if let Some(target) = node.reference {
return smallest(schema, target, depth + 1);
}
if let Some(first) = schema.non_null_forms(id).first()
&& *first != id
{
return smallest(schema, *first, depth + 1);
}
let types = node.types.unwrap_or_else(|| schema.types(id));
if types.contains(Types::OBJECT) || !node.properties.is_empty() {
let mut entries = Vec::new();
for name in &node.required {
let property = node.property(name)?;
entries.push((name.clone(), smallest(schema, property, depth + 1)?));
}
return Some(Node::map(entries));
}
if types.contains(Types::ARRAY) {
let count = node.min_items.unwrap_or(0);
if count == 0 {
return Some(Node::list(Vec::new()));
}
let item = match node.items {
Some(crate::schema::Additional::Schema(item)) => smallest(schema, item, depth + 1)?,
_ => return None,
};
return Some(Node::list(vec![item; count]));
}
if types.contains(Types::NUMBER) {
return Some(
node.minimum
.map_or_else(|| Node::integer(0), |minimum| Node::float(minimum.max(0.0))),
);
}
if types.contains(Types::INTEGER) {
#[expect(
clippy::cast_possible_truncation,
reason = "a schema bound is a small whole number"
)]
return Some(Node::integer(
node.minimum
.map_or(0, |minimum| minimum.max(0.0).ceil() as i64),
));
}
if types.contains(Types::BOOLEAN) {
return Some(Node::bool(false));
}
if types.contains(Types::STRING) && node.min_length.unwrap_or(0) == 0 {
return Some(Node::text(""));
}
if types.contains(Types::NULL) {
return Some(Node::null());
}
None
}
const SERDE_UNKNOWN_FIELD: &str = "unknown field `";
const SERDE_UNKNOWN_VARIANT: &str = "unknown variant `";
#[must_use]
pub fn serde_refusal(diagnostic: Diagnostic, tree: &Node) -> Diagnostic {
if let Some((field, expected)) = quoted_after(&diagnostic.message, SERDE_UNKNOWN_FIELD) {
return unknown_field_refusal(diagnostic, tree, &field, &expected);
}
if let Some((value, expected)) = quoted_after(&diagnostic.message, SERDE_UNKNOWN_VARIANT) {
return unknown_variant_refusal(diagnostic, tree, &value, &expected);
}
diagnostic
}
fn unknown_field_refusal(
mut diagnostic: Diagnostic,
tree: &Node,
field: &str,
expected: &[String],
) -> Diagnostic {
let Some((path, key_span)) = tree
.at(&diagnostic.path)
.and_then(|object| below(object, &diagnostic.path, |key, _| key == Some(field)))
else {
return diagnostic;
};
let present: Vec<&str> = path
.parent()
.and_then(|object| tree.at(&object))
.and_then(Node::as_map)
.map(|entries| entries.iter().map(|entry| entry.key.as_str()).collect())
.unwrap_or_default();
diagnostic.path = path;
diagnostic.span = key_span.or(diagnostic.span);
let free: Vec<&str> = expected
.iter()
.map(String::as_str)
.filter(|name| !present.contains(name))
.collect();
let same: Vec<&str> = free
.iter()
.copied()
.filter(|name| suggest::same_name(name, field))
.collect();
let at = diagnostic.path.clone();
let rename = |to: &str| Edit::RenameKey {
path: at.clone(),
to: to.to_owned(),
};
if let [name] = same.as_slice() {
let fix = Fix::certain(
format!("rename {} to {}", quote(field), quote(name)),
vec![rename(name)],
);
diagnostic
.help
.push(format!("the field is spelt {}", quote(name)));
diagnostic.fixes.push(fix);
return diagnostic;
}
let fix = |name: &str| {
Fix::likely(
format!("rename {} to {}", quote(field), quote(name)),
vec![rename(name)],
)
};
suggest_close(&mut diagnostic, field, &free, fix);
diagnostic
}
fn unknown_variant_refusal(
mut diagnostic: Diagnostic,
tree: &Node,
value: &str,
expected: &[String],
) -> Diagnostic {
let Some((path, _)) = tree.at(&diagnostic.path).and_then(|object| {
below(object, &diagnostic.path, |_, node| {
node.as_str() == Some(value)
})
}) else {
return diagnostic;
};
diagnostic.span = tree
.at(&path)
.and_then(|node| node.span)
.or(diagnostic.span);
diagnostic.path = path;
let names: Vec<&str> = expected.iter().map(String::as_str).collect();
let at = diagnostic.path.clone();
let fix = |name: &str| {
Fix::likely(
format!("write {}", quote(name)),
vec![Edit::Replace {
path: at.clone(),
value: Node::text(name),
}],
)
};
suggest_close(&mut diagnostic, value, &names, fix);
diagnostic
}
fn suggest_close(
diagnostic: &mut Diagnostic,
written: &str,
names: &[&str],
fix: impl Fn(&str) -> Fix,
) {
match suggest::closest(written, names.iter().copied()) {
Suggestion::One(name) => {
diagnostic
.help
.push(format!("did you mean {}?", quote(name)));
diagnostic.fixes.push(fix(name));
}
Suggestion::Several(list) => diagnostic.help.push(format!(
"did you mean one of {}?",
suggest::listed(list, suggest::MAX_CANDIDATES)
)),
Suggestion::None => {}
}
}
fn quoted_after(message: &str, opening: &str) -> Option<(String, Vec<String>)> {
let start = message.find(opening)? + opening.len();
let (name, rest) = message[start..].split_once('`')?;
let expected = rest
.split_once("expected")
.map(|(_, list)| {
list.split('`')
.skip(1)
.step_by(2)
.map(str::to_owned)
.collect()
})
.unwrap_or_default();
Some((name.to_owned(), expected))
}
pub fn below(
object: &Node,
at: &Path,
wanted: impl Fn(Option<&str>, &Node) -> bool,
) -> Option<(Path, Option<crate::Span>)> {
let mut level = vec![(object, at.clone())];
while !level.is_empty() {
let mut found = Vec::new();
let mut next = Vec::new();
for (node, path) in level {
match &node.value {
Value::Map(entries) => {
for entry in entries {
let inner = path.key(entry.key.clone());
if wanted(Some(&entry.key), &entry.value) {
found.push((inner.clone(), entry.key_span));
}
next.push((&entry.value, inner));
}
}
Value::List(items) => {
for (index, item) in items.iter().enumerate() {
let inner = path.index(index);
if wanted(None, item) {
found.push((inner.clone(), item.span));
}
next.push((item, inner));
}
}
_ => {}
}
}
match found.len() {
0 => level = next,
1 => return found.pop(),
_ => return None,
}
}
None
}
#[cfg(test)]
#[path = "advise_tests.rs"]
mod tests;