ocpi-tariffs 0.52.0

OCPI tariff calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
pub mod v211;
pub mod v221;

mod build;

#[cfg(test)]
mod tests;

use std::collections::BTreeSet;

use crate::{
    json,
    warning::{self, IntoCaveat as _},
    Caveat, Verdict,
};

/// Lower a borrowed schema IR object `Source` into a domain type.
///
/// The schema has already validated the kind, length, cardinality, and enum
/// variants. The `FromSchema` only needs to perform semantic interpretation.
// `allow`, not `expect`: the trait is exercised by tests (so the lint does not fire in
// the test build) but is not yet called from non-test code (so it does fire in the lib
// build). An `expect` cannot hold for both until the integration lands.
#[allow(dead_code, reason = "Pending `FromSchema` integration in a feature")]
pub(crate) trait FromSchema<'buf, Source>: Sized {
    /// Warning type emitted for semantic issues found while lowering.
    type Warning: warning::Warning;

    /// Convert `source` to `Self`, collecting any semantic issues as warnings.
    fn from_schema(source: &Source) -> Verdict<Self, Self::Warning>;
}

/// A schema-IR value that carries the [`json::Element`] it was built from.
///
/// Every leaf ([`Str`], [`Number`], [`Enum`]) and every object IR value that retains its
/// element implements this. It gives the lowering step a uniform way to reach a value's
/// element without naming the concrete type.
///
/// See [`warning::Set::ok_or_bail`].
pub(crate) trait HasElement<'buf> {
    /// The element this value was built from.
    fn element(&self) -> &json::Element<'buf>;
}

/// Describes the expected structure of a JSON value.
#[derive(Clone, Copy)]
enum Schema {
    /// A scalar value of a known JSON kind (see [`Scalar`]).
    Scalar(Scalar),
    /// A JSON object with a known set of fields.
    Object(&'static Object),
    /// A JSON object the spec for this version does not define, but which this layer reads
    /// anyway (see [`Presence::NonSpec`]).
    ///
    /// A field the object does not list is not reported: the object itself is already
    /// flagged as non-spec, so listing what it contains adds noise rather than
    /// information.
    NonSpecObject(&'static Object),
    /// A `Price` value, which may be either a JSON object or a bare JSON number.
    ///
    /// OCPI 2.1.1 wrote a price as a bare `number`; 2.2.1 made it a `Price` object.
    /// A JSON object is validated against the wrapped [`Object`] as usual. A bare JSON
    /// number is accepted (and flagged as a type mismatch) and lowered to a `Price`
    /// whose `excl_vat` is that number, leaving `incl_vat` absent. Any other kind is a
    /// type error.
    Price(&'static Object),
    /// A homogeneous JSON array; each element validated against `item`, with a
    /// minimum element count given by `cardinality`.
    Array {
        item: &'static Schema,
        cardinality: Cardinality,
    },
}

/// The minimum number of elements an array must contain.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cardinality {
    /// An array with zero or more element is expected. An empty array is valid.
    ZeroOrMore,
    /// An array with one or more elements is expected. An empty array is a violation.
    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"),
        }
    }
}

/// The expected JSON kind of a scalar field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Scalar {
    /// A JSON string with no length bound. Covers OCPI `DateTime`, `date`, and
    /// `time` (which are format-constrained, not length-constrained) and any
    /// string the spec defines without a declared length. Strings the spec
    /// declares as `string(n)` / `CiString(n)` use [`Scalar::StringMax`]; enum
    /// types use [`Scalar::Enum`].
    String,
    /// A JSON string with a maximum character length, per the OCPI `string(n)`
    /// or `CiString(n)` declaration. The value is checked to be a string and
    /// then its decoded character count is compared against the length bound.
    StringMax(usize),
    /// A JSON string constrained to a fixed set of enum variants as defined
    /// in the OCPI spec. Every OCPI enum serializes as a string. This table
    /// lists each permitted spec value (the spec requires uppercase). The value
    /// is matched case-insensitively and the matched spec value is stored in
    /// [`Enum`], to be resolved to a typed variant during extraction.
    Enum(&'static [&'static str]),
    /// A JSON number. Covers OCPI `number`, `int`, and `decimal`.
    Number,
    /// A JSON boolean.
    Boolean,
    /// Any value; the JSON kind is not constrained. Used for fields whose value
    /// is a nested object or array this schema layer deliberately does not
    /// model (e.g. `BusinessDetails`, `Hours`).
    Any,
}

/// The integrity of a field. Building an IR value is infallible.
/// Every field ends in one of these states rather than aborting the build.
/// The detail behind `Err` (the kind mismatch, the invalid value) is recorded
/// in the accompanying [`warning::Set`].
///
/// A field the OCPI spec defines as optional is typed `Integrity<Option<T>>`: an
/// absent optional field is `Ok(None)`, not [`Integrity::Missing`].
/// [`Integrity::Missing`] therefore only ever describes an absent (or `null`)
/// *required* field, which is also reported as a [`Warning::MissingField`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Integrity<T> {
    /// The field was present and built successfully.
    Ok(T),
    /// A required field was absent or `null`. This is also reported as a
    /// [`Warning::MissingField`]. The location is the containing object's, since an
    /// absent field has no element of its own.
    Missing(warning::Element),
    /// The field was present but could not be built (wrong JSON kind, or an
    /// otherwise invalid value). The location is the field's own.
    Err(warning::Element),
}

impl<T> Integrity<Option<T>> {
    /// Map the contained `Option<T>` to `Option<U>`.
    /// Return `Some(U)` if `Ok(Some(T))`.
    /// Otherwise, return `None` if `Ok(None)`, `Missing`, or `Err`.
    pub 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,
        }
    }
}

impl<T> Integrity<T> {
    /// Map the contained value, leaving `Missing`/`Err` unchanged.
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Integrity<U> {
        match self {
            Integrity::Ok(value) => Integrity::Ok(op(value)),
            Integrity::Missing(loc) => Integrity::Missing(loc),
            Integrity::Err(loc) => Integrity::Err(loc),
        }
    }

    /// Borrow the contained value.
    pub fn as_ref(&self) -> Integrity<&T> {
        match self {
            Integrity::Ok(value) => Integrity::Ok(value),
            Integrity::Missing(elem) => Integrity::Missing(elem.clone()),
            Integrity::Err(elem) => Integrity::Err(elem.clone()),
        }
    }

    /// The contained value, if `Ok`.
    pub fn ok(self) -> Option<T> {
        match self {
            Integrity::Ok(value) => Some(value),
            Integrity::Missing(_) | Integrity::Err(_) => None,
        }
    }
}

/// Generate an all-[`Integrity::Missing`] `new` constructor for an IR object struct.
macro_rules! ir_object {
    ($ty:ident { $($field:ident),* $(,)? }) => {
        impl<'buf> $ty<'buf> {
            /// An empty builder for the object at `elem`: every field starts `Missing`,
            /// anchored to `elem`, and is filled by the walk.
            pub(super) fn new(elem: &json::Element<'buf>) -> Self {
                Self {
                    $($field: super::Integrity::Missing(
                        $crate::warning::Element::from_json(elem),
                    ),)*
                }
            }
        }
    };
}
pub(crate) use ir_object;

/// Identifies which schema intermediate-representation (IR) value an [`Object`]
/// should be mapped to during the [`walk`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BuilderKind {
    /// The object is validated for warnings but not built into any IR value.
    Ignore,
    V221Tariff,
    V221Element,
    V221PriceComponent,
    V221Restrictions,
    V221Price,
    V221Cdr,
    V221CdrLocation,
    V221ChargingPeriod,
    V221CdrDimension,
    V211Tariff,
    V211Element,
    V211PriceComponent,
    V211Restrictions,
    V211Cdr,
    V211Location,
    V211ChargingPeriod,
    V211CdrDimension,
}

/// The expected fields of a JSON object.
#[derive(Clone, Copy)]
struct Object {
    fields: &'static [Field],
    /// The IR value this object is built into during the [`walk`].
    kind: BuilderKind,
}

/// One field expected in a JSON object.
#[derive(Clone, Copy)]
struct Field {
    /// JSON key name.
    ///
    /// This value is hardcoded and will never contain escapes.
    name: &'static str,
    /// Whether the field must be present.
    presence: Presence,
    /// Expected substructure of the field value.
    schema: Schema,
}

impl Field {
    /// Define a required scalar of the given JSON kind.
    const fn required(name: &'static str, scalar: Scalar) -> Self {
        Self {
            name,
            presence: Presence::Required,
            schema: Schema::Scalar(scalar),
        }
    }

    /// Define a required array (OCPI `+`: present and nonempty).
    const fn required_array(name: &'static str, item: &'static Schema) -> Self {
        Self {
            name,
            presence: Presence::Required,
            schema: Schema::Array {
                item,
                cardinality: Cardinality::OneOrMore,
            },
        }
    }

    /// Define a required object.
    const fn required_object(name: &'static str, schema: &'static Object) -> Self {
        Self {
            name,
            presence: Presence::Required,
            schema: Schema::Object(schema),
        }
    }

    /// Define a required `Price` field, which per OCPI's 2.1.1-to-2.2.1 evolution
    /// accepts either a `Price` object or a bare number.
    const fn required_price(name: &'static str, schema: &'static Object) -> Self {
        Self {
            name,
            presence: Presence::Required,
            schema: Schema::Price(schema),
        }
    }

    /// Define an optional scalar of the given JSON kind.
    const fn optional(name: &'static str, scalar: Scalar) -> Self {
        Self {
            name,
            presence: Presence::Optional,
            schema: Schema::Scalar(scalar),
        }
    }

    /// Define an optional array (OCPI `*`: may be absent or empty).
    const fn optional_array(name: &'static str, item: &'static Schema) -> Self {
        Self {
            name,
            presence: Presence::Optional,
            schema: Schema::Array {
                item,
                cardinality: Cardinality::ZeroOrMore,
            },
        }
    }

    /// Define an optional object.
    const fn optional_object(name: &'static str, schema: &'static Object) -> Self {
        Self {
            name,
            presence: Presence::Optional,
            schema: Schema::Object(schema),
        }
    }

    /// Define an optional `Price` field, which per OCPI's 2.1.1-to-2.2.1 evolution
    /// accepts either a `Price` object or a bare number.
    const fn optional_price(name: &'static str, schema: &'static Object) -> Self {
        Self {
            name,
            presence: Presence::Optional,
            schema: Schema::Price(schema),
        }
    }

    /// Define a scalar the spec for this version does not define, but which this layer
    /// reads anyway (see [`Presence::NonSpec`]).
    const fn non_spec(name: &'static str, scalar: Scalar) -> Self {
        Self {
            name,
            presence: Presence::NonSpec,
            schema: Schema::Scalar(scalar),
        }
    }

    /// Define an object the spec for this version does not define, but which this layer
    /// reads anyway (see [`Presence::NonSpec`] and [`Schema::NonSpecObject`]).
    const fn non_spec_object(name: &'static str, schema: &'static Object) -> Self {
        Self {
            name,
            presence: Presence::NonSpec,
            schema: Schema::NonSpecObject(schema),
        }
    }
}

/// Whether a field must be present in its containing object.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
    /// The schema requires the field. Its absence is a violation (also reported as
    /// [`Warning::MissingField`]).
    Required,
    /// The schema permits the field to be absent.
    Optional,
    /// The spec for this version does not define the field, but this layer reads it when a
    /// document supplies it, because real-world documents carry it.
    ///
    /// Its absence is not a violation; its presence is reported as
    /// [`Warning::NonSpecField`] so the caller still learns the document is off-spec.
    NonSpec,
}

/// A structural problem found while validating a JSON document against a [`Schema`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Warning {
    /// A field present in the JSON that the schema does not list.
    UnexpectedField,
    /// A field the spec for this version does not define, which this layer reads anyway
    /// (see [`Presence::NonSpec`]). The value is still validated and retained.
    NonSpecField,
    /// A required field absent from its containing object.
    MissingField {
        /// The field name the schema expected.
        name: &'static str,
    },
    /// A field whose value is JSON `null`. `null` fields can simply be omitted.
    NullField,
    /// A value whose JSON kind does not match the schema.
    TypeMismatch {
        /// The JSON kind the schema expects.
        expected: json::ValueKind,
        /// The JSON kind encountered.
        actual: json::ValueKind,
    },
    /// A string longer than the maximum length the schema permits.
    StringTooLong {
        /// The maximum character length the schema allows.
        max: usize,
        /// The character length actually encountered.
        len: usize,
    },
    /// A string value that is not one of an enum field's permitted variants.
    FieldInvalidValue {
        /// The permitted spec values (the spec requires uppercase).
        expected: &'static [&'static str],
        /// The value encountered, as written in the JSON (escapes not decoded).
        actual: String,
    },
    /// An array holding fewer elements than its declared [`Cardinality`] requires.
    Cardinality {
        /// The cardinality the schema requires.
        expected: Cardinality,
        /// The number of elements actually present.
        len: usize,
    },
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::UnexpectedField => warning::Id::from_static("unexpected_field"),
            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::TypeMismatch { actual, .. } => {
                warning::Id::from_string(format!("invalid_type({actual})"))
            }
            Self::StringTooLong { .. } => warning::Id::from_static("string_too_long"),
            Self::FieldInvalidValue { actual, .. } => {
                warning::Id::from_string(format!("field_invalid_value({actual})"))
            }
            Self::Cardinality { expected, .. } => {
                warning::Id::from_string(format!("cardinality({expected})"))
            }
        }
    }
}

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::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::TypeMismatch { expected, actual } => {
                write!(f, "expected {expected} found {actual}")
            }
            Self::StringTooLong { max, len } => {
                write!(
                    f,
                    "string is `{len}` characters, but the maximum allowed is `{max}`"
                )
            }
            Self::FieldInvalidValue { expected, actual } => {
                write!(
                    f,
                    "value `{actual}` is not one of the permitted values: {}",
                    expected.join(", ")
                )
            }
            Self::Cardinality { expected, len } => {
                write!(f, "expected {expected} elements, found {len}")
            }
        }
    }
}

impl warning::Set<Warning> {
    /// Collect the field paths of all [`Warning::UnexpectedField`] warnings into a set of `json::Path`s.
    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)
    }

    /// Collect the field paths of all [`Warning::NonSpecField`] warnings into a set of `json::Path`s.
    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)
    }

    /// Collect the field paths of all [`Warning::MissingField`] warnings into a set of `json::Path`s.
    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 { .. }));

            if has_missing_field {
                paths.insert(&element.path);
            }
        }

        json::PathSet::new(paths)
    }

    /// Remove all [`Warning::UnexpectedField`] warnings from the set.
    pub fn remove_unexpected_fields(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::UnexpectedField));
    }

    /// Remove all [`Warning::MissingField`] warnings from the set.
    pub fn remove_missing_fields(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::MissingField { .. }));
    }

    /// Remove all [`Warning::TypeMismatch`] warnings from the set.
    pub fn remove_type_mismatches(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::TypeMismatch { .. }));
    }

    /// Remove all [`Warning::NullField`] warnings from the set.
    pub fn remove_null_fields(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::NullField));
    }

    /// Remove all [`Warning::Cardinality`] warnings from the set.
    pub fn remove_cardinalities(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::Cardinality { .. }));
    }

    /// Remove all [`Warning::StringTooLong`] warnings from the set.
    pub fn remove_string_too_longs(&mut self) {
        self.retain(|warning| !matches!(warning, Warning::StringTooLong { .. }));
    }
}

/// Opaque-subtree marker: a value the schema does not model. The subtree is still
/// walked so nested `null`s are reported.
static ANY: Schema = Schema::Scalar(Scalar::Any);

/// A step in the [`walk`]'s work stack.
enum Step<'a, 'buf> {
    /// Visit a node: record its warnings and build its leaf, or open its
    /// object/array builder.
    Visit {
        elem: &'a json::Element<'buf>,
        schema: &'a Schema,
        slot: Slot,
    },
    /// Finalize the builder on top of the builder stack and route it to its parent.
    Close { slot: Slot },
}

/// Where a built [`build::Node`] attaches within its parent.
#[derive(Clone, Copy)]
enum Slot {
    /// The root value of the walk.
    Root,
    /// A named field of the parent object.
    Field { name: &'static str },
    /// An item of the parent array.
    Item,
    /// A value that is discarded (an unmodeled [`Scalar::Any`] subtree).
    Ignore,
}

/// Validate `doc` against `schema` and build its intermediate representation (IR) in a
/// single pass.
///
/// The returned [`build::Node`] is the value of the root [`Object`]'s [`BuilderKind`].
/// When used through the public API the returned object will be one of the CDR or tariffs
/// root types.
///
/// Building is infallible. Problems with a field emit a [`Warning`] and are stored as
/// an [`Integrity::Err`] or [`Integrity::Missing`] on the IR object's field.
///
/// NOTE: A value whose type is invalid (a type mismatch) or whose key is
/// unexpected is recorded but not descended into. Its substructure cannot
/// be compared to the schema. Opaque [`Scalar::Any`] values are still
/// walked, so nested `null`s are still reported for the inner JSON.
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;

    // Iteration order: an object's own problems are recorded before its descendants'
    // because its fields are scanned (emitting unexpected/missing warnings) when the
    // object is opened, before the field `Visit`s pushed here are popped.
    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 {
                    // An unmodeled subtree: walk children only to report nested nulls.
                    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) => {
                        // A bare number is the 2.1.1 price shape; accept it directly.
                        // Any other kind (including an object) is validated as an 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)
}

/// Build the leaf [`build::Node`] for a scalar, recording any kind, length, enum, or
/// string-encoded-number warning. Returns [`Integrity::Err`] for a wrong-kind value.
fn check_scalar<'buf>(
    warnings: &mut warning::Set<Warning>,
    elem: &json::Element<'buf>,
    scalar: Scalar,
) -> Integrity<build::Node<'buf>> {
    let expected = match scalar {
        // Enums serialize as JSON strings; their kind check is the same as a plain
        // string, with the value-membership check applied below.
        Scalar::String | Scalar::StringMax(_) | Scalar::Enum(_) => json::ValueKind::String,
        Scalar::Number => json::ValueKind::Number,
        Scalar::Boolean => json::ValueKind::Bool,
        // `Any` is handled by the caller; never built here.
        Scalar::Any => return Integrity::Missing(warning::Element::from_json(elem)),
    };

    let actual = elem.value().kind();

    // A `number` may be encoded as a JSON string; that is accepted but flagged below.
    let string_encoded_number =
        expected == json::ValueKind::Number && actual == json::ValueKind::String;
    if actual != expected && !string_encoded_number {
        warnings.insert(elem, Warning::TypeMismatch { expected, actual });
        return Integrity::Err(warning::Element::from_json(elem));
    }

    match scalar {
        Scalar::String => {
            // The kind gate above guarantees a 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::StringMax(max) => {
            // The kind gate above guarantees a string.
            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 {
                warnings.insert(
                    elem,
                    Warning::FieldInvalidValue {
                        expected: variants,
                        actual: value.as_unescaped_str().to_owned(),
                    },
                );
                return Integrity::Err(warning::Element::from_json(elem));
            };
            Integrity::Ok(build::Node::Enum(elem.clone(), canonical, value))
        }
        Scalar::Number => {
            // OCPI permits a number to be encoded as a JSON string. The value is accepted
            // either way; the linter can choose to flag the string-encoded form later. The
            // match is exhaustive in practice: the kind gate above already rejected any
            // value that is neither a JSON number nor a JSON string.
            match elem.value() {
                json::Value::Number(digits) => Integrity::Ok(build::Node::Number(Number::Number {
                    elem: elem.clone(),
                    digits,
                })),
                json::Value::String(text) => {
                    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 => Integrity::Ok(build::Node::Bool),
        // Unreachable: handled above.
        Scalar::Any => Integrity::Missing(warning::Element::from_json(elem)),
    }
}

/// If `elem` is a bare JSON number, build the [`v221::Price`] node it stands for: the
/// number becomes `excl_vat` and `incl_vat` is left absent. The bare-number form is
/// flagged as a type mismatch (an object is the 2.2.1 shape) but still accepted, per
/// OCPI's evolution from a `number` price in 2.1.1. Returns `None` for any other kind,
/// which the caller then validates as an object.
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::TypeMismatch {
            expected: json::ValueKind::Object,
            actual: json::ValueKind::Number,
        },
    );

    Some(build::Node::Price(v221::Price::from_number(
        elem.clone(),
        digits,
    )))
}

/// The [`open_array`] and [`open_object`] return whether the type they expected is
/// the type they encountered.
#[derive(Copy, Clone)]
enum TypeExpectation {
    Satisfied,
    Invalid,
}

impl TypeExpectation {
    fn is_type_invalid(self) -> bool {
        matches!(self, Self::Invalid)
    }
}

/// Whether [`open_object`] reports a field the object's schema does not list.
#[derive(Copy, Clone)]
enum Unlisted {
    /// Report it as a [`Warning::UnexpectedField`].
    Report,
    /// Say nothing. Used for a [`Schema::NonSpecObject`], which is already reported as a
    /// whole.
    Ignore,
}

/// Open an object: push its builder and a [`Step::Close`], then queue its
/// schema-matched fields. Records unexpected and missing-required-field warnings.
/// Returns `false` (and opens nothing) if `elem` is not a JSON object.
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 {
    // `fields` are sorted alphabetically by `Field::name` so the `binary_search_by_key`
    // below is valid; the `debug_assert` guards that against an out-of-order schema.
    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::TypeMismatch {
                expected: json::ValueKind::Object,
                actual: elem.value().kind(),
            },
        );
        return TypeExpectation::Invalid;
    };

    builders.push(build::empty(object.kind, elem));
    stack.push(Step::Close { slot });

    // Mark, by schema-field position, which fields the document supplies. Reusing each
    // binary-search hit here lets the missing-field scan below be a single indexed pass
    // instead of a linear `contains` per schema field.
    let mut seen = vec![false; object.fields.len()];
    for field in fields {
        let key = field.key().as_unescaped_str();
        let Ok(idx) = object.fields.binary_search_by_key(&key, |fd| fd.name) else {
            // Not in the schema: record it and do not walk its subtree.
            if let Unlisted::Report = unlisted {
                warnings.insert(field.element(), Warning::UnexpectedField);
            }
            continue;
        };
        if let Some(flag) = seen.get_mut(idx) {
            *flag = true;
        }
        if let Some(fd) = object.fields.get(idx) {
            // A field the spec does not define is read anyway, but the document is still
            // off-spec for supplying it.
            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 },
            });
        }
    }

    // An absent field has no element of its own to `Visit`, so it is recorded here.
    // Every absent field is set to `Integrity::Missing`; the field's extractor then
    // interprets that per the field's optionality (an optional field becomes
    // `Integrity::Ok(None)`, a required field stays `Integrity::Missing`). A required
    // field additionally records a `MissingField` warning against the parent, so its
    // absence is visible in both the IR and the warnings.
    for (field, &present) in object.fields.iter().zip(seen.iter()) {
        if present {
            continue;
        }

        // An absent `NonSpec` field is not a violation; the spec does not define it.
        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
}

/// Open an array: push its accumulator builder and a [`Step::Close`], then queue its
/// items in document order. Records a cardinality warning for an empty `OneOrMore`
/// array.
///
/// Returns `false` (and opens nothing) if `elem` is not a JSON array.
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::TypeMismatch {
                expected: json::ValueKind::Array,
                actual: elem.value().kind(),
            },
        );
        return TypeExpectation::Invalid;
    };

    if cardinality == Cardinality::OneOrMore && items.is_empty() {
        warnings.insert(
            elem,
            Warning::Cardinality {
                expected: cardinality,
                len: 0,
            },
        );
    }

    builders.push(build::Node::Array(
        elem.clone(),
        Vec::with_capacity(items.len()),
    ));
    stack.push(Step::Close { slot });

    // Push in reverse so items are visited, and accumulated, in document order.
    for child in items.iter().rev() {
        stack.push(Step::Visit {
            elem: child,
            schema: item,
            slot: Slot::Item,
        });
    }

    TypeExpectation::Satisfied
}

/// Queue the children of an opaque [`Scalar::Any`] element so nested `null`s are
/// still reported. Their values are discarded.
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(_) => {}
    }
}

// Constrained leaf types for the schema intermediate representation (IR).
//
// A leaf wraps a [`json::Element`] that the IR builder has already confirmed to be
// the right JSON kind. Downstream lowering (the `FromSchema` impls) therefore does
// not repeat the kind check; it only does semantic interpretation (parsing a number
// into a `Decimal`, validating an ISO currency code, and so on).
//
// The leaves keep a (cheap, reference-counted) clone of their [`json::Element`] so
// the lowering step can still attach its semantic warnings to the right path.

/// A JSON array the builder walked, retaining the element it was built from.
///
/// The items are kept as `Integrity` values so one unreadable entry does not cost the
/// others. The element is what a warning about the array *as a whole* anchors to - an empty
/// list, or a list whose contents are individually fine but collectively wrong - which no
/// item can stand in for.
#[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 }
    }

    /// The number of items in the array, readable or not.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// True if the array holds no items at all.
    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>;

    /// # Panics
    ///
    /// Panics if `index` is out of bounds, as every `Index` implementation does. Use
    /// `IntoIterator` to walk the items without naming a position.
    #[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
    }
}

/// A JSON value the builder confirmed to be a string.
///
/// `text` is the confirmed string content (escapes not yet decoded), borrowed from the
/// source buffer; the builder proved its kind, so the lowering step reads it without
/// rechecking. Length and other lexical checks are applied by the builder when the leaf
/// is constructed; see [`crate::schema::build`].
#[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 }
    }

    /// The confirmed string content (escapes not yet decoded).
    pub fn value(&self) -> json::RawStr<'buf> {
        self.value
    }
}

impl<'buf> HasElement<'buf> for Str<'buf> {
    fn element(&self) -> &json::Element<'buf> {
        &self.elem
    }
}

/// A JSON value the builder confirmed to be a number, remembering whether it was
/// written as a JSON number or encoded as a JSON string.
///
/// OCPI allows a `number` to be encoded as a string; the [`Number::StringEncoded`]
/// variant records that so the builder can flag it and the lowering step can still
/// read the digits.
#[derive(Clone, Debug)]
pub(crate) enum Number<'buf> {
    /// A syntactically valid RFC 8259 JSON number.
    ///
    /// `digits` is the validated number text, borrowed from the source buffer. The
    /// builder proved its shape, so the lowering step reads it without rechecking.
    Number {
        elem: json::Element<'buf>,
        digits: &'buf str,
    },
    /// A number encoded as a JSON string.
    ///
    /// There are no guarantees made about the contents of the string; `text` may, for
    /// example, contain escape sequences the lowering step must still decode.
    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, .. } | Self::StringEncoded { elem, .. } => elem,
        }
    }
}

/// A JSON string the builder confirmed to be one of an enum's permitted variants,
/// carrying the typed OCPI enum `T` it resolved to.
///
/// The builder resolves the string to its typed variant during extraction (the
/// schema field's concrete `T` is known there), so the lowering step reads a typed
/// Rust enum directly and never re-parses the string or repeats the membership check.
///
/// The text as written is kept alongside the resolved variant. The builder matches
/// variants case-insensitively and says nothing about the case, so a linter that wants to
/// advise on it needs the original spelling; see `raw`.
#[derive(Clone, Debug)]
pub(crate) struct Enum<'buf, T> {
    elem: json::Element<'buf>,
    value: T,
    raw: json::RawStr<'buf>,
}

impl<'buf, T: OcpiEnum> Enum<'buf, T> {
    pub fn new(elem: json::Element<'buf>, value: T, raw: json::RawStr<'buf>) -> Self {
        Self { elem, value, raw }
    }

    /// The value as written in the document (escapes not decoded).
    ///
    /// The resolved variant says what the value means; this says how it was spelled. Only a
    /// lint that advises on spelling needs it - everything else should read `value`.
    #[expect(dead_code, reason = "Used by the case lints as they are reintroduced")]
    pub fn raw(&self) -> json::RawStr<'buf> {
        self.raw
    }

    /// The typed OCPI enum the value resolved to.
    #[allow(dead_code, reason = "Will be used in FromSchema integration PR")]
    pub fn value(&self) -> T {
        self.value
    }

    /// The spec value of the wrapped variant.
    #[allow(dead_code, reason = "Will be used in FromSchema integration PR")]
    pub fn canonical(&self) -> &'static str {
        self.value.canonical()
    }
}

impl<'buf, T> HasElement<'buf> for Enum<'buf, T> {
    fn element(&self) -> &json::Element<'buf> {
        &self.elem
    }
}

/// A single OCPI enum, as modeled by the schema layer. Implemented (via the
/// [`ocpi_enum!`] macro) by each version-specific OCPI enum so a generic
/// [`Enum<T>`] can be resolved and rendered without naming the concrete type.
pub(crate) trait OcpiEnum: Copy {
    /// Resolve a canonical spec value (one of the schema's permitted variants) to
    /// its typed variant. Returns `None` for a value outside this enum's set.
    fn from_canonical(value: &str) -> Option<Self>;

    /// The spec value of this variant (the spec requires uppercase).
    fn canonical(self) -> &'static str;
}

/// Define an OCPI enum: its Rust type, the variant table used by [`Scalar::Enum`],
/// and the [`OcpiEnum`] impl that maps between the typed variant and its spec value.
///
/// The body lists each Rust variant with the exact spec value it serializes to.
/// `VARIANTS` (the permitted spec values), [`OcpiEnum::from_canonical`]
/// (value-to-variant), and [`OcpiEnum::canonical`] (variant-to-value) are all
/// generated from that single list, so the three cannot drift.
macro_rules! ocpi_enum {
    ($kind:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub enum $kind {
            $($variant),+
        }

        impl $kind {
            /// The permitted spec values (the spec requires uppercase). Used as the
            /// `Scalar::Enum` table.
            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,
                }
            }

            fn canonical(self) -> &'static str {
                match self {
                    $(Self::$variant => $value),+
                }
            }
        }
    };
}
pub(crate) use ocpi_enum;