ocpi-tariffs 0.54.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
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
//! Validate a [`json::Document`] against the OCPI schema for a given version.
//!
//! The walk checks the JSON kind, string length, array cardinality, and enum variant of
//! every field the spec defines, and reports each violation as a [`Warning`]. It also
//! builds the intermediate representation the pricing, linting, and explain features read.
//!
//! [`Warning`] is the only public item here. The intermediate representation and the
//! per-version schema tables are an implementation detail: callers reach the validated
//! data through [`cdr::from_json`](crate::cdr::from_json) and
//! [`tariff::from_json`](crate::tariff::from_json), which return the [`Warning`]s this
//! module produced alongside the object they built.

pub(crate) mod v211;
pub(crate) mod v221;

mod build;

#[cfg(test)]
mod test_nearest_spellings;
#[cfg(test)]
mod test_walk;

use std::{borrow::Cow, collections::BTreeSet};

use rust_decimal::Decimal;

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

/// 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.
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(crate) 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` (which is 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`], a date uses [`Scalar::Date`] and a time of day uses [`Scalar::Time`].
    String,
    /// A JSON string holding a calendar date, which the spec writes as `YYYY-MM-DD`. A date the
    /// library reads but that is written another way, such as `2023-1-5`, is reported as
    /// [`Warning::IncorrectFormat`]. A date the library does not read is left for the lowering to
    /// reject.
    Date,
    /// A JSON string holding a time of day, which the spec writes as `HH:MM`. A time the library
    /// reads but that is written another way, such as `9:05`, is reported as
    /// [`Warning::IncorrectFormat`]. A time the library does not read is left for the lowering to
    /// reject.
    Time,
    /// 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(crate) 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(crate) fn map_some<U, F: FnOnce(&T) -> U>(&self, op: F) -> Option<U> {
        match self {
            Integrity::Ok(Some(v)) => Some(op(v)),
            Integrity::Ok(None) | Integrity::Missing(_) | Integrity::Err(_) => None,
        }
    }
}

/// 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),
                    ),)*
                }
            }
        }
    };
    (@keep_element $ty:ident { $($field:ident),* $(,)? }) => {
        impl<'buf> $ty<'buf> {
            /// An empty builder for the JSON object at `elem`.
            ///
            /// Most IR objects don't need to save the JSON element they were created from.
            /// But some objects are removed when empty. An element's byte span is needed
            /// for the removal. Every field starts `Missing` with an associated `elem`.
            /// Each field is then set by the IR walk.
            pub(super) fn new(elem: &json::Element<'buf>) -> Self {
                Self {
                    elem: elem.clone(),
                    $($field: super::Integrity::Missing(
                        $crate::warning::Element::from_json(elem),
                    ),)*
                }
            }
        }

        impl<'buf> super::HasElement<'buf> for $ty<'buf> {
            fn element(&self) -> &json::Element<'buf> {
                &self.elem
            }
        }
    };
}
pub(crate) use ir_object;

/// 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(crate) 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 the OCPI schema.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Warning {
    /// A field present in the JSON that the schema does not list.
    UnexpectedField,
    /// A field whose name is a few edits from the name of a field the object doesn't list, and no
    /// farther from it than from any other. Parsing reports the field as misspelled or unexpected,
    /// never both.
    ///
    /// Counting edits ignores ASCII case and `_`, so parsing reports `dayOfWeek` as a misspelling
    /// of `day_of_week`. When the name and the field both have fewer than 3 characters, not
    /// counting `_`, parsing doesn't allow any edit between them, so it reports `ip` as unexpected
    /// rather than as a misspelling of `id`. Parsing reports a name equally near several fields as
    /// a possible misspelling of each, because it can't tell which one the author meant.
    MisspelledField {
        /// The schema fields the misspelled name is nearest to, in the order the schema lists them.
        /// It is never empty, and holds more than one name when several are equally near.
        expected: Vec<&'static str>,
    },
    /// A field the spec for this version does not define, which this layer reads anyway
    /// because real-world documents carry it. The value is still validated and retained.
    NonSpecField,
    /// An object carries this key more than once, and a later occurrence supersedes this one.
    ///
    /// Duplicate keys are legal JSON and the OCPI spec does not define them, so the value is
    /// resolved to the **last** occurrence. Every earlier occurrence is reported as a warning,
    /// so the anchors are exactly the ones a fix would remove.
    DuplicateField,
    /// A field name written with escapes that all decode, such as `"min\u005fkwh"`. Parsing reads
    /// the field as `min_kwh`. No field OCPI defines needs an escape, so a real document is
    /// unlikely to contain one.
    FieldNameContainsEscapeCodes,
    /// A field name with an escape that fails to decode, such as `"min\u00zfkwh"`. Parsing
    /// can't tell which field the name means, so it ignores the field and also raises
    /// `UnexpectedField` for it.
    FieldNameInvalidEscape,
    /// 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.
    InvalidType {
        /// The JSON kind the schema expects.
        expected: json::ValueKind,
        /// The JSON kind encountered.
        actual: json::ValueKind,
    },
    /// A number carrying more decimals than the OCPI spec permits.
    ExcessivePrecision {
        /// The maximum number of decimals the spec allows.
        max: u32,
        /// The number of decimals actually encountered.
        scale: u32,
    },
    /// 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, read without
    /// regard to case.
    ///
    /// Parsing reports most values a few edits from a variant as [`Warning::MisspelledValue`]
    /// instead. That variant's doc says which ones parsing still reports as invalid.
    /// Parsing reads neither, so a caller looking for every unread value matches on both.
    InvalidValue {
        /// The permitted spec values, in the spec's defined case.
        expected: &'static [&'static str],
        /// The value encountered, as written in the JSON (escapes not decoded).
        actual: String,
    },
    /// A string value that is a few edits from one or more of an enum field's variants, and no
    /// farther from those than from any other variant. Parsing reports the value as misspelled or
    /// invalid, never both. Parsing doesn't read a misspelled value, just as it doesn't read an
    /// invalid one.
    ///
    /// Parsing counts edits as it does for [`Warning::MisspelledField`], so it reports `MONDAI` as
    /// a misspelling of `MONDAY`, and `AC` as invalid rather than as a misspelling of `DC`. Parsing
    /// reports a value with an escape that fails to decode as invalid. Parsing reports a value
    /// equally near more than 4 variants as [`Warning::InvalidValue`], because a list that long
    /// doesn't narrow down what the author meant.
    MisspelledValue {
        /// The variants the misspelled value is nearest to, in the order the schema lists them. It
        /// is never empty, and holds more than one variant when several are equally near.
        expected: Vec<&'static str>,
        /// The value encountered, as written in the JSON (escapes not decoded).
        actual: String,
    },

    /// A string value that names one of an enum field's variants, but not in the spec's case.
    ///
    /// Both OCPI versions state that strings in messages and enumerations are case-sensitive,
    /// so the value is off-spec rather than merely unconventional. This crate reads it anyway,
    /// and says which variant it read.
    IncorrectCase {
        /// The variant the value named, in the spec's defined case.
        expected: &'static str,
        /// The value encountered, as written in the JSON (escapes not decoded).
        actual: String,
    },

    /// A date or time of day this crate reads, but not written in the form the spec uses. The spec
    /// writes a date as `YYYY-MM-DD` and a time as `HH:MM`. So validating a tariff reports
    /// `2023-1-5` with an `expected` of `2023-01-05`, and `9:5` with an `expected` of `09:05`. A
    /// value with spaces around it is reported too.
    ///
    /// OCPI 2.2.1 gives `start_date` and `end_date` a regex the value has to match exactly. OCPI
    /// 2.1.1 gives only the example `2015-12-24`. Both versions give `start_time` and `end_time` a
    /// regex. This crate reports the same warning for both versions, and reads the value either
    /// way.
    ///
    /// * See: [OCPI spec 2.2.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>)
    /// * See: [OCPI spec 2.1.1: Tariff Restrictions](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#45-tariffrestrictions-class>)
    IncorrectFormat {
        /// The value this crate read, written in the spec's form.
        expected: String,
        /// The value encountered, as written in the JSON (escapes not decoded).
        actual: String,
    },
    /// An empty array for a field whose schema requires one or more elements.
    ///
    /// The only cardinality the schema can violate is "one or more", and the only way to
    /// violate it is to hold nothing, so this variant carries no data.
    Cardinality,
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::UnexpectedField => warning::Id::from_static("unexpected_field"),
            Self::MisspelledField { expected } => {
                warning::Id::from_string(format!("misspelled_field({})", expected.join(", ")))
            }
            Self::NonSpecField => warning::Id::from_static("non_spec_field"),
            Self::MissingField { name } => {
                warning::Id::from_string(format!("missing_field({name})"))
            }
            Self::NullField => warning::Id::from_static("null_field"),
            Self::DuplicateField => warning::Id::from_static("duplicate_field"),
            Self::FieldNameContainsEscapeCodes => {
                warning::Id::from_static("field_name_contains_escape_codes")
            }
            Self::FieldNameInvalidEscape => warning::Id::from_static("field_name_invalid_escape"),
            Self::InvalidType {
                actual,
                expected: _,
            } => warning::Id::from_string(format!("invalid_type({actual})")),
            Self::ExcessivePrecision { max: _, scale: _ } => {
                warning::Id::from_static("excessive_precision")
            }
            Self::StringTooLong { max: _, len: _ } => warning::Id::from_static("string_too_long"),
            Self::InvalidValue {
                actual,
                expected: _,
            } => warning::Id::from_string(format!("invalid_value({actual})")),
            Self::MisspelledValue {
                expected,
                actual: _,
            } => warning::Id::from_string(format!("misspelled_value({})", expected.join(", "))),
            Self::IncorrectCase {
                expected: _,
                actual: _,
            } => warning::Id::from_static("incorrect_case"),
            Self::IncorrectFormat {
                expected: _,
                actual: _,
            } => warning::Id::from_static("incorrect_format"),
            Self::Cardinality => warning::Id::from_static("cardinality(one or more)"),
        }
    }
}

impl std::fmt::Display for Warning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnexpectedField => f.write_str("field is not part of the schema"),
            Self::MisspelledField { expected } => write!(
                f,
                "field is not part of the schema, but may be a misspelling of `{}`",
                expected.join("` or `")
            ),
            Self::NonSpecField => f.write_str(
                "field is not defined by the OCPI version of this document; it is read anyway",
            ),
            Self::MissingField { name } => write!(f, "required field `{name}` is missing"),
            Self::NullField => f.write_str(
                "field is `null`. `null` fields have no semantic meaning for OCPI objects",
            ),
            Self::DuplicateField => f.write_str(
                "field appears more than once in this object; a later occurrence is the value used",
            ),
            Self::FieldNameContainsEscapeCodes => {
                f.write_str("field name contains escape codes, which no OCPI field name needs")
            }
            Self::FieldNameInvalidEscape => {
                f.write_str("field name contains an escape that fails to decode")
            }
            Self::InvalidType { expected, actual } => {
                write!(f, "expected {expected} found {actual}")
            }
            Self::ExcessivePrecision { max, scale } => {
                write!(
                    f,
                    "number has `{scale}` decimals, but the maximum allowed is `{max}`"
                )
            }
            Self::StringTooLong { max, len } => {
                write!(
                    f,
                    "string is `{len}` characters, but the maximum allowed is `{max}`"
                )
            }
            Self::InvalidValue { expected, actual } => {
                write!(
                    f,
                    "value `{actual}` is not one of the permitted values: {}",
                    expected.join(", ")
                )
            }
            Self::MisspelledValue { expected, actual } => write!(
                f,
                "value `{actual}` is not one of the permitted values, but may be a misspelling of `{}`",
                expected.join("` or `")
            ),
            Self::IncorrectCase { expected, actual } => {
                write!(
                    f,
                    "value `{actual}` is not written in the case the spec uses: `{expected}`"
                )
            }
            Self::IncorrectFormat { expected, actual } => {
                write!(
                    f,
                    "value `{actual}` is not written in the format the spec uses: `{expected}`"
                )
            }
            Self::Cardinality => f.write_str("expected one or more elements, found 0"),
        }
    }
}

impl warning::Set<Warning> {
    /// 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 { name: _ }));

            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 { name: _ }));
    }

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

    /// 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 { max: _, len: _ }));
    }
}

/// 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(_) | Scalar::Date | Scalar::Time => {
            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::InvalidType { 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::Date => {
            // The kind gate above guarantees a string.
            let json::Value::String(text) = elem.value() else {
                unreachable!("kind gate guarantees a string");
            };
            check_date_format(elem, *text, warnings);
            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
        }
        Scalar::Time => {
            // The kind gate above guarantees a string.
            let json::Value::String(text) = elem.value() else {
                unreachable!("kind gate guarantees a string");
            };
            check_time_format(elem, *text, warnings);
            Integrity::Ok(build::Node::Str(Str::new(elem.clone(), *text)))
        }
        Scalar::StringMax(max) => {
            // 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 {
                let decoded = value.decode_escapes().ignore_warnings();

                // `decode_escapes` borrows the value as written when an escape fails to decode, so
                // a borrowed value with a backslash is malformed. The walk can't tell which variant
                // a malformed value means, just as it can't for a malformed field name, so it
                // suggests none.
                let nearest = match &decoded {
                    Cow::Borrowed(raw) if raw.contains('\\') => Vec::new(),
                    Cow::Borrowed(_) | Cow::Owned(_) => {
                        nearest_spellings(&decoded, variants.iter().copied())
                    }
                };
                let actual = value.as_unescaped_str().to_owned();
                let warning = match nearest.len() {
                    1..=MISSPELLED_VALUE_MAX_EXPECTED => Warning::MisspelledValue {
                        expected: nearest,
                        actual,
                    },
                    _ => Warning::InvalidValue {
                        expected: variants,
                        actual,
                    },
                };
                warnings.insert(elem, warning);
                return Integrity::Err(warning::Element::from_json(elem));
            };

            // The match above ignores case and decodes escapes, so a value that reaches here
            // and still differs from the variant differs in case alone.
            if !value.eq_any_escape_aware(&[canonical]) {
                warnings.insert(
                    elem,
                    Warning::IncorrectCase {
                        expected: canonical,
                        actual: value.as_unescaped_str().to_owned(),
                    },
                );
            }

            Integrity::Ok(build::Node::Enum(elem.clone(), canonical))
        }
        Scalar::Number => {
            // 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) => {
                    check_precision(elem, digits, warnings);
                    Integrity::Ok(build::Node::Number(Number::Number {
                        elem: elem.clone(),
                        digits,
                    }))
                }
                json::Value::String(text) => {
                    let decoded = text.decode_escapes().ignore_warnings();
                    check_precision(elem, &decoded, warnings);
                    Integrity::Ok(build::Node::Number(Number::StringEncoded {
                        elem: elem.clone(),
                        value: *text,
                    }))
                }
                json::Value::Null
                | json::Value::True
                | json::Value::False
                | json::Value::Array(_)
                | json::Value::Object(_) => unreachable!(
                    "kind gate rejects any value that is neither a number nor a string"
                ),
            }
        }
        Scalar::Boolean => match elem.value() {
            json::Value::True => Integrity::Ok(build::Node::Bool(true)),
            json::Value::False => Integrity::Ok(build::Node::Bool(false)),
            json::Value::Null
            | json::Value::Number(_)
            | json::Value::String(_)
            | json::Value::Array(_)
            | json::Value::Object(_) => unreachable!("kind gate rejects any value but a boolean"),
        },
        // Unreachable: handled above.
        Scalar::Any => Integrity::Missing(warning::Element::from_json(elem)),
    }
}

/// Report a number written with more decimals than the spec allows.
///
/// Raised here rather than during lowering because the walk visits every numeric field, so
/// coverage does not depend on which consumer happens to lower which value: `price` lowered all of
/// them and reported, `lint` lowered three and reported three.
///
/// A value that does not parse is left alone. The lowering reports the parse failure with the
/// reason, and a number that is not a number has no precision to complain about.
fn check_precision(elem: &json::Element<'_>, digits: &str, warnings: &mut warning::Set<Warning>) {
    let Ok(decimal) = Decimal::from_str_exact(digits) else {
        return;
    };

    let scale = decimal.scale();
    if scale > number::SCALE {
        warnings.insert(
            elem,
            Warning::ExcessivePrecision {
                max: number::SCALE,
                scale,
            },
        );
    }
}

/// Report a date written other than as `YYYY-MM-DD`, with the same date in that form.
///
/// This function reads the date with `datetime::parse_date`, the function the date lowering uses.
/// So it reports only a date the library reads, and the date it proposes is the one the library
/// already uses, which is why `--fix` can apply it without changing what a session costs. The
/// forms `parse_date` reads besides `YYYY-MM-DD` are listed on it.
///
/// A date that does not parse is left to the lowering, which reports it. So is a date written with
/// escapes: `NaiveDate::from_schema` rejects one, so rewriting it would turn a date the library
/// does not read into one it does. The raw text of such a date holds a backslash, which
/// `parse_date` rejects anyway, so the escape check states the rule rather than being what enforces
/// it.
fn check_date_format(
    elem: &json::Element<'_>,
    text: json::RawStr<'_>,
    warnings: &mut warning::Set<Warning>,
) {
    if text.lexical_issues().escapes {
        return;
    }

    let actual = text.as_unescaped_str();

    let Ok(date) = datetime::parse_date(actual) else {
        return;
    };

    let expected = date.format("%Y-%m-%d").to_string();

    if actual != expected {
        warnings.insert(
            elem,
            Warning::IncorrectFormat {
                expected,
                actual: actual.to_owned(),
            },
        );
    }
}

/// Report a time of day written other than as `HH:MM`, with the same time in that form.
///
/// This is `check_date_format` for a time. It reads the time with `datetime::parse_time`, the
/// function the time lowering uses, so the time it proposes is the one the library already uses.
///
/// A time that does not parse is left to the lowering, which reports it. So is a time written with
/// escapes: `NaiveTime::from_schema` rejects one, so rewriting it would turn a time the library
/// does not read into one it does. The raw text of such a time holds a backslash, which
/// `parse_time` rejects anyway, so the escape check states the rule rather than being what enforces
/// it.
fn check_time_format(
    elem: &json::Element<'_>,
    text: json::RawStr<'_>,
    warnings: &mut warning::Set<Warning>,
) {
    if text.lexical_issues().escapes {
        return;
    }

    let actual = text.as_unescaped_str();

    let Ok(time) = datetime::parse_time(actual) else {
        return;
    };

    let expected = time.format("%H:%M").to_string();

    if actual != expected {
        warnings.insert(
            elem,
            Warning::IncorrectFormat {
                expected,
                actual: actual.to_owned(),
            },
        );
    }
}

/// 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::InvalidType {
            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`], or as a [`Warning::MisspelledField`] when its
    /// name is a few edits from a field the object doesn't list.
    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 in document order, so a duplicated key resolves to its last
/// occurrence. Records unexpected, duplicate 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::InvalidType {
                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.
    //
    // Iterate in reverse, the way `open_array` does, so the `Step::Visit`s are pushed in
    // reverse and therefore popped in document order. Each visit assigns into the builder,
    // so a key carried twice resolves to its last occurrence.
    let mut seen = vec![false; object.fields.len()];
    let mut holds_value = vec![false; object.fields.len()];
    let mut claimed: BTreeSet<json::Key<'buf>> = BTreeSet::new();
    let mut unlisted_fields = Vec::new();
    for field in fields.iter().rev() {
        let key = field.key().to_key();

        // Reverse order means the first sighting of a key is its *last* occurrence in the
        // document, the one whose value survives; every sighting after that is superseded.
        // Reported even inside a `NonSpecObject`, because a document carrying one field
        // twice is a fault of the document rather than a question about the schema.
        if !claimed.insert(key.clone()) {
            warnings.insert(field.element(), Warning::DuplicateField);
        }

        // The walk raises `FieldNameContainsEscapeCodes` and `FieldNameInvalidEscape` even inside a
        // `NonSpecObject`, because an escape in a field name is a fault of the document rather than
        // a question about the schema.
        let name = match &key {
            json::Key::Plain(name) => *name,
            json::Key::Decoded(name) => {
                warnings.insert(field.element(), Warning::FieldNameContainsEscapeCodes);
                name.as_str()
            }
            json::Key::Malformed(_) => {
                // No schema field name contains a backslash, so a malformed name can't match a
                // schema field. The walk raises `UnexpectedField` for the field as for any other
                // unlisted name, so a caller who removes unexpected fields removes this field too.
                // The walk doesn't visit the field's value.
                warnings.insert(field.element(), Warning::FieldNameInvalidEscape);
                if let Unlisted::Report = unlisted {
                    warnings.insert(field.element(), Warning::UnexpectedField);
                }
                continue;
            }
        };
        let Ok(idx) = object.fields.binary_search_by_key(&name, |fd| fd.name) else {
            // Not in the schema: record it and do not walk its subtree.
            if let Unlisted::Report = unlisted {
                unlisted_fields.push((field.element(), name.to_owned()));
            }
            continue;
        };
        if let Some(flag) = seen.get_mut(idx) {
            *flag = true;
        }
        if !matches!(field.element().value(), json::Value::Null)
            && let Some(flag) = holds_value.get_mut(idx)
        {
            *flag = true;
        }
        if let Some(fd) = object.fields.get(idx) {
            // 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 },
            });
        }
    }

    // The walk suggests only a schema field absent from the object, because renaming an unlisted
    // field to a present one would repeat that key. Which fields are present is known only once the
    // loop above has seen every field, so the walk reports the unlisted fields here.
    //
    // The candidates come from `holds_value` rather than `seen`, so a field whose value is `null`
    // counts as absent. The fix for `NullField` removes that field. If a `null` field is not
    // removed, renaming a misspelled sibling could result in duplicate fields. Built from `seen`,
    // the candidates would leave `dayOfWeek` beside `"day_of_week": null` reported as unexpected,
    // and `--fix` would remove both.
    for (field, name) in unlisted_fields {
        let absent = object
            .fields
            .iter()
            .zip(&holds_value)
            .filter(|(_, holds)| !**holds)
            .map(|(fd, _)| fd.name);
        let expected = nearest_spellings(&name, absent);
        let warning = if expected.is_empty() {
            Warning::UnexpectedField
        } else {
            Warning::MisspelledField { expected }
        };
        warnings.insert(field, warning);
    }

    // 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
}

/// The length below which a name or value is tiny. [`nearest_spellings`] doesn't allow any edit
/// between a name and a candidate that are both tiny, so only a difference of case or `_` makes the
/// name a misspelling. The characters are counted after [`spelling_key`] removes `_`.
///
/// One edit changes half of a two-character name. `AC` is 1 edit from `DC`, and allowing that edit
/// would report an AC connector's `connector_power_type` as a misspelling of the opposite power
/// type.
///
/// Requiring both to be tiny keeps a longer name a misspelling of a tiny field. `idd` is 1 edit
/// from `id`. Applying the rule when only the shorter name is tiny would report `idd` as
/// unexpected, and `lint --fix`, asked to remove unexpected fields, would delete the tariff's only
/// copy of its id.
const TINY_NAME_LEN: usize = 3;

/// Where [`nearest_spellings`] separates short names from long ones. A name with fewer characters
/// than this is short. The characters are counted after [`spelling_key`] removes `_`, so `max_kwh`
/// is short at 6 characters and `day_of_week` is long at 9.
///
/// A name may be at most [`SHORT_NAME_MAX_EDITS`] edits from a candidate when either of the two is
/// short, and at most [`LONG_NAME_MAX_EDITS`] when both are long. When both are shorter than
/// [`TINY_NAME_LEN`], [`nearest_spellings`] doesn't allow any edit. A long name is allowed more
/// edits because each one changes a smaller share of it: two edits turn `VAT` into `FLAT`, a
/// different word, while `max_durtaoin` is still plainly `max_duration`. A length of `8` is the
/// shortest at which two edits change no more than a quarter of the name.
///
/// Taking the edits allowed from the shorter of the two names keeps a long name from being reported
/// as a misspelling of a short candidate. Taken from the misspelled name alone, `max_kwh_ac` would
/// be allowed 2 edits, and deleting its suffix would make it a misspelling of `max_kwh`.
const SHORT_NAME_LEN: usize = 8;

/// The most edits [`nearest_spellings`] allows between a short name and a candidate.
/// [`SHORT_NAME_LEN`] says what makes a name short and why it is allowed fewer edits.
const SHORT_NAME_MAX_EDITS: usize = 1;

/// The most edits [`nearest_spellings`] allows between a long name and a candidate.
/// [`SHORT_NAME_LEN`] says what makes a name long.
///
/// A value of `3` would let a real extension field pass for a misspelling. The CDR in the
/// `v211/real_world/zero_energy_use` fixture contains `total_vat`, a field OCPI doesn't define,
/// which holds the VAT on the session. Compared as `totalvat`, it is 3 edits from `totalcost`:
/// `v` becomes `c`, `a` becomes `o` and an `s` is inserted. In a CDR that lacks `total_cost`, the
/// walk would then report the VAT as a misspelling of the cost, though the two are different
/// amounts. The spec requires `total_cost`, so only an invalid CDR is exposed, but at `2` none is.
const LONG_NAME_MAX_EDITS: usize = 2;

/// The most variants a [`Warning::MisspelledValue`] names. The walk reports a value equally near
/// more variants than this as [`Warning::InvalidValue`], which lists every variant the field allows.
///
/// Each single-character insertion, deletion, substitution and adjacent swap of a variant in either
/// schema gives a typo. Outside the `DOMESTIC_*` connector types, no such typo is equally near more
/// than 4 variants. `IEC_62196_T3` is equally near `IEC_62196_T1`, `IEC_62196_T2`, `IEC_62196_T3A`
/// and `IEC_62196_T3C`. `DOMESTIC_Z` is 1 edit from every `DOMESTIC_*` type, 12 in OCPI 2.1.1 and
/// 15 in OCPI 2.2.1. A list that long doesn't narrow down what the author meant.
const MISSPELLED_VALUE_MAX_EXPECTED: usize = 4;

/// The candidates nearest to `actual` in edits, taken as the names `actual` may misspell.
///
/// Returns every candidate at the nearest distance, in the order `candidates` gives them, because
/// when several are equally near nothing says which one the author meant. Returns an empty list
/// when no candidate is within the allowed edits.
///
/// Both names are compared through [`spelling_key`], which lowercases them and removes `_`, so
/// `dayOfWeek` is 0 edits from `day_of_week`. The raw names are 4 edits apart, two inserted `_`
/// and two changes of case, which is more than [`LONG_NAME_MAX_EDITS`] allows.
///
/// [`TINY_NAME_LEN`] and [`SHORT_NAME_LEN`] say how many edits a name is allowed.
fn nearest_spellings(
    actual: &str,
    candidates: impl IntoIterator<Item = &'static str>,
) -> Vec<&'static str> {
    let actual = spelling_key(actual);

    let mut nearest = Vec::new();
    let mut nearest_distance = usize::MAX;
    for candidate in candidates {
        let candidate_key = spelling_key(candidate);
        let shorter_len = actual.len().min(candidate_key.len());
        let longer_len = actual.len().max(candidate_key.len());
        let max_distance = if longer_len < TINY_NAME_LEN {
            0
        } else if shorter_len < SHORT_NAME_LEN {
            SHORT_NAME_MAX_EDITS
        } else {
            LONG_NAME_MAX_EDITS
        };

        // A candidate farther than the nearest one found so far can't join the result.
        let allowed_distance = max_distance.min(nearest_distance);

        // An edit changes the length by at most one character, so a candidate whose length differs
        // from `actual` by more than `allowed_distance` can't be within `allowed_distance`. The
        // name comes from the input and may be millions of characters long, while every candidate
        // is a short schema name. Skipping on length keeps `edit_distance` from building a large
        // matrix.
        if actual.len().abs_diff(candidate_key.len()) > allowed_distance {
            continue;
        }

        let distance = edit_distance(&actual, &candidate_key);
        if distance > allowed_distance {
            continue;
        }
        if distance < nearest_distance {
            nearest.clear();
            nearest_distance = distance;
        }
        nearest.push(candidate);
    }

    nearest
}

/// The form of `name` that [`nearest_spellings`] compares. OCPI writes field names in snake case and
/// enum values in upper snake case, so ignoring case and `_` makes a camel-case or wrongly cased
/// name compare equal to the one the spec writes.
///
/// Returns characters rather than a string, so [`edit_distance`] counts a non-ASCII character as
/// one character rather than as each of its UTF-8 bytes.
fn spelling_key(name: &str) -> Vec<char> {
    name.chars()
        .filter(|&c| c != '_')
        .map(|c| c.to_ascii_lowercase())
        .collect()
}

/// The fewest single-character insertions, deletions, substitutions and swaps of two adjacent
/// characters that turn `a` into `b`.
///
/// This is the optimal string alignment distance. Plain Levenshtein distance would count a swapped
/// pair, a common typo, as two edits.
///
/// Wikipedia gives the algorithm as pseudocode, and this function follows it: [Optimal string
/// alignment distance][osa].
///
/// [osa]: https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
#[expect(
    clippy::indexing_slicing,
    reason = "every index is at most the length of the string that sizes that matrix dimension"
)]
#[expect(
    clippy::arithmetic_side_effects,
    reason = "each `- 1` and `- 2` is guarded by the loop bounds, and a distance can't exceed the longer length"
)]
fn edit_distance(a: &[char], b: &[char]) -> usize {
    // `distances[i][j]` is the distance from the first `i` characters of `a` to the first `j`
    // characters of `b`. Row `0` and column `0` are the empty prefix, so the matrix has one row and
    // one column more than the strings have characters. In the loop below, each `+ 1` is one edit.
    let mut distances = vec![vec![0; b.len() + 1]; a.len() + 1];

    // Column `0` holds the distance from each prefix of `a` to the empty string, one deletion per
    // character. Row `0` holds the distance from the empty string to each prefix of `b`, one
    // insertion per character.
    for (i, row) in distances.iter_mut().enumerate() {
        row[0] = i;
    }
    for (j, cell) in distances[0].iter_mut().enumerate() {
        *cell = j;
    }

    for i in 1..=a.len() {
        for j in 1..=b.len() {
            // Row `i` and column `j` are prefixes ending with `a[i - 1]` and `b[j - 1]`.
            let a_last = a[i - 1];
            let b_last = b[j - 1];

            let deletion = distances[i - 1][j] + 1;
            let insertion = distances[i][j - 1] + 1;
            let substitution = distances[i - 1][j - 1] + usize::from(a_last != b_last);
            let mut distance = deletion.min(insertion).min(substitution);

            // The two prefixes end in the same two characters in swapped order, so one swap added
            // to the distance before that pair, `distances[i - 2][j - 2]`, is another way to reach
            // this cell.
            if i > 1 && j > 1 && a_last == b[j - 2] && a[i - 2] == b_last {
                let transposition = distances[i - 2][j - 2] + 1;
                distance = distance.min(transposition);
            }

            distances[i][j] = distance;
        }
    }

    distances[a.len()][b.len()]
}

/// 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::InvalidType {
                expected: json::ValueKind::Array,
                actual: elem.value().kind(),
            },
        );
        return TypeExpectation::Invalid;
    };

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

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

    // 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, digits: _ } | Self::StringEncoded { elem, value: _ } => 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.
///
/// Only the resolved variant is kept. The case a value was written in is the walk's
/// business, which reports on it from the element before an `Enum` exists.
#[derive(Clone, Debug)]
pub(crate) struct Enum<'buf, T> {
    elem: json::Element<'buf>,
    value: T,
}

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

    /// The typed OCPI enum the value resolved to.
    pub fn value(&self) -> T {
        self.value
    }
}

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>;
}

/// 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) and [`OcpiEnum::from_canonical`]
/// (value-to-variant) are both generated from that single list, so the two
/// cannot drift.
macro_rules! ocpi_enum {
    ($kind:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub(crate) enum $kind {
            $($variant),+
        }

        impl $kind {
            /// The permitted spec values, in the case the spec writes them. 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,
                }
            }
        }
    };
}
pub(crate) use ocpi_enum;