compmd 0.12.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! Pure expressions (spec §8.2): a host's own expressions, such as a value type's `read`, `show` and `check`,
//! compiled once against their variables' types and evaluated for each value, with nothing of a render.

mod functions;
#[cfg(test)]
mod tests;

use super::check::{self, Profile};
use super::{BUDGET, Error, Program, Scope, Type, Value, Values, eval};
use functions::{PureRender, PureSignatures};

/// A pure expression (spec §8.2), compiled: checked against its variables' types, so what isn't pure is found
/// before it is evaluated. Compile it once, and evaluate it as often as needed.
///
/// ```
/// use compmd::cel::{Pure, Scope, Type, Value, Values};
///
/// let scope = Scope::default().with("value", Type::Double);
/// let show = Pure::compile(r#""%d:%02d".format([int(value) / 60, int(value) % 60])"#, &scope).expect("pure");
/// assert_eq!(show.result_type(), &Type::String);
/// let shown = show.evaluate(&Values::default().with("value", Value::Double(65.0))).expect("shown");
/// assert_eq!(shown.to_json(), "1:05");
///
/// let error = Pure::compile("md.today()", &Scope::default()).expect_err("not pure");
/// assert_eq!(error.message(), "a pure expression can't call md.today(), which reads the render or its locale");
/// ```
#[derive(Clone, Debug)]
pub struct Pure {
    program: Program,
    result: Type,
}

impl Pure {
    /// Compiles `source`, an expression without its parentheses, against the variables of `scope`.
    ///
    /// # Errors
    ///
    /// A parse or type error, or what isn't pure: `md`, an `md.` function that reads the render or the locale, a
    /// timestamp's getter without a time zone. Each at its column; a scope with a variable `md` at the first.
    pub fn compile(source: &str, scope: &Scope) -> Result<Self, Error> {
        if scope.get("md").is_some() {
            return Err(Error::type_error(
                0,
                "a pure expression has no variable md, which is a render's",
            ));
        }
        let program = Program::parse(source)?;
        let result = check::check(&program.expr, scope, &PureSignatures, Profile::Pure)?;
        Ok(Self { program, result })
    }

    /// The type it gives.
    #[must_use]
    pub fn result_type(&self) -> &Type {
        &self.result
    }

    /// Evaluates it with `values`, one for each variable of the scope it was compiled against, within [`BUDGET`]
    /// steps.
    ///
    /// # Errors
    ///
    /// An evaluation error, at its column: division by zero, an index out of range, a time zone that isn't an offset,
    /// the budget spent ([`Error::reported_at`] is the first column).
    pub fn evaluate(&self, values: &Values) -> Result<Value, Error> {
        eval::evaluate(&self.program.expr, values, &PureRender::new(), BUDGET)
    }
}