use crate::cel::time;
use crate::cel::{FunctionTypes, Functions, Type, Value, library};
use crate::md::{Md, MdFunction};
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,
];
#[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,
];
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)
}
}
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)
}
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}'")
})
}
}