Skip to main content

ocpi_tariffs/
warning.rs

1//! 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.
2//!
3//! 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.
4//!
5//! 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.
6//!
7//! # Introducing Verdict
8//!
9//! A [`Verdict`] is a [`Result`] where both variants carry [`Warning`]s.
10//!
11//! The `Ok` variant is a [`Caveat`]: the value the function built, together with a [`Set`] of
12//! warnings to take into account when using it. Hence the name.
13//!
14//! The `Err` variant is a [`Failure`] that contains the single [`Warning`] that stopped the
15//! function and the set of warnings accumulated before it.
16//! The failing warning is represented as an [`Error`] so it is ready to take part in Rust's
17//! error system. The failing warning is not repeated in that set.
18//!
19//! So a resilient function always returns its [`Warning`]s, and the caller either gathers them
20//! into a set of its own and carries on, or fails.
21//!
22//! Gathering warnings into a parent [`Set`] moves the responsibility of alerting the caller to
23//! the existence of those warnings to the owner of that set.
24//!
25//! # A concrete example
26//!
27//! Lowering a JSON string into a [`country::Code`](crate::country::Code) illustrates the
28//! general pattern.
29//!
30//! The schema walk has already proven the value is a string of the permitted length, so the
31//! lowering is never handed a value of the wrong kind and makes no kind check. What is left is
32//! semantics, and each finding is a warning rather than a hard stop:
33//!
34//! - The string may carry escape codes, which a country code has no use for.
35//! - It may be lower case where the standard is upper case.
36//! - It may be three characters where two were expected. This is the interesting case, as some
37//!   [`country::Code`](crate::country::Code) fields are `alpha-3` where others are `alpha-2`.
38//!   An `alpha-3` code converts to an `alpha-2` simply, so processing continues while emitting a
39//!   [`Warning`].
40//! - It may not name a country at all, which is the one case the lowering cannot recover from.
41//!
42//! The lowering is written as a `LowerSchema` impl. The sketch below names types that are private
43//! to this crate but is here to illustrate the general pattern:
44//!
45//! ```rust,ignore
46//! // file: country.rs
47//!
48//! pub enum Warning {
49//!     ContainsEscapeCodes,
50//!     Decode(json::decode::Warning),
51//!     IncorrectCase,
52//!     InvalidCode,
53//! }
54//!
55//! impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for CodeSet {
56//!     type Warning = Warning;
57//!
58//!     fn lower_schema(
59//!         source: &schema::Str<'buf>,
60//!         warnings: &mut dyn warning::Gather<Warning>,
61//!     ) -> Result<Self, warning::Error<Warning>> {
62//!         // Read the string, gathering a warning per semantic problem found.
63//!     }
64//! }
65//! ```
66//!
67//! The caller decides whether the result is acceptable.
68
69mod gather;
70
71#[cfg(test)]
72pub(crate) mod test;
73
74#[cfg(test)]
75mod test_assert_warnings;
76
77#[cfg(test)]
78mod test_contains;
79
80#[cfg(test)]
81mod test_failure_unwrap;
82
83#[cfg(test)]
84mod test_find;
85
86#[cfg(test)]
87mod test_gather;
88
89#[cfg(test)]
90mod test_group_by_elem;
91
92#[cfg(test)]
93mod test_id_path_map;
94
95#[cfg(test)]
96mod test_ids;
97
98#[cfg(test)]
99mod test_iter_warnings;
100
101#[cfg(test)]
102mod test_path_map;
103
104#[cfg(test)]
105mod test_warnings_at;
106
107use std::{
108    borrow::Cow,
109    collections::{BTreeMap, BTreeSet, HashSet, btree_map},
110    fmt,
111    ops::Deref,
112    vec,
113};
114
115use tracing::{debug, info};
116
117use crate::json;
118
119pub(crate) use gather::{Converting, Gather, Gatherer};
120
121#[doc(hidden)]
122#[macro_export]
123macro_rules! from_warning_all {
124    ($($source_kind:path => $target_kind:ident::$target_variant:ident),+) => {
125        $(
126            /// Convert from `Warning` A to B.
127            impl From<$source_kind> for $target_kind {
128                fn from(warning: $source_kind) -> Self {
129                    $target_kind::$target_variant(warning)
130                }
131            }
132        )+
133    };
134}
135
136/// The stable identifier of a [`Warning`] kind, such as `missing_field(id)`.
137///
138/// Two warnings of the same kind share an `Id`, so this is what a caller matches on to accept
139/// or reject a class of warning without depending on the `Warning` type itself.
140#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
141pub struct Id(Cow<'static, str>);
142
143impl Id {
144    /// Create an `Id` from a `'static str`.
145    pub(crate) const fn from_static(s: &'static str) -> Self {
146        Self(Cow::Borrowed(s))
147    }
148
149    /// Create an `Id` from a `String`.
150    pub(crate) const fn from_string(s: String) -> Self {
151        Self(Cow::Owned(s))
152    }
153
154    /// Return the contained `str`.
155    pub fn as_str(&self) -> &str {
156        &self.0
157    }
158}
159
160impl fmt::Debug for Id {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        fmt::Debug::fmt(&self.0, f)
163    }
164}
165
166impl fmt::Display for Id {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        fmt::Display::fmt(&self.0, f)
169    }
170}
171
172/// A `Verdict` is a standard [`Result`] with [`Warning`]s potentially issued for both the `Ok` and `Err` variants.
173pub type Verdict<T, W> = Result<Caveat<T, W>, Failure<W>>;
174
175/// A value that may have associated [`Warning`]s.
176///
177/// Even though the value has been created there may be certain caveats you should be aware of before using it.
178#[derive(Debug)]
179pub struct Caveat<T, W: Warning> {
180    /// The value created by the function.
181    value: T,
182
183    /// A list of [`Warning`]s or caveats issued when creating the value.
184    warnings: Set<W>,
185}
186
187/// Read the value without taking it, which leaves the warnings attached.
188///
189/// `Deref` is justified here because a `Caveat` behaves transparently like its `T` and the deref is
190/// a field read. It borrows, so the value cannot leave a caveat this way and the warnings cannot be
191/// lost by accident.
192///
193/// See: <https://doc.rust-lang.org/std/ops/trait.Deref.html#when-to-implement-deref-or-derefmut>.
194impl<T, W> Deref for Caveat<T, W>
195where
196    W: Warning,
197{
198    type Target = T;
199
200    fn deref(&self) -> &T {
201        &self.value
202    }
203}
204
205impl<T, W> Caveat<T, W>
206where
207    W: Warning,
208{
209    /// Pair `value` with the warnings raised while producing it.
210    pub(crate) fn new(value: T, warnings: Set<W>) -> Self {
211        Self { value, warnings }
212    }
213
214    /// Return a ref to the warning Set.
215    pub fn warnings(&self) -> &Set<W> {
216        &self.warnings
217    }
218
219    /// Return the value and any [`Warning`]s stored in the `Caveat`.
220    pub fn into_parts(self) -> (T, Set<W>) {
221        let Self { value, warnings } = self;
222        (value, warnings)
223    }
224
225    /// Return the value and drop any warnings contained within.
226    pub fn ignore_warnings(self) -> T {
227        self.value
228    }
229
230    /// Map the value to another target type while retaining the warnings about the source type.
231    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Caveat<U, W> {
232        let Self { value, warnings } = self;
233        Caveat {
234            value: op(value),
235            warnings,
236        }
237    }
238}
239
240/// `Verdict` specific extension methods for the `Result` type.
241pub trait VerdictExt<T, W: Warning> {
242    /// Discard all warnings in the `Err` variant and keep only the warning that caused the error.
243    fn only_error(self) -> Result<Caveat<T, W>, Error<W>>;
244}
245
246/// Used to log the contents of various `Verdict` impls.
247#[expect(dead_code, reason = "for debugging")]
248pub(crate) trait VerdictTrace<T, W: Warning> {
249    /// Log the contents as `info` level.
250    fn info_verdict(self, msg: &'static str) -> Self;
251
252    /// Log the contents as `debug` level.
253    fn debug_verdict(self, msg: &'static str) -> Self;
254}
255
256/// Used to log the contents of various `Result` impls.
257#[expect(dead_code, reason = "for debugging")]
258pub(crate) trait ResultTrace<T, W: Warning> {
259    /// Log the contents as `info` level.
260    fn info_result(self, msg: &'static str) -> Self;
261
262    /// Log the contents as `debug` level.
263    fn debug_result(self, msg: &'static str) -> Self;
264}
265
266impl<T, W: Warning> VerdictExt<T, W> for Verdict<T, W> {
267    fn only_error(self) -> Result<Caveat<T, W>, Error<W>> {
268        match self {
269            Ok(c) => Ok(c),
270            Err(failure) => Err(failure.ignore_warnings()),
271        }
272    }
273}
274
275impl<T, W: Warning> VerdictTrace<T, W> for Verdict<T, W>
276where
277    T: fmt::Debug,
278{
279    fn info_verdict(self, msg: &'static str) -> Self {
280        match self {
281            Ok(c) => {
282                info!("{msg}: {c:#?}");
283                Ok(c)
284            }
285            Err(failure) => {
286                info!("{msg}: {failure:#?}");
287                Err(failure)
288            }
289        }
290    }
291
292    fn debug_verdict(self, msg: &'static str) -> Self {
293        match self {
294            Ok(c) => {
295                debug!("{msg}: {c:#?}");
296                Ok(c)
297            }
298            Err(failure) => {
299                debug!("{msg}: {failure:#?}");
300                Err(failure)
301            }
302        }
303    }
304}
305
306impl<T, W: Warning> ResultTrace<T, W> for Result<T, Failure<W>>
307where
308    T: fmt::Debug,
309{
310    fn info_result(self, msg: &'static str) -> Self {
311        match self {
312            Ok(c) => {
313                info!("{msg}: {c:#?}");
314                Ok(c)
315            }
316            Err(failure) => {
317                info!("{msg}: {failure:#?}");
318                Err(failure)
319            }
320        }
321    }
322
323    fn debug_result(self, msg: &'static str) -> Self {
324        match self {
325            Ok(c) => {
326                debug!("{msg}: {c:#?}");
327                Ok(c)
328            }
329            Err(failure) => {
330                debug!("{msg}: {failure:#?}");
331                Err(failure)
332            }
333        }
334    }
335}
336
337/// The warning that caused an operation to fail.
338///
339/// The warning is stored apart from the source set so it is
340/// clear which warning has been escalated to an error.
341#[derive(Debug)]
342pub struct Error<W: Warning> {
343    /// The warning the operation failed on.
344    warning: W,
345
346    /// The element the warning was reported against.
347    element: Element,
348}
349
350impl<W: Warning> Error<W> {
351    /// Create an `Error` to be returned by a function that can't continue due to `warning`.
352    /// Each warning is reported against an `element`.
353    pub(crate) fn new(element: &json::Element<'_>, warning: W) -> Self {
354        Self {
355            warning,
356            element: Element::from_json(element),
357        }
358    }
359
360    /// Create an `Error` reported against an `element` taken from the schema IR.
361    ///
362    /// [`Error::new`] takes a [`json::Element`], which an absent or unbuildable IR field doesn't
363    /// have. [`Integrity::Missing`] and [`Integrity::Err`] hold an [`Element`] instead, and `at`
364    /// takes that.
365    ///
366    /// [`Integrity::Missing`]: crate::schema::Integrity::Missing
367    /// [`Integrity::Err`]: crate::schema::Integrity::Err
368    pub(crate) fn at(element: Element, warning: W) -> Self {
369        Self { warning, element }
370    }
371
372    /// Return reference to the [`Warning`].
373    pub fn warning(&self) -> &W {
374        &self.warning
375    }
376
377    /// Consume the `Error` and return the [`Warning`].
378    pub fn into_warning(self) -> W {
379        self.warning
380    }
381
382    /// Return a reference to the [`Element`] that caused the [`Warning`].
383    pub fn element(&self) -> &Element {
384        &self.element
385    }
386
387    /// Return the constituent parts.
388    pub fn parts(&self) -> (&W, &Element) {
389        (&self.warning, &self.element)
390    }
391
392    /// Consume the `Cause` and return the constituent parts.
393    pub fn into_parts(self) -> (W, Element) {
394        let Self { warning, element } = self;
395        (warning, element)
396    }
397
398    /// Converts `Error<W>` into `Error<WA>` using the `impl Into<WA> for W`.
399    ///
400    /// [`FromSchema::from_schema`](crate::schema::FromSchema::from_schema) uses this, as
401    /// does each caller that passes another module's error up with `map_err`.
402    pub(crate) fn into_other<WA>(self) -> Error<WA>
403    where
404        W: Into<WA>,
405        WA: Warning,
406    {
407        let Self { warning, element } = self;
408        Error {
409            warning: warning.into(),
410            element,
411        }
412    }
413}
414
415impl<W: Warning> std::error::Error for Error<W> {}
416
417impl<W: Warning> fmt::Display for Error<W> {
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        write!(
420            f,
421            "A warning for element at `{}` was upgraded to an `error`: {}",
422            self.element.path, self.warning
423        )
424    }
425}
426
427/// A representation of a JSON element that satisfies the needs of most consumers of a [`Warning`].
428///
429/// This representation avoids the complexity of needing to provide a `'buf` lifetime to the JSON element.
430/// This would complicate all warnings types with that lifetime.
431///
432/// A consumer of warnings wants them grouped by the element they were reported against and
433/// then displayed by path. [`Set`] is keyed by [`Element::id`], so it groups them on insert
434/// and emits the groups in the order the elements appear in the document.
435///
436/// The linter report also wants to highlight the source JSON that a warning refers to.
437#[derive(Clone, Debug, PartialEq, Eq)]
438pub struct Element {
439    /// The Id of the element that caused the [`Warning`].
440    ///
441    /// [`Set`] groups and orders warnings by this id.
442    pub id: json::ElemId,
443
444    /// The `Span` that delimits the JSON element.
445    pub span: json::Span,
446
447    /// The elements path.
448    ///
449    /// Most consumers of warnings just want this data.
450    pub path: json::Path,
451
452    /// The location (line, column) of the beginning of this element in the JSON file.
453    pub location: json::Location,
454}
455
456impl Element {
457    /// Create an owned `Element` from a `json::Element<'buf'>`.
458    pub(crate) fn from_json(element: &json::Element<'_>) -> Element {
459        Self {
460            id: element.id(),
461            span: element.span(),
462            path: element.path(),
463            location: element.location(),
464        }
465    }
466}
467
468/// Each mod defines warnings for the type that it's trying to parse or lint from a JSON element.
469///
470/// The `Warning` in the mod should impl this trait to take part in the [`Warning`] system.
471pub trait Warning: Sized + fmt::Debug + fmt::Display + Send + Sync {
472    /// Return the human readable identifier for the [`Warning`].
473    ///
474    /// This is used in the `auto_test` assertion system.
475    /// Changing these strings may require updating `output_price__cdr.json` files.
476    fn id(&self) -> Id;
477
478    /// Whether this is the [`Rejected`] marker a feature emits when it rejects the schema IR
479    /// for the object it is building.
480    ///
481    /// The precise structural cause (a missing or wrong-typed field) was already reported by
482    /// the schema walk, so a consumer can drop these follow-on markers via
483    /// [`Set::remove_rejected`]. Other Warnings return `false`.
484    fn is_rejected(&self) -> bool {
485        false
486    }
487}
488
489/// A content-free marker seeded into any [`Warning`] (via `From<Rejected>`) when a feature
490/// rejects the schema IR for the object it is building, because a required field was absent
491/// or could not be built.
492///
493/// A feature accepts a checked object, such as a [`tariff::Checked`](crate::tariff::Checked),
494/// and rejects it based on the warnings the schema walk already reported,
495/// so this marker carries no detail of its own. It is still anchored to the
496/// offending field's [`Element`], and is easily filtered via [`Warning::is_rejected`].
497#[derive(Clone, Copy, Debug)]
498pub struct Rejected;
499
500/// A transparent container that stores the source line where the [`Warning`] occurred in a test build.
501#[derive(Debug)]
502struct Source<W: Warning> {
503    #[cfg(test)]
504    /// The line in the source code where this [`Warning`] occurred.
505    #[expect(
506        dead_code,
507        reason = "only the derived `Debug` reads it, to show where a failing test's warning was raised"
508    )]
509    location: &'static std::panic::Location<'static>,
510
511    /// The warning.
512    warning: W,
513}
514
515impl<W: Warning> Source<W> {
516    #[track_caller]
517    /// Create a new `Source` object.
518    fn new(warning: W) -> Self {
519        #[cfg(test)]
520        {
521            Self {
522                location: std::panic::Location::caller(),
523                warning,
524            }
525        }
526
527        #[expect(
528            clippy::cfg_not_test,
529            reason = "This is code that is designed for use in tests"
530        )]
531        #[cfg(not(test))]
532        {
533            Self { warning }
534        }
535    }
536
537    /// Discard the debug info and return the inner [`Warning`].
538    fn into_warning(self) -> W {
539        self.warning
540    }
541}
542
543impl<W: Warning> Deref for Source<W> {
544    type Target = W;
545
546    fn deref(&self) -> &Self::Target {
547        &self.warning
548    }
549}
550
551/// A set of [`Warning`]s transported through the system using a [`Caveat`].
552#[derive(Debug)]
553pub struct Set<W: Warning>(BTreeMap<json::ElemId, Group<W>>);
554
555impl<W: Warning> Set<W> {
556    /// Remove every [`Rejected`] marker from the set (see [`Warning::is_rejected`]).
557    ///
558    /// The schema walk already reported the located structural cause, so a consumer that has
559    /// those warnings can drop these follow-on markers.
560    pub fn remove_rejected(&mut self) {
561        self.retain(|warning| !warning.is_rejected());
562    }
563
564    /// Retain only the [`Warning`]s for which `keep` returns `true`.
565    ///
566    /// Any [`Group`] left without warnings is removed from the set.
567    pub fn retain<F>(&mut self, mut keep: F)
568    where
569        F: FnMut(&W) -> bool,
570    {
571        self.0.retain(|_elem_id, group| {
572            group.warnings.retain(|source| keep(&source.warning));
573            !group.warnings.is_empty()
574        });
575    }
576
577    /// Return true if the [`Warning`] set is empty.
578    pub fn is_empty(&self) -> bool {
579        self.0.is_empty()
580    }
581
582    /// Return an iterator over every [`Warning`] in the set, each paired with the
583    /// [`Element`] it was reported against.
584    ///
585    /// This is [`Set::iter`] with each [`Group`] flattened into its warnings.
586    /// The warnings come in document order of their elements,
587    /// and in the order they were inserted for one element.
588    /// A predicate on one warning goes straight into `filter` or `find`:
589    ///
590    /// ```
591    /// # use ocpi_tariffs::{cdr, warning};
592    /// fn paths_outside_cdr(warnings: &warning::Set<cdr::Warning>) -> Vec<&str> {
593    ///     warnings
594    ///         .iter_warnings()
595    ///         .filter(|(_element, warning)| {
596    ///             matches!(
597    ///                 warning,
598    ///                 cdr::Warning::PeriodsOutsideStartEndDateTime { .. }
599    ///             )
600    ///         })
601    ///         .map(|(element, _warning)| element.path.as_str())
602    ///         .collect()
603    /// }
604    /// ```
605    pub fn iter_warnings(&self) -> impl Iterator<Item = (&Element, &W)> {
606        self.iter().flat_map(|group| {
607            group
608                .warnings
609                .iter()
610                .map(|source| (&group.element, &source.warning))
611        })
612    }
613
614    /// Return true if any [`Warning`] in the set makes `predicate` return `true`.
615    ///
616    /// A warning can hold fields, so whether two warnings are the same depends on which
617    /// fields a caller cares about. The predicate leaves that choice to the caller,
618    /// who usually looks for a variant with `matches!`:
619    ///
620    /// ```
621    /// # use ocpi_tariffs::{price, warning};
622    /// fn periods_state_no_time(warnings: &warning::Set<price::Warning>) -> bool {
623    ///     warnings.contains(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))
624    /// }
625    /// ```
626    pub fn contains<F>(&self, predicate: F) -> bool
627    where
628        F: FnMut(&W) -> bool,
629    {
630        self.find(predicate).is_some()
631    }
632
633    /// Return the first [`Warning`] in the set that makes `predicate` return `true`,
634    /// paired with the [`Element`] it was reported against.
635    ///
636    /// "First" means first in the order [`Set::iter_warnings`] yields.
637    /// The [`Element`] tells a caller where in the document the warning sits:
638    ///
639    /// ```
640    /// # use ocpi_tariffs::{price, warning};
641    /// fn path_of_periods_state_no_time(warnings: &warning::Set<price::Warning>) -> Option<&str> {
642    ///     let (element, _warning) =
643    ///         warnings.find(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))?;
644    ///     Some(element.path.as_str())
645    /// }
646    /// ```
647    pub fn find<F>(&self, mut predicate: F) -> Option<(&Element, &W)>
648    where
649        F: FnMut(&W) -> bool,
650    {
651        self.iter_warnings()
652            .find(|(_element, warning)| predicate(warning))
653    }
654
655    /// Return every distinct [`Id`] of the [`Warning`]s in the set.
656    ///
657    /// A caller can compare the returned IDs with a list of the IDs it accepts,
658    /// rather than matching on the variants of each warning.
659    ///
660    /// Some IDs include a value from the warning, such as the field name in
661    /// `missing_field(country_code)`. Two warnings of one variant can then give two IDs.
662    pub fn ids(&self) -> BTreeSet<Id> {
663        self.iter_warnings()
664            .map(|(_element, warning)| warning.id())
665            .collect()
666    }
667
668    /// Return an iterator over the [`Warning`]s reported against the element at `path`,
669    /// such as `$.charging_periods`.
670    ///
671    /// Duplicate JSON keys give several elements the same path.
672    /// The iterator yields the warnings of every one of them, in document order,
673    /// where [`Set::path_map`] would keep only the last.
674    pub fn warnings_at<'set>(&'set self, path: &str) -> impl Iterator<Item = &'set W> {
675        self.iter_warnings()
676            .filter(move |(element, _warning)| element.path.as_str() == path)
677            .map(|(_element, warning)| warning)
678    }
679
680    /// Return the amount of [`Element`]s in this set.
681    ///
682    /// Each [`Element`] can have many [`Warning`]s associated with it.
683    pub fn len_elements(&self) -> usize {
684        self.0.len()
685    }
686
687    /// Return the total amount of [`Warning`]s in this set for all [`Element`]s.
688    pub fn len_warnings(&self) -> usize {
689        self.0
690            .values()
691            .fold(0, |acc, group| acc.saturating_add(group.warnings.len()))
692    }
693
694    /// Return an iterator of [`Warning`]s grouped by JSON element.
695    pub fn iter(&self) -> Iter<'_, W> {
696        Iter {
697            warnings: self.0.iter(),
698        }
699    }
700
701    /// Return a collection of `Id`s mapped to the paths they occurred at.
702    pub fn id_path_map(&self, config: Limit) -> IdPathMap<'_> {
703        let report = match config {
704            Limit::None => limit_none(&self.0),
705            Limit::WarningTypes(max_warning_types) => {
706                limit_warning_types(max_warning_types, &self.0)
707            }
708            Limit::ElemPathsPerId(max_elem_paths_per_warning_id) => {
709                limit_elem_paths_per_id(max_elem_paths_per_warning_id, &self.0)
710            }
711            Limit::All {
712                max_warning_types,
713                max_elem_paths_per_warning_id,
714            } => limit_all(max_warning_types, max_elem_paths_per_warning_id, &self.0),
715        };
716
717        let LimitReport {
718            elements_filtered,
719            warning_distinct_types_filtered,
720            warnings,
721        } = report;
722
723        IdPathMap {
724            total_warnings: self.len_warnings(),
725            total_elements: self.len_elements(),
726            elements_filtered,
727            warning_distinct_types_filtered,
728            warnings,
729        }
730    }
731
732    /// Return a collection of warning messages mapped to the paths they occurred at.
733    pub fn msg_path_map(&self, config: Limit) -> MsgPathMap<'_> {
734        let IdPathMap {
735            total_warnings,
736            total_elements,
737            elements_filtered,
738            warning_distinct_types_filtered,
739            warnings,
740        } = self.id_path_map(config);
741
742        let warnings = warnings
743            .into_iter()
744            .map(|(id, paths)| (id.to_string(), paths))
745            .collect();
746
747        MsgPathMap {
748            total_warnings,
749            total_elements,
750            elements_filtered,
751            warning_distinct_types_filtered,
752            warnings,
753        }
754    }
755
756    /// Return a map of element paths to a list of [`Warning`].
757    ///
758    /// This is designed to be used to print out maps of warnings associated with elements.
759    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
760    /// with indentation.
761    ///
762    /// # A path does not identify an element
763    ///
764    /// The set is keyed by [`json::ElemId`], this map is keyed by path. Duplicate JSON keys are
765    /// legal, and every occurrence of one has the same path, so several elements can compete for
766    /// a single entry. The entries are built in `ElemId` order and collected, so **the last
767    /// occurrence in the document wins and the earlier ones' warnings are absent from the map**.
768    ///
769    /// Nothing is lost from the set itself, so a caller that iterates groups - as
770    /// `cli::print::warning_set` does - still sees every warning. Reach for [`Set::iter`] rather
771    /// than this map when a warning may be reported against more than one occurrence of a field;
772    /// [`Warning::DuplicateField`](crate::schema::Warning::DuplicateField) is the case that
773    /// makes this reachable in practice.
774    pub fn path_map(&self) -> BTreeMap<&str, Vec<&W>> {
775        self.0
776            .values()
777            .map(|Group { element, warnings }| {
778                let path = element.path.as_str();
779                let warnings = warnings.iter().map(|w| &**w).collect();
780                (path, warnings)
781            })
782            .collect()
783    }
784
785    /// Consume the `Set` and return a map of element paths to a list of [`Warning`]s.
786    ///
787    /// This is designed to be used to print out maps of warnings associated with elements.
788    pub fn into_path_map(self) -> BTreeMap<json::Path, Vec<W>> {
789        self.0
790            .into_values()
791            .map(|Group { element, warnings }| {
792                let warnings = warnings.into_iter().map(Source::into_warning).collect();
793                (element.path, warnings)
794            })
795            .collect()
796    }
797
798    /// Return a map of element paths to a list of [`Warning`] ids as Strings.
799    ///
800    /// This is designed to be used to print out maps of warnings associated with elements.
801    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
802    /// with indentation.
803    ///
804    /// Note: This representation is also valid JSON and can be copied directly to
805    /// a test expectation file.
806    pub fn path_id_map(&self) -> BTreeMap<&str, Vec<Id>> {
807        self.0
808            .values()
809            .map(|group| {
810                let warnings = group.warnings.iter().map(|w| w.id()).collect();
811                (group.element.path.as_str(), warnings)
812            })
813            .collect()
814    }
815
816    /// Return a map of element paths to a list of [`Warning`] messages as Strings.
817    ///
818    /// This is designed to be used to print out maps of warnings associated with elements.
819    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
820    /// with indentation.
821    pub fn path_msg_map(&self) -> BTreeMap<&str, Vec<String>> {
822        self.0
823            .values()
824            .map(|group| {
825                let warnings = group.warnings.iter().map(|w| w.to_string()).collect();
826                (group.element.path.as_str(), warnings)
827            })
828            .collect()
829    }
830}
831
832/// The outcome of calling the `limit_*` functions related to the [`Set::id_path_map`] function.
833#[derive(Debug)]
834struct LimitReport<'set> {
835    /// The amount of element paths filtered due to a [`Limit`] being set.
836    pub elements_filtered: usize,
837
838    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
839    ///
840    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
841    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
842    /// this counts as one type, as all the IDs that were filtered are the same.
843    pub warning_distinct_types_filtered: usize,
844
845    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
846    pub warnings: BTreeMap<Id, Vec<&'set str>>,
847}
848
849/// The logic for the [`Limit::None`] variant.
850fn limit_none<W: Warning>(warnings: &BTreeMap<json::ElemId, Group<W>>) -> LimitReport<'_> {
851    let mut out = BTreeMap::new();
852
853    for group in warnings.values() {
854        let Group { element, warnings } = group;
855        let path = element.path.as_str();
856
857        for w in warnings {
858            match out.entry(w.id()) {
859                btree_map::Entry::Vacant(entry) => {
860                    entry.insert(vec![path]);
861                }
862                btree_map::Entry::Occupied(mut entry) => {
863                    entry.get_mut().push(path);
864                }
865            }
866        }
867    }
868
869    LimitReport {
870        warnings: out,
871        elements_filtered: 0,
872        warning_distinct_types_filtered: 0,
873    }
874}
875
876/// The logic for the [`Limit::WarningTypes`] variant.
877fn limit_warning_types<W: Warning>(
878    max_warning_types: usize,
879    warnings: &BTreeMap<json::ElemId, Group<W>>,
880) -> LimitReport<'_> {
881    let mut out = BTreeMap::new();
882    // A set of element paths encountered and filtered. Element paths can be encountered more
883    // than once, so a simple `usize` can't be used to count the encounters.
884    let mut elements_filtered = HashSet::new();
885    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
886    // so a simple `usize` can't be used to count the encounters.
887    let mut warning_distinct_types_filtered = HashSet::new();
888
889    for group in warnings.values() {
890        let Group { element, warnings } = group;
891        let path = element.path.as_str();
892        // True if any of the warnings are filtered,
893        // therefore this element should be considered filtered too.
894        let mut filtered = false;
895
896        for w in warnings {
897            let len = out.len();
898            let id = w.id();
899
900            match out.entry(id.clone()) {
901                btree_map::Entry::Vacant(entry) => {
902                    if len < max_warning_types {
903                        entry.insert(vec![path]);
904                    } else {
905                        warning_distinct_types_filtered.insert(id);
906                        filtered = true;
907                    }
908                }
909                btree_map::Entry::Occupied(mut entry) => {
910                    entry.get_mut().push(path);
911                }
912            }
913        }
914
915        if filtered {
916            elements_filtered.insert(path);
917        }
918    }
919
920    LimitReport {
921        warnings: out,
922        elements_filtered: elements_filtered.len(),
923        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
924    }
925}
926
927/// The logic for the [`Limit::ElemPathsPerId`] variant.
928fn limit_elem_paths_per_id<W: Warning>(
929    max_elem_paths_per_warning_id: usize,
930    warnings: &BTreeMap<json::ElemId, Group<W>>,
931) -> LimitReport<'_> {
932    let mut out = BTreeMap::new();
933    // A set of element paths encountered and filtered. Element paths can be encountered more
934    // than once, so a simple `usize` can't be used to count the encounters.
935    let mut elements_filtered = HashSet::new();
936
937    if max_elem_paths_per_warning_id == 0 {
938        for group in warnings.values() {
939            let Group { element, warnings } = group;
940
941            for w in warnings {
942                if let btree_map::Entry::Vacant(entry) = out.entry(w.id()) {
943                    entry.insert(vec![]);
944                }
945            }
946            elements_filtered.insert(element.path.as_str());
947        }
948    } else {
949        for group in warnings.values() {
950            let Group { element, warnings } = group;
951            let path = element.path.as_str();
952
953            for w in warnings {
954                let id = w.id();
955
956                match out.entry(id.clone()) {
957                    btree_map::Entry::Vacant(entry) => {
958                        entry.insert(vec![path]);
959                    }
960                    btree_map::Entry::Occupied(mut entry) => {
961                        if entry.get().len() < max_elem_paths_per_warning_id {
962                            entry.get_mut().push(path);
963                        } else {
964                            elements_filtered.insert(path);
965                        }
966                    }
967                }
968            }
969        }
970    }
971
972    LimitReport {
973        warnings: out,
974        elements_filtered: elements_filtered.len(),
975        warning_distinct_types_filtered: 0,
976    }
977}
978
979/// The logic for the [`Limit::All`] variant.
980fn limit_all<W: Warning>(
981    max_warning_types: usize,
982    max_elem_paths_per_warning_id: usize,
983    warnings: &BTreeMap<json::ElemId, Group<W>>,
984) -> LimitReport<'_> {
985    let mut out = BTreeMap::new();
986    // A set of element paths encountered and filtered. Element paths can be encountered more
987    // than once, so a simple `usize` can't be used to count the encounters.
988    let mut elements_filtered = HashSet::new();
989    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
990    // so a simple `usize` can't be used to count the encounters.
991    let mut warning_distinct_types_filtered = HashSet::new();
992
993    if max_warning_types > 0 && max_elem_paths_per_warning_id == 0 {
994        for group in warnings.values() {
995            let Group { element, warnings } = group;
996            let path = element.path.as_str();
997
998            for w in warnings {
999                let len = out.len();
1000                let id = w.id();
1001
1002                if let btree_map::Entry::Vacant(entry) = out.entry(id.clone()) {
1003                    if len < max_warning_types {
1004                        entry.insert(vec![]);
1005                    } else {
1006                        warning_distinct_types_filtered.insert(id);
1007                    }
1008                }
1009            }
1010
1011            elements_filtered.insert(path);
1012        }
1013    } else {
1014        for group in warnings.values() {
1015            let Group { element, warnings } = group;
1016            let path = element.path.as_str();
1017
1018            for w in warnings {
1019                let len = out.len();
1020                let id = w.id();
1021
1022                match out.entry(id.clone()) {
1023                    btree_map::Entry::Vacant(entry) => {
1024                        if len < max_warning_types {
1025                            entry.insert(vec![path]);
1026                        } else {
1027                            warning_distinct_types_filtered.insert(id);
1028                            elements_filtered.insert(path);
1029                        }
1030                    }
1031                    btree_map::Entry::Occupied(mut entry) => {
1032                        if entry.get().len() < max_elem_paths_per_warning_id {
1033                            entry.get_mut().push(path);
1034                        } else {
1035                            elements_filtered.insert(path);
1036                        }
1037                    }
1038                }
1039            }
1040        }
1041    }
1042
1043    LimitReport {
1044        warnings: out,
1045        elements_filtered: elements_filtered.len(),
1046        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
1047    }
1048}
1049
1050/// The outcome of calling the [`Set::id_path_map`] function.
1051#[derive(Debug)]
1052pub struct IdPathMap<'set> {
1053    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
1054    pub total_warnings: usize,
1055
1056    /// The total amount of element paths in the source [`Set`].
1057    pub total_elements: usize,
1058
1059    /// The amount of element paths filtered due to a [`Limit`] being set.
1060    pub elements_filtered: usize,
1061
1062    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
1063    ///
1064    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
1065    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
1066    /// this counts as one type, as all the IDs that were filtered are the same.
1067    pub warning_distinct_types_filtered: usize,
1068
1069    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
1070    pub warnings: BTreeMap<Id, Vec<&'set str>>,
1071}
1072
1073/// The outcome of calling the [`Set::msg_path_map`] function.
1074#[derive(Debug)]
1075pub struct MsgPathMap<'set> {
1076    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
1077    pub total_warnings: usize,
1078
1079    /// The total amount of element paths in the source [`Set`].
1080    pub total_elements: usize,
1081
1082    /// The amount of element paths filtered due to a [`Limit`] being set.
1083    pub elements_filtered: usize,
1084
1085    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
1086    ///
1087    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
1088    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
1089    /// this counts as one type, as all the IDs that were filtered are the same.
1090    pub warning_distinct_types_filtered: usize,
1091
1092    /// The map of all [`Warning`] [`Id`]s mapped to the element paths where they occurred.
1093    pub warnings: BTreeMap<String, Vec<&'set str>>,
1094}
1095
1096/// The limiting configuration of the [`Set::path_id_map`] function.
1097#[derive(Copy, Clone, Debug)]
1098pub enum Limit {
1099    /// Don't enforce any limits on [`Warning`] [`Id`]s or element [`json::Path`]s.
1100    None,
1101
1102    /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
1103    WarningTypes(usize),
1104
1105    /// Forbid more than this amount of element [`json::Path`]s to be inserted into the list for each [`Id`].
1106    ElemPathsPerId(usize),
1107
1108    /// Enforce both limits at once.
1109    All {
1110        /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
1111        max_warning_types: usize,
1112
1113        /// Forbid more than this amount of element [`json::Path`]s to be inserted into the list for each [`Id`].
1114        max_elem_paths_per_warning_id: usize,
1115    },
1116}
1117
1118/// A failed attempt to make a value: the [`Error`] that stopped it, and every
1119/// [`Warning`] raised before it.
1120///
1121/// A [`Caveat`] is a value that was made, with the warnings to bear in mind when using it. A
1122/// `Failure` is the attempt that didn't make one, so it's the `Err` of a [`Verdict`]. A caller
1123/// reads a `Failure`'s warnings with the same methods as a `Caveat`'s.
1124#[derive(Debug)]
1125pub struct Failure<W: Warning> {
1126    /// The warning that caused an operation to fail.
1127    ///
1128    /// The warning is converted to an [`Error`] so it's ready to take part in Rust's error system.
1129    error: Box<Error<W>>,
1130
1131    /// The warnings accumulated up until the failure moment.
1132    ///
1133    /// This set doesn't include the warning that caused the operation to fail.
1134    warnings: Set<W>,
1135}
1136
1137impl<W> Failure<W>
1138where
1139    W: Warning,
1140{
1141    /// Return the warnings raised before the failure, without the [`Error`].
1142    pub fn warnings(&self) -> &Set<W> {
1143        &self.warnings
1144    }
1145
1146    /// Consume the `Failure` and return the [`Error`] and the warnings raised before it.
1147    pub fn into_parts(self) -> (Error<W>, Set<W>) {
1148        let Self { error, warnings } = self;
1149        (*error, warnings)
1150    }
1151
1152    /// Return the [`Error`] and drop the warnings raised before it.
1153    pub fn ignore_warnings(self) -> Error<W> {
1154        *self.error
1155    }
1156}
1157
1158/// A group of warning `Warning`s associated with an `Element`.
1159///
1160/// This group is emitted from the `IntoGroupByElem` iterator.
1161/// The warning `Warning`s are owned and so can be moved to another location.
1162#[derive(Debug)]
1163pub struct Group<W: Warning> {
1164    /// The [`json::Element`] that has [`Warning`]s.
1165    element: Element,
1166
1167    /// The list of warnings for the [`json::Element`].
1168    warnings: Vec<Source<W>>,
1169}
1170
1171impl<W> Group<W>
1172where
1173    W: Warning,
1174{
1175    /// Consume the `Group` and return the constituent parts.
1176    pub fn into_parts(self) -> (Element, Vec<W>) {
1177        let Self { element, warnings } = self;
1178        let warnings = warnings.into_iter().map(Source::into_warning).collect();
1179        (element, warnings)
1180    }
1181
1182    /// Borrow the element and its [`Warning`]s.
1183    pub fn to_parts(&self) -> (&Element, Vec<&W>) {
1184        let Self { element, warnings } = self;
1185        let warnings = warnings.iter().map(|w| &**w).collect();
1186        (element, warnings)
1187    }
1188
1189    /// Borrow just the [`Warning`]s, without the element.
1190    pub fn warnings(&self) -> Vec<&W> {
1191        self.warnings.iter().map(|w| &**w).collect()
1192    }
1193
1194    /// Consume the group and return just the [`Warning`]s, discarding the element.
1195    pub fn into_warnings(self) -> Vec<W> {
1196        let Self {
1197            element: _,
1198            warnings,
1199        } = self;
1200        warnings.into_iter().map(Source::into_warning).collect()
1201    }
1202}
1203
1204/// An iterator of borrowed [`Warning`]s grouped by JSON element.
1205pub struct Iter<'caller, W>
1206where
1207    W: Warning,
1208{
1209    /// The iterator over every [`Warning`].
1210    warnings: btree_map::Iter<'caller, json::ElemId, Group<W>>,
1211}
1212
1213impl<W> Iter<'_, W> where W: Warning {}
1214
1215impl<'caller, W: Warning> Iterator for Iter<'caller, W> {
1216    type Item = &'caller Group<W>;
1217
1218    fn next(&mut self) -> Option<Self::Item> {
1219        let (_elem_id, group) = self.warnings.next()?;
1220        Some(group)
1221    }
1222}
1223
1224/// An iterator of borrowed [`Warning`]s grouped by JSON element.
1225pub struct IntoIter<W>
1226where
1227    W: Warning,
1228{
1229    /// The iterator over every [`Warning`].
1230    warnings: btree_map::IntoIter<json::ElemId, Group<W>>,
1231}
1232
1233impl<W: Warning> Iterator for IntoIter<W> {
1234    type Item = Group<W>;
1235
1236    fn next(&mut self) -> Option<Self::Item> {
1237        let (_elem_id, group) = self.warnings.next()?;
1238        Some(group)
1239    }
1240}
1241
1242impl<W: Warning> IntoIterator for Set<W> {
1243    type Item = Group<W>;
1244    type IntoIter = IntoIter<W>;
1245
1246    fn into_iter(self) -> Self::IntoIter {
1247        let Set(warnings) = self;
1248        IntoIter {
1249            warnings: warnings.into_iter(),
1250        }
1251    }
1252}
1253
1254impl<'a, W: Warning> IntoIterator for &'a Set<W> {
1255    type Item = &'a Group<W>;
1256    type IntoIter = Iter<'a, W>;
1257
1258    fn into_iter(self) -> Self::IntoIter {
1259        self.iter()
1260    }
1261}