ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
//! Resolving a tariff's fixable warnings, repeating until a pass proposes no edit the caller
//! allows.
//!
//! One pass cannot resolve everything, because a fix can be what raises the next warning, or
//! what allows the next fix to be proposed at all:
//!
//! - An `IncorrectCase` day rewrites to the spec's spelling, and only then can
//!   [`lint::tariff::Warning::DayOfWeekUnsorted`] be fixed: the sort is incorrect while any day
//!   is miscased, since it would re-case the surviving days as well as reorder them.
//! - Removing the last restriction from a `restrictions` object leaves an object that restricts
//!   nothing, which the linter reports on the next walk.
//! - A time bound covering the whole day is two fields, and removing one with a warning raises
//!   the same warning on the other.
//!
//! Each pass is therefore a whole walk: parse the source, build the tariff, lint it, and turn
//! both warning sets into [`fix::Edit`]s. [`fix::apply`] resolves each pass's edits against one
//! another, so the passes exist for edits that could not have been proposed together, not to
//! apply known edits one at a time.
//!
//! Use [`tariff::fix`](crate::tariff::fix) to fix a tariff.

#[cfg(test)]
mod test_passes;

use crate::{Versioned as _, fix, json, lint, schema, string, warning};

/// The most passes made over one document before we decide to stop trying to fix issues.
///
/// A document that is still proposing edits after this many passes is a bug in a [`fix::Fixable`]
/// implementation, not a document that needs more passes. The fixes that need a second pass need
/// one more, and no fix proposes an edit for a fault it has already resolved. This bound prevents
/// any infinite or overly long spinning through the lint/fix loop.
const MAX_PASSES: usize = 8;

/// Resolve the fixable warnings of `tariff`, repeating until a pass proposes no edit that
/// `options` allows.
///
/// Both the schema warnings and the lint warnings are fixed. The schema warnings are recomputed
/// rather than taken from the caller, so that every pass reads the document it is about to edit.
///
/// The version is the one the `tariff` was built against and every pass reuses it, rather than
/// inferring a version per pass. An inference reads the fields that are present, and removing a
/// field is one of the edits, so re-inferring would let a fix carry the document into another
/// OCPI version.
pub(crate) fn tariff(
    tariff: &crate::tariff::Versioned<'_>,
    options: Options,
) -> Result<Fixed, fix::Error> {
    fix_until_no_edits(tariff.as_json_str(), tariff.version(), options, MAX_PASSES)
}

/// Which fixes [`tariff::fix`](crate::tariff::fix) applies.
///
/// The default keeps unexpected fields and applies only the edits whose meaning is
/// [`fix::Meaning::Preserves`], which leave the document meaning the same under OCPI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Options {
    unexpected: UnexpectedFields,
    changes: Changes,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            unexpected: UnexpectedFields::Keep,
            changes: Changes::HoldBack,
        }
    }
}

impl Options {
    /// Set whether fixing removes unexpected fields.
    #[must_use]
    pub fn unexpected_fields(mut self, unexpected: UnexpectedFields) -> Self {
        self.unexpected = unexpected;
        self
    }

    /// Apply the edits whose meaning is [`fix::Meaning::Changes`], as well as those that
    /// leave the document meaning the same. Without this, fixing leaves the `Changes` edits out and
    /// counts them in [`Fixed::changes_held_back`].
    ///
    /// Even with this set, fixing refuses a rename whose new name would clash with the name of
    /// another field in the same object, and lists it in [`Fixed::refused`].
    #[must_use]
    pub fn allow_changes(mut self) -> Self {
        self.changes = Changes::Apply;
        self
    }

    fn allows(self, meaning: fix::Meaning) -> bool {
        match (meaning, self.changes) {
            (fix::Meaning::Preserves, Changes::Apply | Changes::HoldBack)
            | (fix::Meaning::Changes, Changes::Apply) => true,
            (fix::Meaning::Changes, Changes::HoldBack) => false,
        }
    }
}

/// What fixing does with an edit whose meaning is [`fix::Meaning::Changes`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Changes {
    /// Apply the edit.
    Apply,

    /// Leave the edit out and count it in [`Fixed::changes_held_back`].
    HoldBack,
}

/// What fixing a tariff produced.
#[derive(Debug)]
pub struct Fixed {
    /// The fixed tariff's JSON, which is the original source when no edit was made.
    pub source: String,

    /// How many edits were applied in total across all passes.
    pub edits: usize,

    /// How many passes made an edit.
    pub passes: usize,

    /// How many edits the last pass left out because [`Options`] doesn't allow them.
    ///
    /// Only the last pass is counted, so an edit that every pass proposes again counts once. Two
    /// warnings that propose the same edit count twice, as they do in [`Fixed::edits`].
    ///
    /// A refused fix, such as a rename whose new name would clash, isn't counted here, because
    /// allowing changes wouldn't make it either. [`Fixed::refused`] lists it instead.
    pub changes_held_back: usize,

    /// The fixes the last pass proposed and then refused, whatever [`Options`] allows.
    ///
    /// Only the last pass is listed, as for [`Fixed::changes_held_back`]. A fix refused in an
    /// earlier pass and made in a later one isn't listed.
    pub refused: Vec<fix::Refused>,

    /// Whether the lint/fix loop ran out of edits that [`Options`] allows or hit the loop limit.
    pub outcome: Outcome,
}

/// Why the fixing stopped.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Outcome {
    /// The last pass didn't propose any edit that [`Options`] allows.
    /// [`Fixed::changes_held_back`] counts the edits it left out because `Options` doesn't allow
    /// them, and [`Fixed::refused`] lists the fixes it refused.
    AllFixesApplied,

    /// The lint/fix loop limit was reached while edits were still being proposed.
    /// The tariff is the output of the last pass that ran.
    ///
    /// Reaching this is a bug in a [`fix::Fixable`] implementation. It is reported rather than
    /// raised as an error because the passes that did run resolved real warnings, and a caller
    /// that asked for a fix is better served by those than by nothing.
    FixLimit,
}

/// Whether fixing a tariff removes its unexpected fields.
///
/// A field whose name is a possible misspelling of a schema field is kept either way, because its
/// name is the only record of what the author meant. Parsing reports it as a
/// [`schema::Warning::MisspelledField`] rather than as unexpected.
///
/// A tariff's version can be inferred from which fields are present, so removing a field can
/// change what a later inference concludes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnexpectedFields {
    /// Remove unexpected fields.
    Remove,

    /// Leave unexpected fields in place.
    Keep,
}

/// Fix `source` until a pass proposes no edit that `options` allows, or until `max_passes` have
/// made one.
fn fix_until_no_edits(
    source: &str,
    version: crate::Version,
    options: Options,
    max_passes: usize,
) -> Result<Fixed, fix::Error> {
    let mut source = source.to_owned();
    let mut edits: usize = 0;
    let mut passes: usize = 0;

    let (outcome, changes_held_back, refused) = loop {
        let len = string::ReasonableLen::new(&source).map_err(|_e| fix::Error::OutputTooLarge)?;
        let doc = json::parse(len).map_err(fix::Error::Internal)?;
        let (built, schema_warnings) = crate::tariff::from_json(doc, version).into_parts();
        let (proposed, refused) = pass_edits(&built, schema_warnings, options.unexpected)?;
        let (edits_this_pass, changes_held_back) = hold_back(proposed, options);

        if edits_this_pass.is_empty() {
            break (Outcome::AllFixesApplied, changes_held_back, refused);
        }

        if passes == max_passes {
            break (Outcome::FixLimit, changes_held_back, refused);
        }

        let next = fix::apply(built.as_doc(), &edits_this_pass)?;

        edits = edits.saturating_add(edits_this_pass.len());
        passes = passes.saturating_add(1);
        source = next;
    };

    Ok(Fixed {
        source,
        edits,
        passes,
        changes_held_back,
        refused,
        outcome,
    })
}

/// Split `edits` into the ones `options` allows and the count of the ones it doesn't.
fn hold_back(edits: Vec<fix::Edit>, options: Options) -> (Vec<fix::Edit>, usize) {
    let (allowed, held_back): (Vec<fix::Edit>, Vec<fix::Edit>) = edits
        .into_iter()
        .partition(|edit| options.allows(edit.meaning()));

    (allowed, held_back.len())
}

/// The edits resulting from one pass over `tariff`.
///
/// These edits come from both the schema warnings and the lint warnings.
///
/// Also returns the fixes the pass refused. The clashing renames are refused once, over
/// the edits of both warning sets joined, so a rename from one set that writes the same key as a
/// rename from the other is refused too.
fn pass_edits(
    tariff: &crate::tariff::Versioned<'_>,
    mut schema_warnings: warning::Set<schema::Warning>,
    unexpected: UnexpectedFields,
) -> Result<(Vec<fix::Edit>, Vec<fix::Refused>), fix::Error> {
    if unexpected == UnexpectedFields::Keep {
        schema_warnings.remove_unexpected_fields();
    }

    let lint::tariff::Report {
        warnings: lint_warnings,
    } = lint::tariff(tariff);

    let doc = tariff.as_doc();
    let mut proposed = fix::proposed_edits(doc, &schema_warnings)?;
    let lint_proposed = fix::proposed_edits(doc, &lint_warnings)?;

    proposed.extend(lint_proposed);
    let refused = fix::refuse_clashing_renames(doc, &mut proposed);
    let edits = proposed.into_iter().map(fix::Proposed::into_edit).collect();

    Ok((edits, refused))
}