ocpi-tariffs 0.55.0

OCPI tariff calculations
Documentation
//! Gathering the warnings a function raises into a set its caller passes down.
//!
//! A function that raises warnings takes a `&mut dyn Gather<W>`, where `W` is its own module's
//! [`Warning`] type. The root of the chain is a [`Gatherer`], which a public entry point creates
//! and turns into the [`Caveat`] or [`Failure`] it returns.
//!
//! A function that calls a function of another module converts what comes back in two ways. It
//! hands the callee a [`Converting`] view, which converts each warning to `W`, and it converts
//! the [`Error`] the callee may return with [`Error::into_other`].
//! [`FromSchema::from_schema`](crate::schema::FromSchema::from_schema) does both for a
//! lowering, so a caller hands a lowering its own gatherer.
//!
//! A function that fails returns only the [`Error`] that stopped it. Every warning it raised
//! before the failure is already in the caller's gatherer.

use std::collections::{BTreeMap, btree_map::Entry};

use crate::{json, schema::Integrity};

use super::{Caveat, Element, Error, Failure, Group, Rejected, Set, Source, Verdict, Warning};

/// Gathers the warnings a function raises, each reported against a JSON element.
///
/// A function takes its gatherer as `&mut dyn Gather<W>`, so the function is compiled once,
/// whatever warning type its caller gathers.
pub(crate) trait Gather<W: Warning> {
    /// Add `warning`, reported against the element with the id `elem_id`.
    ///
    /// The gatherer calls `element` only for the first warning on an element, because building
    /// an [`Element`] allocates its path.
    #[track_caller]
    fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element);

    /// Add `warning`, reported against `element`.
    #[track_caller]
    fn insert(&mut self, element: &json::Element<'_>, warning: W) {
        self.insert_lazy(element.id(), warning, &|| Element::from_json(element));
    }

    /// Demote `error` to an ordinary warning.
    ///
    /// An [`Error`] is the warning that stopped a function from building its value. A caller
    /// that can do without that value de-escalates the error, which keeps the warning and ends
    /// the failure at that caller.
    #[track_caller]
    fn deescalate(&mut self, error: Error<W>) {
        let Error { warning, element } = error;
        self.insert_lazy(element.id, warning, &|| element.clone());
    }
}

impl<W: Warning> dyn Gather<W> + '_ {
    /// Borrow the built value of a required schema-IR field, or reject the object.
    ///
    /// The schema walk has already reported why the field could not be built, so the
    /// [`Rejected`] marker adds no detail of its own.
    #[expect(
        clippy::unused_self,
        reason = "the receiver only supplies the warning type"
    )]
    pub(crate) fn ok_or_reject<'a, T>(&self, integrity: &'a Integrity<T>) -> Result<&'a T, Error<W>>
    where
        W: From<Rejected>,
    {
        match integrity {
            Integrity::Ok(value) => Ok(value),
            Integrity::Missing(element) | Integrity::Err(element) => Err(Error {
                warning: Rejected.into(),
                element: element.clone(),
            }),
        }
    }
}

/// The warnings gathered by a call to a function that takes a `&mut dyn Gather<W>`, and
/// by every such function it calls in turn.
///
/// A function that returns a [`Verdict`] creates one and passes it down. Then
/// [`Gatherer::into_verdict`] turns it into that [`Verdict`].
#[derive(Debug)]
pub(crate) struct Gatherer<W: Warning>(BTreeMap<json::ElemId, Group<W>>);

impl<W: Warning> Gatherer<W> {
    pub(crate) fn new() -> Self {
        Self(BTreeMap::new())
    }

    /// Combine the outcome of the function this gatherer was passed to with the
    /// warnings it gathered, into a [`Verdict`].
    ///
    /// On failure, every warning gathered before the failure goes into the [`Failure`], so a
    /// caller can see what else was wrong with the input.
    pub(crate) fn into_verdict<T>(self, outcome: Result<T, Error<W>>) -> Verdict<T, W> {
        let Self(warnings) = self;

        match outcome {
            Ok(value) => Ok(Caveat::new(value, Set(warnings))),
            Err(error) => Err(Failure {
                error: Box::new(error),
                warnings: Set(warnings),
            }),
        }
    }

    /// Turn the gathered warnings into a [`Set`], for a function that can't fail and so
    /// returns no [`Verdict`].
    pub(crate) fn into_set(self) -> Set<W> {
        let Self(warnings) = self;
        Set(warnings)
    }
}

impl<W: Warning> Gather<W> for Gatherer<W> {
    #[track_caller]
    fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element) {
        match self.0.entry(elem_id) {
            Entry::Vacant(entry) => {
                entry.insert_entry(Group {
                    element: element(),
                    warnings: vec![Source::new(warning)],
                });
            }
            Entry::Occupied(mut entry) => {
                entry.get_mut().warnings.push(Source::new(warning));
            }
        }
    }
}

/// A view of a gatherer of `WA` warnings. The view converts each `W` warning it is given
/// to `WA` and adds it to that gatherer.
///
/// A caller hands this down when it calls into a module with another warning type.
pub(crate) struct Converting<'p, WA: Warning>(&'p mut dyn Gather<WA>);

impl<'p, WA: Warning> Converting<'p, WA> {
    pub(crate) fn new(parent: &'p mut dyn Gather<WA>) -> Self {
        Self(parent)
    }
}

impl<W, WA> Gather<W> for Converting<'_, WA>
where
    W: Warning + Into<WA>,
    WA: Warning,
{
    #[track_caller]
    fn insert_lazy(&mut self, elem_id: json::ElemId, warning: W, element: &dyn Fn() -> Element) {
        self.0.insert_lazy(elem_id, warning.into(), element);
    }
}