ocpi-tariffs 0.55.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
//! These types are the basis for writing functions that can emit a set of [`Warning`]s based on the value they are trying to create.
//!
//! The aim is for functions to be as resilient as possible while creating the value and emit commentary on their progress in the form of a growing set of [`Warning`]s.
//!
//! The caller of the function can use the set of [`Warning`]s to decide whether the operation was a success or failure and whether the value can be used or needs to be modified.
//!
//! # Introducing Verdict
//!
//! A [`Verdict`] is a [`Result`] where both variants carry [`Warning`]s.
//!
//! The `Ok` variant is a [`Caveat`]: the value the function built, together with a [`Set`] of
//! warnings to take into account when using it. Hence the name.
//!
//! The `Err` variant is a [`Failure`] that contains the single [`Warning`] that stopped the
//! function and the set of warnings accumulated before it.
//! The failing warning is represented as an [`Error`] so it is ready to take part in Rust's
//! error system. The failing warning is not repeated in that set.
//!
//! So a resilient function always returns its [`Warning`]s, and the caller either gathers them
//! into a set of its own and carries on, or fails.
//!
//! Gathering warnings into a parent [`Set`] moves the responsibility of alerting the caller to
//! the existence of those warnings to the owner of that set.
//!
//! # A concrete example
//!
//! Lowering a JSON string into a [`country::Code`](crate::country::Code) illustrates the
//! general pattern.
//!
//! The schema walk has already proven the value is a string of the permitted length, so the
//! lowering is never handed a value of the wrong kind and makes no kind check. What is left is
//! semantics, and each finding is a warning rather than a hard stop:
//!
//! - The string may carry escape codes, which a country code has no use for.
//! - It may be lower case where the standard is upper case.
//! - It may be three characters where two were expected. This is the interesting case, as some
//!   [`country::Code`](crate::country::Code) fields are `alpha-3` where others are `alpha-2`.
//!   An `alpha-3` code converts to an `alpha-2` simply, so processing continues while emitting a
//!   [`Warning`].
//! - It may not name a country at all, which is the one case the lowering cannot recover from.
//!
//! The lowering is written as a `LowerSchema` impl. The sketch below names types that are private
//! to this crate but is here to illustrate the general pattern:
//!
//! ```rust,ignore
//! // file: country.rs
//!
//! pub enum Warning {
//!     ContainsEscapeCodes,
//!     Decode(json::decode::Warning),
//!     IncorrectCase,
//!     InvalidCode,
//! }
//!
//! impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for CodeSet {
//!     type Warning = Warning;
//!
//!     fn lower_schema(
//!         source: &schema::Str<'buf>,
//!         warnings: &mut dyn warning::Gather<Warning>,
//!     ) -> Result<Self, warning::Error<Warning>> {
//!         // Read the string, gathering a warning per semantic problem found.
//!     }
//! }
//! ```
//!
//! The caller decides whether the result is acceptable.

mod gather;

#[cfg(test)]
pub(crate) mod test;

#[cfg(test)]
mod test_assert_warnings;

#[cfg(test)]
mod test_contains;

#[cfg(test)]
mod test_failure_unwrap;

#[cfg(test)]
mod test_find;

#[cfg(test)]
mod test_gather;

#[cfg(test)]
mod test_group_by_elem;

#[cfg(test)]
mod test_id_path_map;

#[cfg(test)]
mod test_ids;

#[cfg(test)]
mod test_iter_warnings;

#[cfg(test)]
mod test_path_map;

#[cfg(test)]
mod test_warnings_at;

use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashSet, btree_map},
    fmt,
    ops::Deref,
    vec,
};

use tracing::{debug, info};

use crate::json;

pub(crate) use gather::{Converting, Gather, Gatherer};

#[doc(hidden)]
#[macro_export]
macro_rules! from_warning_all {
    ($($source_kind:path => $target_kind:ident::$target_variant:ident),+) => {
        $(
            /// Convert from `Warning` A to B.
            impl From<$source_kind> for $target_kind {
                fn from(warning: $source_kind) -> Self {
                    $target_kind::$target_variant(warning)
                }
            }
        )+
    };
}

/// The stable identifier of a [`Warning`] kind, such as `missing_field(id)`.
///
/// Two warnings of the same kind share an `Id`, so this is what a caller matches on to accept
/// or reject a class of warning without depending on the `Warning` type itself.
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Id(Cow<'static, str>);

impl Id {
    /// Create an `Id` from a `'static str`.
    pub(crate) const fn from_static(s: &'static str) -> Self {
        Self(Cow::Borrowed(s))
    }

    /// Create an `Id` from a `String`.
    pub(crate) const fn from_string(s: String) -> Self {
        Self(Cow::Owned(s))
    }

    /// Return the contained `str`.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A `Verdict` is a standard [`Result`] with [`Warning`]s potentially issued for both the `Ok` and `Err` variants.
pub type Verdict<T, W> = Result<Caveat<T, W>, Failure<W>>;

/// A value that may have associated [`Warning`]s.
///
/// Even though the value has been created there may be certain caveats you should be aware of before using it.
#[derive(Debug)]
pub struct Caveat<T, W: Warning> {
    /// The value created by the function.
    value: T,

    /// A list of [`Warning`]s or caveats issued when creating the value.
    warnings: Set<W>,
}

/// Read the value without taking it, which leaves the warnings attached.
///
/// `Deref` is justified here because a `Caveat` behaves transparently like its `T` and the deref is
/// a field read. It borrows, so the value cannot leave a caveat this way and the warnings cannot be
/// lost by accident.
///
/// See: <https://doc.rust-lang.org/std/ops/trait.Deref.html#when-to-implement-deref-or-derefmut>.
impl<T, W> Deref for Caveat<T, W>
where
    W: Warning,
{
    type Target = T;

    fn deref(&self) -> &T {
        &self.value
    }
}

impl<T, W> Caveat<T, W>
where
    W: Warning,
{
    /// Pair `value` with the warnings raised while producing it.
    pub(crate) fn new(value: T, warnings: Set<W>) -> Self {
        Self { value, warnings }
    }

    /// Return a ref to the warning Set.
    pub fn warnings(&self) -> &Set<W> {
        &self.warnings
    }

    /// Return the value and any [`Warning`]s stored in the `Caveat`.
    pub fn into_parts(self) -> (T, Set<W>) {
        let Self { value, warnings } = self;
        (value, warnings)
    }

    /// Return the value and drop any warnings contained within.
    pub fn ignore_warnings(self) -> T {
        self.value
    }

    /// Map the value to another target type while retaining the warnings about the source type.
    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Caveat<U, W> {
        let Self { value, warnings } = self;
        Caveat {
            value: op(value),
            warnings,
        }
    }
}

/// `Verdict` specific extension methods for the `Result` type.
pub trait VerdictExt<T, W: Warning> {
    /// Discard all warnings in the `Err` variant and keep only the warning that caused the error.
    fn only_error(self) -> Result<Caveat<T, W>, Error<W>>;
}

/// Used to log the contents of various `Verdict` impls.
#[expect(dead_code, reason = "for debugging")]
pub(crate) trait VerdictTrace<T, W: Warning> {
    /// Log the contents as `info` level.
    fn info_verdict(self, msg: &'static str) -> Self;

    /// Log the contents as `debug` level.
    fn debug_verdict(self, msg: &'static str) -> Self;
}

/// Used to log the contents of various `Result` impls.
#[expect(dead_code, reason = "for debugging")]
pub(crate) trait ResultTrace<T, W: Warning> {
    /// Log the contents as `info` level.
    fn info_result(self, msg: &'static str) -> Self;

    /// Log the contents as `debug` level.
    fn debug_result(self, msg: &'static str) -> Self;
}

impl<T, W: Warning> VerdictExt<T, W> for Verdict<T, W> {
    fn only_error(self) -> Result<Caveat<T, W>, Error<W>> {
        match self {
            Ok(c) => Ok(c),
            Err(failure) => Err(failure.ignore_warnings()),
        }
    }
}

impl<T, W: Warning> VerdictTrace<T, W> for Verdict<T, W>
where
    T: fmt::Debug,
{
    fn info_verdict(self, msg: &'static str) -> Self {
        match self {
            Ok(c) => {
                info!("{msg}: {c:#?}");
                Ok(c)
            }
            Err(failure) => {
                info!("{msg}: {failure:#?}");
                Err(failure)
            }
        }
    }

    fn debug_verdict(self, msg: &'static str) -> Self {
        match self {
            Ok(c) => {
                debug!("{msg}: {c:#?}");
                Ok(c)
            }
            Err(failure) => {
                debug!("{msg}: {failure:#?}");
                Err(failure)
            }
        }
    }
}

impl<T, W: Warning> ResultTrace<T, W> for Result<T, Failure<W>>
where
    T: fmt::Debug,
{
    fn info_result(self, msg: &'static str) -> Self {
        match self {
            Ok(c) => {
                info!("{msg}: {c:#?}");
                Ok(c)
            }
            Err(failure) => {
                info!("{msg}: {failure:#?}");
                Err(failure)
            }
        }
    }

    fn debug_result(self, msg: &'static str) -> Self {
        match self {
            Ok(c) => {
                debug!("{msg}: {c:#?}");
                Ok(c)
            }
            Err(failure) => {
                debug!("{msg}: {failure:#?}");
                Err(failure)
            }
        }
    }
}

/// The warning that caused an operation to fail.
///
/// The warning is stored apart from the source set so it is
/// clear which warning has been escalated to an error.
#[derive(Debug)]
pub struct Error<W: Warning> {
    /// The warning the operation failed on.
    warning: W,

    /// The element the warning was reported against.
    element: Element,
}

impl<W: Warning> Error<W> {
    /// Create an `Error` to be returned by a function that can't continue due to `warning`.
    /// Each warning is reported against an `element`.
    pub(crate) fn new(element: &json::Element<'_>, warning: W) -> Self {
        Self {
            warning,
            element: Element::from_json(element),
        }
    }

    /// Create an `Error` reported against an `element` taken from the schema IR.
    ///
    /// [`Error::new`] takes a [`json::Element`], which an absent or unbuildable IR field doesn't
    /// have. [`Integrity::Missing`] and [`Integrity::Err`] hold an [`Element`] instead, and `at`
    /// takes that.
    ///
    /// [`Integrity::Missing`]: crate::schema::Integrity::Missing
    /// [`Integrity::Err`]: crate::schema::Integrity::Err
    pub(crate) fn at(element: Element, warning: W) -> Self {
        Self { warning, element }
    }

    /// Return reference to the [`Warning`].
    pub fn warning(&self) -> &W {
        &self.warning
    }

    /// Consume the `Error` and return the [`Warning`].
    pub fn into_warning(self) -> W {
        self.warning
    }

    /// Return a reference to the [`Element`] that caused the [`Warning`].
    pub fn element(&self) -> &Element {
        &self.element
    }

    /// Return the constituent parts.
    pub fn parts(&self) -> (&W, &Element) {
        (&self.warning, &self.element)
    }

    /// Consume the `Cause` and return the constituent parts.
    pub fn into_parts(self) -> (W, Element) {
        let Self { warning, element } = self;
        (warning, element)
    }

    /// Converts `Error<W>` into `Error<WA>` using the `impl Into<WA> for W`.
    ///
    /// [`FromSchema::from_schema`](crate::schema::FromSchema::from_schema) uses this, as
    /// does each caller that passes another module's error up with `map_err`.
    pub(crate) fn into_other<WA>(self) -> Error<WA>
    where
        W: Into<WA>,
        WA: Warning,
    {
        let Self { warning, element } = self;
        Error {
            warning: warning.into(),
            element,
        }
    }
}

impl<W: Warning> std::error::Error for Error<W> {}

impl<W: Warning> fmt::Display for Error<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "A warning for element at `{}` was upgraded to an `error`: {}",
            self.element.path, self.warning
        )
    }
}

/// A representation of a JSON element that satisfies the needs of most consumers of a [`Warning`].
///
/// This representation avoids the complexity of needing to provide a `'buf` lifetime to the JSON element.
/// This would complicate all warnings types with that lifetime.
///
/// A consumer of warnings wants them grouped by the element they were reported against and
/// then displayed by path. [`Set`] is keyed by [`Element::id`], so it groups them on insert
/// and emits the groups in the order the elements appear in the document.
///
/// The linter report also wants to highlight the source JSON that a warning refers to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Element {
    /// The Id of the element that caused the [`Warning`].
    ///
    /// [`Set`] groups and orders warnings by this id.
    pub id: json::ElemId,

    /// The `Span` that delimits the JSON element.
    pub span: json::Span,

    /// The elements path.
    ///
    /// Most consumers of warnings just want this data.
    pub path: json::Path,

    /// The location (line, column) of the beginning of this element in the JSON file.
    pub location: json::Location,
}

impl Element {
    /// Create an owned `Element` from a `json::Element<'buf'>`.
    pub(crate) fn from_json(element: &json::Element<'_>) -> Element {
        Self {
            id: element.id(),
            span: element.span(),
            path: element.path(),
            location: element.location(),
        }
    }
}

/// Each mod defines warnings for the type that it's trying to parse or lint from a JSON element.
///
/// The `Warning` in the mod should impl this trait to take part in the [`Warning`] system.
pub trait Warning: Sized + fmt::Debug + fmt::Display + Send + Sync {
    /// Return the human readable identifier for the [`Warning`].
    ///
    /// This is used in the `auto_test` assertion system.
    /// Changing these strings may require updating `output_price__cdr.json` files.
    fn id(&self) -> Id;

    /// Whether this is the [`Rejected`] marker a feature emits when it rejects the schema IR
    /// for the object it is building.
    ///
    /// The precise structural cause (a missing or wrong-typed field) was already reported by
    /// the schema walk, so a consumer can drop these follow-on markers via
    /// [`Set::remove_rejected`]. Other Warnings return `false`.
    fn is_rejected(&self) -> bool {
        false
    }
}

/// A content-free marker seeded into any [`Warning`] (via `From<Rejected>`) when a feature
/// rejects the schema IR for the object it is building, because a required field was absent
/// or could not be built.
///
/// A feature accepts a checked object, such as a [`tariff::Checked`](crate::tariff::Checked),
/// and rejects it based on the warnings the schema walk already reported,
/// so this marker carries no detail of its own. It is still anchored to the
/// offending field's [`Element`], and is easily filtered via [`Warning::is_rejected`].
#[derive(Clone, Copy, Debug)]
pub struct Rejected;

/// A transparent container that stores the source line where the [`Warning`] occurred in a test build.
#[derive(Debug)]
struct Source<W: Warning> {
    #[cfg(test)]
    /// The line in the source code where this [`Warning`] occurred.
    #[expect(
        dead_code,
        reason = "only the derived `Debug` reads it, to show where a failing test's warning was raised"
    )]
    location: &'static std::panic::Location<'static>,

    /// The warning.
    warning: W,
}

impl<W: Warning> Source<W> {
    #[track_caller]
    /// Create a new `Source` object.
    fn new(warning: W) -> Self {
        #[cfg(test)]
        {
            Self {
                location: std::panic::Location::caller(),
                warning,
            }
        }

        #[expect(
            clippy::cfg_not_test,
            reason = "This is code that is designed for use in tests"
        )]
        #[cfg(not(test))]
        {
            Self { warning }
        }
    }

    /// Discard the debug info and return the inner [`Warning`].
    fn into_warning(self) -> W {
        self.warning
    }
}

impl<W: Warning> Deref for Source<W> {
    type Target = W;

    fn deref(&self) -> &Self::Target {
        &self.warning
    }
}

/// A set of [`Warning`]s transported through the system using a [`Caveat`].
#[derive(Debug)]
pub struct Set<W: Warning>(BTreeMap<json::ElemId, Group<W>>);

impl<W: Warning> Set<W> {
    /// Remove every [`Rejected`] marker from the set (see [`Warning::is_rejected`]).
    ///
    /// The schema walk already reported the located structural cause, so a consumer that has
    /// those warnings can drop these follow-on markers.
    pub fn remove_rejected(&mut self) {
        self.retain(|warning| !warning.is_rejected());
    }

    /// Retain only the [`Warning`]s for which `keep` returns `true`.
    ///
    /// Any [`Group`] left without warnings is removed from the set.
    pub fn retain<F>(&mut self, mut keep: F)
    where
        F: FnMut(&W) -> bool,
    {
        self.0.retain(|_elem_id, group| {
            group.warnings.retain(|source| keep(&source.warning));
            !group.warnings.is_empty()
        });
    }

    /// Return true if the [`Warning`] set is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return an iterator over every [`Warning`] in the set, each paired with the
    /// [`Element`] it was reported against.
    ///
    /// This is [`Set::iter`] with each [`Group`] flattened into its warnings.
    /// The warnings come in document order of their elements,
    /// and in the order they were inserted for one element.
    /// A predicate on one warning goes straight into `filter` or `find`:
    ///
    /// ```
    /// # use ocpi_tariffs::{cdr, warning};
    /// fn paths_outside_cdr(warnings: &warning::Set<cdr::Warning>) -> Vec<&str> {
    ///     warnings
    ///         .iter_warnings()
    ///         .filter(|(_element, warning)| {
    ///             matches!(
    ///                 warning,
    ///                 cdr::Warning::PeriodsOutsideStartEndDateTime { .. }
    ///             )
    ///         })
    ///         .map(|(element, _warning)| element.path.as_str())
    ///         .collect()
    /// }
    /// ```
    pub fn iter_warnings(&self) -> impl Iterator<Item = (&Element, &W)> {
        self.iter().flat_map(|group| {
            group
                .warnings
                .iter()
                .map(|source| (&group.element, &source.warning))
        })
    }

    /// Return true if any [`Warning`] in the set makes `predicate` return `true`.
    ///
    /// A warning can hold fields, so whether two warnings are the same depends on which
    /// fields a caller cares about. The predicate leaves that choice to the caller,
    /// who usually looks for a variant with `matches!`:
    ///
    /// ```
    /// # use ocpi_tariffs::{price, warning};
    /// fn periods_state_no_time(warnings: &warning::Set<price::Warning>) -> bool {
    ///     warnings.contains(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))
    /// }
    /// ```
    pub fn contains<F>(&self, predicate: F) -> bool
    where
        F: FnMut(&W) -> bool,
    {
        self.find(predicate).is_some()
    }

    /// Return the first [`Warning`] in the set that makes `predicate` return `true`,
    /// paired with the [`Element`] it was reported against.
    ///
    /// "First" means first in the order [`Set::iter_warnings`] yields.
    /// The [`Element`] tells a caller where in the document the warning sits:
    ///
    /// ```
    /// # use ocpi_tariffs::{price, warning};
    /// fn path_of_periods_state_no_time(warnings: &warning::Set<price::Warning>) -> Option<&str> {
    ///     let (element, _warning) =
    ///         warnings.find(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))?;
    ///     Some(element.path.as_str())
    /// }
    /// ```
    pub fn find<F>(&self, mut predicate: F) -> Option<(&Element, &W)>
    where
        F: FnMut(&W) -> bool,
    {
        self.iter_warnings()
            .find(|(_element, warning)| predicate(warning))
    }

    /// Return every distinct [`Id`] of the [`Warning`]s in the set.
    ///
    /// A caller can compare the returned IDs with a list of the IDs it accepts,
    /// rather than matching on the variants of each warning.
    ///
    /// Some IDs include a value from the warning, such as the field name in
    /// `missing_field(country_code)`. Two warnings of one variant can then give two IDs.
    pub fn ids(&self) -> BTreeSet<Id> {
        self.iter_warnings()
            .map(|(_element, warning)| warning.id())
            .collect()
    }

    /// Return an iterator over the [`Warning`]s reported against the element at `path`,
    /// such as `$.charging_periods`.
    ///
    /// Duplicate JSON keys give several elements the same path.
    /// The iterator yields the warnings of every one of them, in document order,
    /// where [`Set::path_map`] would keep only the last.
    pub fn warnings_at<'set>(&'set self, path: &str) -> impl Iterator<Item = &'set W> {
        self.iter_warnings()
            .filter(move |(element, _warning)| element.path.as_str() == path)
            .map(|(_element, warning)| warning)
    }

    /// Return the amount of [`Element`]s in this set.
    ///
    /// Each [`Element`] can have many [`Warning`]s associated with it.
    pub fn len_elements(&self) -> usize {
        self.0.len()
    }

    /// Return the total amount of [`Warning`]s in this set for all [`Element`]s.
    pub fn len_warnings(&self) -> usize {
        self.0
            .values()
            .fold(0, |acc, group| acc.saturating_add(group.warnings.len()))
    }

    /// Return an iterator of [`Warning`]s grouped by JSON element.
    pub fn iter(&self) -> Iter<'_, W> {
        Iter {
            warnings: self.0.iter(),
        }
    }

    /// Return a collection of `Id`s mapped to the paths they occurred at.
    pub fn id_path_map(&self, config: Limit) -> IdPathMap<'_> {
        let report = match config {
            Limit::None => limit_none(&self.0),
            Limit::WarningTypes(max_warning_types) => {
                limit_warning_types(max_warning_types, &self.0)
            }
            Limit::ElemPathsPerId(max_elem_paths_per_warning_id) => {
                limit_elem_paths_per_id(max_elem_paths_per_warning_id, &self.0)
            }
            Limit::All {
                max_warning_types,
                max_elem_paths_per_warning_id,
            } => limit_all(max_warning_types, max_elem_paths_per_warning_id, &self.0),
        };

        let LimitReport {
            elements_filtered,
            warning_distinct_types_filtered,
            warnings,
        } = report;

        IdPathMap {
            total_warnings: self.len_warnings(),
            total_elements: self.len_elements(),
            elements_filtered,
            warning_distinct_types_filtered,
            warnings,
        }
    }

    /// Return a collection of warning messages mapped to the paths they occurred at.
    pub fn msg_path_map(&self, config: Limit) -> MsgPathMap<'_> {
        let IdPathMap {
            total_warnings,
            total_elements,
            elements_filtered,
            warning_distinct_types_filtered,
            warnings,
        } = self.id_path_map(config);

        let warnings = warnings
            .into_iter()
            .map(|(id, paths)| (id.to_string(), paths))
            .collect();

        MsgPathMap {
            total_warnings,
            total_elements,
            elements_filtered,
            warning_distinct_types_filtered,
            warnings,
        }
    }

    /// Return a map of element paths to a list of [`Warning`].
    ///
    /// This is designed to be used to print out maps of warnings associated with elements.
    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
    /// with indentation.
    ///
    /// # A path does not identify an element
    ///
    /// The set is keyed by [`json::ElemId`], this map is keyed by path. Duplicate JSON keys are
    /// legal, and every occurrence of one has the same path, so several elements can compete for
    /// a single entry. The entries are built in `ElemId` order and collected, so **the last
    /// occurrence in the document wins and the earlier ones' warnings are absent from the map**.
    ///
    /// Nothing is lost from the set itself, so a caller that iterates groups - as
    /// `cli::print::warning_set` does - still sees every warning. Reach for [`Set::iter`] rather
    /// than this map when a warning may be reported against more than one occurrence of a field;
    /// [`Warning::DuplicateField`](crate::schema::Warning::DuplicateField) is the case that
    /// makes this reachable in practice.
    pub fn path_map(&self) -> BTreeMap<&str, Vec<&W>> {
        self.0
            .values()
            .map(|Group { element, warnings }| {
                let path = element.path.as_str();
                let warnings = warnings.iter().map(|w| &**w).collect();
                (path, warnings)
            })
            .collect()
    }

    /// Consume the `Set` and return a map of element paths to a list of [`Warning`]s.
    ///
    /// This is designed to be used to print out maps of warnings associated with elements.
    pub fn into_path_map(self) -> BTreeMap<json::Path, Vec<W>> {
        self.0
            .into_values()
            .map(|Group { element, warnings }| {
                let warnings = warnings.into_iter().map(Source::into_warning).collect();
                (element.path, warnings)
            })
            .collect()
    }

    /// Return a map of element paths to a list of [`Warning`] ids as Strings.
    ///
    /// This is designed to be used to print out maps of warnings associated with elements.
    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
    /// with indentation.
    ///
    /// Note: This representation is also valid JSON and can be copied directly to
    /// a test expectation file.
    pub fn path_id_map(&self) -> BTreeMap<&str, Vec<Id>> {
        self.0
            .values()
            .map(|group| {
                let warnings = group.warnings.iter().map(|w| w.id()).collect();
                (group.element.path.as_str(), warnings)
            })
            .collect()
    }

    /// Return a map of element paths to a list of [`Warning`] messages as Strings.
    ///
    /// This is designed to be used to print out maps of warnings associated with elements.
    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
    /// with indentation.
    pub fn path_msg_map(&self) -> BTreeMap<&str, Vec<String>> {
        self.0
            .values()
            .map(|group| {
                let warnings = group.warnings.iter().map(|w| w.to_string()).collect();
                (group.element.path.as_str(), warnings)
            })
            .collect()
    }
}

/// The outcome of calling the `limit_*` functions related to the [`Set::id_path_map`] function.
#[derive(Debug)]
struct LimitReport<'set> {
    /// The amount of element paths filtered due to a [`Limit`] being set.
    pub elements_filtered: usize,

    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
    ///
    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
    /// this counts as one type, as all the IDs that were filtered are the same.
    pub warning_distinct_types_filtered: usize,

    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
    pub warnings: BTreeMap<Id, Vec<&'set str>>,
}

/// The logic for the [`Limit::None`] variant.
fn limit_none<W: Warning>(warnings: &BTreeMap<json::ElemId, Group<W>>) -> LimitReport<'_> {
    let mut out = BTreeMap::new();

    for group in warnings.values() {
        let Group { element, warnings } = group;
        let path = element.path.as_str();

        for w in warnings {
            match out.entry(w.id()) {
                btree_map::Entry::Vacant(entry) => {
                    entry.insert(vec![path]);
                }
                btree_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().push(path);
                }
            }
        }
    }

    LimitReport {
        warnings: out,
        elements_filtered: 0,
        warning_distinct_types_filtered: 0,
    }
}

/// The logic for the [`Limit::WarningTypes`] variant.
fn limit_warning_types<W: Warning>(
    max_warning_types: usize,
    warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
    let mut out = BTreeMap::new();
    // A set of element paths encountered and filtered. Element paths can be encountered more
    // than once, so a simple `usize` can't be used to count the encounters.
    let mut elements_filtered = HashSet::new();
    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
    // so a simple `usize` can't be used to count the encounters.
    let mut warning_distinct_types_filtered = HashSet::new();

    for group in warnings.values() {
        let Group { element, warnings } = group;
        let path = element.path.as_str();
        // True if any of the warnings are filtered,
        // therefore this element should be considered filtered too.
        let mut filtered = false;

        for w in warnings {
            let len = out.len();
            let id = w.id();

            match out.entry(id.clone()) {
                btree_map::Entry::Vacant(entry) => {
                    if len < max_warning_types {
                        entry.insert(vec![path]);
                    } else {
                        warning_distinct_types_filtered.insert(id);
                        filtered = true;
                    }
                }
                btree_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().push(path);
                }
            }
        }

        if filtered {
            elements_filtered.insert(path);
        }
    }

    LimitReport {
        warnings: out,
        elements_filtered: elements_filtered.len(),
        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
    }
}

/// The logic for the [`Limit::ElemPathsPerId`] variant.
fn limit_elem_paths_per_id<W: Warning>(
    max_elem_paths_per_warning_id: usize,
    warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
    let mut out = BTreeMap::new();
    // A set of element paths encountered and filtered. Element paths can be encountered more
    // than once, so a simple `usize` can't be used to count the encounters.
    let mut elements_filtered = HashSet::new();

    if max_elem_paths_per_warning_id == 0 {
        for group in warnings.values() {
            let Group { element, warnings } = group;

            for w in warnings {
                if let btree_map::Entry::Vacant(entry) = out.entry(w.id()) {
                    entry.insert(vec![]);
                }
            }
            elements_filtered.insert(element.path.as_str());
        }
    } else {
        for group in warnings.values() {
            let Group { element, warnings } = group;
            let path = element.path.as_str();

            for w in warnings {
                let id = w.id();

                match out.entry(id.clone()) {
                    btree_map::Entry::Vacant(entry) => {
                        entry.insert(vec![path]);
                    }
                    btree_map::Entry::Occupied(mut entry) => {
                        if entry.get().len() < max_elem_paths_per_warning_id {
                            entry.get_mut().push(path);
                        } else {
                            elements_filtered.insert(path);
                        }
                    }
                }
            }
        }
    }

    LimitReport {
        warnings: out,
        elements_filtered: elements_filtered.len(),
        warning_distinct_types_filtered: 0,
    }
}

/// The logic for the [`Limit::All`] variant.
fn limit_all<W: Warning>(
    max_warning_types: usize,
    max_elem_paths_per_warning_id: usize,
    warnings: &BTreeMap<json::ElemId, Group<W>>,
) -> LimitReport<'_> {
    let mut out = BTreeMap::new();
    // A set of element paths encountered and filtered. Element paths can be encountered more
    // than once, so a simple `usize` can't be used to count the encounters.
    let mut elements_filtered = HashSet::new();
    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
    // so a simple `usize` can't be used to count the encounters.
    let mut warning_distinct_types_filtered = HashSet::new();

    if max_warning_types > 0 && max_elem_paths_per_warning_id == 0 {
        for group in warnings.values() {
            let Group { element, warnings } = group;
            let path = element.path.as_str();

            for w in warnings {
                let len = out.len();
                let id = w.id();

                if let btree_map::Entry::Vacant(entry) = out.entry(id.clone()) {
                    if len < max_warning_types {
                        entry.insert(vec![]);
                    } else {
                        warning_distinct_types_filtered.insert(id);
                    }
                }
            }

            elements_filtered.insert(path);
        }
    } else {
        for group in warnings.values() {
            let Group { element, warnings } = group;
            let path = element.path.as_str();

            for w in warnings {
                let len = out.len();
                let id = w.id();

                match out.entry(id.clone()) {
                    btree_map::Entry::Vacant(entry) => {
                        if len < max_warning_types {
                            entry.insert(vec![path]);
                        } else {
                            warning_distinct_types_filtered.insert(id);
                            elements_filtered.insert(path);
                        }
                    }
                    btree_map::Entry::Occupied(mut entry) => {
                        if entry.get().len() < max_elem_paths_per_warning_id {
                            entry.get_mut().push(path);
                        } else {
                            elements_filtered.insert(path);
                        }
                    }
                }
            }
        }
    }

    LimitReport {
        warnings: out,
        elements_filtered: elements_filtered.len(),
        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
    }
}

/// The outcome of calling the [`Set::id_path_map`] function.
#[derive(Debug)]
pub struct IdPathMap<'set> {
    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
    pub total_warnings: usize,

    /// The total amount of element paths in the source [`Set`].
    pub total_elements: usize,

    /// The amount of element paths filtered due to a [`Limit`] being set.
    pub elements_filtered: usize,

    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
    ///
    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
    /// this counts as one type, as all the IDs that were filtered are the same.
    pub warning_distinct_types_filtered: usize,

    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
    pub warnings: BTreeMap<Id, Vec<&'set str>>,
}

/// The outcome of calling the [`Set::msg_path_map`] function.
#[derive(Debug)]
pub struct MsgPathMap<'set> {
    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
    pub total_warnings: usize,

    /// The total amount of element paths in the source [`Set`].
    pub total_elements: usize,

    /// The amount of element paths filtered due to a [`Limit`] being set.
    pub elements_filtered: usize,

    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
    ///
    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
    /// this counts as one type, as all the IDs that were filtered are the same.
    pub warning_distinct_types_filtered: usize,

    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
    pub warnings: BTreeMap<String, Vec<&'set str>>,
}

/// The limiting configuration of the [`Set::path_id_map`] function.
#[derive(Copy, Clone, Debug)]
pub enum Limit {
    /// Don't enforce any limits on [`Warning`] [`Id`]s or element [`json::Path`]s.
    None,

    /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
    WarningTypes(usize),

    /// Forbid more than this amount of element [`json::Path`]s to be inserted into the list for each [`Id`].
    ElemPathsPerId(usize),

    /// Enforce both limits at once.
    All {
        /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
        max_warning_types: usize,

        /// Forbid more than this amount of element [`json::Path`]s to be inserted into the list for each [`Id`].
        max_elem_paths_per_warning_id: usize,
    },
}

/// A failed attempt to make a value: the [`Error`] that stopped it, and every
/// [`Warning`] raised before it.
///
/// A [`Caveat`] is a value that was made, with the warnings to bear in mind when using it. A
/// `Failure` is the attempt that didn't make one, so it's the `Err` of a [`Verdict`]. A caller
/// reads a `Failure`'s warnings with the same methods as a `Caveat`'s.
#[derive(Debug)]
pub struct Failure<W: Warning> {
    /// The warning that caused an operation to fail.
    ///
    /// The warning is converted to an [`Error`] so it's ready to take part in Rust's error system.
    error: Box<Error<W>>,

    /// The warnings accumulated up until the failure moment.
    ///
    /// This set doesn't include the warning that caused the operation to fail.
    warnings: Set<W>,
}

impl<W> Failure<W>
where
    W: Warning,
{
    /// Return the warnings raised before the failure, without the [`Error`].
    pub fn warnings(&self) -> &Set<W> {
        &self.warnings
    }

    /// Consume the `Failure` and return the [`Error`] and the warnings raised before it.
    pub fn into_parts(self) -> (Error<W>, Set<W>) {
        let Self { error, warnings } = self;
        (*error, warnings)
    }

    /// Return the [`Error`] and drop the warnings raised before it.
    pub fn ignore_warnings(self) -> Error<W> {
        *self.error
    }
}

/// A group of warning `Warning`s associated with an `Element`.
///
/// This group is emitted from the `IntoGroupByElem` iterator.
/// The warning `Warning`s are owned and so can be moved to another location.
#[derive(Debug)]
pub struct Group<W: Warning> {
    /// The [`json::Element`] that has [`Warning`]s.
    element: Element,

    /// The list of warnings for the [`json::Element`].
    warnings: Vec<Source<W>>,
}

impl<W> Group<W>
where
    W: Warning,
{
    /// Consume the `Group` and return the constituent parts.
    pub fn into_parts(self) -> (Element, Vec<W>) {
        let Self { element, warnings } = self;
        let warnings = warnings.into_iter().map(Source::into_warning).collect();
        (element, warnings)
    }

    /// Borrow the element and its [`Warning`]s.
    pub fn to_parts(&self) -> (&Element, Vec<&W>) {
        let Self { element, warnings } = self;
        let warnings = warnings.iter().map(|w| &**w).collect();
        (element, warnings)
    }

    /// Borrow just the [`Warning`]s, without the element.
    pub fn warnings(&self) -> Vec<&W> {
        self.warnings.iter().map(|w| &**w).collect()
    }

    /// Consume the group and return just the [`Warning`]s, discarding the element.
    pub fn into_warnings(self) -> Vec<W> {
        let Self {
            element: _,
            warnings,
        } = self;
        warnings.into_iter().map(Source::into_warning).collect()
    }
}

/// An iterator of borrowed [`Warning`]s grouped by JSON element.
pub struct Iter<'caller, W>
where
    W: Warning,
{
    /// The iterator over every [`Warning`].
    warnings: btree_map::Iter<'caller, json::ElemId, Group<W>>,
}

impl<W> Iter<'_, W> where W: Warning {}

impl<'caller, W: Warning> Iterator for Iter<'caller, W> {
    type Item = &'caller Group<W>;

    fn next(&mut self) -> Option<Self::Item> {
        let (_elem_id, group) = self.warnings.next()?;
        Some(group)
    }
}

/// An iterator of borrowed [`Warning`]s grouped by JSON element.
pub struct IntoIter<W>
where
    W: Warning,
{
    /// The iterator over every [`Warning`].
    warnings: btree_map::IntoIter<json::ElemId, Group<W>>,
}

impl<W: Warning> Iterator for IntoIter<W> {
    type Item = Group<W>;

    fn next(&mut self) -> Option<Self::Item> {
        let (_elem_id, group) = self.warnings.next()?;
        Some(group)
    }
}

impl<W: Warning> IntoIterator for Set<W> {
    type Item = Group<W>;
    type IntoIter = IntoIter<W>;

    fn into_iter(self) -> Self::IntoIter {
        let Set(warnings) = self;
        IntoIter {
            warnings: warnings.into_iter(),
        }
    }
}

impl<'a, W: Warning> IntoIterator for &'a Set<W> {
    type Item = &'a Group<W>;
    type IntoIter = Iter<'a, W>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}