Skip to main content

mln_style/expression/functions/
mod.rs

1//! The expression functions: the operators that the parser resolves by name
2//! against a [`Functions`] value and that evaluate their already-parsed
3//! arguments.
4//!
5//! A function has one or more overloads, each with its parameter and result
6//! types, the inputs it reads ([`Dependency`]) and an evaluator. Parsing tries
7//! a name's overloads in the order they were added. The expression syntax
8//! (`let`, `match`, `case`, `interpolate` and the other forms that parse their
9//! own arguments) isn't a function and can't be registered as one.
10//!
11//! A compound expression crosses the worker codec as its function's name and
12//! its overload's position, which the reading side resolves against the
13//! [`Functions`] in the reader's context (`mln_wire::Context`).
14
15pub(crate) mod builtin;
16
17use std::borrow::Cow;
18use std::sync::{Arc, LazyLock};
19
20use mln_util::Color;
21use mln_util::hash::HashMap;
22
23pub use self::builtin::register_builtin_functions;
24use crate::expression::parse::is_special_form;
25use crate::expression::type_::Type;
26use crate::expression::{Dependency, EvalResult, EvaluationContext, EvaluationResult, Expr};
27
28/// The parameter list of an overload: fixed types, or any number of
29/// arguments of one type.
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub enum Params {
32    Fixed(Vec<Type>),
33    Varargs(Type),
34}
35
36impl Params {
37    /// Whether some number of arguments fits both.
38    fn overlaps(&self, other: &Params) -> bool {
39        match (self, other) {
40            (Params::Fixed(a), Params::Fixed(b)) => a.len() == b.len(),
41            _ => true,
42        }
43    }
44}
45
46/// What the built-in static analyses may assume about a function. `Plain`
47/// for all but six built-ins. Only one function may claim `Zoom` and only
48/// one `GlobalState` ([`Functions::add`] rejects a second).
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum Role {
51    Plain,
52    /// Reads the feature property whose key is the literal first argument
53    /// (`get`, `has`).
54    FeatureProperty,
55    /// Reads the feature's id (`id`).
56    FeatureId,
57    /// Reads the feature's geometry type (`geometry-type`).
58    GeometryType,
59    /// The zoom level that a top-level `step` or `interpolate` may take as
60    /// its input (`zoom`).
61    Zoom,
62    /// Reads the global-state property whose key is the literal first
63    /// argument (`global-state`).
64    GlobalState,
65}
66
67/// An overload's evaluator, typed by its result so that a number, boolean,
68/// string or color evaluates without a [`Value`](crate::expression::Value) in between.
69/// `Value` is for every other result type.
70#[derive(Clone, Copy, Debug)]
71pub enum Eval {
72    Number(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<f64>),
73    Boolean(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<bool>),
74    String(for<'e> fn(&'e [Expr], &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>>),
75    Color(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<Color>),
76    Value(fn(&[Expr], &EvaluationContext<'_>) -> EvaluationResult),
77}
78
79impl Eval {
80    fn matches(&self, result: &Type) -> bool {
81        match self {
82            Eval::Number(_) => *result == Type::Number,
83            Eval::Boolean(_) => *result == Type::Boolean,
84            Eval::String(_) => *result == Type::String,
85            Eval::Color(_) => *result == Type::Color,
86            Eval::Value(_) => !matches!(result, Type::Number | Type::Boolean | Type::String | Type::Color),
87        }
88    }
89}
90
91/// An overload as [`Functions::add`] takes it.
92#[doc(hidden)]
93#[derive(Clone, Debug)]
94pub struct OverloadSpec {
95    pub result: Type,
96    pub params: Params,
97    pub dependencies: Dependency,
98    pub role: Role,
99    pub eval: Eval,
100}
101
102#[derive(Debug)]
103pub struct Overload {
104    pub(crate) name: Arc<str>,
105    /// The overload's position among its name's.
106    pub(crate) index: u8,
107    pub result: Type,
108    pub params: Params,
109    pub dependencies: Dependency,
110    pub role: Role,
111    pub eval: Eval,
112}
113
114impl Overload {
115    #[must_use]
116    pub fn name(&self) -> &str {
117        &self.name
118    }
119}
120
121/// A function: its name and its overloads, in the order parsing tries them.
122#[derive(Debug)]
123pub struct FunctionDef {
124    name: Arc<str>,
125    overloads: Box<[Arc<Overload>]>,
126}
127
128impl FunctionDef {
129    #[must_use]
130    pub fn name(&self) -> &str {
131        &self.name
132    }
133
134    #[must_use]
135    pub fn overloads(&self) -> &[Arc<Overload>] {
136        &self.overloads
137    }
138}
139
140/// Why [`Functions::add`] refused a function.
141#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
142pub enum RegisterError {
143    #[error("\"{0}\" is already registered")]
144    Duplicate(String),
145    #[error("\"{0}\" is an expression form, not a function")]
146    SpecialForm(String),
147    #[error("\"{0}\" needs between 1 and 256 overloads")]
148    OverloadCount(String),
149    #[error("two overloads of \"{0}\" take the same number of arguments")]
150    AmbiguousArity(String),
151    #[error("an overload of \"{0}\" evaluates to another type than its result")]
152    EvalMismatch(String),
153    #[error("\"{0}\" claims a role that another function has")]
154    RoleTaken(String),
155}
156
157/// The expression functions that parsing resolves names against.
158#[derive(Debug, Default)]
159pub struct Functions {
160    defs: Vec<FunctionDef>,
161    by_name: HashMap<Arc<str>, usize>,
162}
163
164impl Functions {
165    /// No functions.
166    #[must_use]
167    pub fn new() -> Self {
168        Functions::default()
169    }
170
171    /// The style specification's functions. Every call returns the same
172    /// value, built on the first: it never changes, so sharing it is a cache.
173    #[must_use]
174    pub fn with_builtins() -> Arc<Functions> {
175        static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
176            let mut functions = Functions::new();
177            // Into no functions, the built-ins register: no two share a name
178            // or a role, and none is an expression form.
179            let registered = register_builtin_functions(&mut functions);
180            debug_assert_eq!(registered, Ok(()));
181            Arc::new(functions)
182        });
183        Arc::clone(&BUILTINS)
184    }
185
186    /// Adds the function `name` with its overloads, in the order parsing
187    /// tries them. Fails for a name that is taken or is an expression form,
188    /// two overloads that take the same number of arguments, an evaluator of
189    /// another type than its overload's result, or a role that only one
190    /// function may have and another has.
191    #[doc(hidden)]
192    pub fn add(&mut self, name: &str, overloads: Vec<OverloadSpec>) -> Result<(), RegisterError> {
193        if is_special_form(name) {
194            return Err(RegisterError::SpecialForm(name.to_owned()));
195        }
196        if self.by_name.contains_key(name) {
197            return Err(RegisterError::Duplicate(name.to_owned()));
198        }
199        if overloads.is_empty() || overloads.len() > usize::from(u8::MAX) + 1 {
200            return Err(RegisterError::OverloadCount(name.to_owned()));
201        }
202        // Parsing parses the arguments for the one overload that takes as many
203        // as it finds, so two of one arity would leave the second unreachable.
204        for (i, a) in overloads.iter().enumerate() {
205            if overloads[..i].iter().any(|b| a.params.overlaps(&b.params)) {
206                return Err(RegisterError::AmbiguousArity(name.to_owned()));
207            }
208        }
209        if overloads.iter().any(|overload| !overload.eval.matches(&overload.result)) {
210            return Err(RegisterError::EvalMismatch(name.to_owned()));
211        }
212        for role in [Role::Zoom, Role::GlobalState] {
213            let claims = |def: &FunctionDef| def.overloads.iter().any(|overload| overload.role == role);
214            if overloads.iter().any(|overload| overload.role == role) && self.defs.iter().any(claims) {
215                return Err(RegisterError::RoleTaken(name.to_owned()));
216            }
217        }
218        let name: Arc<str> = Arc::from(name);
219        let overloads = (0u8..=u8::MAX)
220            .zip(overloads)
221            .map(|(index, spec)| {
222                Arc::new(Overload {
223                    name: Arc::clone(&name),
224                    index,
225                    result: spec.result,
226                    params: spec.params,
227                    dependencies: spec.dependencies,
228                    role: spec.role,
229                    eval: spec.eval,
230                })
231            })
232            .collect();
233        self.by_name.insert(Arc::clone(&name), self.defs.len());
234        self.defs.push(FunctionDef { name, overloads });
235        Ok(())
236    }
237
238    #[must_use]
239    pub fn get(&self, name: &str) -> Option<&FunctionDef> {
240        self.by_name.get(name).map(|&index| &self.defs[index])
241    }
242
243    pub(crate) fn contains(&self, name: &str) -> bool {
244        self.by_name.contains_key(name)
245    }
246}
247
248/// A context in which reading an [`Expr`] from the worker codec resolves
249/// compound expressions against these functions.
250impl mln_wire::Context for &Functions {
251    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
252        request.give::<Functions>(self);
253    }
254}
255
256/// The overload `index` of `name` among the functions in `r`'s context.
257pub(crate) fn decoding_overload(
258    r: &mut mln_wire::Reader<'_>,
259    name: &str,
260    index: u8,
261) -> Result<Arc<Overload>, &'static str> {
262    match r.context::<Functions>() {
263        None => Err("an expression function without functions to resolve it against"),
264        Some(functions) => match functions.get(name) {
265            None => Err("unknown expression function"),
266            Some(def) => def.overloads.get(usize::from(index)).cloned().ok_or("no such overload of a function"),
267        },
268    }
269}