compmd 0.12.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! The `md.` functions a pure expression may call (spec ยง8.2): those that read neither the render nor its locale.

use crate::cel::time;
use crate::cel::{FunctionTypes, Functions, Type, Value, library};
use crate::md::{Md, MdFunction};

/// The `md.` functions that read nothing of a render: they give the same result for the same arguments anywhere.
pub(super) const PURE: [MdFunction; 12] = [
    MdFunction::ParseNumber,
    MdFunction::AddDays,
    MdFunction::DaysBetween,
    MdFunction::Sort,
    MdFunction::SortBy,
    MdFunction::Reverse,
    MdFunction::Slice,
    MdFunction::Sum,
    MdFunction::Min,
    MdFunction::Max,
    MdFunction::Unique,
    MdFunction::GroupBy,
];

/// The `md.` functions that read the render (its time, its time zone) or its locale, which a pure expression has
/// none of: with [`PURE`], every one, so a new function is a decision.
#[cfg(test)]
pub(super) const RENDER: [MdFunction; 9] = [
    MdFunction::Now,
    MdFunction::Today,
    MdFunction::DateOf,
    MdFunction::StartOf,
    MdFunction::Currency,
    MdFunction::Number,
    MdFunction::Date,
    MdFunction::Plural,
    MdFunction::List,
];

/// The types of the pure `md.` functions, for the checker; any other is refused.
pub(super) struct PureSignatures;

impl FunctionTypes for PureSignatures {
    fn result_type(&self, name: &str, args: &[Type]) -> Result<Type, String> {
        if MdFunction::from_name(name).is_some_and(|function| !PURE.contains(&function)) {
            return Err(format!(
                "a pure expression can't call md.{name}(), which reads the render or its locale"
            ));
        }
        library::type_of::<MdFunction>(name, None, args)
    }
}

/// What a pure evaluation calls: the pure `md.` functions, which read nothing of the render they are given, and time
/// zones written as offsets.
pub(super) struct PureRender(Md<'static>);

impl PureRender {
    pub(super) fn new() -> Self {
        Self(Md::new(0, "und", "UTC", &()))
    }
}

impl Functions for PureRender {
    fn names(&self) -> &[&'static str] {
        self.0.names()
    }

    fn call(&self, name: &str, args: &[Value]) -> Result<Value, String> {
        self.0.call(name, args)
    }

    fn result_size(&self, name: &str, args: &[Value]) -> Option<usize> {
        self.0.result_size(name, args)
    }

    /// Only an offset: a pure expression has no `md.tz`, and reads no host's time zone data.
    fn offset(&self, zone: Option<&str>, _: i64) -> Result<i32, String> {
        let zone = zone.ok_or(
            "a pure expression has no md.tz: name the time zone, an offset such as \"+00:00\"",
        )?;
        time::parse_offset(zone).ok_or_else(|| {
            format!("a pure expression names a time zone by its offset, such as \"+02:00\", not '{zone}'")
        })
    }
}