Cotton code
265 lines · 10.0 KB · RustRaw
//! Small, typed row expressions. Objects are a column read or one binary operator.//!//! Beside arithmetic and comparison, three operators work on days (a date//! column's `YYYY-MM-DD`, `today`): `add_days` [day, number] is the day that//! many days on (back, when negative); `later_of` [day, day] is the later of//! two days; `first_of` [a, b] is `a` while it holds a value, else `b`. Each//! says nothing (null) where its day is empty — a membership with no end yet.//!//! The Worker runs this too (as WASM): one evaluator for every automation and//! act. Validation against a table's columns is cotton-core's (it knows the//! column types); the shape and the arithmetic are here.use crate::lines::refusal;use serde_json::{Map, Value};fn refusal_words(piece: &str) -> String {    refusal(piece, &[])}fn said(piece: &str, fills: &[(&str, &dyn std::fmt::Display)]) -> String {    let fills: Vec<(&str, String)> = fills.iter().map(|(name, value)| (*name, value.to_string())).collect();    let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect();    refusal(piece, &fills)}#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Type {    Number,    Bool,    Text,    Other,    Null,}/// The type an expression has, read against `column` for each column it names.pub fn visit(    value: &Value,    column: &mut impl FnMut(&str) -> Result<Type, String>,    depth: usize,) -> Result<Type, String> {    if depth > 32 {        return Err(refusal_words("expression_is_too_deeply_nested"));    }    if let Some(key) = value.as_str().and_then(|s| s.strip_prefix("$record.")) {        return column(key);    }    if let Some(object) = value.as_object() {        if object.len() != 1 {            return Err(refusal_words("expression_needs_one_operator"));        }        if let Some(clock) = object.get("now").or_else(|| object.get("today")) {            return if clock == &Value::Bool(true) {                Ok(Type::Text)            } else {                Err(refusal_words("clock_expression_needs_true"))            };        }        if let Some(key) = object.get("column") {            return column(key.as_str().ok_or_else(|| refusal_words("column_needs_a_key"))?);        }        let Some((op, operands)) = object.iter().next() else {            return Err(refusal_words("expression_needs_one_operator"));        };        let operands = operands            .as_array()            .filter(|a| a.len() == 2)            .ok_or_else(|| refusal_words("operator_needs_two_operands"))?;        let left = visit(&operands[0], column, depth + 1)?;        let right = visit(&operands[1], column, depth + 1)?;        let day = |t: Type| t == Type::Text || t == Type::Null;        match op.as_str() {            "add_days" if day(left) && (right == Type::Number || right == Type::Null) => Ok(Type::Text),            "later_of" if day(left) && day(right) => Ok(Type::Text),            "first_of" if left == right || left == Type::Null => Ok(right),            "first_of" if right == Type::Null => Ok(left),            "+" | "-" | "*" | "/" if left == Type::Number && right == Type::Number => {                Ok(Type::Number)            }            ">" | ">=" | "<" | "<=" if left == Type::Number && right == Type::Number => {                Ok(Type::Bool)            }            "==" | "!=" if left == right || left == Type::Null || right == Type::Null => {                Ok(Type::Bool)            }            "and" | "or" if left == Type::Bool && right == Type::Bool => Ok(Type::Bool),            _ => Err(said("invalid_expression_operator_or_operand_types", &[("op", &op)])),        }    } else {        Ok(if value.is_number() {            Type::Number        } else if value.is_boolean() {            Type::Bool        } else if value.is_string() {            Type::Text        } else if value.is_null() {            Type::Null        } else {            Type::Other        })    }}/// Evaluate all clock reads against the write's instant and workspace calendar day.pub fn evaluate_at(    value: &Value,    row: &Map<String, Value>,    now: &str,    today: &str,) -> Result<Value, String> {    // Validate structure before recursion, including its depth bound.    visit(        value,        &mut |key| {            row.get(key)                .map(|v| {                    if v.is_number() {                        Type::Number                    } else if v.is_boolean() {                        Type::Bool                    } else if v.is_string() {                        Type::Text                    } else if v.is_null() {                        Type::Null                    } else {                        Type::Other                    }                })                .ok_or_else(|| said("record_has_no_column", &[("key", &key)]))        },        0,    )?;    eval(value, row, now, today)}fn eval(value: &Value, row: &Map<String, Value>, now: &str, today: &str) -> Result<Value, String> {    if value.get("now") == Some(&Value::Bool(true)) {        return Ok(Value::String(now.into()));    }    if value.get("today") == Some(&Value::Bool(true)) {        return Ok(Value::String(today.into()));    }    let reference = value        .as_str()        .and_then(|s| s.strip_prefix("$record."))        .or_else(|| value.get("column").and_then(Value::as_str));    if let Some(key) = reference {        return row            .get(key)            .cloned()            .ok_or_else(|| said("record_has_no_column", &[("key", &key)]));    }    let Some(object) = value.as_object() else {        return Ok(value.clone());    };    let (Some((op, args)), 1) = (object.iter().next(), object.len()) else {        return Err(refusal_words("expression_needs_one_operator"));    };    let Some([left, right]) = args.as_array().map(Vec::as_slice) else {        return Err(refusal_words("operator_needs_two_operands"));    };    let a = eval(left, row, now, today)?;    let b = eval(right, row, now, today)?;    match op.as_str() {        "first_of" => return Ok(if a.is_null() { b } else { a }),        "add_days" => {            let (Some(from), Some(days)) = (day_of(&a)?, whole(&b)) else { return Ok(Value::Null) };            let on = chrono::Days::new(days.unsigned_abs());            let moved = if days < 0 { from.checked_sub_days(on) } else { from.checked_add_days(on) };            return moved.map(|day| Value::String(day.format("%Y-%m-%d").to_string())).ok_or_else(|| refusal_words("expression_needs_a_day"));        }        "later_of" => {            return Ok(match (day_of(&a)?, day_of(&b)?) {                (Some(x), Some(y)) => Value::String(x.max(y).format("%Y-%m-%d").to_string()),                (Some(x), None) | (None, Some(x)) => Value::String(x.format("%Y-%m-%d").to_string()),                (None, None) => Value::Null,            });        }        _ => {}    }    let equal = if a.is_number() && b.is_number() {        match (whole(&a), whole(&b)) {            (Some(x), Some(y)) => x == y,            _ => a.as_f64() == b.as_f64(),        }    } else {        a == b    };    match op.as_str() {        "==" => return Ok(Value::Bool(equal)),        "!=" => return Ok(Value::Bool(!equal)),        "and" | "or" => {            let (Some(x), Some(y)) = (a.as_bool(), b.as_bool()) else {                return Err(said("invalid_expression_operator_or_operand_types", &[("op", &op)]));            };            return Ok(Value::Bool(if op == "and" { x && y } else { x || y }));        }        _ => {}    }    if let (Some(x), Some(y)) = (whole(&a), whole(&b)) {        match op.as_str() {            ">" => return Ok(Value::Bool(x > y)),            ">=" => return Ok(Value::Bool(x >= y)),            "<" => return Ok(Value::Bool(x < y)),            "<=" => return Ok(Value::Bool(x <= y)),            _ => {}        }    }    let x = a.as_f64().ok_or_else(|| refusal_words("expression_needs_a_number"))?;    let y = b.as_f64().ok_or_else(|| refusal_words("expression_needs_a_number"))?;    match op.as_str() {        ">" => return Ok(Value::Bool(x > y)),        ">=" => return Ok(Value::Bool(x >= y)),        "<" => return Ok(Value::Bool(x < y)),        "<=" => return Ok(Value::Bool(x <= y)),        _ => {}    }    // Whole operands stay whole: no float rounding of money and no silent overflow.    if let (Some(x), Some(y)) = (whole(&a), whole(&b)) {        let n = match op.as_str() {            "+" => x.checked_add(y),            "-" => x.checked_sub(y),            "*" => x.checked_mul(y),            "/" if y != 0 && x.checked_rem(y) == Some(0) => x.checked_div(y),            "/" if y != 0 => None,            _ => None,        };        if let Some(n) = n {            return Ok(Value::from(n));        }        if op != "/" || y == 0 || x.checked_rem(y).is_none() || x.checked_rem(y) == Some(0) {            return Err(refusal_words("arithmetic_overflow_or_division_by_zero"));        }    }    let n = match op.as_str() {        "+" => x + y,        "-" => x - y,        "*" => x * y,        "/" if y != 0.0 => x / y,        _ => return Err(refusal_words("division_by_zero")),    };    serde_json::Number::from_f64(n)        .map(Value::Number)        .ok_or_else(|| refusal_words("non_finite_expression_result"))}/// A day a value holds: a date's `YYYY-MM-DD` (a moment's own day), none for/// null; any other value is not a day and is refused.fn day_of(value: &Value) -> Result<Option<chrono::NaiveDate>, String> {    match value {        Value::Null => Ok(None),        Value::String(text) => text            .get(..10)            .and_then(|day| chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").ok())            .map(Some)            .ok_or_else(|| refusal_words("expression_needs_a_day")),        _ => Err(refusal_words("expression_needs_a_day")),    }}fn whole(value: &Value) -> Option<i64> {    value.as_i64().or_else(|| {        value            .as_f64()            .filter(|n| {                n.is_finite() && n.fract() == 0.0 && *n >= i64::MIN as f64 && *n < i64::MAX as f64            })            .map(|n| n as i64)    })}