Skip to main content

ocpi_tariffs/
schema.rs

1//! Check a [`json::Document`] against the OCPI schema for a given version.
2//!
3//! The walk checks the JSON kind, string length, array cardinality, and enum variant of
4//! every field the spec defines, and reports each violation as a [`Warning`]. It also
5//! builds the intermediate representation the pricing, linting, and explain features read.
6//!
7//! [`Warning`] is the only public item here. The intermediate representation and the
8//! per-version schema tables are an implementation detail: callers reach the checked
9//! data through [`cdr::check`](crate::cdr::check) and
10//! [`tariff::check`](crate::tariff::check), which return the [`Warning`]s this
11//! module produced alongside the object they built.
12
13pub(crate) mod v211;
14pub(crate) mod v221;
15
16mod build;
17
18#[cfg(test)]
19pub(crate) mod test;
20#[cfg(test)]
21mod test_nearest_spellings;
22#[cfg(test)]
23mod test_walk;
24
25use std::{borrow::Cow, collections::BTreeSet};
26
27use rust_decimal::Decimal;
28
29use crate::{datetime, json, number, warning};
30
31/// Define what lowering a schema IR value `Source` into this type means.
32///
33/// The schema walk has already checked the value's JSON kind, string length, array cardinality
34/// and enum variant, so an impl only decides what the value means. An impl gathers its warnings
35/// as `Self::Warning`.
36///
37/// Implement this for each type. Inside `lower_schema`, lower a field by calling its type's
38/// [`FromSchema::from_schema`] with `warnings`, which converts the field type's warnings and
39/// error to this type's.
40pub(crate) trait LowerSchema<'buf, Source>: Sized {
41    /// Warning type emitted for semantic issues found while lowering.
42    type Warning: warning::Warning;
43
44    /// Convert `source` to `Self`, gathering any semantic issues into `warnings`.
45    fn lower_schema(
46        source: &Source,
47        warnings: &mut dyn warning::Gather<Self::Warning>,
48    ) -> Result<Self, warning::Error<Self::Warning>>;
49}
50
51/// Lower a schema IR value `Source` into this type, gathering into the caller's
52/// gatherer.
53///
54/// The blanket impl over [`LowerSchema`] is the only impl, so every type converts its warnings
55/// and its error to the caller's warning type the same way.
56pub(crate) trait FromSchema<'buf, Source>: LowerSchema<'buf, Source> {
57    /// Convert `source` to `Self`, gathering any semantic issues into `warnings` as `WA`, the
58    /// caller's warning type.
59    fn from_schema<WA>(
60        source: &Source,
61        warnings: &mut dyn warning::Gather<WA>,
62    ) -> Result<Self, warning::Error<WA>>
63    where
64        Self::Warning: Into<WA>,
65        WA: warning::Warning;
66}
67
68impl<'buf, Source, T> FromSchema<'buf, Source> for T
69where
70    T: LowerSchema<'buf, Source>,
71{
72    fn from_schema<WA>(
73        source: &Source,
74        warnings: &mut dyn warning::Gather<WA>,
75    ) -> Result<Self, warning::Error<WA>>
76    where
77        Self::Warning: Into<WA>,
78        WA: warning::Warning,
79    {
80        let mut converting = warning::Converting::new(warnings);
81        let value = Self::lower_schema(source, &mut converting);
82        value.map_err(warning::Error::into_other)
83    }
84}
85
86/// A schema-IR value that carries the [`json::Element`] it was built from.
87///
88/// Every leaf ([`Str`], [`Number`], [`Enum`]) and every object IR value that retains its
89/// element implements this. It gives the lowering step a uniform way to reach a value's
90/// element without naming the concrete type.
91pub(crate) trait HasElement<'buf> {
92    /// The element this value was built from.
93    fn element(&self) -> &json::Element<'buf>;
94}
95
96/// Describes the expected structure of a JSON value.
97#[derive(Clone, Copy)]
98enum Schema {
99    /// A scalar value of a known JSON kind (see [`Scalar`]).
100    Scalar(Scalar),
101    /// A JSON object with a known set of fields.
102    Object(&'static Object),
103    /// A JSON object the spec for this version does not define, but which this layer reads
104    /// anyway (see [`Presence::NonSpec`]).
105    ///
106    /// A field the object does not list is not reported: the object itself is already
107    /// flagged as non-spec, so listing what it contains adds noise rather than
108    /// information.
109    NonSpecObject(&'static Object),
110    /// A `Price` value, which may be either a JSON object or a bare JSON number.
111    ///
112    /// OCPI 2.1.1 wrote a price as a bare `number`; 2.2.1 made it a `Price` object.
113    /// A JSON object is validated against the wrapped [`Object`] as usual. A bare JSON
114    /// number is accepted (and flagged as a type mismatch) and lowered to a `Price`
115    /// whose `excl_vat` is that number, leaving `incl_vat` absent. Any other kind is a
116    /// type error.
117    Price(&'static Object),
118    /// A homogeneous JSON array; each element validated against `item`, with a
119    /// minimum element count given by `cardinality`.
120    Array {
121        item: &'static Schema,
122        cardinality: Cardinality,
123    },
124}
125
126/// The minimum number of elements an array must contain.
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub(crate) enum Cardinality {
129    /// An array with zero or more element is expected. An empty array is valid.
130    ZeroOrMore,
131    /// An array with one or more elements is expected. An empty array is a violation.
132    OneOrMore,
133}
134
135impl std::fmt::Display for Cardinality {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        match self {
138            Cardinality::ZeroOrMore => f.write_str("zero or more"),
139            Cardinality::OneOrMore => f.write_str("one or more"),
140        }
141    }
142}
143
144/// The expected JSON kind of a scalar field.
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146enum Scalar {
147    /// A JSON string with no length bound. Covers OCPI `DateTime` (which is format-constrained, not
148    /// length-constrained) and any string the spec defines without a declared length. Strings the
149    /// spec declares as `string(n)` / `CiString(n)` use [`Scalar::StringMax`]. Enum types use
150    /// [`Scalar::Enum`], a date uses [`Scalar::Date`] and a time of day uses [`Scalar::Time`].
151    String,
152    /// A JSON string holding a calendar date, which the spec writes as `YYYY-MM-DD`. A date the
153    /// library reads but that is written another way, such as `2023-1-5`, is reported as
154    /// [`Warning::IncorrectFormat`]. A date the library does not read is left for the lowering to
155    /// reject.
156    Date,
157    /// A JSON string holding a time of day, which the spec writes as `HH:MM`. A time the library
158    /// reads but that is written another way, such as `9:05`, is reported as
159    /// [`Warning::IncorrectFormat`]. A time the library does not read is left for the lowering to
160    /// reject.
161    Time,
162    /// A JSON string with a maximum character length, per the OCPI `string(n)`
163    /// or `CiString(n)` declaration. The value is checked to be a string and
164    /// then its decoded character count is compared against the length bound.
165    StringMax(usize),
166    /// A JSON string constrained to a fixed set of enum variants as defined
167    /// in the OCPI spec. Every OCPI enum serializes as a string. This table
168    /// lists each permitted spec value (the spec requires uppercase). The value
169    /// is matched case-insensitively and the matched spec value is stored in
170    /// [`Enum`], to be resolved to a typed variant during extraction.
171    Enum(&'static [&'static str]),
172    /// A JSON number. Covers OCPI `number`, `int`, and `decimal`.
173    Number,
174    /// A JSON boolean.
175    Boolean,
176    /// Any value; the JSON kind is not constrained. Used for fields whose value
177    /// is a nested object or array this schema layer deliberately does not
178    /// model (e.g. `BusinessDetails`, `Hours`).
179    Any,
180}
181
182/// The integrity of a field. Building an IR value is infallible.
183/// Every field ends in one of these states rather than aborting the build.
184/// The detail behind `Err` (the kind mismatch, the invalid value) is recorded
185/// in the accompanying [`warning::Set`].
186///
187/// A field the OCPI spec defines as optional is typed `Integrity<Option<T>>`: an
188/// absent optional field is `Ok(None)`, not [`Integrity::Missing`].
189/// [`Integrity::Missing`] therefore only ever describes an absent (or `null`)
190/// *required* field, which is also reported as a [`Warning::MissingField`].
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub(crate) enum Integrity<T> {
193    /// The field was present and built successfully.
194    Ok(T),
195    /// A required field was absent or `null`. This is also reported as a
196    /// [`Warning::MissingField`]. The location is the containing object's, since an
197    /// absent field has no element of its own.
198    Missing(warning::Element),
199    /// The field was present but could not be built (wrong JSON kind, or an
200    /// otherwise invalid value). The location is the field's own.
201    Err(warning::Element),
202}
203
204impl<T> Integrity<Option<T>> {
205    /// Map the contained `Option<T>` to `Option<U>`.
206    /// Return `Some(U)` if `Ok(Some(T))`.
207    /// Otherwise, return `None` if `Ok(None)`, `Missing`, or `Err`.
208    pub(crate) fn map_some<U, F: FnOnce(&T) -> U>(&self, op: F) -> Option<U> {
209        match self {
210            Integrity::Ok(Some(v)) => Some(op(v)),
211            Integrity::Ok(None) | Integrity::Missing(_) | Integrity::Err(_) => None,
212        }
213    }
214}
215
216/// Generate an all-[`Integrity::Missing`] `new` constructor for an IR object struct.
217macro_rules! ir_object {
218    ($ty:ident { $($field:ident),* $(,)? }) => {
219        impl<'buf> $ty<'buf> {
220            /// An empty builder for the object at `elem`: every field starts `Missing`,
221            /// anchored to `elem`, and is filled by the walk.
222            pub(super) fn new(elem: &json::Element<'buf>) -> Self {
223                Self {
224                    $($field: super::Integrity::Missing(
225                        $crate::warning::Element::from_json(elem),
226                    ),)*
227                }
228            }
229        }
230    };
231    (@keep_element $ty:ident { $($field:ident),* $(,)? }) => {
232        impl<'buf> $ty<'buf> {
233            /// An empty builder for the JSON object at `elem`.
234            ///
235            /// Most IR objects don't need to save the JSON element they were created from.
236            /// But some objects are removed when empty. An element's byte span is needed
237            /// for the removal. Every field starts `Missing` with an associated `elem`.
238            /// Each field is then set by the IR walk.
239            pub(super) fn new(elem: &json::Element<'buf>) -> Self {
240                Self {
241                    elem: elem.clone(),
242                    $($field: super::Integrity::Missing(
243                        $crate::warning::Element::from_json(elem),
244                    ),)*
245                }
246            }
247        }
248
249        impl<'buf> super::HasElement<'buf> for $ty<'buf> {
250            fn element(&self) -> &json::Element<'buf> {
251                &self.elem
252            }
253        }
254    };
255}
256pub(crate) use ir_object;
257
258/// Identifies which schema intermediate-representation (IR) value an [`Object`]
259/// should be mapped to during the [`walk`].
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261enum BuilderKind {
262    /// The object is validated for warnings but not built into any IR value.
263    Ignore,
264    V221Tariff,
265    V221Element,
266    V221PriceComponent,
267    V221Restrictions,
268    V221Price,
269    V221Cdr,
270    V221CdrLocation,
271    V221ChargingPeriod,
272    V221CdrDimension,
273    V211Tariff,
274    V211Element,
275    V211PriceComponent,
276    V211Restrictions,
277    V211Cdr,
278    V211Location,
279    V211ChargingPeriod,
280    V211CdrDimension,
281}
282
283/// The expected fields of a JSON object.
284#[derive(Clone, Copy)]
285struct Object {
286    fields: &'static [Field],
287    /// The IR value this object is built into during the [`walk`].
288    kind: BuilderKind,
289}
290
291/// One field expected in a JSON object.
292#[derive(Clone, Copy)]
293struct Field {
294    /// JSON key name.
295    ///
296    /// This value is hardcoded and will never contain escapes.
297    name: &'static str,
298    /// Whether the field must be present.
299    presence: Presence,
300    /// Expected substructure of the field value.
301    schema: Schema,
302}
303
304impl Field {
305    /// Define a required scalar of the given JSON kind.
306    const fn required(name: &'static str, scalar: Scalar) -> Self {
307        Self {
308            name,
309            presence: Presence::Required,
310            schema: Schema::Scalar(scalar),
311        }
312    }
313
314    /// Define a required array (OCPI `+`: present and nonempty).
315    const fn required_array(name: &'static str, item: &'static Schema) -> Self {
316        Self {
317            name,
318            presence: Presence::Required,
319            schema: Schema::Array {
320                item,
321                cardinality: Cardinality::OneOrMore,
322            },
323        }
324    }
325
326    /// Define a required object.
327    const fn required_object(name: &'static str, schema: &'static Object) -> Self {
328        Self {
329            name,
330            presence: Presence::Required,
331            schema: Schema::Object(schema),
332        }
333    }
334
335    /// Define a required `Price` field, which per OCPI's 2.1.1-to-2.2.1 evolution
336    /// accepts either a `Price` object or a bare number.
337    const fn required_price(name: &'static str, schema: &'static Object) -> Self {
338        Self {
339            name,
340            presence: Presence::Required,
341            schema: Schema::Price(schema),
342        }
343    }
344
345    /// Define an optional scalar of the given JSON kind.
346    const fn optional(name: &'static str, scalar: Scalar) -> Self {
347        Self {
348            name,
349            presence: Presence::Optional,
350            schema: Schema::Scalar(scalar),
351        }
352    }
353
354    /// Define an optional array (OCPI `*`: may be absent or empty).
355    const fn optional_array(name: &'static str, item: &'static Schema) -> Self {
356        Self {
357            name,
358            presence: Presence::Optional,
359            schema: Schema::Array {
360                item,
361                cardinality: Cardinality::ZeroOrMore,
362            },
363        }
364    }
365
366    /// Define an optional object.
367    const fn optional_object(name: &'static str, schema: &'static Object) -> Self {
368        Self {
369            name,
370            presence: Presence::Optional,
371            schema: Schema::Object(schema),
372        }
373    }
374
375    /// Define an optional `Price` field, which per OCPI's 2.1.1-to-2.2.1 evolution
376    /// accepts either a `Price` object or a bare number.
377    const fn optional_price(name: &'static str, schema: &'static Object) -> Self {
378        Self {
379            name,
380            presence: Presence::Optional,
381            schema: Schema::Price(schema),
382        }
383    }
384
385    /// Define a scalar the spec for this version does not define, but which this layer
386    /// reads anyway (see [`Presence::NonSpec`]).
387    const fn non_spec(name: &'static str, scalar: Scalar) -> Self {
388        Self {
389            name,
390            presence: Presence::NonSpec,
391            schema: Schema::Scalar(scalar),
392        }
393    }
394
395    /// Define an object the spec for this version does not define, but which this layer
396    /// reads anyway (see [`Presence::NonSpec`] and [`Schema::NonSpecObject`]).
397    const fn non_spec_object(name: &'static str, schema: &'static Object) -> Self {
398        Self {
399            name,
400            presence: Presence::NonSpec,
401            schema: Schema::NonSpecObject(schema),
402        }
403    }
404}
405
406/// Whether a field must be present in its containing object.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub(crate) enum Presence {
409    /// The schema requires the field. Its absence is a violation (also reported as
410    /// [`Warning::MissingField`]).
411    Required,
412    /// The schema permits the field to be absent.
413    Optional,
414    /// The spec for this version does not define the field, but this layer reads it when a
415    /// document supplies it, because real-world documents carry it.
416    ///
417    /// Its absence is not a violation; its presence is reported as
418    /// [`Warning::NonSpecField`] so the caller still learns the document is off-spec.
419    NonSpec,
420}
421
422/// A structural problem found while validating a JSON document against the OCPI schema.
423#[derive(Clone, Debug, PartialEq, Eq)]
424pub enum Warning {
425    /// A field present in the JSON that the schema does not list.
426    UnexpectedField,
427    /// A field whose name is a few edits from the name of a field the object doesn't list, and no
428    /// farther from it than from any other. Parsing reports the field as misspelled or unexpected,
429    /// never both.
430    ///
431    /// Counting edits ignores ASCII case and `_`, so parsing reports `dayOfWeek` as a misspelling
432    /// of `day_of_week`. When the name and the field both have fewer than 3 characters, not
433    /// counting `_`, parsing doesn't allow any edit between them, so it reports `ip` as unexpected
434    /// rather than as a misspelling of `id`. Parsing reports a name equally near several fields as
435    /// a possible misspelling of each, because it can't tell which one the author meant.
436    MisspelledField {
437        /// The schema fields the misspelled name is nearest to, in the order the schema lists them.
438        /// It is never empty, and holds more than one name when several are equally near.
439        expected: Vec<&'static str>,
440    },
441    /// A field the spec for this version does not define, which this layer reads anyway
442    /// because real-world documents carry it. The value is still validated and retained.
443    NonSpecField,
444    /// An object carries this key more than once, and a later occurrence supersedes this one.
445    ///
446    /// Duplicate keys are legal JSON and the OCPI spec does not define them, so the value is
447    /// resolved to the **last** occurrence. Every earlier occurrence is reported as a warning,
448    /// so the anchors are exactly the ones a fix would remove.
449    DuplicateField,
450    /// A field name written with escapes that all decode, such as `"min\u005fkwh"`. Parsing reads
451    /// the field as `min_kwh`. No field OCPI defines needs an escape, so a real document is
452    /// unlikely to contain one.
453    FieldNameContainsEscapeCodes,
454    /// A field name with an escape that fails to decode, such as `"min\u00zfkwh"`. Parsing
455    /// can't tell which field the name means, so it ignores the field and also raises
456    /// `UnexpectedField` for it.
457    FieldNameInvalidEscape,
458    /// A required field absent from its containing object.
459    MissingField {
460        /// The field name the schema expected.
461        name: &'static str,
462    },
463    /// A field whose value is JSON `null`. `null` fields can simply be omitted.
464    NullField,
465    /// A value whose JSON kind does not match the schema.
466    InvalidType {
467        /// The JSON kind the schema expects.
468        expected: json::ValueKind,
469        /// The JSON kind encountered.
470        actual: json::ValueKind,
471    },
472    /// A number carrying more decimals than the OCPI spec permits.
473    ExcessivePrecision {
474        /// The maximum number of decimals the spec allows.
475        max: u32,
476        /// The number of decimals actually encountered.
477        scale: u32,
478    },
479    /// A string longer than the maximum length the schema permits.
480    StringTooLong {
481        /// The maximum character length the schema allows.
482        max: usize,
483        /// The character length actually encountered.
484        len: usize,
485    },
486    /// A string value that is not one of an enum field's permitted variants, read without
487    /// regard to case.
488    ///
489    /// Parsing reports most values a few edits from a variant as [`Warning::MisspelledValue`]
490    /// instead. That variant's doc says which ones parsing still reports as invalid.
491    /// Parsing reads neither, so a caller looking for every unread value matches on both.
492    InvalidValue {
493        /// The permitted spec values, in the spec's defined case.
494        expected: &'static [&'static str],
495        /// The value encountered, as written in the JSON (escapes not decoded).
496        actual: String,
497    },
498    /// A string value that is a few edits from one or more of an enum field's variants, and no
499    /// farther from those than from any other variant. Parsing reports the value as misspelled or
500    /// invalid, never both. Parsing doesn't read a misspelled value, just as it doesn't read an
501    /// invalid one.
502    ///
503    /// Parsing counts edits as it does for [`Warning::MisspelledField`], so it reports `MONDAI` as
504    /// a misspelling of `MONDAY`, and `AC` as invalid rather than as a misspelling of `DC`. Parsing
505    /// reports a value with an escape that fails to decode as invalid. Parsing reports a value
506    /// equally near more than 4 variants as [`Warning::InvalidValue`], because a list that long
507    /// doesn't narrow down what the author meant.
508    MisspelledValue {
509        /// The variants the misspelled value is nearest to, in the order the schema lists them. It
510        /// is never empty, and holds more than one variant when several are equally near.
511        expected: Vec<&'static str>,
512        /// The value encountered, as written in the JSON (escapes not decoded).
513        actual: String,
514    },
515
516    /// A string value that names one of an enum field's variants, but not in the spec's case.
517    ///
518    /// Both OCPI versions state that strings in messages and enumerations are case-sensitive,
519    /// so the value is off-spec rather than merely unconventional. This crate reads it anyway,
520    /// and says which variant it read.
521    IncorrectCase {
522        /// The variant the value named, in the spec's defined case.
523        expected: &'static str,
524        /// The value encountered, as written in the JSON (escapes not decoded).
525        actual: String,
526    },
527
528    /// A date or time of day this crate reads, but not written in the form the spec uses. The spec
529    /// writes a date as `YYYY-MM-DD` and a time as `HH:MM`. So validating a tariff reports
530    /// `2023-1-5` with an `expected` of `2023-01-05`, and `9:5` with an `expected` of `09:05`. A
531    /// value with spaces around it is reported too.
532    ///
533    /// OCPI 2.2.1 gives `start_date` and `end_date` a regex the value has to match exactly. OCPI
534    /// 2.1.1 gives only the example `2015-12-24`. Both versions give `start_time` and `end_time` a
535    /// regex. This crate reports the same warning for both versions, and reads the value either
536    /// way.
537    ///
538    /// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>)
539    /// * See: [OCPI spec 2.1.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#45-tariffrestrictions-class>)
540    IncorrectFormat {
541        /// The value this crate read, written in the spec's form.
542        expected: String,
543        /// The value encountered, as written in the JSON (escapes not decoded).
544        actual: String,
545    },
546    /// An empty array for a field whose schema requires one or more elements.
547    ///
548    /// The only cardinality the schema can violate is "one or more", and the only way to
549    /// violate it is to hold nothing, so this variant carries no data.
550    Cardinality,
551}
552
553impl crate::Warning for Warning {
554    fn id(&self) -> warning::Id {
555        match self {
556            Self::UnexpectedField => warning::Id::from_static("unexpected_field"),
557            Self::MisspelledField { expected } => {
558                warning::Id::from_string(format!("misspelled_field({})", expected.join(", ")))
559            }
560            Self::NonSpecField => warning::Id::from_static("non_spec_field"),
561            Self::MissingField { name } => {
562                warning::Id::from_string(format!("missing_field({name})"))
563            }
564            Self::NullField => warning::Id::from_static("null_field"),
565            Self::DuplicateField => warning::Id::from_static("duplicate_field"),
566            Self::FieldNameContainsEscapeCodes => {
567                warning::Id::from_static("field_name_contains_escape_codes")
568            }
569            Self::FieldNameInvalidEscape => warning::Id::from_static("field_name_invalid_escape"),
570            Self::InvalidType {
571                actual,
572                expected: _,
573            } => warning::Id::from_string(format!("invalid_type({actual})")),
574            Self::ExcessivePrecision { max: _, scale: _ } => {
575                warning::Id::from_static("excessive_precision")
576            }
577            Self::StringTooLong { max: _, len: _ } => warning::Id::from_static("string_too_long"),
578            Self::InvalidValue {
579                actual,
580                expected: _,
581            } => warning::Id::from_string(format!("invalid_value({actual})")),
582            Self::MisspelledValue {
583                expected,
584                actual: _,
585            } => warning::Id::from_string(format!("misspelled_value({})", expected.join(", "))),
586            Self::IncorrectCase {
587                expected: _,
588                actual: _,
589            } => warning::Id::from_static("incorrect_case"),
590            Self::IncorrectFormat {
591                expected: _,
592                actual: _,
593            } => warning::Id::from_static("incorrect_format"),
594            Self::Cardinality => warning::Id::from_static("cardinality(one or more)"),
595        }
596    }
597}
598
599impl std::fmt::Display for Warning {
600    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601        match self {
602            Self::UnexpectedField => f.write_str("field is not part of the schema"),
603            Self::MisspelledField { expected } => write!(
604                f,
605                "field is not part of the schema, but may be a misspelling of `{}`",
606                expected.join("` or `")
607            ),
608            Self::NonSpecField => f.write_str(
609                "field is not defined by the OCPI version of this document; it is read anyway",
610            ),
611            Self::MissingField { name } => write!(f, "required field `{name}` is missing"),
612            Self::NullField => f.write_str(
613                "field is `null`. `null` fields have no semantic meaning for OCPI objects",
614            ),
615            Self::DuplicateField => f.write_str(
616                "field appears more than once in this object; a later occurrence is the value used",
617            ),
618            Self::FieldNameContainsEscapeCodes => {
619                f.write_str("field name contains escape codes, which no OCPI field name needs")
620            }
621            Self::FieldNameInvalidEscape => {
622                f.write_str("field name contains an escape that fails to decode")
623            }
624            Self::InvalidType { expected, actual } => {
625                write!(f, "expected {expected} found {actual}")
626            }
627            Self::ExcessivePrecision { max, scale } => {
628                write!(
629                    f,
630                    "number has `{scale}` decimals, but the maximum allowed is `{max}`"
631                )
632            }
633            Self::StringTooLong { max, len } => {
634                write!(
635                    f,
636                    "string is `{len}` characters, but the maximum allowed is `{max}`"
637                )
638            }
639            Self::InvalidValue { expected, actual } => {
640                write!(
641                    f,
642                    "value `{actual}` is not one of the permitted values: {}",
643                    expected.join(", ")
644                )
645            }
646            Self::MisspelledValue { expected, actual } => write!(
647                f,
648                "value `{actual}` is not one of the permitted values, but may be a misspelling of `{}`",
649                expected.join("` or `")
650            ),
651            Self::IncorrectCase { expected, actual } => {
652                write!(
653                    f,
654                    "value `{actual}` is not written in the case the spec uses: `{expected}`"
655                )
656            }
657            Self::IncorrectFormat { expected, actual } => {
658                write!(
659                    f,
660                    "value `{actual}` is not written in the format the spec uses: `{expected}`"
661                )
662            }
663            Self::Cardinality => f.write_str("expected one or more elements, found 0"),
664        }
665    }
666}
667
668impl warning::Set<Warning> {
669    /// Collect the field paths of all [`Warning::UnexpectedField`] warnings into a set of `json::Path`s.
670    pub fn unexpected_fields(&self) -> json::PathSet<'_> {
671        let mut paths = BTreeSet::new();
672
673        for group in self {
674            let (element, group_warnings) = group.to_parts();
675
676            let has_unexpected_field = group_warnings
677                .iter()
678                .any(|warning| matches!(warning, Warning::UnexpectedField));
679
680            if has_unexpected_field {
681                paths.insert(&element.path);
682            }
683        }
684
685        json::PathSet::new(paths)
686    }
687
688    /// Collect the field paths of all [`Warning::NonSpecField`] warnings into a set of `json::Path`s.
689    pub fn non_spec_fields(&self) -> json::PathSet<'_> {
690        let mut paths = BTreeSet::new();
691
692        for group in self {
693            let (element, group_warnings) = group.to_parts();
694
695            let has_non_spec_field = group_warnings
696                .iter()
697                .any(|warning| matches!(warning, Warning::NonSpecField));
698
699            if has_non_spec_field {
700                paths.insert(&element.path);
701            }
702        }
703
704        json::PathSet::new(paths)
705    }
706
707    /// Collect the field paths of all [`Warning::MissingField`] warnings into a set of `json::Path`s.
708    pub fn missing_fields(&self) -> json::PathSet<'_> {
709        let mut paths = BTreeSet::new();
710
711        for group in self {
712            let (element, group_warnings) = group.to_parts();
713
714            let has_missing_field = group_warnings
715                .iter()
716                .any(|warning| matches!(warning, Warning::MissingField { name: _ }));
717
718            if has_missing_field {
719                paths.insert(&element.path);
720            }
721        }
722
723        json::PathSet::new(paths)
724    }
725
726    /// Remove all [`Warning::UnexpectedField`] warnings from the set.
727    pub fn remove_unexpected_fields(&mut self) {
728        self.retain(|warning| !matches!(warning, Warning::UnexpectedField));
729    }
730
731    /// Remove all [`Warning::MissingField`] warnings from the set.
732    pub fn remove_missing_fields(&mut self) {
733        self.retain(|warning| !matches!(warning, Warning::MissingField { name: _ }));
734    }
735
736    /// Remove all [`Warning::InvalidType`] warnings from the set.
737    pub fn remove_invalid_types(&mut self) {
738        self.retain(|warning| {
739            !matches!(
740                warning,
741                Warning::InvalidType {
742                    expected: _,
743                    actual: _
744                }
745            )
746        });
747    }
748
749    /// Remove all [`Warning::NullField`] warnings from the set.
750    pub fn remove_null_fields(&mut self) {
751        self.retain(|warning| !matches!(warning, Warning::NullField));
752    }
753
754    /// Remove all [`Warning::Cardinality`] warnings from the set.
755    pub fn remove_cardinalities(&mut self) {
756        self.retain(|warning| !matches!(warning, Warning::Cardinality));
757    }
758
759    /// Remove all [`Warning::StringTooLong`] warnings from the set.
760    pub fn remove_string_too_longs(&mut self) {
761        self.retain(|warning| !matches!(warning, Warning::StringTooLong { max: _, len: _ }));
762    }
763}
764
765/// Opaque-subtree marker: a value the schema does not model. The subtree is still
766/// walked so nested `null`s are reported.
767static ANY: Schema = Schema::Scalar(Scalar::Any);
768
769/// A step in the [`walk`]'s work stack.
770enum Step<'a, 'buf> {
771    /// Visit a node: record its warnings and build its leaf, or open its
772    /// object/array builder.
773    Visit {
774        elem: &'a json::Element<'buf>,
775        schema: &'a Schema,
776        slot: Slot,
777    },
778    /// Finalize the builder on top of the builder stack and route it to its parent.
779    Close { slot: Slot },
780}
781
782/// Where a built [`build::Node`] attaches within its parent.
783#[derive(Clone, Copy)]
784enum Slot {
785    /// The root value of the walk.
786    Root,
787    /// A named field of the parent object.
788    Field { name: &'static str },
789    /// An item of the parent array.
790    Item,
791    /// A value that is discarded (an unmodeled [`Scalar::Any`] subtree).
792    Ignore,
793}
794
795/// Validate `doc` against `schema` and build its intermediate representation (IR) in a
796/// single pass.
797///
798/// The returned [`build::Node`] is the value of the root [`Object`]'s [`BuilderKind`].
799/// When used through the public API the returned object will be one of the CDR or tariffs
800/// root types.
801///
802/// Building is infallible. Problems with a field emit a [`Warning`] and are stored as
803/// an [`Integrity::Err`] or [`Integrity::Missing`] on the IR object's field.
804///
805/// NOTE: A value whose type is invalid (a type mismatch) or whose key is
806/// unexpected is recorded but not descended into. Its substructure cannot
807/// be compared to the schema. Opaque [`Scalar::Any`] values are still
808/// walked, so nested `null`s are still reported for the inner JSON.
809fn walk<'a, 'buf>(
810    doc: &'a json::Document<'buf>,
811    schema: &'a Schema,
812    warnings: &mut dyn warning::Gather<Warning>,
813) -> build::Node<'buf> {
814    let mut builders: Vec<build::Node<'buf>> = Vec::new();
815    let mut root = build::Node::Ignore;
816
817    // Iteration order: an object's own problems are recorded before its descendants'
818    // because its fields are scanned (emitting unexpected/missing warnings) when the
819    // object is opened, before the field `Visit`s pushed here are popped.
820    let mut stack = vec![Step::Visit {
821        elem: doc.root(),
822        schema,
823        slot: Slot::Root,
824    }];
825
826    while let Some(step) = stack.pop() {
827        match step {
828            Step::Visit { elem, schema, slot } => {
829                if let json::Value::Null = elem.value() {
830                    warnings.insert(elem, Warning::NullField);
831                    root.route_to_parent(
832                        &mut builders,
833                        slot,
834                        Integrity::Missing(warning::Element::from_json(elem)),
835                    );
836                    continue;
837                }
838                match schema {
839                    // An unmodeled subtree: walk children only to report nested nulls.
840                    Schema::Scalar(Scalar::Any) => {
841                        enqueue_all_children(&mut stack, elem);
842                        root.route_to_parent(
843                            &mut builders,
844                            slot,
845                            Integrity::Missing(warning::Element::from_json(elem)),
846                        );
847                    }
848                    Schema::Scalar(scalar) => {
849                        let built = check_scalar(warnings, elem, *scalar);
850                        root.route_to_parent(&mut builders, slot, built);
851                    }
852                    Schema::Array { item, cardinality } => {
853                        let type_expectation = open_array(
854                            &mut stack,
855                            &mut builders,
856                            warnings,
857                            elem,
858                            item,
859                            *cardinality,
860                            slot,
861                        );
862                        if type_expectation.is_type_invalid() {
863                            root.route_to_parent(
864                                &mut builders,
865                                slot,
866                                Integrity::Err(warning::Element::from_json(elem)),
867                            );
868                        }
869                    }
870                    Schema::Object(object) => {
871                        let type_expectation = open_object(
872                            &mut stack,
873                            &mut builders,
874                            warnings,
875                            elem,
876                            object,
877                            slot,
878                            Unlisted::Report,
879                        );
880                        if type_expectation.is_type_invalid() {
881                            root.route_to_parent(
882                                &mut builders,
883                                slot,
884                                Integrity::Err(warning::Element::from_json(elem)),
885                            );
886                        }
887                    }
888                    Schema::NonSpecObject(object) => {
889                        let type_expectation = open_object(
890                            &mut stack,
891                            &mut builders,
892                            warnings,
893                            elem,
894                            object,
895                            slot,
896                            Unlisted::Ignore,
897                        );
898                        if type_expectation.is_type_invalid() {
899                            root.route_to_parent(
900                                &mut builders,
901                                slot,
902                                Integrity::Err(warning::Element::from_json(elem)),
903                            );
904                        }
905                    }
906                    Schema::Price(object) => {
907                        // A bare number is the 2.1.1 price shape; accept it directly.
908                        // Any other kind (including an object) is validated as an object.
909                        if let Some(node) = price_from_number(warnings, elem) {
910                            root.route_to_parent(&mut builders, slot, Integrity::Ok(node));
911                        } else {
912                            let type_expectation = open_object(
913                                &mut stack,
914                                &mut builders,
915                                warnings,
916                                elem,
917                                object,
918                                slot,
919                                Unlisted::Report,
920                            );
921                            if type_expectation.is_type_invalid() {
922                                root.route_to_parent(
923                                    &mut builders,
924                                    slot,
925                                    Integrity::Err(warning::Element::from_json(elem)),
926                                );
927                            }
928                        }
929                    }
930                }
931            }
932            Step::Close { slot } => {
933                if let Some(node) = builders.pop() {
934                    root.route_to_parent(&mut builders, slot, Integrity::Ok(node));
935                }
936            }
937        }
938    }
939
940    root
941}
942
943/// Build the leaf [`build::Node`] for a scalar, recording any kind, length, enum, or
944/// string-encoded-number warning. Returns [`Integrity::Err`] for a wrong-kind value.
945fn check_scalar<'buf>(
946    warnings: &mut dyn warning::Gather<Warning>,
947    elem: &json::Element<'buf>,
948    scalar: Scalar,
949) -> Integrity<build::Node<'buf>> {
950    let expected = match scalar {
951        // Enums serialize as JSON strings; their kind check is the same as a plain
952        // string, with the value-membership check applied below.
953        Scalar::String | Scalar::StringMax(_) | Scalar::Enum(_) | Scalar::Date | Scalar::Time => {
954            json::ValueKind::String
955        }
956        Scalar::Number => json::ValueKind::Number,
957        Scalar::Boolean => json::ValueKind::Bool,
958        // `Any` is handled by the caller; never built here.
959        Scalar::Any => return Integrity::Missing(warning::Element::from_json(elem)),
960    };
961
962    let actual = elem.value().kind();
963
964    // A `number` may be encoded as a JSON string; that is accepted but flagged below.
965    let string_encoded_number =
966        expected == json::ValueKind::Number && actual == json::ValueKind::String;
967    if actual != expected && !string_encoded_number {
968        warnings.insert(elem, Warning::InvalidType { expected, actual });
969        return Integrity::Err(warning::Element::from_json(elem));
970    }
971
972    match scalar {
973        Scalar::String => {
974            // The kind gate above guarantees a string.
975            let json::Value::String(text) = elem.value() else {
976                unreachable!("kind gate guarantees a string");
977            };
978            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
979        }
980        Scalar::Date => {
981            // The kind gate above guarantees a string.
982            let json::Value::String(text) = elem.value() else {
983                unreachable!("kind gate guarantees a string");
984            };
985            check_date_format(elem, *text, warnings);
986            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
987        }
988        Scalar::Time => {
989            // The kind gate above guarantees a string.
990            let json::Value::String(text) = elem.value() else {
991                unreachable!("kind gate guarantees a string");
992            };
993            check_time_format(elem, *text, warnings);
994            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
995        }
996        Scalar::StringMax(max) => {
997            // The kind gate above guarantees a string.
998            let json::Value::String(text) = elem.value() else {
999                unreachable!("kind gate guarantees a string");
1000            };
1001            let (decoded, _warning) = text.decode_escapes();
1002            let len = decoded.chars().count();
1003            if len > max {
1004                warnings.insert(elem, Warning::StringTooLong { max, len });
1005            }
1006            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
1007        }
1008        Scalar::Enum(variants) => {
1009            let Some(value) = elem.value().to_raw_str() else {
1010                return Integrity::Err(warning::Element::from_json(elem));
1011            };
1012            let matched = variants
1013                .iter()
1014                .copied()
1015                .find(|&s| value.eq_any_escape_aware_ignore_ascii_case(&[s]));
1016            let Some(canonical) = matched else {
1017                let (decoded, _warning) = value.decode_escapes();
1018
1019                // `decode_escapes` borrows the value as written when an escape fails to decode, so
1020                // a borrowed value with a backslash is malformed. The walk can't tell which variant
1021                // a malformed value means, just as it can't for a malformed field name, so it
1022                // suggests none.
1023                let nearest = match &decoded {
1024                    Cow::Borrowed(raw) if raw.contains('\\') => Vec::new(),
1025                    Cow::Borrowed(_) | Cow::Owned(_) => {
1026                        nearest_spellings(&decoded, variants.iter().copied())
1027                    }
1028                };
1029                let actual = value.as_unescaped_str().to_owned();
1030                let warning = match nearest.len() {
1031                    1..=MISSPELLED_VALUE_MAX_EXPECTED => Warning::MisspelledValue {
1032                        expected: nearest,
1033                        actual,
1034                    },
1035                    _ => Warning::InvalidValue {
1036                        expected: variants,
1037                        actual,
1038                    },
1039                };
1040                warnings.insert(elem, warning);
1041                return Integrity::Err(warning::Element::from_json(elem));
1042            };
1043
1044            // The match above ignores case and decodes escapes, so a value that reaches here
1045            // and still differs from the variant differs in case alone.
1046            if !value.eq_any_escape_aware(&[canonical]) {
1047                warnings.insert(
1048                    elem,
1049                    Warning::IncorrectCase {
1050                        expected: canonical,
1051                        actual: value.as_unescaped_str().to_owned(),
1052                    },
1053                );
1054            }
1055
1056            Integrity::Ok(build::Node::Enum(elem.clone(), canonical))
1057        }
1058        Scalar::Number => {
1059            // OCPI permits a number to be encoded as a JSON string. The value is accepted
1060            // either way; the linter can choose to flag the string-encoded form later. The
1061            // match is exhaustive in practice: the kind gate above already rejected any
1062            // value that is neither a JSON number nor a JSON string.
1063            match elem.value() {
1064                json::Value::Number(digits) => {
1065                    check_precision(elem, digits, warnings);
1066                    Integrity::Ok(build::Node::Number(Number::Number {
1067                        elem: elem.clone(),
1068                        digits,
1069                    }))
1070                }
1071                json::Value::String(text) => {
1072                    let (decoded, _warning) = text.decode_escapes();
1073                    check_precision(elem, &decoded, warnings);
1074                    Integrity::Ok(build::Node::Number(Number::StringEncoded {
1075                        elem: elem.clone(),
1076                        value: *text,
1077                    }))
1078                }
1079                json::Value::Null
1080                | json::Value::True
1081                | json::Value::False
1082                | json::Value::Array(_)
1083                | json::Value::Object(_) => unreachable!(
1084                    "kind gate rejects any value that is neither a number nor a string"
1085                ),
1086            }
1087        }
1088        Scalar::Boolean => match elem.value() {
1089            json::Value::True => Integrity::Ok(build::Node::Bool(true)),
1090            json::Value::False => Integrity::Ok(build::Node::Bool(false)),
1091            json::Value::Null
1092            | json::Value::Number(_)
1093            | json::Value::String(_)
1094            | json::Value::Array(_)
1095            | json::Value::Object(_) => unreachable!("kind gate rejects any value but a boolean"),
1096        },
1097        // Unreachable: handled above.
1098        Scalar::Any => Integrity::Missing(warning::Element::from_json(elem)),
1099    }
1100}
1101
1102/// Report a number written with more decimals than the spec allows.
1103///
1104/// Raised here rather than during lowering because the walk visits every numeric field, so
1105/// coverage does not depend on which consumer happens to lower which value: `price` lowered all of
1106/// them and reported, `lint` lowered three and reported three.
1107///
1108/// A value that does not parse is left alone. The lowering reports the parse failure with the
1109/// reason, and a number that is not a number has no precision to complain about.
1110fn check_precision(
1111    elem: &json::Element<'_>,
1112    digits: &str,
1113    warnings: &mut dyn warning::Gather<Warning>,
1114) {
1115    let Ok(decimal) = Decimal::from_str_exact(digits) else {
1116        return;
1117    };
1118
1119    let scale = decimal.scale();
1120    if scale > number::SCALE {
1121        warnings.insert(
1122            elem,
1123            Warning::ExcessivePrecision {
1124                max: number::SCALE,
1125                scale,
1126            },
1127        );
1128    }
1129}
1130
1131/// Report a date written other than as `YYYY-MM-DD`, with the same date in that form.
1132///
1133/// This function reads the date with `datetime::parse_date`, the function the date lowering uses.
1134/// So it reports only a date the library reads, and the date it proposes is the one the library
1135/// already uses, which is why `--fix` can apply it without changing what a session costs. The
1136/// forms `parse_date` reads besides `YYYY-MM-DD` are listed on it.
1137///
1138/// A date that does not parse is left to the lowering, which reports it. So is a date written with
1139/// escapes: `civil::Date::from_schema` rejects one, so rewriting it would turn a date the library
1140/// does not read into one it does. The raw text of such a date holds a backslash, which
1141/// `parse_date` rejects anyway, so the escape check states the rule rather than being what enforces
1142/// it.
1143fn check_date_format(
1144    elem: &json::Element<'_>,
1145    text: json::RawStr<'_>,
1146    warnings: &mut dyn warning::Gather<Warning>,
1147) {
1148    if text.lexical_issues().escapes {
1149        return;
1150    }
1151
1152    let actual = text.as_unescaped_str();
1153
1154    let Ok(date) = datetime::parse_date(actual) else {
1155        return;
1156    };
1157
1158    let expected = date.strftime("%Y-%m-%d").to_string();
1159
1160    if actual != expected {
1161        warnings.insert(
1162            elem,
1163            Warning::IncorrectFormat {
1164                expected,
1165                actual: actual.to_owned(),
1166            },
1167        );
1168    }
1169}
1170
1171/// Report a time of day written other than as `HH:MM`, with the same time in that form.
1172///
1173/// This is `check_date_format` for a time. It reads the time with `datetime::parse_time`, the
1174/// function the time lowering uses, so the time it proposes is the one the library already uses.
1175///
1176/// A time that does not parse is left to the lowering, which reports it. So is a time written with
1177/// escapes: `civil::Time::from_schema` rejects one, so rewriting it would turn a time the library
1178/// does not read into one it does. The raw text of such a time holds a backslash, which
1179/// `parse_time` rejects anyway, so the escape check states the rule rather than being what enforces
1180/// it.
1181fn check_time_format(
1182    elem: &json::Element<'_>,
1183    text: json::RawStr<'_>,
1184    warnings: &mut dyn warning::Gather<Warning>,
1185) {
1186    if text.lexical_issues().escapes {
1187        return;
1188    }
1189
1190    let actual = text.as_unescaped_str();
1191
1192    let Ok(time) = datetime::parse_time(actual) else {
1193        return;
1194    };
1195
1196    let expected = time.strftime("%H:%M").to_string();
1197
1198    if actual != expected {
1199        warnings.insert(
1200            elem,
1201            Warning::IncorrectFormat {
1202                expected,
1203                actual: actual.to_owned(),
1204            },
1205        );
1206    }
1207}
1208
1209/// If `elem` is a bare JSON number, build the [`v221::Price`] node it stands for: the
1210/// number becomes `excl_vat` and `incl_vat` is left absent. The bare-number form is
1211/// flagged as a type mismatch (an object is the 2.2.1 shape) but still accepted, per
1212/// OCPI's evolution from a `number` price in 2.1.1. Returns `None` for any other kind,
1213/// which the caller then validates as an object.
1214fn price_from_number<'buf>(
1215    warnings: &mut dyn warning::Gather<Warning>,
1216    elem: &json::Element<'buf>,
1217) -> Option<build::Node<'buf>> {
1218    let json::Value::Number(digits) = elem.value() else {
1219        return None;
1220    };
1221
1222    warnings.insert(
1223        elem,
1224        Warning::InvalidType {
1225            expected: json::ValueKind::Object,
1226            actual: json::ValueKind::Number,
1227        },
1228    );
1229
1230    Some(build::Node::Price(v221::Price::from_number(
1231        elem.clone(),
1232        digits,
1233    )))
1234}
1235
1236/// The [`open_array`] and [`open_object`] return whether the type they expected is
1237/// the type they encountered.
1238#[derive(Copy, Clone)]
1239enum TypeExpectation {
1240    Satisfied,
1241    Invalid,
1242}
1243
1244impl TypeExpectation {
1245    fn is_type_invalid(self) -> bool {
1246        matches!(self, Self::Invalid)
1247    }
1248}
1249
1250/// Whether [`open_object`] reports a field the object's schema does not list.
1251#[derive(Copy, Clone)]
1252enum Unlisted {
1253    /// Report it as a [`Warning::UnexpectedField`], or as a [`Warning::MisspelledField`] when its
1254    /// name is a few edits from a field the object doesn't list.
1255    Report,
1256    /// Say nothing. Used for a [`Schema::NonSpecObject`], which is already reported as a
1257    /// whole.
1258    Ignore,
1259}
1260
1261/// Open an object: push its builder and a [`Step::Close`], then queue its
1262/// schema-matched fields in document order, so a duplicated key resolves to its last
1263/// occurrence. Records unexpected, duplicate and missing-required-field warnings.
1264/// Returns `false` (and opens nothing) if `elem` is not a JSON object.
1265fn open_object<'a, 'buf>(
1266    stack: &mut Vec<Step<'a, 'buf>>,
1267    builders: &mut Vec<build::Node<'buf>>,
1268    warnings: &mut dyn warning::Gather<Warning>,
1269    elem: &'a json::Element<'buf>,
1270    object: &'a Object,
1271    slot: Slot,
1272    unlisted: Unlisted,
1273) -> TypeExpectation {
1274    // `fields` are sorted alphabetically by `Field::name` so the `binary_search_by_key`
1275    // below is valid; the `debug_assert` guards that against an out-of-order schema.
1276    debug_assert!(
1277        object
1278            .fields
1279            .windows(2)
1280            .all(|pair| matches!(pair, [a, b] if a.name <= b.name)),
1281        "Object::fields must be sorted alphabetically by name"
1282    );
1283    let json::Value::Object(fields) = elem.value() else {
1284        warnings.insert(
1285            elem,
1286            Warning::InvalidType {
1287                expected: json::ValueKind::Object,
1288                actual: elem.value().kind(),
1289            },
1290        );
1291        return TypeExpectation::Invalid;
1292    };
1293
1294    builders.push(build::empty(object.kind, elem));
1295    stack.push(Step::Close { slot });
1296
1297    // Mark, by schema-field position, which fields the document supplies. Reusing each
1298    // binary-search hit here lets the missing-field scan below be a single indexed pass
1299    // instead of a linear `contains` per schema field.
1300    //
1301    // Iterate in reverse, the way `open_array` does, so the `Step::Visit`s are pushed in
1302    // reverse and therefore popped in document order. Each visit assigns into the builder,
1303    // so a key carried twice resolves to its last occurrence.
1304    let mut seen = vec![false; object.fields.len()];
1305    let mut holds_value = vec![false; object.fields.len()];
1306    let mut claimed: BTreeSet<json::Key<'buf>> = BTreeSet::new();
1307    let mut unlisted_fields = Vec::new();
1308    for field in fields.iter().rev() {
1309        let key = field.key().to_key();
1310
1311        // Reverse order means the first sighting of a key is its *last* occurrence in the
1312        // document, the one whose value survives; every sighting after that is superseded.
1313        // Reported even inside a `NonSpecObject`, because a document carrying one field
1314        // twice is a fault of the document rather than a question about the schema.
1315        if !claimed.insert(key.clone()) {
1316            warnings.insert(field.element(), Warning::DuplicateField);
1317        }
1318
1319        // The walk raises `FieldNameContainsEscapeCodes` and `FieldNameInvalidEscape` even inside a
1320        // `NonSpecObject`, because an escape in a field name is a fault of the document rather than
1321        // a question about the schema.
1322        let name = match &key {
1323            json::Key::Plain(name) => *name,
1324            json::Key::Decoded(name) => {
1325                warnings.insert(field.element(), Warning::FieldNameContainsEscapeCodes);
1326                name.as_str()
1327            }
1328            json::Key::Malformed(_) => {
1329                // No schema field name contains a backslash, so a malformed name can't match a
1330                // schema field. The walk raises `UnexpectedField` for the field as for any other
1331                // unlisted name, so a caller who removes unexpected fields removes this field too.
1332                // The walk doesn't visit the field's value.
1333                warnings.insert(field.element(), Warning::FieldNameInvalidEscape);
1334                if let Unlisted::Report = unlisted {
1335                    warnings.insert(field.element(), Warning::UnexpectedField);
1336                }
1337                continue;
1338            }
1339        };
1340        let Ok(idx) = object.fields.binary_search_by_key(&name, |fd| fd.name) else {
1341            // Not in the schema: record it and do not walk its subtree.
1342            if let Unlisted::Report = unlisted {
1343                unlisted_fields.push((field.element(), name.to_owned()));
1344            }
1345            continue;
1346        };
1347        if let Some(flag) = seen.get_mut(idx) {
1348            *flag = true;
1349        }
1350        if !matches!(field.element().value(), json::Value::Null)
1351            && let Some(flag) = holds_value.get_mut(idx)
1352        {
1353            *flag = true;
1354        }
1355        if let Some(fd) = object.fields.get(idx) {
1356            // A field the spec does not define is read anyway, but the document is still
1357            // off-spec for supplying it.
1358            if let Presence::NonSpec = fd.presence {
1359                warnings.insert(field.element(), Warning::NonSpecField);
1360            }
1361            stack.push(Step::Visit {
1362                elem: field.element(),
1363                schema: &fd.schema,
1364                slot: Slot::Field { name: fd.name },
1365            });
1366        }
1367    }
1368
1369    // The walk suggests only a schema field absent from the object, because renaming an unlisted
1370    // field to a present one would repeat that key. Which fields are present is known only once the
1371    // loop above has seen every field, so the walk reports the unlisted fields here.
1372    //
1373    // The candidates come from `holds_value` rather than `seen`, so a field whose value is `null`
1374    // counts as absent. The fix for `NullField` removes that field. If a `null` field is not
1375    // removed, renaming a misspelled sibling could result in duplicate fields. Built from `seen`,
1376    // the candidates would leave `dayOfWeek` beside `"day_of_week": null` reported as unexpected,
1377    // and `--fix` would remove both.
1378    for (field, name) in unlisted_fields {
1379        let absent = object
1380            .fields
1381            .iter()
1382            .zip(&holds_value)
1383            .filter(|(_, holds)| !**holds)
1384            .map(|(fd, _)| fd.name);
1385        let expected = nearest_spellings(&name, absent);
1386        let warning = if expected.is_empty() {
1387            Warning::UnexpectedField
1388        } else {
1389            Warning::MisspelledField { expected }
1390        };
1391        warnings.insert(field, warning);
1392    }
1393
1394    // An absent field has no element of its own to `Visit`, so it is recorded here.
1395    // Every absent field is set to `Integrity::Missing`; the field's extractor then
1396    // interprets that per the field's optionality (an optional field becomes
1397    // `Integrity::Ok(None)`, a required field stays `Integrity::Missing`). A required
1398    // field additionally records a `MissingField` warning against the parent, so its
1399    // absence is visible in both the IR and the warnings.
1400    for (field, &present) in object.fields.iter().zip(seen.iter()) {
1401        if present {
1402            continue;
1403        }
1404
1405        // An absent `NonSpec` field is not a violation; the spec does not define it.
1406        if let Presence::Required = field.presence {
1407            warnings.insert(elem, Warning::MissingField { name: field.name });
1408        }
1409        build::set_top_field(
1410            builders,
1411            field.name,
1412            Integrity::Missing(warning::Element::from_json(elem)),
1413        );
1414    }
1415
1416    TypeExpectation::Satisfied
1417}
1418
1419/// The length below which a name or value is tiny. [`nearest_spellings`] doesn't allow any edit
1420/// between a name and a candidate that are both tiny, so only a difference of case or `_` makes the
1421/// name a misspelling. The characters are counted after [`spelling_key`] removes `_`.
1422///
1423/// One edit changes half of a two-character name. `AC` is 1 edit from `DC`, and allowing that edit
1424/// would report an AC connector's `connector_power_type` as a misspelling of the opposite power
1425/// type.
1426///
1427/// Requiring both to be tiny keeps a longer name a misspelling of a tiny field. `idd` is 1 edit
1428/// from `id`. Applying the rule when only the shorter name is tiny would report `idd` as
1429/// unexpected, and `lint --fix`, asked to remove unexpected fields, would delete the tariff's only
1430/// copy of its id.
1431const TINY_NAME_LEN: usize = 3;
1432
1433/// Where [`nearest_spellings`] separates short names from long ones. A name with fewer characters
1434/// than this is short. The characters are counted after [`spelling_key`] removes `_`, so `max_kwh`
1435/// is short at 6 characters and `day_of_week` is long at 9.
1436///
1437/// A name may be at most [`SHORT_NAME_MAX_EDITS`] edits from a candidate when either of the two is
1438/// short, and at most [`LONG_NAME_MAX_EDITS`] when both are long. When both are shorter than
1439/// [`TINY_NAME_LEN`], [`nearest_spellings`] doesn't allow any edit. A long name is allowed more
1440/// edits because each one changes a smaller share of it: two edits turn `VAT` into `FLAT`, a
1441/// different word, while `max_durtaoin` is still plainly `max_duration`. A length of `8` is the
1442/// shortest at which two edits change no more than a quarter of the name.
1443///
1444/// Taking the edits allowed from the shorter of the two names keeps a long name from being reported
1445/// as a misspelling of a short candidate. Taken from the misspelled name alone, `max_kwh_ac` would
1446/// be allowed 2 edits, and deleting its suffix would make it a misspelling of `max_kwh`.
1447const SHORT_NAME_LEN: usize = 8;
1448
1449/// The most edits [`nearest_spellings`] allows between a short name and a candidate.
1450/// [`SHORT_NAME_LEN`] says what makes a name short and why it is allowed fewer edits.
1451const SHORT_NAME_MAX_EDITS: usize = 1;
1452
1453/// The most edits [`nearest_spellings`] allows between a long name and a candidate.
1454/// [`SHORT_NAME_LEN`] says what makes a name long.
1455///
1456/// A value of `3` would let a real extension field pass for a misspelling. The CDR in the
1457/// `v211/real_world/zero_energy_use` fixture contains `total_vat`, a field OCPI doesn't define,
1458/// which holds the VAT on the session. Compared as `totalvat`, it is 3 edits from `totalcost`:
1459/// `v` becomes `c`, `a` becomes `o` and an `s` is inserted. In a CDR that lacks `total_cost`, the
1460/// walk would then report the VAT as a misspelling of the cost, though the two are different
1461/// amounts. The spec requires `total_cost`, so only an invalid CDR is exposed, but at `2` none is.
1462const LONG_NAME_MAX_EDITS: usize = 2;
1463
1464/// The most variants a [`Warning::MisspelledValue`] names. The walk reports a value equally near
1465/// more variants than this as [`Warning::InvalidValue`], which lists every variant the field allows.
1466///
1467/// Each single-character insertion, deletion, substitution and adjacent swap of a variant in either
1468/// schema gives a typo. Outside the `DOMESTIC_*` connector types, no such typo is equally near more
1469/// than 4 variants. `IEC_62196_T3` is equally near `IEC_62196_T1`, `IEC_62196_T2`, `IEC_62196_T3A`
1470/// and `IEC_62196_T3C`. `DOMESTIC_Z` is 1 edit from every `DOMESTIC_*` type, 12 in OCPI 2.1.1 and
1471/// 15 in OCPI 2.2.1. A list that long doesn't narrow down what the author meant.
1472const MISSPELLED_VALUE_MAX_EXPECTED: usize = 4;
1473
1474/// The candidates nearest to `actual` in edits, taken as the names `actual` may misspell.
1475///
1476/// Returns every candidate at the nearest distance, in the order `candidates` gives them, because
1477/// when several are equally near nothing says which one the author meant. Returns an empty list
1478/// when no candidate is within the allowed edits.
1479///
1480/// Both names are compared through [`spelling_key`], which lowercases them and removes `_`, so
1481/// `dayOfWeek` is 0 edits from `day_of_week`. The raw names are 4 edits apart, two inserted `_`
1482/// and two changes of case, which is more than [`LONG_NAME_MAX_EDITS`] allows.
1483///
1484/// [`TINY_NAME_LEN`] and [`SHORT_NAME_LEN`] say how many edits a name is allowed.
1485fn nearest_spellings(
1486    actual: &str,
1487    candidates: impl IntoIterator<Item = &'static str>,
1488) -> Vec<&'static str> {
1489    let actual = spelling_key(actual);
1490
1491    let mut nearest = Vec::new();
1492    let mut nearest_distance = usize::MAX;
1493    for candidate in candidates {
1494        let candidate_key = spelling_key(candidate);
1495        let shorter_len = actual.len().min(candidate_key.len());
1496        let longer_len = actual.len().max(candidate_key.len());
1497        let max_distance = if longer_len < TINY_NAME_LEN {
1498            0
1499        } else if shorter_len < SHORT_NAME_LEN {
1500            SHORT_NAME_MAX_EDITS
1501        } else {
1502            LONG_NAME_MAX_EDITS
1503        };
1504
1505        // A candidate farther than the nearest one found so far can't join the result.
1506        let allowed_distance = max_distance.min(nearest_distance);
1507
1508        // An edit changes the length by at most one character, so a candidate whose length differs
1509        // from `actual` by more than `allowed_distance` can't be within `allowed_distance`. The
1510        // name comes from the input and may be millions of characters long, while every candidate
1511        // is a short schema name. Skipping on length keeps `edit_distance` from building a large
1512        // matrix.
1513        if actual.len().abs_diff(candidate_key.len()) > allowed_distance {
1514            continue;
1515        }
1516
1517        let distance = edit_distance(&actual, &candidate_key);
1518        if distance > allowed_distance {
1519            continue;
1520        }
1521        if distance < nearest_distance {
1522            nearest.clear();
1523            nearest_distance = distance;
1524        }
1525        nearest.push(candidate);
1526    }
1527
1528    nearest
1529}
1530
1531/// The form of `name` that [`nearest_spellings`] compares. OCPI writes field names in snake case and
1532/// enum values in upper snake case, so ignoring case and `_` makes a camel-case or wrongly cased
1533/// name compare equal to the one the spec writes.
1534///
1535/// Returns characters rather than a string, so [`edit_distance`] counts a non-ASCII character as
1536/// one character rather than as each of its UTF-8 bytes.
1537fn spelling_key(name: &str) -> Vec<char> {
1538    name.chars()
1539        .filter(|&c| c != '_')
1540        .map(|c| c.to_ascii_lowercase())
1541        .collect()
1542}
1543
1544/// The fewest single-character insertions, deletions, substitutions and swaps of two adjacent
1545/// characters that turn `a` into `b`.
1546///
1547/// This is the optimal string alignment distance. Plain Levenshtein distance would count a swapped
1548/// pair, a common typo, as two edits.
1549///
1550/// Wikipedia gives the algorithm as pseudocode, and this function follows it: [Optimal string
1551/// alignment distance][osa].
1552///
1553/// [osa]: https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
1554#[expect(
1555    clippy::indexing_slicing,
1556    reason = "every index is at most the length of the string that sizes that matrix dimension"
1557)]
1558#[expect(
1559    clippy::arithmetic_side_effects,
1560    reason = "each `- 1` and `- 2` is guarded by the loop bounds, and a distance can't exceed the longer length"
1561)]
1562fn edit_distance(a: &[char], b: &[char]) -> usize {
1563    // `distances[i][j]` is the distance from the first `i` characters of `a` to the first `j`
1564    // characters of `b`. Row `0` and column `0` are the empty prefix, so the matrix has one row and
1565    // one column more than the strings have characters. In the loop below, each `+ 1` is one edit.
1566    let mut distances = vec![vec![0; b.len() + 1]; a.len() + 1];
1567
1568    // Column `0` holds the distance from each prefix of `a` to the empty string, one deletion per
1569    // character. Row `0` holds the distance from the empty string to each prefix of `b`, one
1570    // insertion per character.
1571    for (i, row) in distances.iter_mut().enumerate() {
1572        row[0] = i;
1573    }
1574    for (j, cell) in distances[0].iter_mut().enumerate() {
1575        *cell = j;
1576    }
1577
1578    for i in 1..=a.len() {
1579        for j in 1..=b.len() {
1580            // Row `i` and column `j` are prefixes ending with `a[i - 1]` and `b[j - 1]`.
1581            let a_last = a[i - 1];
1582            let b_last = b[j - 1];
1583
1584            let deletion = distances[i - 1][j] + 1;
1585            let insertion = distances[i][j - 1] + 1;
1586            let substitution = distances[i - 1][j - 1] + usize::from(a_last != b_last);
1587            let mut distance = deletion.min(insertion).min(substitution);
1588
1589            // The two prefixes end in the same two characters in swapped order, so one swap added
1590            // to the distance before that pair, `distances[i - 2][j - 2]`, is another way to reach
1591            // this cell.
1592            if i > 1 && j > 1 && a_last == b[j - 2] && a[i - 2] == b_last {
1593                let transposition = distances[i - 2][j - 2] + 1;
1594                distance = distance.min(transposition);
1595            }
1596
1597            distances[i][j] = distance;
1598        }
1599    }
1600
1601    distances[a.len()][b.len()]
1602}
1603
1604/// Open an array: push its accumulator builder and a [`Step::Close`], then queue its
1605/// items in document order. Records a cardinality warning for an empty `OneOrMore`
1606/// array.
1607///
1608/// Returns `false` (and opens nothing) if `elem` is not a JSON array.
1609fn open_array<'a, 'buf>(
1610    stack: &mut Vec<Step<'a, 'buf>>,
1611    builders: &mut Vec<build::Node<'buf>>,
1612    warnings: &mut dyn warning::Gather<Warning>,
1613    elem: &'a json::Element<'buf>,
1614    item: &'a Schema,
1615    cardinality: Cardinality,
1616    slot: Slot,
1617) -> TypeExpectation {
1618    let json::Value::Array(items) = elem.value() else {
1619        warnings.insert(
1620            elem,
1621            Warning::InvalidType {
1622                expected: json::ValueKind::Array,
1623                actual: elem.value().kind(),
1624            },
1625        );
1626        return TypeExpectation::Invalid;
1627    };
1628
1629    if cardinality == Cardinality::OneOrMore && items.is_empty() {
1630        warnings.insert(elem, Warning::Cardinality);
1631    }
1632
1633    builders.push(build::Node::Array(
1634        elem.clone(),
1635        Vec::with_capacity(items.len()),
1636    ));
1637    stack.push(Step::Close { slot });
1638
1639    // Push in reverse so items are visited, and accumulated, in document order.
1640    for child in items.iter().rev() {
1641        stack.push(Step::Visit {
1642            elem: child,
1643            schema: item,
1644            slot: Slot::Item,
1645        });
1646    }
1647
1648    TypeExpectation::Satisfied
1649}
1650
1651/// Queue the children of an opaque [`Scalar::Any`] element so nested `null`s are
1652/// still reported. Their values are discarded.
1653fn enqueue_all_children<'a, 'buf>(stack: &mut Vec<Step<'a, 'buf>>, elem: &'a json::Element<'buf>) {
1654    match elem.value() {
1655        json::Value::Array(items) => {
1656            for child in items.iter().rev() {
1657                stack.push(Step::Visit {
1658                    elem: child,
1659                    schema: &ANY,
1660                    slot: Slot::Ignore,
1661                });
1662            }
1663        }
1664        json::Value::Object(fields) => {
1665            for field in fields.iter().rev() {
1666                stack.push(Step::Visit {
1667                    elem: field.element(),
1668                    schema: &ANY,
1669                    slot: Slot::Ignore,
1670                });
1671            }
1672        }
1673        json::Value::Null
1674        | json::Value::True
1675        | json::Value::False
1676        | json::Value::String(_)
1677        | json::Value::Number(_) => {}
1678    }
1679}
1680
1681// Constrained leaf types for the schema intermediate representation (IR).
1682//
1683// A leaf wraps a [`json::Element`] that the IR builder has already checked is the correct JSON
1684// kind. So the `LowerSchema` impls don't check the kind again. They only decide what the value
1685// means, such as parsing a number into a `Decimal` or looking up an ISO currency code.
1686//
1687// The leaves keep a (cheap, reference-counted) clone of their [`json::Element`] so
1688// the lowering step can still attach its semantic warnings to the right path.
1689
1690/// A JSON array the builder walked, retaining the element it was built from.
1691///
1692/// The items are kept as `Integrity` values so one unreadable entry does not cost the
1693/// others. The element is what a warning about the array *as a whole* anchors to - an empty
1694/// list, or a list whose contents are individually fine but collectively wrong - which no
1695/// item can stand in for.
1696#[derive(Clone, Debug, PartialEq, Eq)]
1697pub(crate) struct List<'buf, T> {
1698    elem: json::Element<'buf>,
1699    items: Vec<Integrity<T>>,
1700}
1701
1702impl<'buf, T> List<'buf, T> {
1703    pub(super) fn new(elem: json::Element<'buf>, items: Vec<Integrity<T>>) -> Self {
1704        Self { elem, items }
1705    }
1706
1707    /// The number of items in the array, readable or not.
1708    pub fn len(&self) -> usize {
1709        self.items.len()
1710    }
1711
1712    /// True if the array holds no items at all.
1713    pub fn is_empty(&self) -> bool {
1714        self.items.is_empty()
1715    }
1716}
1717
1718impl<'a, T> IntoIterator for &'a List<'_, T> {
1719    type Item = &'a Integrity<T>;
1720    type IntoIter = std::slice::Iter<'a, Integrity<T>>;
1721
1722    fn into_iter(self) -> Self::IntoIter {
1723        self.items.iter()
1724    }
1725}
1726
1727impl<T> std::ops::Index<usize> for List<'_, T> {
1728    type Output = Integrity<T>;
1729
1730    /// # Panics
1731    ///
1732    /// Panics if `index` is out of bounds, as every `Index` implementation does. Use
1733    /// `IntoIterator` to walk the items without naming a position.
1734    #[expect(
1735        clippy::indexing_slicing,
1736        reason = "an `Index` impl is a bounds-checked panic by definition"
1737    )]
1738    fn index(&self, index: usize) -> &Self::Output {
1739        &self.items[index]
1740    }
1741}
1742
1743impl<'buf, T> HasElement<'buf> for List<'buf, T> {
1744    fn element(&self) -> &json::Element<'buf> {
1745        &self.elem
1746    }
1747}
1748
1749/// A JSON value the builder confirmed to be a string.
1750///
1751/// `text` is the confirmed string content (escapes not yet decoded), borrowed from the
1752/// source buffer; the builder proved its kind, so the lowering step reads it without
1753/// rechecking. Length and other lexical checks are applied by the builder when the leaf
1754/// is constructed; see [`crate::schema::build`].
1755#[derive(Clone, Debug)]
1756pub(crate) struct Str<'buf> {
1757    elem: json::Element<'buf>,
1758    value: json::RawStr<'buf>,
1759}
1760
1761impl<'buf> Str<'buf> {
1762    pub(super) fn new(elem: json::Element<'buf>, value: json::RawStr<'buf>) -> Self {
1763        Self { elem, value }
1764    }
1765
1766    /// The confirmed string content (escapes not yet decoded).
1767    pub fn value(&self) -> json::RawStr<'buf> {
1768        self.value
1769    }
1770}
1771
1772impl<'buf> HasElement<'buf> for Str<'buf> {
1773    fn element(&self) -> &json::Element<'buf> {
1774        &self.elem
1775    }
1776}
1777
1778/// A JSON value the builder confirmed to be a number, remembering whether it was
1779/// written as a JSON number or encoded as a JSON string.
1780///
1781/// OCPI allows a `number` to be encoded as a string; the [`Number::StringEncoded`]
1782/// variant records that so the builder can flag it and the lowering step can still
1783/// read the digits.
1784#[derive(Clone, Debug)]
1785pub(crate) enum Number<'buf> {
1786    /// A syntactically valid RFC 8259 JSON number.
1787    ///
1788    /// `digits` is the validated number text, borrowed from the source buffer. The
1789    /// builder proved its shape, so the lowering step reads it without rechecking.
1790    Number {
1791        elem: json::Element<'buf>,
1792        digits: &'buf str,
1793    },
1794    /// A number encoded as a JSON string.
1795    ///
1796    /// There are no guarantees made about the contents of the string; `text` may, for
1797    /// example, contain escape sequences the lowering step must still decode.
1798    StringEncoded {
1799        elem: json::Element<'buf>,
1800        value: json::RawStr<'buf>,
1801    },
1802}
1803
1804impl<'buf> HasElement<'buf> for Number<'buf> {
1805    fn element(&self) -> &json::Element<'buf> {
1806        match self {
1807            Self::Number { elem, digits: _ } | Self::StringEncoded { elem, value: _ } => elem,
1808        }
1809    }
1810}
1811
1812/// A JSON string the builder confirmed to be one of an enum's permitted variants,
1813/// carrying the typed OCPI enum `T` it resolved to.
1814///
1815/// The builder resolves the string to its typed variant during extraction (the
1816/// schema field's concrete `T` is known there), so the lowering step reads a typed
1817/// Rust enum directly and never re-parses the string or repeats the membership check.
1818///
1819/// Only the resolved variant is kept. The case a value was written in is the walk's
1820/// business, which reports on it from the element before an `Enum` exists.
1821#[derive(Clone, Debug)]
1822pub(crate) struct Enum<'buf, T> {
1823    elem: json::Element<'buf>,
1824    value: T,
1825}
1826
1827impl<'buf, T: OcpiEnum> Enum<'buf, T> {
1828    pub fn new(elem: json::Element<'buf>, value: T) -> Self {
1829        Self { elem, value }
1830    }
1831
1832    /// The typed OCPI enum the value resolved to.
1833    pub fn value(&self) -> T {
1834        self.value
1835    }
1836}
1837
1838impl<'buf, T> HasElement<'buf> for Enum<'buf, T> {
1839    fn element(&self) -> &json::Element<'buf> {
1840        &self.elem
1841    }
1842}
1843
1844/// A single OCPI enum, as modeled by the schema layer. Implemented (via the
1845/// [`ocpi_enum!`] macro) by each version-specific OCPI enum so a generic
1846/// [`Enum<T>`] can be resolved and rendered without naming the concrete type.
1847pub(crate) trait OcpiEnum: Copy {
1848    /// Resolve a canonical spec value (one of the schema's permitted variants) to
1849    /// its typed variant. Returns `None` for a value outside this enum's set.
1850    fn from_canonical(value: &str) -> Option<Self>;
1851}
1852
1853/// Define an OCPI enum: its Rust type, the variant table used by [`Scalar::Enum`],
1854/// and the [`OcpiEnum`] impl that maps between the typed variant and its spec value.
1855///
1856/// The body lists each Rust variant with the exact spec value it serializes to.
1857/// `VARIANTS` (the permitted spec values) and [`OcpiEnum::from_canonical`]
1858/// (value-to-variant) are both generated from that single list, so the two
1859/// cannot drift.
1860macro_rules! ocpi_enum {
1861    ($kind:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
1862        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1863        pub(crate) enum $kind {
1864            $($variant),+
1865        }
1866
1867        impl $kind {
1868            /// The permitted spec values, in the case the spec writes them. Used as the
1869            /// `Scalar::Enum` table.
1870            const VARIANTS: &'static [&'static str] = &[$($value),+];
1871        }
1872
1873        impl super::OcpiEnum for $kind {
1874            fn from_canonical(value: &str) -> Option<Self> {
1875                match value {
1876                    $($value => Some(Self::$variant),)+
1877                    _ => None,
1878                }
1879            }
1880        }
1881    };
1882}
1883pub(crate) use ocpi_enum;