pub(crate) mod v211;
pub(crate) mod v221;
mod build;
#[cfg(test)]
mod test_nearest_spellings;
#[cfg(test)]
mod test_walk;
use std::{borrow::Cow, collections::BTreeSet};
use rust_decimal::Decimal;
use crate::{
Caveat, Verdict, datetime, json, number,
warning::{self, IntoCaveat as _},
};
pub(crate) trait FromSchema<'buf, Source>: Sized {
type Warning: warning::Warning;
fn from_schema(source: &Source) -> Verdict<Self, Self::Warning>;
}
pub(crate) trait HasElement<'buf> {
fn element(&self) -> &json::Element<'buf>;
}
#[derive(Clone, Copy)]
enum Schema {
Scalar(Scalar),
Object(&'static Object),
NonSpecObject(&'static Object),
Price(&'static Object),
Array {
item: &'static Schema,
cardinality: Cardinality,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Cardinality {
ZeroOrMore,
OneOrMore,
}
impl std::fmt::Display for Cardinality {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Cardinality::ZeroOrMore => f.write_str("zero or more"),
Cardinality::OneOrMore => f.write_str("one or more"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Scalar {
String,
Date,
Time,
StringMax(usize),
Enum(&'static [&'static str]),
Number,
Boolean,
Any,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Integrity<T> {
Ok(T),
Missing(warning::Element),
Err(warning::Element),
}
impl<T> Integrity<Option<T>> {
pub(crate) fn map_some<U, F: FnOnce(&T) -> U>(&self, op: F) -> Option<U> {
match self {
Integrity::Ok(Some(v)) => Some(op(v)),
Integrity::Ok(None) | Integrity::Missing(_) | Integrity::Err(_) => None,
}
}
}
macro_rules! ir_object {
($ty:ident { $($field:ident),* $(,)? }) => {
impl<'buf> $ty<'buf> {
pub(super) fn new(elem: &json::Element<'buf>) -> Self {
Self {
$($field: super::Integrity::Missing(
$crate::warning::Element::from_json(elem),
),)*
}
}
}
};
(@keep_element $ty:ident { $($field:ident),* $(,)? }) => {
impl<'buf> $ty<'buf> {
pub(super) fn new(elem: &json::Element<'buf>) -> Self {
Self {
elem: elem.clone(),
$($field: super::Integrity::Missing(
$crate::warning::Element::from_json(elem),
),)*
}
}
}
impl<'buf> super::HasElement<'buf> for $ty<'buf> {
fn element(&self) -> &json::Element<'buf> {
&self.elem
}
}
};
}
pub(crate) use ir_object;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BuilderKind {
Ignore,
V221Tariff,
V221Element,
V221PriceComponent,
V221Restrictions,
V221Price,
V221Cdr,
V221CdrLocation,
V221ChargingPeriod,
V221CdrDimension,
V211Tariff,
V211Element,
V211PriceComponent,
V211Restrictions,
V211Cdr,
V211Location,
V211ChargingPeriod,
V211CdrDimension,
}
#[derive(Clone, Copy)]
struct Object {
fields: &'static [Field],
kind: BuilderKind,
}
#[derive(Clone, Copy)]
struct Field {
name: &'static str,
presence: Presence,
schema: Schema,
}
impl Field {
const fn required(name: &'static str, scalar: Scalar) -> Self {
Self {
name,
presence: Presence::Required,
schema: Schema::Scalar(scalar),
}
}
const fn required_array(name: &'static str, item: &'static Schema) -> Self {
Self {
name,
presence: Presence::Required,
schema: Schema::Array {
item,
cardinality: Cardinality::OneOrMore,
},
}
}
const fn required_object(name: &'static str, schema: &'static Object) -> Self {
Self {
name,
presence: Presence::Required,
schema: Schema::Object(schema),
}
}
const fn required_price(name: &'static str, schema: &'static Object) -> Self {
Self {
name,
presence: Presence::Required,
schema: Schema::Price(schema),
}
}
const fn optional(name: &'static str, scalar: Scalar) -> Self {
Self {
name,
presence: Presence::Optional,
schema: Schema::Scalar(scalar),
}
}
const fn optional_array(name: &'static str, item: &'static Schema) -> Self {
Self {
name,
presence: Presence::Optional,
schema: Schema::Array {
item,
cardinality: Cardinality::ZeroOrMore,
},
}
}
const fn optional_object(name: &'static str, schema: &'static Object) -> Self {
Self {
name,
presence: Presence::Optional,
schema: Schema::Object(schema),
}
}
const fn optional_price(name: &'static str, schema: &'static Object) -> Self {
Self {
name,
presence: Presence::Optional,
schema: Schema::Price(schema),
}
}
const fn non_spec(name: &'static str, scalar: Scalar) -> Self {
Self {
name,
presence: Presence::NonSpec,
schema: Schema::Scalar(scalar),
}
}
const fn non_spec_object(name: &'static str, schema: &'static Object) -> Self {
Self {
name,
presence: Presence::NonSpec,
schema: Schema::NonSpecObject(schema),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Presence {
Required,
Optional,
NonSpec,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Warning {
UnexpectedField,
MisspelledField {
expected: Vec<&'static str>,
},
NonSpecField,
DuplicateField,
FieldNameContainsEscapeCodes,
FieldNameInvalidEscape,
MissingField {
name: &'static str,
},
NullField,
InvalidType {
expected: json::ValueKind,
actual: json::ValueKind,
},
ExcessivePrecision {
max: u32,
scale: u32,
},
StringTooLong {
max: usize,
len: usize,
},
InvalidValue {
expected: &'static [&'static str],
actual: String,
},
MisspelledValue {
expected: Vec<&'static str>,
actual: String,
},
IncorrectCase {
expected: &'static str,
actual: String,
},
IncorrectFormat {
expected: String,
actual: String,
},
Cardinality,
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::UnexpectedField => warning::Id::from_static("unexpected_field"),
Self::MisspelledField { expected } => {
warning::Id::from_string(format!("misspelled_field({})", expected.join(", ")))
}
Self::NonSpecField => warning::Id::from_static("non_spec_field"),
Self::MissingField { name } => {
warning::Id::from_string(format!("missing_field({name})"))
}
Self::NullField => warning::Id::from_static("null_field"),
Self::DuplicateField => warning::Id::from_static("duplicate_field"),
Self::FieldNameContainsEscapeCodes => {
warning::Id::from_static("field_name_contains_escape_codes")
}
Self::FieldNameInvalidEscape => warning::Id::from_static("field_name_invalid_escape"),
Self::InvalidType {
actual,
expected: _,
} => warning::Id::from_string(format!("invalid_type({actual})")),
Self::ExcessivePrecision { max: _, scale: _ } => {
warning::Id::from_static("excessive_precision")
}
Self::StringTooLong { max: _, len: _ } => warning::Id::from_static("string_too_long"),
Self::InvalidValue {
actual,
expected: _,
} => warning::Id::from_string(format!("invalid_value({actual})")),
Self::MisspelledValue {
expected,
actual: _,
} => warning::Id::from_string(format!("misspelled_value({})", expected.join(", "))),
Self::IncorrectCase {
expected: _,
actual: _,
} => warning::Id::from_static("incorrect_case"),
Self::IncorrectFormat {
expected: _,
actual: _,
} => warning::Id::from_static("incorrect_format"),
Self::Cardinality => warning::Id::from_static("cardinality(one or more)"),
}
}
}
impl std::fmt::Display for Warning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnexpectedField => f.write_str("field is not part of the schema"),
Self::MisspelledField { expected } => write!(
f,
"field is not part of the schema, but may be a misspelling of `{}`",
expected.join("` or `")
),
Self::NonSpecField => f.write_str(
"field is not defined by the OCPI version of this document; it is read anyway",
),
Self::MissingField { name } => write!(f, "required field `{name}` is missing"),
Self::NullField => f.write_str(
"field is `null`. `null` fields have no semantic meaning for OCPI objects",
),
Self::DuplicateField => f.write_str(
"field appears more than once in this object; a later occurrence is the value used",
),
Self::FieldNameContainsEscapeCodes => {
f.write_str("field name contains escape codes, which no OCPI field name needs")
}
Self::FieldNameInvalidEscape => {
f.write_str("field name contains an escape that fails to decode")
}
Self::InvalidType { expected, actual } => {
write!(f, "expected {expected} found {actual}")
}
Self::ExcessivePrecision { max, scale } => {
write!(
f,
"number has `{scale}` decimals, but the maximum allowed is `{max}`"
)
}
Self::StringTooLong { max, len } => {
write!(
f,
"string is `{len}` characters, but the maximum allowed is `{max}`"
)
}
Self::InvalidValue { expected, actual } => {
write!(
f,
"value `{actual}` is not one of the permitted values: {}",
expected.join(", ")
)
}
Self::MisspelledValue { expected, actual } => write!(
f,
"value `{actual}` is not one of the permitted values, but may be a misspelling of `{}`",
expected.join("` or `")
),
Self::IncorrectCase { expected, actual } => {
write!(
f,
"value `{actual}` is not written in the case the spec uses: `{expected}`"
)
}
Self::IncorrectFormat { expected, actual } => {
write!(
f,
"value `{actual}` is not written in the format the spec uses: `{expected}`"
)
}
Self::Cardinality => f.write_str("expected one or more elements, found 0"),
}
}
}
impl warning::Set<Warning> {
pub fn unexpected_fields(&self) -> json::PathSet<'_> {
let mut paths = BTreeSet::new();
for group in self {
let (element, group_warnings) = group.to_parts();
let has_unexpected_field = group_warnings
.iter()
.any(|warning| matches!(warning, Warning::UnexpectedField));
if has_unexpected_field {
paths.insert(&element.path);
}
}
json::PathSet::new(paths)
}
pub fn non_spec_fields(&self) -> json::PathSet<'_> {
let mut paths = BTreeSet::new();
for group in self {
let (element, group_warnings) = group.to_parts();
let has_non_spec_field = group_warnings
.iter()
.any(|warning| matches!(warning, Warning::NonSpecField));
if has_non_spec_field {
paths.insert(&element.path);
}
}
json::PathSet::new(paths)
}
pub fn missing_fields(&self) -> json::PathSet<'_> {
let mut paths = BTreeSet::new();
for group in self {
let (element, group_warnings) = group.to_parts();
let has_missing_field = group_warnings
.iter()
.any(|warning| matches!(warning, Warning::MissingField { name: _ }));
if has_missing_field {
paths.insert(&element.path);
}
}
json::PathSet::new(paths)
}
pub fn remove_unexpected_fields(&mut self) {
self.retain(|warning| !matches!(warning, Warning::UnexpectedField));
}
pub fn remove_missing_fields(&mut self) {
self.retain(|warning| !matches!(warning, Warning::MissingField { name: _ }));
}
pub fn remove_invalid_types(&mut self) {
self.retain(|warning| {
!matches!(
warning,
Warning::InvalidType {
expected: _,
actual: _
}
)
});
}
pub fn remove_null_fields(&mut self) {
self.retain(|warning| !matches!(warning, Warning::NullField));
}
pub fn remove_cardinalities(&mut self) {
self.retain(|warning| !matches!(warning, Warning::Cardinality));
}
pub fn remove_string_too_longs(&mut self) {
self.retain(|warning| !matches!(warning, Warning::StringTooLong { max: _, len: _ }));
}
}
static ANY: Schema = Schema::Scalar(Scalar::Any);
enum Step<'a, 'buf> {
Visit {
elem: &'a json::Element<'buf>,
schema: &'a Schema,
slot: Slot,
},
Close { slot: Slot },
}
#[derive(Clone, Copy)]
enum Slot {
Root,
Field { name: &'static str },
Item,
Ignore,
}
fn walk<'a, 'buf>(
doc: &'a json::Document<'buf>,
schema: &'a Schema,
) -> Caveat<build::Node<'buf>, Warning> {
let mut warnings = warning::Set::new();
let mut builders: Vec<build::Node<'buf>> = Vec::new();
let mut root = build::Node::Ignore;
let mut stack = vec![Step::Visit {
elem: doc.root(),
schema,
slot: Slot::Root,
}];
while let Some(step) = stack.pop() {
match step {
Step::Visit { elem, schema, slot } => {
if let json::Value::Null = elem.value() {
warnings.insert(elem, Warning::NullField);
root.route_to_parent(
&mut builders,
slot,
Integrity::Missing(warning::Element::from_json(elem)),
);
continue;
}
match schema {
Schema::Scalar(Scalar::Any) => {
enqueue_all_children(&mut stack, elem);
root.route_to_parent(
&mut builders,
slot,
Integrity::Missing(warning::Element::from_json(elem)),
);
}
Schema::Scalar(scalar) => {
let built = check_scalar(&mut warnings, elem, *scalar);
root.route_to_parent(&mut builders, slot, built);
}
Schema::Array { item, cardinality } => {
let type_expectation = open_array(
&mut stack,
&mut builders,
&mut warnings,
elem,
item,
*cardinality,
slot,
);
if type_expectation.is_type_invalid() {
root.route_to_parent(
&mut builders,
slot,
Integrity::Err(warning::Element::from_json(elem)),
);
}
}
Schema::Object(object) => {
let type_expectation = open_object(
&mut stack,
&mut builders,
&mut warnings,
elem,
object,
slot,
Unlisted::Report,
);
if type_expectation.is_type_invalid() {
root.route_to_parent(
&mut builders,
slot,
Integrity::Err(warning::Element::from_json(elem)),
);
}
}
Schema::NonSpecObject(object) => {
let type_expectation = open_object(
&mut stack,
&mut builders,
&mut warnings,
elem,
object,
slot,
Unlisted::Ignore,
);
if type_expectation.is_type_invalid() {
root.route_to_parent(
&mut builders,
slot,
Integrity::Err(warning::Element::from_json(elem)),
);
}
}
Schema::Price(object) => {
if let Some(node) = price_from_number(&mut warnings, elem) {
root.route_to_parent(&mut builders, slot, Integrity::Ok(node));
} else {
let type_expectation = open_object(
&mut stack,
&mut builders,
&mut warnings,
elem,
object,
slot,
Unlisted::Report,
);
if type_expectation.is_type_invalid() {
root.route_to_parent(
&mut builders,
slot,
Integrity::Err(warning::Element::from_json(elem)),
);
}
}
}
}
}
Step::Close { slot } => {
if let Some(node) = builders.pop() {
root.route_to_parent(&mut builders, slot, Integrity::Ok(node));
}
}
}
}
root.into_caveat(warnings)
}
fn check_scalar<'buf>(
warnings: &mut warning::Set<Warning>,
elem: &json::Element<'buf>,
scalar: Scalar,
) -> Integrity<build::Node<'buf>> {
let expected = match scalar {
Scalar::String | Scalar::StringMax(_) | Scalar::Enum(_) | Scalar::Date | Scalar::Time => {
json::ValueKind::String
}
Scalar::Number => json::ValueKind::Number,
Scalar::Boolean => json::ValueKind::Bool,
Scalar::Any => return Integrity::Missing(warning::Element::from_json(elem)),
};
let actual = elem.value().kind();
let string_encoded_number =
expected == json::ValueKind::Number && actual == json::ValueKind::String;
if actual != expected && !string_encoded_number {
warnings.insert(elem, Warning::InvalidType { expected, actual });
return Integrity::Err(warning::Element::from_json(elem));
}
match scalar {
Scalar::String => {
let json::Value::String(text) = elem.value() else {
unreachable!("kind gate guarantees a string");
};
Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
}
Scalar::Date => {
let json::Value::String(text) = elem.value() else {
unreachable!("kind gate guarantees a string");
};
check_date_format(elem, *text, warnings);
Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
}
Scalar::Time => {
let json::Value::String(text) = elem.value() else {
unreachable!("kind gate guarantees a string");
};
check_time_format(elem, *text, warnings);
Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
}
Scalar::StringMax(max) => {
let json::Value::String(text) = elem.value() else {
unreachable!("kind gate guarantees a string");
};
let len = text.decode_escapes().ignore_warnings().chars().count();
if len > max {
warnings.insert(elem, Warning::StringTooLong { max, len });
}
Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
}
Scalar::Enum(variants) => {
let Some(value) = elem.value().to_raw_str() else {
return Integrity::Err(warning::Element::from_json(elem));
};
let matched = variants
.iter()
.copied()
.find(|&s| value.eq_any_escape_aware_ignore_ascii_case(&[s]));
let Some(canonical) = matched else {
let decoded = value.decode_escapes().ignore_warnings();
let nearest = match &decoded {
Cow::Borrowed(raw) if raw.contains('\\') => Vec::new(),
Cow::Borrowed(_) | Cow::Owned(_) => {
nearest_spellings(&decoded, variants.iter().copied())
}
};
let actual = value.as_unescaped_str().to_owned();
let warning = match nearest.len() {
1..=MISSPELLED_VALUE_MAX_EXPECTED => Warning::MisspelledValue {
expected: nearest,
actual,
},
_ => Warning::InvalidValue {
expected: variants,
actual,
},
};
warnings.insert(elem, warning);
return Integrity::Err(warning::Element::from_json(elem));
};
if !value.eq_any_escape_aware(&[canonical]) {
warnings.insert(
elem,
Warning::IncorrectCase {
expected: canonical,
actual: value.as_unescaped_str().to_owned(),
},
);
}
Integrity::Ok(build::Node::Enum(elem.clone(), canonical))
}
Scalar::Number => {
match elem.value() {
json::Value::Number(digits) => {
check_precision(elem, digits, warnings);
Integrity::Ok(build::Node::Number(Number::Number {
elem: elem.clone(),
digits,
}))
}
json::Value::String(text) => {
let decoded = text.decode_escapes().ignore_warnings();
check_precision(elem, &decoded, warnings);
Integrity::Ok(build::Node::Number(Number::StringEncoded {
elem: elem.clone(),
value: *text,
}))
}
json::Value::Null
| json::Value::True
| json::Value::False
| json::Value::Array(_)
| json::Value::Object(_) => unreachable!(
"kind gate rejects any value that is neither a number nor a string"
),
}
}
Scalar::Boolean => match elem.value() {
json::Value::True => Integrity::Ok(build::Node::Bool(true)),
json::Value::False => Integrity::Ok(build::Node::Bool(false)),
json::Value::Null
| json::Value::Number(_)
| json::Value::String(_)
| json::Value::Array(_)
| json::Value::Object(_) => unreachable!("kind gate rejects any value but a boolean"),
},
Scalar::Any => Integrity::Missing(warning::Element::from_json(elem)),
}
}
fn check_precision(elem: &json::Element<'_>, digits: &str, warnings: &mut warning::Set<Warning>) {
let Ok(decimal) = Decimal::from_str_exact(digits) else {
return;
};
let scale = decimal.scale();
if scale > number::SCALE {
warnings.insert(
elem,
Warning::ExcessivePrecision {
max: number::SCALE,
scale,
},
);
}
}
fn check_date_format(
elem: &json::Element<'_>,
text: json::RawStr<'_>,
warnings: &mut warning::Set<Warning>,
) {
if text.lexical_issues().escapes {
return;
}
let actual = text.as_unescaped_str();
let Ok(date) = datetime::parse_date(actual) else {
return;
};
let expected = date.format("%Y-%m-%d").to_string();
if actual != expected {
warnings.insert(
elem,
Warning::IncorrectFormat {
expected,
actual: actual.to_owned(),
},
);
}
}
fn check_time_format(
elem: &json::Element<'_>,
text: json::RawStr<'_>,
warnings: &mut warning::Set<Warning>,
) {
if text.lexical_issues().escapes {
return;
}
let actual = text.as_unescaped_str();
let Ok(time) = datetime::parse_time(actual) else {
return;
};
let expected = time.format("%H:%M").to_string();
if actual != expected {
warnings.insert(
elem,
Warning::IncorrectFormat {
expected,
actual: actual.to_owned(),
},
);
}
}
fn price_from_number<'buf>(
warnings: &mut warning::Set<Warning>,
elem: &json::Element<'buf>,
) -> Option<build::Node<'buf>> {
let json::Value::Number(digits) = elem.value() else {
return None;
};
warnings.insert(
elem,
Warning::InvalidType {
expected: json::ValueKind::Object,
actual: json::ValueKind::Number,
},
);
Some(build::Node::Price(v221::Price::from_number(
elem.clone(),
digits,
)))
}
#[derive(Copy, Clone)]
enum TypeExpectation {
Satisfied,
Invalid,
}
impl TypeExpectation {
fn is_type_invalid(self) -> bool {
matches!(self, Self::Invalid)
}
}
#[derive(Copy, Clone)]
enum Unlisted {
Report,
Ignore,
}
fn open_object<'a, 'buf>(
stack: &mut Vec<Step<'a, 'buf>>,
builders: &mut Vec<build::Node<'buf>>,
warnings: &mut warning::Set<Warning>,
elem: &'a json::Element<'buf>,
object: &'a Object,
slot: Slot,
unlisted: Unlisted,
) -> TypeExpectation {
debug_assert!(
object
.fields
.windows(2)
.all(|pair| matches!(pair, [a, b] if a.name <= b.name)),
"Object::fields must be sorted alphabetically by name"
);
let json::Value::Object(fields) = elem.value() else {
warnings.insert(
elem,
Warning::InvalidType {
expected: json::ValueKind::Object,
actual: elem.value().kind(),
},
);
return TypeExpectation::Invalid;
};
builders.push(build::empty(object.kind, elem));
stack.push(Step::Close { slot });
let mut seen = vec![false; object.fields.len()];
let mut holds_value = vec![false; object.fields.len()];
let mut claimed: BTreeSet<json::Key<'buf>> = BTreeSet::new();
let mut unlisted_fields = Vec::new();
for field in fields.iter().rev() {
let key = field.key().to_key();
if !claimed.insert(key.clone()) {
warnings.insert(field.element(), Warning::DuplicateField);
}
let name = match &key {
json::Key::Plain(name) => *name,
json::Key::Decoded(name) => {
warnings.insert(field.element(), Warning::FieldNameContainsEscapeCodes);
name.as_str()
}
json::Key::Malformed(_) => {
warnings.insert(field.element(), Warning::FieldNameInvalidEscape);
if let Unlisted::Report = unlisted {
warnings.insert(field.element(), Warning::UnexpectedField);
}
continue;
}
};
let Ok(idx) = object.fields.binary_search_by_key(&name, |fd| fd.name) else {
if let Unlisted::Report = unlisted {
unlisted_fields.push((field.element(), name.to_owned()));
}
continue;
};
if let Some(flag) = seen.get_mut(idx) {
*flag = true;
}
if !matches!(field.element().value(), json::Value::Null)
&& let Some(flag) = holds_value.get_mut(idx)
{
*flag = true;
}
if let Some(fd) = object.fields.get(idx) {
if let Presence::NonSpec = fd.presence {
warnings.insert(field.element(), Warning::NonSpecField);
}
stack.push(Step::Visit {
elem: field.element(),
schema: &fd.schema,
slot: Slot::Field { name: fd.name },
});
}
}
for (field, name) in unlisted_fields {
let absent = object
.fields
.iter()
.zip(&holds_value)
.filter(|(_, holds)| !**holds)
.map(|(fd, _)| fd.name);
let expected = nearest_spellings(&name, absent);
let warning = if expected.is_empty() {
Warning::UnexpectedField
} else {
Warning::MisspelledField { expected }
};
warnings.insert(field, warning);
}
for (field, &present) in object.fields.iter().zip(seen.iter()) {
if present {
continue;
}
if let Presence::Required = field.presence {
warnings.insert(elem, Warning::MissingField { name: field.name });
}
build::set_top_field(
builders,
field.name,
Integrity::Missing(warning::Element::from_json(elem)),
);
}
TypeExpectation::Satisfied
}
const TINY_NAME_LEN: usize = 3;
const SHORT_NAME_LEN: usize = 8;
const SHORT_NAME_MAX_EDITS: usize = 1;
const LONG_NAME_MAX_EDITS: usize = 2;
const MISSPELLED_VALUE_MAX_EXPECTED: usize = 4;
fn nearest_spellings(
actual: &str,
candidates: impl IntoIterator<Item = &'static str>,
) -> Vec<&'static str> {
let actual = spelling_key(actual);
let mut nearest = Vec::new();
let mut nearest_distance = usize::MAX;
for candidate in candidates {
let candidate_key = spelling_key(candidate);
let shorter_len = actual.len().min(candidate_key.len());
let longer_len = actual.len().max(candidate_key.len());
let max_distance = if longer_len < TINY_NAME_LEN {
0
} else if shorter_len < SHORT_NAME_LEN {
SHORT_NAME_MAX_EDITS
} else {
LONG_NAME_MAX_EDITS
};
let allowed_distance = max_distance.min(nearest_distance);
if actual.len().abs_diff(candidate_key.len()) > allowed_distance {
continue;
}
let distance = edit_distance(&actual, &candidate_key);
if distance > allowed_distance {
continue;
}
if distance < nearest_distance {
nearest.clear();
nearest_distance = distance;
}
nearest.push(candidate);
}
nearest
}
fn spelling_key(name: &str) -> Vec<char> {
name.chars()
.filter(|&c| c != '_')
.map(|c| c.to_ascii_lowercase())
.collect()
}
#[expect(
clippy::indexing_slicing,
reason = "every index is at most the length of the string that sizes that matrix dimension"
)]
#[expect(
clippy::arithmetic_side_effects,
reason = "each `- 1` and `- 2` is guarded by the loop bounds, and a distance can't exceed the longer length"
)]
fn edit_distance(a: &[char], b: &[char]) -> usize {
let mut distances = vec![vec![0; b.len() + 1]; a.len() + 1];
for (i, row) in distances.iter_mut().enumerate() {
row[0] = i;
}
for (j, cell) in distances[0].iter_mut().enumerate() {
*cell = j;
}
for i in 1..=a.len() {
for j in 1..=b.len() {
let a_last = a[i - 1];
let b_last = b[j - 1];
let deletion = distances[i - 1][j] + 1;
let insertion = distances[i][j - 1] + 1;
let substitution = distances[i - 1][j - 1] + usize::from(a_last != b_last);
let mut distance = deletion.min(insertion).min(substitution);
if i > 1 && j > 1 && a_last == b[j - 2] && a[i - 2] == b_last {
let transposition = distances[i - 2][j - 2] + 1;
distance = distance.min(transposition);
}
distances[i][j] = distance;
}
}
distances[a.len()][b.len()]
}
fn open_array<'a, 'buf>(
stack: &mut Vec<Step<'a, 'buf>>,
builders: &mut Vec<build::Node<'buf>>,
warnings: &mut warning::Set<Warning>,
elem: &'a json::Element<'buf>,
item: &'a Schema,
cardinality: Cardinality,
slot: Slot,
) -> TypeExpectation {
let json::Value::Array(items) = elem.value() else {
warnings.insert(
elem,
Warning::InvalidType {
expected: json::ValueKind::Array,
actual: elem.value().kind(),
},
);
return TypeExpectation::Invalid;
};
if cardinality == Cardinality::OneOrMore && items.is_empty() {
warnings.insert(elem, Warning::Cardinality);
}
builders.push(build::Node::Array(
elem.clone(),
Vec::with_capacity(items.len()),
));
stack.push(Step::Close { slot });
for child in items.iter().rev() {
stack.push(Step::Visit {
elem: child,
schema: item,
slot: Slot::Item,
});
}
TypeExpectation::Satisfied
}
fn enqueue_all_children<'a, 'buf>(stack: &mut Vec<Step<'a, 'buf>>, elem: &'a json::Element<'buf>) {
match elem.value() {
json::Value::Array(items) => {
for child in items.iter().rev() {
stack.push(Step::Visit {
elem: child,
schema: &ANY,
slot: Slot::Ignore,
});
}
}
json::Value::Object(fields) => {
for field in fields.iter().rev() {
stack.push(Step::Visit {
elem: field.element(),
schema: &ANY,
slot: Slot::Ignore,
});
}
}
json::Value::Null
| json::Value::True
| json::Value::False
| json::Value::String(_)
| json::Value::Number(_) => {}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct List<'buf, T> {
elem: json::Element<'buf>,
items: Vec<Integrity<T>>,
}
impl<'buf, T> List<'buf, T> {
pub(super) fn new(elem: json::Element<'buf>, items: Vec<Integrity<T>>) -> Self {
Self { elem, items }
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
impl<'a, T> IntoIterator for &'a List<'_, T> {
type Item = &'a Integrity<T>;
type IntoIter = std::slice::Iter<'a, Integrity<T>>;
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
impl<T> std::ops::Index<usize> for List<'_, T> {
type Output = Integrity<T>;
#[expect(
clippy::indexing_slicing,
reason = "an `Index` impl is a bounds-checked panic by definition"
)]
fn index(&self, index: usize) -> &Self::Output {
&self.items[index]
}
}
impl<'buf, T> HasElement<'buf> for List<'buf, T> {
fn element(&self) -> &json::Element<'buf> {
&self.elem
}
}
#[derive(Clone, Debug)]
pub(crate) struct Str<'buf> {
elem: json::Element<'buf>,
value: json::RawStr<'buf>,
}
impl<'buf> Str<'buf> {
pub(super) fn new(elem: json::Element<'buf>, value: json::RawStr<'buf>) -> Self {
Self { elem, value }
}
pub fn value(&self) -> json::RawStr<'buf> {
self.value
}
}
impl<'buf> HasElement<'buf> for Str<'buf> {
fn element(&self) -> &json::Element<'buf> {
&self.elem
}
}
#[derive(Clone, Debug)]
pub(crate) enum Number<'buf> {
Number {
elem: json::Element<'buf>,
digits: &'buf str,
},
StringEncoded {
elem: json::Element<'buf>,
value: json::RawStr<'buf>,
},
}
impl<'buf> HasElement<'buf> for Number<'buf> {
fn element(&self) -> &json::Element<'buf> {
match self {
Self::Number { elem, digits: _ } | Self::StringEncoded { elem, value: _ } => elem,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Enum<'buf, T> {
elem: json::Element<'buf>,
value: T,
}
impl<'buf, T: OcpiEnum> Enum<'buf, T> {
pub fn new(elem: json::Element<'buf>, value: T) -> Self {
Self { elem, value }
}
pub fn value(&self) -> T {
self.value
}
}
impl<'buf, T> HasElement<'buf> for Enum<'buf, T> {
fn element(&self) -> &json::Element<'buf> {
&self.elem
}
}
pub(crate) trait OcpiEnum: Copy {
fn from_canonical(value: &str) -> Option<Self>;
}
macro_rules! ocpi_enum {
($kind:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum $kind {
$($variant),+
}
impl $kind {
const VARIANTS: &'static [&'static str] = &[$($value),+];
}
impl super::OcpiEnum for $kind {
fn from_canonical(value: &str) -> Option<Self> {
match value {
$($value => Some(Self::$variant),)+
_ => None,
}
}
}
};
}
pub(crate) use ocpi_enum;