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 an [`ErrorSet`] 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`] or [`SetDeferred`] moves the responsibility of
23//! alerting the caller to 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 `FromSchema` 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> FromSchema<'buf, schema::Str<'buf>> for CodeSet {
56//!     type Warning = Warning;
57//!
58//!     fn from_schema(source: &schema::Str<'buf>) -> Verdict<CodeSet, Self::Warning> {
59//!         // Read the string, gathering a warning per semantic problem found.
60//!     }
61//! }
62//! ```
63//!
64//! The caller decides whether the result is acceptable.
65
66#[cfg(test)]
67pub(crate) mod test;
68
69#[cfg(test)]
70mod test_assert_path_map_warnings;
71
72#[cfg(test)]
73mod test_assert_warnings;
74
75#[cfg(test)]
76mod test_contains;
77
78#[cfg(test)]
79mod test_error_set_unwrap;
80
81#[cfg(test)]
82mod test_find;
83
84#[cfg(test)]
85mod test_group_by_elem;
86
87#[cfg(test)]
88mod test_id_path_map;
89
90#[cfg(test)]
91mod test_ids;
92
93#[cfg(test)]
94mod test_iter_warnings;
95
96#[cfg(test)]
97mod test_path_map;
98
99#[cfg(test)]
100mod test_warnings_at;
101
102use std::{
103    borrow::Cow,
104    collections::{BTreeMap, BTreeSet, HashSet, btree_map},
105    convert::Infallible,
106    fmt,
107    ops::Deref,
108    vec,
109};
110
111use tracing::{debug, info};
112
113use crate::{json, schema::Integrity};
114
115#[doc(hidden)]
116#[macro_export]
117macro_rules! from_warning_all {
118    ($($source_kind:path => $target_kind:ident::$target_variant:ident),+) => {
119        $(
120            /// Convert from `Warning` A to B.
121            impl From<$source_kind> for $target_kind {
122                fn from(warning: $source_kind) -> Self {
123                    $target_kind::$target_variant(warning)
124                }
125            }
126
127            /// Implement a conversion from `warning::Set<A>` to `warning::Set<B>` so that the `Err` variant
128            /// of a `Verdict<_, A>` can be converted using the `?` operator to `Verdict<_, B>`.
129            ///
130            /// `warning::Set::into_other` is used to perform the conversion between set `A` and `B`.
131            impl From<$crate::warning::ErrorSet<$source_kind>> for $crate::warning::ErrorSet<$target_kind> {
132                fn from(set_a: $crate::warning::ErrorSet<$source_kind>) -> Self {
133                    set_a.into_other()
134                }
135            }
136
137            /// Implement a conversion from `warning::SetDeferred<A>` to `warning::SetDeferred<B>` so that the `Err` variant
138            /// of a `VerdictDeferred<_, A>` can be converted using the `?` operator to `VerdictDeferred<_, B>`.
139            ///
140            /// `warning::SetDeferred::into_other` is used to perform the conversion between set `A` and `B`.
141            impl From<$crate::warning::ErrorSetDeferred<$source_kind>> for $crate::warning::ErrorSetDeferred<$target_kind> {
142                fn from(set_a: $crate::warning::ErrorSetDeferred<$source_kind>) -> Self {
143                    set_a.into_other()
144                }
145            }
146        )+
147    };
148}
149
150/// The stable identifier of a [`Warning`] kind, such as `missing_field(id)`.
151///
152/// Two warnings of the same kind share an `Id`, so this is what a caller matches on to accept
153/// or reject a class of warning without depending on the `Warning` type itself.
154#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
155pub struct Id(Cow<'static, str>);
156
157impl Id {
158    /// Create an `Id` from a `'static str`.
159    pub(crate) const fn from_static(s: &'static str) -> Self {
160        Self(Cow::Borrowed(s))
161    }
162
163    /// Create an `Id` from a `String`.
164    pub(crate) const fn from_string(s: String) -> Self {
165        Self(Cow::Owned(s))
166    }
167
168    /// Return the contained `str`.
169    pub fn as_str(&self) -> &str {
170        &self.0
171    }
172}
173
174impl fmt::Debug for Id {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        fmt::Debug::fmt(&self.0, f)
177    }
178}
179
180impl fmt::Display for Id {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        fmt::Display::fmt(&self.0, f)
183    }
184}
185
186/// A `Verdict` is a standard [`Result`] with [`Warning`]s potentially issued for both the `Ok` and `Err` variants.
187pub type Verdict<T, W> = Result<Caveat<T, W>, ErrorSet<W>>;
188
189/// A `VerdictDeferred` is a standard [`Result`] with [`Warning`]s potentially issued for both the `Ok` and `Err` variants.
190///
191/// This verdict is considered deferred as the warnings still need to be associated with a [`json::Element`].
192///
193/// NOTE: The deferred types are used to avoid passing [`json::Element`] references
194/// to functions just to create [`Warning`]s.
195pub(crate) type VerdictDeferred<T, W> = Result<CaveatDeferred<T, W>, ErrorSetDeferred<W>>;
196
197/// A value that may have associated [`Warning`]s.
198///
199/// This caveat is considered deferred as the warning still need to be associated with
200/// a [`json::Element`] to become [`Warning`]s.
201///
202/// Even though the value has been created there may be certain caveats you should be aware of before using it.
203///
204/// NOTE: The deferred types are used to avoid passing [`json::Element`] references
205/// to functions just to create [`Warning`]s.
206#[derive(Debug)]
207pub struct CaveatDeferred<T, W: Warning> {
208    /// The value created by the function.
209    value: T,
210
211    /// A list of [`Warning`]s or caveats issued when creating the value.
212    warnings: SetDeferred<W>,
213}
214
215/// Read the value without taking it, which leaves the warnings attached.
216///
217/// `Deref` is justified here because a `CaveatDeferred` behaves transparently like its `T` and the
218/// deref is a field read. It borrows, so the value cannot leave a caveat this way and the warnings
219/// cannot be lost by accident.
220///
221/// See: <https://doc.rust-lang.org/std/ops/trait.Deref.html#when-to-implement-deref-or-derefmut>.
222impl<T, W> Deref for CaveatDeferred<T, W>
223where
224    W: Warning,
225{
226    type Target = T;
227
228    fn deref(&self) -> &T {
229        &self.value
230    }
231}
232
233impl<T, W> CaveatDeferred<T, W>
234where
235    W: Warning,
236{
237    /// The only way to create `CaveatDeferred<T>` is if `T` impls `IntoCaveatDeferred`.
238    pub(crate) fn new(value: T, warnings: SetDeferred<W>) -> Self {
239        Self { value, warnings }
240    }
241
242    /// Return the value and any [`Warning`]s stored in the `CaveatDeferred`.
243    pub fn into_parts(self) -> (T, SetDeferred<W>) {
244        let Self { value, warnings } = self;
245        (value, warnings)
246    }
247
248    /// Return the value and drop any warnings contained within.
249    pub fn ignore_warnings(self) -> T {
250        self.value
251    }
252}
253
254/// A value that may have associated [`Warning`]s.
255///
256/// Even though the value has been created there may be certain caveats you should be aware of before using it.
257#[derive(Debug)]
258pub struct Caveat<T, W: Warning> {
259    /// The value created by the function.
260    value: T,
261
262    /// A list of [`Warning`]s or caveats issued when creating the value.
263    warnings: Set<W>,
264}
265
266/// Read the value without taking it, which leaves the warnings attached.
267///
268/// `Deref` is justified here because a `Caveat` behaves transparently like its `T` and the deref is
269/// a field read. It borrows, so the value cannot leave a caveat this way and the warnings cannot be
270/// lost by accident.
271///
272/// See: <https://doc.rust-lang.org/std/ops/trait.Deref.html#when-to-implement-deref-or-derefmut>.
273impl<T, W> Deref for Caveat<T, W>
274where
275    W: Warning,
276{
277    type Target = T;
278
279    fn deref(&self) -> &T {
280        &self.value
281    }
282}
283
284impl<T, W> Caveat<T, W>
285where
286    W: Warning,
287{
288    /// The only way to create `Caveat<T>` is if `T` impls `IntoCaveat`.
289    pub(crate) fn new(value: T, warnings: Set<W>) -> Self {
290        Self { value, warnings }
291    }
292
293    /// Return a ref to the warning Set.
294    pub fn warnings(&self) -> &Set<W> {
295        &self.warnings
296    }
297
298    /// Return the value and any [`Warning`]s stored in the `Caveat`.
299    pub fn into_parts(self) -> (T, Set<W>) {
300        let Self { value, warnings } = self;
301        (value, warnings)
302    }
303
304    /// Return the value and drop any warnings contained within.
305    pub fn ignore_warnings(self) -> T {
306        self.value
307    }
308
309    /// Map the value to another target type while retaining the warnings about the source type.
310    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Caveat<U, W> {
311        let Self { value, warnings } = self;
312        Caveat {
313            value: op(value),
314            warnings,
315        }
316    }
317}
318
319/// Convert a `Caveat`, or a container of them, into a value with the same shape by
320/// gathering up its [`Warning`]s.
321pub trait GatherWarnings<T, W>
322where
323    W: Warning,
324{
325    /// The output type, after all the warnings have been gathered.
326    type Output;
327
328    /// Move each [`Warning`] out of `self` and into the parent set.
329    ///
330    /// The return is `Self::Output`, which is `self` with the `Caveat` wrapper removed.
331    #[must_use = "If you want to ignore the value use `let _ =`"]
332    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
333    where
334        W: Into<WA>,
335        WA: Warning;
336}
337
338/// Convert a `Caveat<T>` into `T` by gathering up its [`Warning`]s.
339impl<T, W> GatherWarnings<T, W> for Caveat<T, W>
340where
341    W: Warning,
342{
343    type Output = T;
344
345    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
346    where
347        W: Into<WA>,
348        WA: Warning,
349    {
350        let Self {
351            value,
352            warnings: inner_warnings,
353        } = self;
354
355        let Set(inner_warnings) = inner_warnings;
356        let inner_warnings = inner_warnings
357            .into_iter()
358            .map(|(elem_id, group)| (elem_id, group.into_other()));
359
360        warnings.extend(inner_warnings);
361
362        value
363    }
364}
365
366/// Convert an `Option<Caveat<T>>` into `Option<T>` by gathering up its [`Warning`]s.
367impl<T, W> GatherWarnings<T, W> for Option<Caveat<T, W>>
368where
369    W: Warning,
370{
371    type Output = Option<T>;
372
373    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
374    where
375        W: Into<WA>,
376        WA: Warning,
377    {
378        match self {
379            Some(cv) => Some(cv.gather_warnings_into(warnings)),
380            None => None,
381        }
382    }
383}
384
385/// Convert a `Result<Caveat<T>, E>` into `Result<T, E>` by gathering up the `Ok` side's
386/// [`Warning`]s. An `Err` passes through with its `E` untouched.
387///
388/// The bound on `E` is `std::error::Error`, which an `ErrorSet` is not, so this impl does not
389/// overlap the one for [`Verdict`].
390impl<T, W, E> GatherWarnings<T, W> for Result<Caveat<T, W>, E>
391where
392    W: Warning,
393    E: std::error::Error,
394{
395    type Output = Result<T, E>;
396
397    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
398    where
399        W: Into<WA>,
400        WA: Warning,
401    {
402        match self {
403            Ok(cv) => Ok(cv.gather_warnings_into(warnings)),
404            Err(err) => Err(err),
405        }
406    }
407}
408
409/// Convert a `Verdict<T, W>` into `Result<T, ErrorSet<W>>` by gathering up the `Ok` side's
410/// [`Warning`]s. An `Err` passes through with its `ErrorSet` untouched.
411impl<T, W> GatherWarnings<T, W> for Verdict<T, W>
412where
413    W: Warning,
414{
415    type Output = Result<T, ErrorSet<W>>;
416
417    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
418    where
419        W: Into<WA>,
420        WA: Warning,
421    {
422        match self {
423            Ok(cv) => Ok(cv.gather_warnings_into(warnings)),
424            Err(err_set) => Err(err_set),
425        }
426    }
427}
428
429/// Convert a `Result` that contains an `ErrorSet` into an `Option<T>`.
430///
431/// An `Err` becomes `None` and its [`Error`] is de-escalated into the parent set as a warning,
432/// which is what separates this from [`GatherWarnings`]: that trait keeps the error, this one
433/// gives it up.
434pub(crate) trait DeescalateError<T, W>
435where
436    W: Warning,
437{
438    /// Move each [`Warning`] out of `self` and into the parent set.
439    ///
440    /// An `Ok` returns as `Some`. An [`Error`] is de-escalated into the parent set as a warning and
441    /// returns `None`.
442    #[must_use = "If you want to ignore the value use `let _ =`"]
443    fn deescalate_error_into<WA>(self, warnings: &mut Set<WA>) -> Option<T>
444    where
445        W: Into<WA>,
446        WA: Warning;
447}
448
449/// Convert a `Verdict<T, W>` into `Option<T>` by gathering up the `Ok` side's [`Warning`]s.
450///
451/// An `Err` gives up both parts: its `ErrorSet`'s warnings and the [`Error`] itself go into the
452/// parent set, the error de-escalated to a warning.
453impl<T, W> DeescalateError<T, W> for Verdict<T, W>
454where
455    W: Warning,
456{
457    fn deescalate_error_into<WA>(self, warnings: &mut Set<WA>) -> Option<T>
458    where
459        W: Into<WA>,
460        WA: Warning,
461    {
462        match self {
463            Ok(cv) => Some(cv.gather_warnings_into(warnings)),
464            Err(err_set) => {
465                warnings.deescalate_error(err_set.into_other());
466                None
467            }
468        }
469    }
470}
471
472/// Convert a `Result<T, ErrorSet<W>>` into `Option<T>`, gathering nothing from an `Ok`,
473/// which carries no caveat.
474///
475/// An `Err` gives up both parts: its `ErrorSet`'s warnings and the [`Error`] itself go into the
476/// parent set, the error de-escalated to a warning.
477impl<T, W> DeescalateError<T, W> for Result<T, ErrorSet<W>>
478where
479    W: Warning,
480{
481    fn deescalate_error_into<WA>(self, warnings: &mut Set<WA>) -> Option<T>
482    where
483        W: Into<WA>,
484        WA: Warning,
485    {
486        match self {
487            Ok(cv) => Some(cv),
488            Err(err_set) => {
489                warnings.deescalate_error(err_set.into_other());
490                None
491            }
492        }
493    }
494}
495
496/// Convert a `Vec<Caveat<T>>` into `Vec<T>` by gathering up each element's [`Warning`]s.
497impl<T, W> GatherWarnings<T, W> for Vec<Caveat<T, W>>
498where
499    W: Warning,
500{
501    type Output = Vec<T>;
502
503    fn gather_warnings_into<WA>(self, warnings: &mut Set<WA>) -> Self::Output
504    where
505        W: Into<WA>,
506        WA: Warning,
507    {
508        self.into_iter()
509            .map(|cv| cv.gather_warnings_into(warnings))
510            .collect()
511    }
512}
513
514/// Convert a `CaveatDeferred`, or a container of them, into a value with the same shape by
515/// gathering up its [`Warning`]s.
516pub(crate) trait GatherDeferredWarnings<T, W>
517where
518    W: Warning,
519{
520    /// The output type, after all the warnings have been gathered.
521    type Output;
522
523    /// Move each [`Warning`] out of `self` and into the parent set.
524    ///
525    /// The return is `Self::Output`, which is `self` with the `CaveatDeferred` wrapper removed.
526    #[must_use = "If you want to ignore the value use `let _ =`"]
527    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
528    where
529        W: Into<WA>,
530        WA: Warning;
531}
532
533/// Convert a `CaveatDeferred<T>` into `T` by gathering up its [`Warning`]s.
534impl<T, W> GatherDeferredWarnings<T, W> for CaveatDeferred<T, W>
535where
536    W: Warning,
537{
538    type Output = T;
539
540    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
541    where
542        W: Into<WA>,
543        WA: Warning,
544    {
545        let Self {
546            value,
547            warnings: inner_warnings,
548        } = self;
549
550        warnings.extend(inner_warnings);
551
552        value
553    }
554}
555
556/// Convert an `Option<CaveatDeferred<T>>` into `Option<T>` by gathering up its
557/// [`Warning`]s.
558impl<T, W> GatherDeferredWarnings<T, W> for Option<CaveatDeferred<T, W>>
559where
560    W: Warning,
561{
562    type Output = Option<T>;
563
564    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
565    where
566        W: Into<WA>,
567        WA: Warning,
568    {
569        match self {
570            Some(cv) => Some(cv.gather_deferred_warnings_into(warnings)),
571            None => None,
572        }
573    }
574}
575
576/// Convert a `Result<CaveatDeferred<T>, E>` into `Result<T, E>` by gathering up the `Ok`
577/// side's [`Warning`]s. An `Err` passes through with its `E` untouched.
578///
579/// The bound on `E` is `std::error::Error`, which an `ErrorSetDeferred` is not, so this impl does
580/// not overlap the one for [`VerdictDeferred`].
581impl<T, W, E> GatherDeferredWarnings<T, W> for Result<CaveatDeferred<T, W>, E>
582where
583    W: Warning,
584    E: std::error::Error,
585{
586    type Output = Result<T, E>;
587
588    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
589    where
590        W: Into<WA>,
591        WA: Warning,
592    {
593        match self {
594            Ok(cv) => Ok(cv.gather_deferred_warnings_into(warnings)),
595            Err(err) => Err(err),
596        }
597    }
598}
599
600/// Convert a `VerdictDeferred<T, W>` into `Result<T, ErrorSetDeferred<W>>` by gathering up
601/// the `Ok` side's [`Warning`]s. An `Err` passes through with its `ErrorSetDeferred` untouched.
602impl<T, W> GatherDeferredWarnings<T, W> for VerdictDeferred<T, W>
603where
604    W: Warning,
605{
606    type Output = Result<T, ErrorSetDeferred<W>>;
607
608    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
609    where
610        W: Into<WA>,
611        WA: Warning,
612    {
613        match self {
614            Ok(cv) => Ok(cv.gather_deferred_warnings_into(warnings)),
615            Err(err_set) => Err(err_set),
616        }
617    }
618}
619
620/// Convert a `Vec<CaveatDeferred<T>>` into `Vec<T>` by gathering up each element's [`Warning`]s.
621impl<T, W> GatherDeferredWarnings<T, W> for Vec<CaveatDeferred<T, W>>
622where
623    W: Warning,
624{
625    type Output = Vec<T>;
626
627    fn gather_deferred_warnings_into<WA>(self, warnings: &mut SetDeferred<WA>) -> Self::Output
628    where
629        W: Into<WA>,
630        WA: Warning,
631    {
632        self.into_iter()
633            .map(|cv| cv.gather_deferred_warnings_into(warnings))
634            .collect()
635    }
636}
637
638/// Converts a value `T` into a `Caveat`.
639///
640/// Each module can use this to whitelist their types for conversion to `Caveat<T>`.
641pub trait IntoCaveat: Sized {
642    /// Any type can be converted to `Caveat<T>` by supplying a list of [`Warning`]s.
643    fn into_caveat<W: Warning>(self, warnings: Set<W>) -> Caveat<Self, W>;
644
645    /// If a `FromSchema` is infallible a `Caveat` can be created using this method.
646    fn into_infallible_caveat(self) -> Caveat<Self, Infallible> {
647        self.into_caveat(Set::new())
648    }
649}
650
651/// Converts a value `T` into a `CaveatDeferred`.
652///
653/// Each module can use this to whitelist their types for conversion to `CaveatDeferred<T>`.
654pub(crate) trait IntoCaveatDeferred: Sized {
655    /// Any type can be converted to `CaveatDeferred<T>` by supplying a list of [`Warning`]s.
656    fn into_caveat_deferred<W: Warning>(self, warnings: SetDeferred<W>) -> CaveatDeferred<Self, W>;
657}
658
659/// Allow all types to be converted into `Caveat<T>`.
660impl<T> IntoCaveat for T {
661    fn into_caveat<W: Warning>(self, warnings: Set<W>) -> Caveat<Self, W> {
662        Caveat::new(self, warnings)
663    }
664}
665
666/// Allow `Vec<T: IntoCaveat>` to be converted into a `CaveatDeferred`.
667impl<T> IntoCaveatDeferred for T {
668    fn into_caveat_deferred<W: Warning>(self, warnings: SetDeferred<W>) -> CaveatDeferred<Self, W> {
669        CaveatDeferred::new(self, warnings)
670    }
671}
672
673/// `Verdict` specific extension methods for the `Result` type.
674pub trait VerdictExt<T, W: Warning> {
675    /// Maps a `Verdict<T, W>` to `Verdict<U, W>` by applying a function to a contained
676    /// [`Ok`] value, leaving an [`Err`] value untouched.
677    fn map_caveat<F, U>(self, op: F) -> Verdict<U, W>
678    where
679        F: FnOnce(T) -> U;
680
681    /// Discard all warnings in the `Err` variant and keep only the warning that caused the error.
682    fn only_error(self) -> Result<Caveat<T, W>, Error<W>>;
683}
684
685/// Used to log the contents of various `Verdict` impls.
686#[expect(dead_code, reason = "for debugging")]
687pub(crate) trait VerdictTrace<T, W: Warning> {
688    /// Log the contents as `info` level.
689    fn info_verdict(self, msg: &'static str) -> Self;
690
691    /// Log the contents as `debug` level.
692    fn debug_verdict(self, msg: &'static str) -> Self;
693}
694
695/// Used to log the contents of various `Result` impls.
696#[expect(dead_code, reason = "for debugging")]
697pub(crate) trait ResultTrace<T, W: Warning> {
698    /// Log the contents as `info` level.
699    fn info_result(self, msg: &'static str) -> Self;
700
701    /// Log the contents as `debug` level.
702    fn debug_result(self, msg: &'static str) -> Self;
703}
704
705impl<T, W: Warning> VerdictExt<T, W> for Verdict<T, W> {
706    fn map_caveat<F, U>(self, op: F) -> Verdict<U, W>
707    where
708        F: FnOnce(T) -> U,
709    {
710        match self {
711            Ok(c) => Ok(c.map(op)),
712            Err(w) => Err(w),
713        }
714    }
715
716    fn only_error(self) -> Result<Caveat<T, W>, Error<W>> {
717        match self {
718            Ok(c) => Ok(c),
719            Err(err_set) => {
720                let ErrorSet { error, warnings: _ } = err_set;
721                Err(*error)
722            }
723        }
724    }
725}
726
727/// Consume a [`Verdict`] whose warning type is uninhabited.
728///
729/// A `FromSchema` impl that can never emit a warning uses [`Infallible`] as its warning
730/// (typically the enum-to-enum lowerings). Such a verdict can neither error nor carry
731/// warnings, so a fallible caller can extract the value directly without threading an
732/// `Infallible`-to-`W` conversion through `?`/`gather_warnings_into`.
733pub(crate) trait IntoInfallible<T> {
734    /// The built value; there is no error path and no warning to gather.
735    fn into_infallible(self) -> T;
736}
737
738impl<T> IntoInfallible<T> for Verdict<T, Infallible> {
739    fn into_infallible(self) -> T {
740        match self {
741            Ok(caveat) => caveat.into_parts().0,
742            // `ErrorSet<Infallible>` cannot be constructed (its warning is uninhabited), so
743            // this arm is unreachable. The `Box` around the error hides that uninhabitedness
744            // from an empty `match`, so state it explicitly.
745            Err(_) => unreachable!("a `Verdict` with an `Infallible` warning cannot be an error"),
746        }
747    }
748}
749
750impl<T, W: Warning> VerdictTrace<T, W> for Verdict<T, W>
751where
752    T: fmt::Debug,
753{
754    fn info_verdict(self, msg: &'static str) -> Self {
755        match self {
756            Ok(c) => {
757                info!("{msg}: {c:#?}");
758                Ok(c)
759            }
760            Err(err_set) => {
761                info!("{msg}: {err_set:#?}");
762                Err(err_set)
763            }
764        }
765    }
766
767    fn debug_verdict(self, msg: &'static str) -> Self {
768        match self {
769            Ok(c) => {
770                debug!("{msg}: {c:#?}");
771                Ok(c)
772            }
773            Err(err_set) => {
774                debug!("{msg}: {err_set:#?}");
775                Err(err_set)
776            }
777        }
778    }
779}
780
781impl<T, W: Warning> ResultTrace<T, W> for Result<T, ErrorSet<W>>
782where
783    T: fmt::Debug,
784{
785    fn info_result(self, msg: &'static str) -> Self {
786        match self {
787            Ok(c) => {
788                info!("{msg}: {c:#?}");
789                Ok(c)
790            }
791            Err(err_set) => {
792                info!("{msg}: {err_set:#?}");
793                Err(err_set)
794            }
795        }
796    }
797
798    fn debug_result(self, msg: &'static str) -> Self {
799        match self {
800            Ok(c) => {
801                debug!("{msg}: {c:#?}");
802                Ok(c)
803            }
804            Err(err_set) => {
805                debug!("{msg}: {err_set:#?}");
806                Err(err_set)
807            }
808        }
809    }
810}
811
812/// The warning that caused an operation to fail.
813///
814/// The warning is stored apart from the source set so it is
815/// clear which warning has been escalated to an error.
816#[derive(Debug)]
817pub struct Error<W: Warning> {
818    /// The warning the operation failed on.
819    warning: W,
820
821    /// The element the warning was reported against.
822    element: Element,
823}
824
825impl<W: Warning> Error<W> {
826    /// Return reference to the [`Warning`].
827    pub fn warning(&self) -> &W {
828        &self.warning
829    }
830
831    /// Consume the `Error` and return the [`Warning`].
832    pub fn into_warning(self) -> W {
833        self.warning
834    }
835
836    /// Return a reference to the [`Element`] that caused the [`Warning`].
837    pub fn element(&self) -> &Element {
838        &self.element
839    }
840
841    /// Return the constituent parts.
842    pub fn parts(&self) -> (&W, &Element) {
843        (&self.warning, &self.element)
844    }
845
846    /// Consume the `Cause` and return the constituent parts.
847    pub fn into_parts(self) -> (W, Element) {
848        let Self { warning, element } = self;
849        (warning, element)
850    }
851
852    /// Converts `Error<W>` into `Error<WA>` using the `impl Into<WA> for W`.
853    ///
854    /// This is used by the [`from_warning_all`] macro.
855    fn into_other<WA>(self) -> Error<WA>
856    where
857        W: Into<WA>,
858        WA: Warning,
859    {
860        let Self { warning, element } = self;
861        Error {
862            warning: warning.into(),
863            element,
864        }
865    }
866}
867
868impl<W: Warning> std::error::Error for Error<W> {}
869
870impl<W: Warning> fmt::Display for Error<W> {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        write!(
873            f,
874            "A warning for element at `{}` was upgraded to an `error`: {}",
875            self.element.path, self.warning
876        )
877    }
878}
879
880/// Associate a [`json::Element`] with a set of deferred [`Warning`]s.
881///
882/// A deferred type carries warnings that are not yet tied to the element they describe, which is
883/// how a lowering avoids threading [`json::Element`] references through every step. This trait is
884/// the step that ties them, converting each deferred type into its associated counterpart: a
885/// [`CaveatDeferred`] becomes a [`Caveat`], and the deferred result type becomes a [`Verdict`].
886pub trait WithElement<T, W: Warning> {
887    /// The associated counterpart of the deferred type this is implemented for.
888    type Output;
889
890    /// Associate every [`Warning`] carried by `self` with `element`.
891    fn with_element(self, element: &json::Element<'_>) -> Self::Output;
892}
893
894impl<T, W: Warning> WithElement<T, W> for CaveatDeferred<T, W> {
895    type Output = Caveat<T, W>;
896
897    fn with_element(self, element: &json::Element<'_>) -> Self::Output {
898        let CaveatDeferred { value, warnings } = self;
899        let SetDeferred(warnings) = warnings;
900        let warnings = if warnings.is_empty() {
901            BTreeMap::new()
902        } else {
903            let warnings = Group {
904                element: Element::from_json(element),
905                warnings,
906            };
907            BTreeMap::from([(element.id(), warnings)])
908        };
909
910        Caveat {
911            value,
912            warnings: Set(warnings),
913        }
914    }
915}
916
917impl<T, W: Warning> WithElement<T, W> for VerdictDeferred<T, W> {
918    type Output = Verdict<T, W>;
919
920    /// Associate a [`json::Element`] with a set of [`Warning`]s.
921    fn with_element(self, element: &json::Element<'_>) -> Self::Output {
922        match self {
923            Ok(v) => Ok(v.with_element(element)),
924            Err(set) => {
925                let ErrorSetDeferred { error, warnings } = set;
926                // An `ErrorSetDeferred` should have at least one warning in it.
927                let warnings = Group {
928                    element: Element::from_json(element),
929                    warnings,
930                };
931                let warnings = BTreeMap::from([(element.id(), warnings)]);
932                Err(ErrorSet {
933                    error: Box::new(Error {
934                        warning: error,
935                        element: Element::from_json(element),
936                    }),
937                    warnings,
938                })
939            }
940        }
941    }
942}
943
944/// A representation of a JSON element that satisfies the needs of most consumers of a [`Warning`].
945///
946/// This representation avoids the complexity of needing to provide a `'buf` lifetime to the [`json::Element`].
947/// This would complicate all warnings types with that lifetime.
948///
949/// A consumer of warnings wants them grouped by the element they were reported against and
950/// then displayed by path. [`Set`] is keyed by [`Element::id`], so it groups them on insert
951/// and emits the groups in the order the elements appear in the document.
952///
953/// The linter report also wants to highlight the source JSON that a warning refers to.
954#[derive(Clone, Debug, PartialEq, Eq)]
955pub struct Element {
956    /// The Id of the element that caused the [`Warning`].
957    ///
958    /// [`Set`] groups and orders warnings by this id.
959    ///
960    /// Pass it to [`json::Document::element`] to get the live [`json::Element`] back, which is
961    /// what acting on a warning takes rather than just reporting it: the value, the child
962    /// elements and [`json::Element::full_span`] are all absent here.
963    pub id: json::ElemId,
964
965    /// The `Span` that delimits the [`json::Element`].
966    pub span: json::Span,
967
968    /// The elements path.
969    ///
970    /// Most consumers of warnings just want this data.
971    pub path: json::Path,
972
973    /// The location (line, column) of the beginning of this element in the JSON file.
974    pub location: json::Location,
975}
976
977impl Element {
978    /// Create an owned `Element` from a `json::Element<'buf'>`.
979    pub(crate) fn from_json(element: &json::Element<'_>) -> Element {
980        Self {
981            id: element.id(),
982            span: element.span(),
983            path: element.path(),
984            location: element.location(),
985        }
986    }
987}
988
989/// A Display object for writing a set of warnings.
990///
991/// The warnings set is formatted as a tree with element paths on the first level
992/// and a list of warning ids on the second.
993///
994/// ```shell
995/// $.path.to.json[0].field:
996///   - list_of_warning_ids
997///   - next_warning_id
998///
999/// $.next.path.to[1].json.field
1000///   - list_of_warning_ids
1001/// ```
1002pub struct SetWriter<'caller, W: Warning> {
1003    /// The list of warnings for the [`json::Element`].
1004    warnings: &'caller Set<W>,
1005
1006    /// The indent to prefix to each warning id.
1007    indent: &'caller str,
1008}
1009
1010impl<'caller, W: Warning> SetWriter<'caller, W> {
1011    /// Create a new `SetWriter` with a default warning id indent of `"  - "`.
1012    pub fn new(warnings: &'caller Set<W>) -> Self {
1013        Self {
1014            warnings,
1015            indent: "  - ",
1016        }
1017    }
1018
1019    /// Create a new `SetWriter` with a custom warning id indent.
1020    pub fn with_indent(warnings: &'caller Set<W>, indent: &'caller str) -> Self {
1021        Self { warnings, indent }
1022    }
1023}
1024
1025impl<W: Warning> fmt::Debug for SetWriter<'_, W> {
1026    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027        fmt::Display::fmt(self, f)
1028    }
1029}
1030
1031impl<W: Warning> fmt::Display for SetWriter<'_, W> {
1032    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033        let mut iter = self.warnings.iter();
1034
1035        {
1036            // Write the first group without an empty line prefix.
1037            let Some((element, warnings)) = iter.next().map(|g| g.to_parts()) else {
1038                return Ok(());
1039            };
1040
1041            writeln!(f, "{}", element.path)?;
1042
1043            for warning in warnings {
1044                write!(f, "{}{}", self.indent, warning)?;
1045            }
1046        }
1047
1048        // Write the rest of the Groups with am empty line padding.
1049        for (element, warnings) in iter.map(|g| g.to_parts()) {
1050            writeln!(f, "\n{}", element.path)?;
1051
1052            for warning in warnings {
1053                write!(f, "{}{}", self.indent, warning)?;
1054            }
1055        }
1056
1057        Ok(())
1058    }
1059}
1060
1061/// Each mod defines warnings for the type that it's trying to parse or lint from a [`json::Element`].
1062///
1063/// The `Warning` in the mod should impl this trait to take part in the [`Warning`] system.
1064pub trait Warning: Sized + fmt::Debug + fmt::Display + Send + Sync {
1065    /// Return the human readable identifier for the [`Warning`].
1066    ///
1067    /// This is used in the `auto_test` assertion system.
1068    /// Changing these strings may require updating `output_price__cdr.json` files.
1069    fn id(&self) -> Id;
1070
1071    /// Whether this is the [`Rejected`] marker a feature emits when it rejects the schema IR
1072    /// for the object it is building.
1073    ///
1074    /// The precise structural cause (a missing or wrong-typed field) was already reported by
1075    /// the schema walk, so a consumer can drop these follow-on markers via
1076    /// [`Set::remove_rejected`]. Other Warnings return `false`.
1077    fn is_rejected(&self) -> bool {
1078        false
1079    }
1080}
1081
1082/// A content-free marker seeded into any [`Warning`] (via `From<Rejected>`) when a feature
1083/// rejects the schema IR for the object it is building, because a required field was absent
1084/// or could not be built.
1085///
1086/// A feature accepts a `Versioned` object and rejects it based on the warnings the schema walk
1087/// already reported, so this marker carries no detail of its own. It is still anchored to the
1088/// offending field's [`Element`], and is easily filtered via [`Warning::is_rejected`].
1089#[derive(Clone, Copy, Debug)]
1090pub struct Rejected;
1091
1092/// A `FromSchema` implementation that can never emit a warning uses [`std::convert::Infallible`]
1093/// as its [`Warning`] type. The type is uninhabited, so every method is unreachable.
1094impl Warning for Infallible {
1095    fn id(&self) -> Id {
1096        match *self {}
1097    }
1098}
1099
1100/// A transparent container that stores the source line where the [`Warning`] occurred in a test build.
1101#[derive(Debug)]
1102struct Source<W: Warning> {
1103    #[cfg(test)]
1104    /// The line in the source code where this [`Warning`] occurred.
1105    location: &'static std::panic::Location<'static>,
1106
1107    /// The warning.
1108    warning: W,
1109}
1110
1111impl<W: Warning> Source<W> {
1112    #[track_caller]
1113    /// Create a new `Source` object.
1114    fn new(warning: W) -> Self {
1115        #[cfg(test)]
1116        {
1117            Self {
1118                location: std::panic::Location::caller(),
1119                warning,
1120            }
1121        }
1122
1123        #[expect(
1124            clippy::cfg_not_test,
1125            reason = "This is code that is designed for use in tests"
1126        )]
1127        #[cfg(not(test))]
1128        {
1129            Self { warning }
1130        }
1131    }
1132
1133    /// Discard the debug info and return the inner [`Warning`].
1134    fn into_warning(self) -> W {
1135        self.warning
1136    }
1137
1138    /// Convert the inner [`Warning`] into another type of `Warning`.
1139    fn into_other<WA>(self) -> Source<WA>
1140    where
1141        W: Into<WA>,
1142        WA: Warning,
1143    {
1144        self.map(Into::into)
1145    }
1146
1147    /// Convert the inner [`Warning`] into another type of `Warning`.
1148    fn map<F, WA>(self, mut f: F) -> Source<WA>
1149    where
1150        F: FnMut(W) -> WA,
1151        WA: Warning,
1152    {
1153        #[cfg(test)]
1154        {
1155            let Self {
1156                location: source,
1157                warning,
1158            } = self;
1159            Source {
1160                location: source,
1161                warning: f(warning),
1162            }
1163        }
1164
1165        #[expect(
1166            clippy::cfg_not_test,
1167            reason = "This is code that is designed for use in tests"
1168        )]
1169        #[cfg(not(test))]
1170        {
1171            let Self { warning } = self;
1172            Source {
1173                warning: f(warning),
1174            }
1175        }
1176    }
1177}
1178
1179impl<W: Warning> Deref for Source<W> {
1180    type Target = W;
1181
1182    fn deref(&self) -> &Self::Target {
1183        &self.warning
1184    }
1185}
1186
1187/// A set of [`Warning`]s transported through the system using a `VerdictDeferred` or `CaveatDeferred`.
1188///
1189///
1190/// This set is considered deferred as the [`Warning`]s need to be associated with a [`json::Element`]
1191/// to become [`Warning`]s.
1192///
1193/// NOTE: The deferred types are used to avoid passing [`json::Element`] references
1194/// to functions just to create [`Warning`]s.
1195#[derive(Debug)]
1196pub struct SetDeferred<W: Warning>(Vec<Source<W>>);
1197
1198impl<W: Warning> SetDeferred<W> {
1199    /// Create a new set of [`Warning`]s.
1200    pub(crate) fn new() -> Self {
1201        Self(Vec::new())
1202    }
1203
1204    /// Create and add a [`Warning`] to the set while consuming the set into a [`VerdictDeferred`].
1205    ///
1206    /// This is designed for use as the last [`Warning`] of a function. The function should exit with the `Err` returned.
1207    #[track_caller]
1208    pub(crate) fn bail<T>(self, warning: W) -> VerdictDeferred<T, W> {
1209        let Self(warnings) = self;
1210        Err(ErrorSetDeferred {
1211            error: warning,
1212            warnings,
1213        })
1214    }
1215
1216    /// Add a single warning to the set.
1217    #[track_caller]
1218    pub(crate) fn insert(&mut self, warning: W) {
1219        self.0.push(Source::new(warning));
1220    }
1221
1222    /// Extend this set with the warnings of another.
1223    ///
1224    /// The other set's warnings will be converted if necessary.
1225    fn extend<WA>(&mut self, warnings: SetDeferred<WA>)
1226    where
1227        WA: Into<W> + Warning,
1228    {
1229        let SetDeferred(warnings) = warnings;
1230        self.0.extend(warnings.into_iter().map(Source::into_other));
1231    }
1232}
1233
1234/// A set of [`Warning`]s and a [`Warning`] that caused an operation to fail to be represented as an [`Error`].
1235///
1236/// This set is transported through the system as the error side of a deferred result.
1237///
1238/// This set is considered deferred as the [`Warning`]s need to be associated with a [`json::Element`]
1239/// to become [`Warning`]s.
1240///
1241/// NOTE: The deferred types are used to avoid passing [`json::Element`] references
1242/// to functions just to create [`Warning`]s.
1243#[derive(Debug)]
1244pub struct ErrorSetDeferred<W: Warning> {
1245    /// The [`Warning`] that caused a function to halt.
1246    error: W,
1247
1248    /// The [`Warning`]s collected up to the halting point.
1249    warnings: Vec<Source<W>>,
1250}
1251
1252impl<W: Warning> ErrorSetDeferred<W> {
1253    /// Create a new set of [`Warning`]s.
1254    pub(crate) fn with_warn(warning: W) -> Self {
1255        Self {
1256            warnings: Vec::new(),
1257            error: warning,
1258        }
1259    }
1260
1261    /// Converts `ErrorSetDeferred<W>` into `ErrorSetDeferred<WA>` using the `impl Into<WA> for W`.
1262    ///
1263    /// This is used by the [`from_warning_all`] macro.
1264    pub(crate) fn into_other<WA>(self) -> ErrorSetDeferred<WA>
1265    where
1266        W: Into<WA>,
1267        WA: Warning,
1268    {
1269        let Self { error, warnings } = self;
1270        let warnings = warnings.into_iter().map(Source::into_other).collect();
1271        ErrorSetDeferred {
1272            error: error.into(),
1273            warnings,
1274        }
1275    }
1276}
1277
1278/// A set of [`Warning`]s transported through the system using a [`Caveat`].
1279#[derive(Debug, Default)]
1280pub struct Set<W: Warning>(BTreeMap<json::ElemId, Group<W>>);
1281
1282impl<W: Warning> Set<W> {
1283    /// Create a new set of [`Warning`]s.
1284    pub fn new() -> Self {
1285        Self(BTreeMap::new())
1286    }
1287
1288    /// Insert a [`Warning`] defined in a domain module and it's associated [`json::Element`].
1289    #[track_caller]
1290    pub fn insert(&mut self, element: &json::Element<'_>, warning: W) {
1291        self.insert_warning(element.id(), warning, || Element::from_json(element));
1292    }
1293
1294    /// Insert [`Warning`] defined in a domain module and it's associated [`Element`].
1295    ///
1296    /// Note: The [`Element`] is created lazily.
1297    #[track_caller]
1298    fn insert_warning<F>(&mut self, elem_id: json::ElemId, warning: W, f: F)
1299    where
1300        F: FnOnce() -> Element,
1301    {
1302        use std::collections::btree_map::Entry;
1303
1304        match self.0.entry(elem_id) {
1305            Entry::Vacant(entry) => {
1306                let element = f();
1307                entry.insert_entry(Group {
1308                    element,
1309                    warnings: vec![Source::new(warning)],
1310                });
1311            }
1312            Entry::Occupied(mut entry) => {
1313                entry.get_mut().warnings.push(Source::new(warning));
1314            }
1315        }
1316    }
1317
1318    /// Consume the set and insert a [`Warning`] while returning a [`Verdict`].
1319    ///
1320    /// This is designed for use as the last [`Warning`] of a function. The function should exit with the `Err` returned.
1321    #[track_caller]
1322    pub fn bail<T>(self, element: &json::Element<'_>, warning: W) -> Verdict<T, W> {
1323        let Self(warnings) = self;
1324
1325        Err(ErrorSet {
1326            error: Box::new(Error {
1327                warning,
1328                element: Element::from_json(element),
1329            }),
1330            warnings,
1331        })
1332    }
1333
1334    /// Bail with `warning` located at an [`Element`] taken from the schema IR.
1335    ///
1336    /// [`bail`](Self::bail) needs a [`json::Element`], which an absent or unbuildable IR
1337    /// field does not have; [`Integrity::Missing`]/[`Integrity::Err`] carry this flat
1338    /// [`Element`] instead. Use this where the feature has its own reason to report and
1339    /// [`ok_or_bail`](Self::ok_or_bail)'s content-free [`Rejected`] would lose it.
1340    #[track_caller]
1341    pub(crate) fn bail_at<T>(self, element: Element, warning: W) -> Verdict<T, W> {
1342        let Self(warnings) = self;
1343
1344        Err(ErrorSet {
1345            error: Box::new(Error { warning, element }),
1346            warnings,
1347        })
1348    }
1349
1350    /// Borrow the built value of a required schema-IR field, or reject the object.
1351    ///
1352    /// Used by `FromSchema` lowering: an [`Integrity::Ok`] field yields a borrow of its
1353    /// value; a [`Integrity::Missing`]/[`Integrity::Err`] field cannot be built, so the set
1354    /// bails with the [`Rejected`] marker anchored to the field's element.
1355    ///
1356    /// The precise cause was already reported by the schema walk, so no
1357    /// new detail is added here - the marker only signals "this feature rejected the IR for
1358    /// this object" and is easily filtered (see [`Warning::is_rejected`]).
1359    #[track_caller]
1360    pub(crate) fn ok_or_bail<'a, T>(
1361        &mut self,
1362        integrity: &'a Integrity<T>,
1363    ) -> Result<&'a T, ErrorSet<W>>
1364    where
1365        W: From<Rejected>,
1366    {
1367        let element = match integrity {
1368            Integrity::Ok(value) => return Ok(value),
1369            Integrity::Missing(element) | Integrity::Err(element) => element.clone(),
1370        };
1371
1372        let warnings = std::mem::take(&mut self.0);
1373
1374        Err(ErrorSet {
1375            error: Box::new(Error {
1376                warning: Rejected.into(),
1377                element,
1378            }),
1379            warnings,
1380        })
1381    }
1382
1383    /// Remove every [`Rejected`] marker from the set (see [`Warning::is_rejected`]).
1384    ///
1385    /// The schema walk already reported the located structural cause, so a consumer that has
1386    /// those warnings can drop these follow-on markers.
1387    pub fn remove_rejected(&mut self) {
1388        self.retain(|warning| !warning.is_rejected());
1389    }
1390
1391    /// Retain only the [`Warning`]s for which `keep` returns `true`.
1392    ///
1393    /// Any [`Group`] left without warnings is removed from the set.
1394    pub fn retain<F>(&mut self, mut keep: F)
1395    where
1396        F: FnMut(&W) -> bool,
1397    {
1398        self.0.retain(|_elem_id, group| {
1399            group.warnings.retain(|source| keep(&source.warning));
1400            !group.warnings.is_empty()
1401        });
1402    }
1403
1404    /// Return true if the [`Warning`] set is empty.
1405    pub fn is_empty(&self) -> bool {
1406        self.0.is_empty()
1407    }
1408
1409    /// Return an iterator over every [`Warning`] in the set, each paired with the
1410    /// [`Element`] it was reported against.
1411    ///
1412    /// This is [`Set::iter`] with each [`Group`] flattened into its warnings.
1413    /// The warnings come in document order of their elements,
1414    /// and in the order they were inserted for one element.
1415    /// A predicate on one warning goes straight into `filter` or `find`:
1416    ///
1417    /// ```
1418    /// # use ocpi_tariffs::{price, warning};
1419    /// fn paths_outside_cdr(warnings: &warning::Set<price::Warning>) -> Vec<&str> {
1420    ///     warnings
1421    ///         .iter_warnings()
1422    ///         .filter(|(_element, warning)| {
1423    ///             matches!(warning, price::Warning::PeriodsOutsideStartEndDateTime { .. })
1424    ///         })
1425    ///         .map(|(element, _warning)| element.path.as_str())
1426    ///         .collect()
1427    /// }
1428    /// ```
1429    pub fn iter_warnings(&self) -> impl Iterator<Item = (&Element, &W)> {
1430        self.iter().flat_map(|group| {
1431            group
1432                .warnings
1433                .iter()
1434                .map(|source| (&group.element, &source.warning))
1435        })
1436    }
1437
1438    /// Return true if any [`Warning`] in the set makes `predicate` return `true`.
1439    ///
1440    /// A warning can hold fields, so whether two warnings are the same depends on which
1441    /// fields a caller cares about. The predicate leaves that choice to the caller,
1442    /// who usually looks for a variant with `matches!`:
1443    ///
1444    /// ```
1445    /// # use ocpi_tariffs::{price, warning};
1446    /// fn periods_state_no_time(warnings: &warning::Set<price::Warning>) -> bool {
1447    ///     warnings.contains(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))
1448    /// }
1449    /// ```
1450    pub fn contains<F>(&self, predicate: F) -> bool
1451    where
1452        F: FnMut(&W) -> bool,
1453    {
1454        self.find(predicate).is_some()
1455    }
1456
1457    /// Return the first [`Warning`] in the set that makes `predicate` return `true`,
1458    /// paired with the [`Element`] it was reported against.
1459    ///
1460    /// "First" means first in the order [`Set::iter_warnings`] yields.
1461    /// The [`Element`] tells a caller where in the document the warning sits:
1462    ///
1463    /// ```
1464    /// # use ocpi_tariffs::{price, warning};
1465    /// fn path_of_periods_state_no_time(warnings: &warning::Set<price::Warning>) -> Option<&str> {
1466    ///     let (element, _warning) =
1467    ///         warnings.find(|warning| matches!(warning, price::Warning::PeriodsStateNoTime))?;
1468    ///     Some(element.path.as_str())
1469    /// }
1470    /// ```
1471    pub fn find<F>(&self, mut predicate: F) -> Option<(&Element, &W)>
1472    where
1473        F: FnMut(&W) -> bool,
1474    {
1475        self.iter_warnings()
1476            .find(|(_element, warning)| predicate(warning))
1477    }
1478
1479    /// Return every distinct [`Id`] of the [`Warning`]s in the set.
1480    ///
1481    /// A caller can compare the returned IDs with a list of the IDs it accepts,
1482    /// rather than matching on the variants of each warning.
1483    ///
1484    /// Some IDs include a value from the warning, such as the field name in
1485    /// `missing_field(country_code)`. Two warnings of one variant can then give two IDs.
1486    pub fn ids(&self) -> BTreeSet<Id> {
1487        self.iter_warnings()
1488            .map(|(_element, warning)| warning.id())
1489            .collect()
1490    }
1491
1492    /// Return an iterator over the [`Warning`]s reported against the element at `path`,
1493    /// such as `$.charging_periods`.
1494    ///
1495    /// Duplicate JSON keys give several elements the same path.
1496    /// The iterator yields the warnings of every one of them, in document order,
1497    /// where [`Set::path_map`] would keep only the last.
1498    pub fn warnings_at<'set>(&'set self, path: &str) -> impl Iterator<Item = &'set W> {
1499        self.iter_warnings()
1500            .filter(move |(element, _warning)| element.path.as_str() == path)
1501            .map(|(_element, warning)| warning)
1502    }
1503
1504    /// Return the amount of [`Element`]s in this set.
1505    ///
1506    /// Each [`Element`] can have many [`Warning`]s associated with it.
1507    pub fn len_elements(&self) -> usize {
1508        self.0.len()
1509    }
1510
1511    /// Return the total amount of [`Warning`]s in this set for all [`Element`]s.
1512    pub fn len_warnings(&self) -> usize {
1513        self.0
1514            .values()
1515            .fold(0, |acc, group| acc.saturating_add(group.warnings.len()))
1516    }
1517
1518    /// Return an iterator of [`Warning`]s grouped by [`json::Element`].
1519    pub fn iter(&self) -> Iter<'_, W> {
1520        Iter {
1521            warnings: self.0.iter(),
1522        }
1523    }
1524
1525    /// Return a collection of `Id`s mapped to the paths they occurred at.
1526    pub fn id_path_map(&self, config: Limit) -> IdPathMap<'_> {
1527        let report = match config {
1528            Limit::None => limit_none(&self.0),
1529            Limit::WarningTypes(max_warning_types) => {
1530                limit_warning_types(max_warning_types, &self.0)
1531            }
1532            Limit::ElemPathsPerId(max_elem_paths_per_warning_id) => {
1533                limit_elem_paths_per_id(max_elem_paths_per_warning_id, &self.0)
1534            }
1535            Limit::All {
1536                max_warning_types,
1537                max_elem_paths_per_warning_id,
1538            } => limit_all(max_warning_types, max_elem_paths_per_warning_id, &self.0),
1539        };
1540
1541        let LimitReport {
1542            elements_filtered,
1543            warning_distinct_types_filtered,
1544            warnings,
1545        } = report;
1546
1547        IdPathMap {
1548            total_warnings: self.len_warnings(),
1549            total_elements: self.len_elements(),
1550            elements_filtered,
1551            warning_distinct_types_filtered,
1552            warnings,
1553        }
1554    }
1555
1556    /// Return a collection of warning messages mapped to the paths they occurred at.
1557    pub fn msg_path_map(&self, config: Limit) -> MsgPathMap<'_> {
1558        let IdPathMap {
1559            total_warnings,
1560            total_elements,
1561            elements_filtered,
1562            warning_distinct_types_filtered,
1563            warnings,
1564        } = self.id_path_map(config);
1565
1566        let warnings = warnings
1567            .into_iter()
1568            .map(|(id, paths)| (id.to_string(), paths))
1569            .collect();
1570
1571        MsgPathMap {
1572            total_warnings,
1573            total_elements,
1574            elements_filtered,
1575            warning_distinct_types_filtered,
1576            warnings,
1577        }
1578    }
1579
1580    /// Return a map of [`json::Element`] paths to a list of [`Warning`].
1581    ///
1582    /// This is designed to be used to print out maps of warnings associated with elements.
1583    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
1584    /// with indentation.
1585    ///
1586    /// # A path does not identify an element
1587    ///
1588    /// The set is keyed by [`json::ElemId`], this map is keyed by path. Duplicate JSON keys are
1589    /// legal, and every occurrence of one has the same path, so several elements can compete for
1590    /// a single entry. The entries are built in `ElemId` order and collected, so **the last
1591    /// occurrence in the document wins and the earlier ones' warnings are absent from the map**.
1592    ///
1593    /// Nothing is lost from the set itself, so a caller that iterates groups - as
1594    /// `cli::print::warning_set` does - still sees every warning. Reach for [`Set::iter`] rather
1595    /// than this map when a warning may be reported against more than one occurrence of a field;
1596    /// [`Warning::DuplicateField`](crate::schema::Warning::DuplicateField) is the case that
1597    /// makes this reachable in practice.
1598    pub fn path_map(&self) -> BTreeMap<&str, Vec<&W>> {
1599        self.0
1600            .values()
1601            .map(|Group { element, warnings }| {
1602                let path = element.path.as_str();
1603                let warnings = warnings.iter().map(|w| &**w).collect();
1604                (path, warnings)
1605            })
1606            .collect()
1607    }
1608
1609    /// Consume the `Set` and return a map of [`json::Element`] paths to a list of [`Warning`]s.
1610    ///
1611    /// This is designed to be used to print out maps of warnings associated with elements.
1612    pub fn into_path_map(self) -> BTreeMap<json::Path, Vec<W>> {
1613        self.0
1614            .into_values()
1615            .map(|Group { element, warnings }| {
1616                let warnings = warnings.into_iter().map(Source::into_warning).collect();
1617                (element.path, warnings)
1618            })
1619            .collect()
1620    }
1621
1622    /// Return a map of [`json::Element`] paths to a list of [`Warning`] ids as Strings.
1623    ///
1624    /// This is designed to be used to print out maps of warnings associated with elements.
1625    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
1626    /// with indentation.
1627    ///
1628    /// Note: This representation is also valid JSON and can be copied directly to
1629    /// a test expectation file.
1630    pub fn path_id_map(&self) -> BTreeMap<&str, Vec<Id>> {
1631        self.0
1632            .values()
1633            .map(|group| {
1634                let warnings = group.warnings.iter().map(|w| w.id()).collect();
1635                (group.element.path.as_str(), warnings)
1636            })
1637            .collect()
1638    }
1639
1640    /// Return a map of [`json::Element`] paths to a list of [`Warning`] messages as Strings.
1641    ///
1642    /// This is designed to be used to print out maps of warnings associated with elements.
1643    /// You can use the debug alternate format `{:#?}` to print the map 'pretty' over multiple lines
1644    /// with indentation.
1645    pub fn path_msg_map(&self) -> BTreeMap<&str, Vec<String>> {
1646        self.0
1647            .values()
1648            .map(|group| {
1649                let warnings = group.warnings.iter().map(|w| w.to_string()).collect();
1650                (group.element.path.as_str(), warnings)
1651            })
1652            .collect()
1653    }
1654
1655    /// De-escalate an [`Error`] by subsuming it back into a `Set`.
1656    pub(crate) fn deescalate_error(&mut self, err_set: ErrorSet<W>) {
1657        let ErrorSet { error, warnings } = err_set;
1658        let Error { warning, element } = *error;
1659        self.0.extend(warnings);
1660        self.insert_warning(element.id, warning, || element);
1661    }
1662
1663    /// Extend this set with the warnings of another.
1664    ///
1665    /// The other set's warnings will be converted if necessary.
1666    pub(crate) fn extend(&mut self, warnings: impl Iterator<Item = (json::ElemId, Group<W>)>) {
1667        use std::collections::btree_map::Entry;
1668
1669        for (elem_id, group) in warnings {
1670            match self.0.entry(elem_id) {
1671                Entry::Vacant(entry) => {
1672                    entry.insert_entry(group);
1673                }
1674                Entry::Occupied(mut entry) => {
1675                    let Group {
1676                        element: _,
1677                        warnings,
1678                    } = group;
1679                    entry.get_mut().warnings.extend(warnings);
1680                }
1681            }
1682        }
1683    }
1684}
1685
1686/// The outcome of calling the `limit_*` functions related to the [`Set::id_path_map`] function.
1687#[derive(Debug)]
1688struct LimitReport<'set> {
1689    /// The amount of [`json::Element`] paths filtered due to a [`Limit`] being set.
1690    pub elements_filtered: usize,
1691
1692    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
1693    ///
1694    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
1695    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
1696    /// this counts as one type, as all the IDs that were filtered are the same.
1697    pub warning_distinct_types_filtered: usize,
1698
1699    /// The map of all [`Warning`] [`Id`]s mapped to the [`json::Element`] paths where they occurred.
1700    pub warnings: BTreeMap<Id, Vec<&'set str>>,
1701}
1702
1703/// The logic for the [`Limit::None`] variant.
1704fn limit_none<W: Warning>(warnings: &BTreeMap<json::ElemId, Group<W>>) -> LimitReport<'_> {
1705    let mut out = BTreeMap::new();
1706
1707    for group in warnings.values() {
1708        let Group { element, warnings } = group;
1709        let path = element.path.as_str();
1710
1711        for w in warnings {
1712            match out.entry(w.id()) {
1713                btree_map::Entry::Vacant(entry) => {
1714                    entry.insert(vec![path]);
1715                }
1716                btree_map::Entry::Occupied(mut entry) => {
1717                    entry.get_mut().push(path);
1718                }
1719            }
1720        }
1721    }
1722
1723    LimitReport {
1724        warnings: out,
1725        elements_filtered: 0,
1726        warning_distinct_types_filtered: 0,
1727    }
1728}
1729
1730/// The logic for the [`Limit::WarningTypes`] variant.
1731fn limit_warning_types<W: Warning>(
1732    max_warning_types: usize,
1733    warnings: &BTreeMap<json::ElemId, Group<W>>,
1734) -> LimitReport<'_> {
1735    let mut out = BTreeMap::new();
1736    // A set of element paths encountered and filtered. Element paths can be encountered more
1737    // than once, so a simple `usize` can't be used to count the encounters.
1738    let mut elements_filtered = HashSet::new();
1739    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
1740    // so a simple `usize` can't be used to count the encounters.
1741    let mut warning_distinct_types_filtered = HashSet::new();
1742
1743    for group in warnings.values() {
1744        let Group { element, warnings } = group;
1745        let path = element.path.as_str();
1746        // True if any of the warnings are filtered,
1747        // therefore this element should be considered filtered too.
1748        let mut filtered = false;
1749
1750        for w in warnings {
1751            let len = out.len();
1752            let id = w.id();
1753
1754            match out.entry(id.clone()) {
1755                btree_map::Entry::Vacant(entry) => {
1756                    if len < max_warning_types {
1757                        entry.insert(vec![path]);
1758                    } else {
1759                        warning_distinct_types_filtered.insert(id);
1760                        filtered = true;
1761                    }
1762                }
1763                btree_map::Entry::Occupied(mut entry) => {
1764                    entry.get_mut().push(path);
1765                }
1766            }
1767        }
1768
1769        if filtered {
1770            elements_filtered.insert(path);
1771        }
1772    }
1773
1774    LimitReport {
1775        warnings: out,
1776        elements_filtered: elements_filtered.len(),
1777        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
1778    }
1779}
1780
1781/// The logic for the [`Limit::ElemPathsPerId`] variant.
1782fn limit_elem_paths_per_id<W: Warning>(
1783    max_elem_paths_per_warning_id: usize,
1784    warnings: &BTreeMap<json::ElemId, Group<W>>,
1785) -> LimitReport<'_> {
1786    let mut out = BTreeMap::new();
1787    // A set of element paths encountered and filtered. Element paths can be encountered more
1788    // than once, so a simple `usize` can't be used to count the encounters.
1789    let mut elements_filtered = HashSet::new();
1790
1791    if max_elem_paths_per_warning_id == 0 {
1792        for group in warnings.values() {
1793            let Group { element, warnings } = group;
1794
1795            for w in warnings {
1796                if let btree_map::Entry::Vacant(entry) = out.entry(w.id()) {
1797                    entry.insert(vec![]);
1798                }
1799            }
1800            elements_filtered.insert(element.path.as_str());
1801        }
1802    } else {
1803        for group in warnings.values() {
1804            let Group { element, warnings } = group;
1805            let path = element.path.as_str();
1806
1807            for w in warnings {
1808                let id = w.id();
1809
1810                match out.entry(id.clone()) {
1811                    btree_map::Entry::Vacant(entry) => {
1812                        entry.insert(vec![path]);
1813                    }
1814                    btree_map::Entry::Occupied(mut entry) => {
1815                        if entry.get().len() < max_elem_paths_per_warning_id {
1816                            entry.get_mut().push(path);
1817                        } else {
1818                            elements_filtered.insert(path);
1819                        }
1820                    }
1821                }
1822            }
1823        }
1824    }
1825
1826    LimitReport {
1827        warnings: out,
1828        elements_filtered: elements_filtered.len(),
1829        warning_distinct_types_filtered: 0,
1830    }
1831}
1832
1833/// The logic for the [`Limit::All`] variant.
1834fn limit_all<W: Warning>(
1835    max_warning_types: usize,
1836    max_elem_paths_per_warning_id: usize,
1837    warnings: &BTreeMap<json::ElemId, Group<W>>,
1838) -> LimitReport<'_> {
1839    let mut out = BTreeMap::new();
1840    // A set of element paths encountered and filtered. Element paths can be encountered more
1841    // than once, so a simple `usize` can't be used to count the encounters.
1842    let mut elements_filtered = HashSet::new();
1843    // A set of warnings encountered and filtered. Warnings can be encountered more than once,
1844    // so a simple `usize` can't be used to count the encounters.
1845    let mut warning_distinct_types_filtered = HashSet::new();
1846
1847    if max_warning_types > 0 && max_elem_paths_per_warning_id == 0 {
1848        for group in warnings.values() {
1849            let Group { element, warnings } = group;
1850            let path = element.path.as_str();
1851
1852            for w in warnings {
1853                let len = out.len();
1854                let id = w.id();
1855
1856                if let btree_map::Entry::Vacant(entry) = out.entry(id.clone()) {
1857                    if len < max_warning_types {
1858                        entry.insert(vec![]);
1859                    } else {
1860                        warning_distinct_types_filtered.insert(id);
1861                    }
1862                }
1863            }
1864
1865            elements_filtered.insert(path);
1866        }
1867    } else {
1868        for group in warnings.values() {
1869            let Group { element, warnings } = group;
1870            let path = element.path.as_str();
1871
1872            for w in warnings {
1873                let len = out.len();
1874                let id = w.id();
1875
1876                match out.entry(id.clone()) {
1877                    btree_map::Entry::Vacant(entry) => {
1878                        if len < max_warning_types {
1879                            entry.insert(vec![path]);
1880                        } else {
1881                            warning_distinct_types_filtered.insert(id);
1882                            elements_filtered.insert(path);
1883                        }
1884                    }
1885                    btree_map::Entry::Occupied(mut entry) => {
1886                        if entry.get().len() < max_elem_paths_per_warning_id {
1887                            entry.get_mut().push(path);
1888                        } else {
1889                            elements_filtered.insert(path);
1890                        }
1891                    }
1892                }
1893            }
1894        }
1895    }
1896
1897    LimitReport {
1898        warnings: out,
1899        elements_filtered: elements_filtered.len(),
1900        warning_distinct_types_filtered: warning_distinct_types_filtered.len(),
1901    }
1902}
1903
1904/// The outcome of calling the [`Set::id_path_map`] function.
1905#[derive(Debug)]
1906pub struct IdPathMap<'set> {
1907    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
1908    pub total_warnings: usize,
1909
1910    /// The total amount of [`json::Element`] paths in the source [`Set`].
1911    pub total_elements: usize,
1912
1913    /// The amount of [`json::Element`] paths filtered due to a [`Limit`] being set.
1914    pub elements_filtered: usize,
1915
1916    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
1917    ///
1918    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
1919    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
1920    /// this counts as one type, as all the IDs that were filtered are the same.
1921    pub warning_distinct_types_filtered: usize,
1922
1923    /// The map of all [`Warning`] [`Id`]s mapped to the [`json::Element`] paths where they occurred.
1924    pub warnings: BTreeMap<Id, Vec<&'set str>>,
1925}
1926
1927/// The outcome of calling the [`Set::msg_path_map`] function.
1928#[derive(Debug)]
1929pub struct MsgPathMap<'set> {
1930    /// The total amount of [`Warning`]s [`Id`]s in the source [`Set`].
1931    pub total_warnings: usize,
1932
1933    /// The total amount of [`json::Element`] paths in the source [`Set`].
1934    pub total_elements: usize,
1935
1936    /// The amount of [`json::Element`] paths filtered due to a [`Limit`] being set.
1937    pub elements_filtered: usize,
1938
1939    /// The amount of [`Warning`] [`Id`]s filtered due to a [`Limit`] being set.
1940    ///
1941    /// Note: This is not a count of how many warnings were filtered. It's a count of how many
1942    /// types of warnings were filtered. If seven `excessive_precision` warnings are filtered,
1943    /// this counts as one type, as all the IDs that were filtered are the same.
1944    pub warning_distinct_types_filtered: usize,
1945
1946    /// The map of all [`Warning`] [`Id`]s mapped to the [`json::Element`] paths where they occurred.
1947    pub warnings: BTreeMap<String, Vec<&'set str>>,
1948}
1949
1950/// The limiting configuration of the [`Set::path_id_map`] function.
1951#[derive(Copy, Clone, Debug)]
1952pub enum Limit {
1953    /// Don't enforce any limits on [`Warning`] [`Id`]s or [`json::Element`] [`json::Path`]s.
1954    None,
1955
1956    /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
1957    WarningTypes(usize),
1958
1959    /// Forbid more than this amount of [`json::Element`] [`json::Path`]s to be inserted into the list for each [`Id`].
1960    ElemPathsPerId(usize),
1961
1962    /// Enforce both limits at once.
1963    All {
1964        /// Forbid more than this amount of [`Warning`] [`Id`]s to be inserted into the map.
1965        max_warning_types: usize,
1966
1967        /// Forbid more than this amount of [`json::Element`] [`json::Path`]s to be inserted into the list for each [`Id`].
1968        max_elem_paths_per_warning_id: usize,
1969    },
1970}
1971
1972/// A set of [`Warning`]s and a [`Warning`] that caused an operation to fail to be represented as an [`Error`].
1973///
1974/// This set is transported through the system using a [`Verdict`]s `Err` variant.
1975#[derive(Debug)]
1976pub struct ErrorSet<W: Warning> {
1977    /// The warning that caused an operation to fail.
1978    ///
1979    /// The warning is converted to an [`Error`] so it's ready to take part in Rust's error system.
1980    error: Box<Error<W>>,
1981
1982    /// The warnings accumulated up until the failure moment.
1983    ///
1984    /// This list does not included the warning that caused the operation to fail.
1985    warnings: BTreeMap<json::ElemId, Group<W>>,
1986}
1987
1988impl<W> ErrorSet<W>
1989where
1990    W: Warning,
1991{
1992    /// Consume the [`ErrorSet`] and return the [`Error`] and warnings as a `Set`.
1993    pub fn into_parts(self) -> (Error<W>, Set<W>) {
1994        let Self { error, warnings } = self;
1995        (*error, Set(warnings))
1996    }
1997
1998    /// Converts `ErrorSet<W>` into `ErrorSet<WA>` using the `impl Into<WA> for K`.
1999    ///
2000    /// This is used by the [`from_warning_all`] macro.
2001    pub(crate) fn into_other<WA>(self) -> ErrorSet<WA>
2002    where
2003        W: Into<WA>,
2004        WA: Warning,
2005    {
2006        let Self { error, warnings } = self;
2007        let warnings = warnings
2008            .into_iter()
2009            .map(|(elem_id, group)| (elem_id, group.into_other()))
2010            .collect();
2011        ErrorSet {
2012            error: Box::new(Error::into_other(*error)),
2013            warnings,
2014        }
2015    }
2016}
2017
2018/// A group of warning `Warning`s associated with an `Element`.
2019///
2020/// This group is emitted from the `IntoGroupByElem` iterator.
2021/// The warning `Warning`s are owned and so can be moved to another location.
2022#[derive(Debug)]
2023pub struct Group<W: Warning> {
2024    /// The [`json::Element`] that has [`Warning`]s.
2025    element: Element,
2026
2027    /// The list of warnings for the [`json::Element`].
2028    warnings: Vec<Source<W>>,
2029}
2030
2031impl<W> Group<W>
2032where
2033    W: Warning,
2034{
2035    /// Consume the `Group` and return the constituent parts.
2036    pub fn into_parts(self) -> (Element, Vec<W>) {
2037        let Self { element, warnings } = self;
2038        let warnings = warnings.into_iter().map(Source::into_warning).collect();
2039        (element, warnings)
2040    }
2041
2042    /// Borrow the element and its [`Warning`]s.
2043    pub fn to_parts(&self) -> (&Element, Vec<&W>) {
2044        let Self { element, warnings } = self;
2045        let warnings = warnings.iter().map(|w| &**w).collect();
2046        (element, warnings)
2047    }
2048
2049    /// Borrow just the [`Warning`]s, without the element.
2050    pub fn warnings(&self) -> Vec<&W> {
2051        self.warnings.iter().map(|w| &**w).collect()
2052    }
2053
2054    /// Consume the group and return just the [`Warning`]s, discarding the element.
2055    pub fn into_warnings(self) -> Vec<W> {
2056        let Self {
2057            element: _,
2058            warnings,
2059        } = self;
2060        warnings.into_iter().map(Source::into_warning).collect()
2061    }
2062
2063    /// Converts `IntoGroup<W>` into `IntoGroup<WA>` using the `impl Into<WA> for K`.
2064    ///
2065    /// This is used by the [`from_warning_all`] macro.
2066    fn into_other<WA>(self) -> Group<WA>
2067    where
2068        W: Into<WA>,
2069        WA: Warning,
2070    {
2071        let Self { element, warnings } = self;
2072        let warnings = warnings.into_iter().map(Source::into_other).collect();
2073        Group { element, warnings }
2074    }
2075}
2076
2077/// An iterator of borrowed [`Warning`]s grouped by [`json::Element`].
2078pub struct Iter<'caller, W>
2079where
2080    W: Warning,
2081{
2082    /// The iterator over every [`Warning`].
2083    warnings: btree_map::Iter<'caller, json::ElemId, Group<W>>,
2084}
2085
2086impl<W> Iter<'_, W> where W: Warning {}
2087
2088impl<'caller, W: Warning> Iterator for Iter<'caller, W> {
2089    type Item = &'caller Group<W>;
2090
2091    fn next(&mut self) -> Option<Self::Item> {
2092        let (_elem_id, group) = self.warnings.next()?;
2093        Some(group)
2094    }
2095}
2096
2097/// An iterator of borrowed [`Warning`]s grouped by [`json::Element`].
2098pub struct IntoIter<W>
2099where
2100    W: Warning,
2101{
2102    /// The iterator over every [`Warning`].
2103    warnings: btree_map::IntoIter<json::ElemId, Group<W>>,
2104}
2105
2106impl<W: Warning> Iterator for IntoIter<W> {
2107    type Item = Group<W>;
2108
2109    fn next(&mut self) -> Option<Self::Item> {
2110        let (_elem_id, group) = self.warnings.next()?;
2111        Some(group)
2112    }
2113}
2114
2115impl<W: Warning> IntoIterator for Set<W> {
2116    type Item = Group<W>;
2117    type IntoIter = IntoIter<W>;
2118
2119    fn into_iter(self) -> Self::IntoIter {
2120        let Set(warnings) = self;
2121        IntoIter {
2122            warnings: warnings.into_iter(),
2123        }
2124    }
2125}
2126
2127impl<'a, W: Warning> IntoIterator for &'a Set<W> {
2128    type Item = &'a Group<W>;
2129    type IntoIter = Iter<'a, W>;
2130
2131    fn into_iter(self) -> Self::IntoIter {
2132        self.iter()
2133    }
2134}