compmd 0.12.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! A pure expression reads only its own variables: the design's value types compile and give their results, and
//! what reads a render is refused when compiled, or fails when evaluated where the checker can't tell.

use super::Pure;
use super::functions::{PURE, RENDER};
use crate::cel::{Error, Scope, Type, Value, Values};
use crate::md::MdFunction;
use serde_json::{Value as Json, json};

/// A duration's `read`, from `docs/typed-values-in-cel.md`: its minutes.
const DURATION_READ: &str = r#"text.trim().lowerAscii().captures("^(\\d+)\\s*h\\s*(\\d+)\\s*m$").optMap(g, double(g[0]) * 60.0 + double(g[1]))
  .or(text.trim().captures("^(\\d+):(\\d{2})$").optMap(g, double(g[0]) * 60.0 + double(g[1])))
  .or(text.trim().lowerAscii().captures("^(\\d+)\\s*min$").optMap(g, double(g[0])))"#;

/// A duration's `show`.
const DURATION_SHOW: &str = r#"int(value) >= 60 ? "%dh %dm".format([int(value) / 60, int(value) % 60]) : "%d min".format([int(value)])"#;

/// A distance's `read`: its miles.
const DISTANCE_READ: &str = r#"text.trim().lowerAscii().captures("^([0-9.]+)\\s*(mi|km)$")
  .optFlatMap(g, md.parseNumber(g[0]).optMap(n, g[1] == "km" ? n / 1.609344 : n))"#;

fn text() -> Scope {
    Scope::default().with("text", Type::String)
}

fn value() -> Scope {
    Scope::default().with("value", Type::Double)
}

fn compiled(source: &str, scope: &Scope) -> Pure {
    Pure::compile(source, scope).unwrap_or_else(|error| panic!("{source}: {error}"))
}

/// What `pure` gives for `values`, as JSON with `int` and `double` apart; an optional none is `null`.
fn evaluated(pure: &Pure, values: &Values) -> Json {
    pure.evaluate(values)
        .unwrap_or_else(|error| panic!("{error}"))
        .typed_json()
}

fn of_text(pure: &Pure, text: &str) -> Json {
    evaluated(pure, &Values::default().with("text", Value::string(text)))
}

fn of_value(pure: &Pure, value: f64) -> Json {
    evaluated(pure, &Values::default().with("value", Value::Double(value)))
}

fn refused(source: &str, scope: &Scope) -> Error {
    Pure::compile(source, scope).expect_err(source)
}

#[test]
fn a_duration_is_read_and_shown() {
    let read = compiled(DURATION_READ, &text());
    assert_eq!(read.result_type(), &Type::optional(Type::Double));
    for (typed, minutes) in [
        ("1h 30m", json!(90.0)),
        ("1:30", json!(90.0)),
        (" 90 MIN ", json!(90.0)),
        ("soon", Json::Null),
    ] {
        assert_eq!(of_text(&read, typed), minutes, "{typed}");
    }
    let show = compiled(DURATION_SHOW, &value());
    assert_eq!(show.result_type(), &Type::String);
    assert_eq!(of_value(&show, 65.0), "1h 5m");
    assert_eq!(of_value(&show, 45.0), "45 min");
    let check = compiled("value >= 0.0", &value());
    assert_eq!(of_value(&check, -1.0), false);
}

#[test]
fn a_distance_is_read_and_shown() {
    let read = compiled(DISTANCE_READ, &text());
    assert_eq!(of_text(&read, "7.5 mi"), json!(7.5));
    assert_eq!(of_text(&read, "12 km"), json!(12.0 / 1.609_344));
    assert_eq!(of_text(&read, "1.2.3 km"), Json::Null);
    let show = compiled(r#""%.1f mi".format([value])"#, &value());
    assert_eq!(of_value(&show, 7.46), "7.5 mi");
}

#[test]
fn md_is_refused_wherever_it_is_read() {
    for (source, at) in [
        ("md.doc.title", 0),
        ("size(md.lang)", 5),
        ("text + md.tz", 7),
    ] {
        let error = refused(source, &text());
        assert_eq!(
            (error.at(), error.message()),
            (at, "a pure expression reads only its own variables, not md"),
            "{source}"
        );
    }
    let local = compiled("[1.0].map(md, md + 1.0)", &Scope::default());
    assert_eq!(local.result_type(), &Type::list(Type::Double));
    let error = Pure::compile("1", &Scope::default().with("md", Type::Dyn)).expect_err("md");
    assert_eq!(
        (error.at(), error.message()),
        (
            0,
            "a pure expression has no variable md, which is a render's"
        )
    );
}

#[test]
fn an_md_function_that_reads_the_render_or_the_locale_is_refused() {
    for (source, name) in [
        ("md.today()", "today"),
        ("md.number(value, 0)", "number"),
        ("md.startOf(\"2026-10-21\", \"month\")", "startOf"),
    ] {
        let error = refused(source, &value());
        assert_eq!(
            error.message(),
            format!(
                "a pure expression can't call md.{name}(), which reads the render or its locale"
            ),
            "{source}"
        );
    }
    let sum = compiled("md.sum([value, 2.0])", &value());
    assert_eq!(of_value(&sum, 1.0), json!(3.0));
    let unknown = refused("md.sumOf([value])", &value());
    assert_eq!(
        unknown.message(),
        "unknown function 'md.sumOf'; did you mean 'md.sum'?"
    );
}

#[test]
fn every_md_function_is_pure_or_reads_the_render() {
    let mut listed: Vec<MdFunction> = PURE.iter().chain(&RENDER).copied().collect();
    listed.sort_by_key(|function| MdFunction::ALL.iter().position(|f| f == function));
    assert_eq!(listed, MdFunction::ALL);
}

#[test]
fn a_timestamp_s_getter_names_its_time_zone() {
    let scope = Scope::default()
        .with("t", Type::Timestamp)
        .with("d", Type::Duration);
    let error = refused("t.getHours() + 1", &scope);
    assert_eq!(
        (error.at(), error.message()),
        (
            2,
            "a pure expression has no md.tz: name the time zone, an offset such as getHours(\"+00:00\")"
        )
    );
    let values = Values::default()
        .with("t", Value::Timestamp(23 * 3_600 * 1_000_000_000))
        .with("d", Value::Duration(5_400 * 1_000_000_000));
    let hours = compiled(r#"t.getHours("+02:00") + d.getHours()"#, &scope);
    assert_eq!(evaluated(&hours, &values), json!(2));
}

#[test]
fn what_the_checker_can_t_tell_fails_when_evaluated() {
    let scope = Scope::default().with("t", Type::Dyn);
    let values = Values::default().with("t", Value::Timestamp(0));
    for (source, message) in [
        (
            "t.getHours()",
            "a pure expression has no md.tz: name the time zone, an offset such as \"+00:00\"",
        ),
        (
            r#"t.getHours("Europe/Berlin")"#,
            "a pure expression names a time zone by its offset, such as \"+02:00\", not 'Europe/Berlin'",
        ),
    ] {
        let error = compiled(source, &scope)
            .evaluate(&values)
            .expect_err(source);
        assert_eq!(error.message(), message, "{source}");
    }
}

#[test]
fn an_evaluation_is_bounded() {
    let scope = Scope::default().with("digits", Type::list(Type::Double));
    let digits = Value::list((0..10).map(|n| Value::Double(f64::from(n))).collect());
    let runaway = compiled(
        "size(digits.map(a, digits.map(b, digits.map(c, digits.map(d, digits.map(e, a))))))",
        &scope,
    );
    let error = runaway
        .evaluate(&Values::default().with("digits", digits))
        .expect_err("too much work");
    assert!(matches!(error, Error::Budget { .. }), "{error}");
    assert_eq!(error.reported_at(), 0);
}