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
20pub use self::builtin::register_builtin_functions;
21use crate::color::Color;
22use crate::expression::parse::is_special_form;
23use crate::expression::type_::Type;
24use crate::expression::{Dependency, EvalResult, EvaluationContext, EvaluationResult, Expr};
25use crate::hash::HashMap;
26
27/// The parameter list of an overload: fixed types, or any number of
28/// arguments of one type.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Params {
31    Fixed(Vec<Type>),
32    Varargs(Type),
33}
34
35impl Params {
36    /// Whether some number of arguments fits both.
37    fn overlaps(&self, other: &Params) -> bool {
38        match (self, other) {
39            (Params::Fixed(a), Params::Fixed(b)) => a.len() == b.len(),
40            _ => true,
41        }
42    }
43}
44
45/// What the built-in static analyses may assume about a function. `Plain`
46/// for all but six built-ins. Only one function may claim `Zoom` and only
47/// one `GlobalState` ([`Functions::add`] rejects a second).
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub(crate) enum Role {
50    Plain,
51    /// Reads the feature property whose key is the literal first argument
52    /// (`get`, `has`).
53    FeatureProperty,
54    /// Reads the feature's id (`id`).
55    FeatureId,
56    /// Reads the feature's geometry type (`geometry-type`).
57    GeometryType,
58    /// The zoom level that a top-level `step` or `interpolate` may take as
59    /// its input (`zoom`).
60    Zoom,
61    /// Reads the global-state property whose key is the literal first
62    /// argument (`global-state`).
63    GlobalState,
64}
65
66/// Stateful evaluator for a dynamically registered expression function
67/// overload.
68///
69/// Implementations are called synchronously from any thread (including parse
70/// threads during constant folding, render threads, and tile worker threads)
71/// and must be thread-safe.
72pub trait DynamicEvaluator: Send + Sync + std::fmt::Debug {
73    fn evaluate(&self, args: &[Expr], cx: &EvaluationContext<'_>) -> EvaluationResult;
74}
75
76/// An overload's evaluator, typed by its result so that a number, boolean,
77/// string or color evaluates without a [`Value`](crate::expression::Value) in
78/// between. `Value` is for every other built-in result type, and `Dynamic` is
79/// for stateful external functions.
80#[derive(Clone, Debug)]
81pub enum Eval {
82    Number(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<f64>),
83    Boolean(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<bool>),
84    String(for<'e> fn(&'e [Expr], &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>>),
85    Color(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<Color>),
86    Value(fn(&[Expr], &EvaluationContext<'_>) -> EvaluationResult),
87    Dynamic(Arc<dyn DynamicEvaluator>),
88}
89
90impl Eval {
91    fn matches(&self, result: &Type) -> bool {
92        match self {
93            Eval::Number(_) => *result == Type::Number,
94            Eval::Boolean(_) => *result == Type::Boolean,
95            Eval::String(_) => *result == Type::String,
96            Eval::Color(_) => *result == Type::Color,
97            Eval::Value(_) => !matches!(result, Type::Number | Type::Boolean | Type::String | Type::Color),
98            Eval::Dynamic(_) => !matches!(result, Type::Collator | Type::Error),
99        }
100    }
101}
102
103/// An overload as internal built-in registration takes it.
104#[derive(Clone, Debug)]
105pub(crate) struct OverloadSpec {
106    pub(crate) result: Type,
107    pub(crate) params: Params,
108    pub(crate) dependencies: Dependency,
109    pub(crate) role: Role,
110    pub(crate) eval: Eval,
111}
112
113/// One overload of a dynamically registered expression function.
114#[derive(Clone, Debug)]
115pub struct DynamicOverload {
116    pub result: Type,
117    pub params: Params,
118    pub dependencies: Dependency,
119    pub eval: Arc<dyn DynamicEvaluator>,
120}
121
122#[derive(Debug)]
123pub struct Overload {
124    pub(crate) name: Arc<str>,
125    /// The overload's position among its name's.
126    pub(crate) index: u8,
127    pub result: Type,
128    pub params: Params,
129    pub dependencies: Dependency,
130    pub(crate) role: Role,
131    pub eval: Eval,
132}
133
134impl Overload {
135    #[must_use]
136    pub fn name(&self) -> &str {
137        &self.name
138    }
139}
140
141/// A function: its name and its overloads, in the order parsing tries them.
142#[derive(Debug)]
143pub struct FunctionDef {
144    name: Arc<str>,
145    overloads: Box<[Arc<Overload>]>,
146}
147
148impl FunctionDef {
149    #[must_use]
150    pub fn name(&self) -> &str {
151        &self.name
152    }
153
154    #[must_use]
155    pub fn overloads(&self) -> &[Arc<Overload>] {
156        &self.overloads
157    }
158}
159
160/// Why a registration was refused: a function by [`Functions::add_dynamic`], or a
161/// layer type, a source type, an extension member or a projection by the
162/// runtime's registry.
163#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
164pub enum RegisterError {
165    #[error("\"{0}\" is already registered")]
166    Duplicate(String),
167    #[error("\"{0}\" is an expression form, not a function")]
168    SpecialForm(String),
169    #[error("\"{0}\" needs between 1 and 256 overloads")]
170    OverloadCount(String),
171    #[error("two overloads of \"{0}\" take the same number of arguments")]
172    AmbiguousArity(String),
173    #[error("an overload of \"{0}\" evaluates to another type than its result")]
174    EvalMismatch(String),
175    #[error("\"{0}\" claims a role that another function has")]
176    RoleTaken(String),
177    #[error(
178        "the projection name \"{0}\" needs a colon, like \"EPSG:2193\": names without one are kept for built-in \
179         projections"
180    )]
181    ProjectionName(String),
182    #[error("the projection \"{0}\" needs a tile matrix set with a finite origin and a positive, finite extent")]
183    TileMatrixSet(String),
184    #[error("expression function name must not be empty")]
185    EmptyFunctionName,
186    #[error("an overload of \"{0}\" declares unsupported dependencies ({1})")]
187    InvalidDependencies(String, Dependency),
188}
189
190/// The expression functions that parsing resolves names against.
191#[derive(Debug, Default)]
192pub struct Functions {
193    defs: Vec<FunctionDef>,
194    by_name: HashMap<Arc<str>, usize>,
195}
196
197impl Functions {
198    /// No functions.
199    #[must_use]
200    pub fn new() -> Self {
201        Functions::default()
202    }
203
204    /// The style specification's functions. Every call returns the same
205    /// value, built on the first: it never changes, so sharing it is a cache.
206    #[must_use]
207    pub fn with_builtins() -> Arc<Functions> {
208        static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
209            let mut functions = Functions::new();
210            // Into no functions, the built-ins register: no two share a name
211            // or a role, and none is an expression form.
212            let registered = register_builtin_functions(&mut functions);
213            debug_assert_eq!(registered, Ok(()));
214            Arc::new(functions)
215        });
216        Arc::clone(&BUILTINS)
217    }
218
219    /// Adds a dynamically registered function `name` with its overloads, in
220    /// the order parsing tries them.
221    ///
222    /// Fails for an empty name, a name that is taken or is an expression form,
223    /// an invalid overload count (not in 1..=256), overlapping arities, an
224    /// unsupported result type (`Collator` or `Error`), or dependencies outside
225    /// [`Dependency::DYNAMIC_CAPABILITIES`].
226    pub fn add_dynamic(&mut self, name: &str, overloads: Vec<DynamicOverload>) -> Result<(), RegisterError> {
227        if name.is_empty() {
228            return Err(RegisterError::EmptyFunctionName);
229        }
230        for overload in &overloads {
231            if !overload.dependencies.is_subset_of(Dependency::DYNAMIC_CAPABILITIES) {
232                return Err(RegisterError::InvalidDependencies(name.to_owned(), overload.dependencies));
233            }
234        }
235        let specs = overloads
236            .into_iter()
237            .map(|o| OverloadSpec {
238                result: o.result,
239                params: o.params,
240                dependencies: o.dependencies,
241                role: Role::Plain,
242                eval: Eval::Dynamic(o.eval),
243            })
244            .collect();
245        self.add(name, specs)
246    }
247
248    /// Adds the function `name` with its overloads, in the order parsing
249    /// tries them. Fails for a name that is taken or is an expression form,
250    /// two overloads that take the same number of arguments, an evaluator of
251    /// another type than its overload's result, or a role that only one
252    /// function may have and another has.
253    pub(crate) fn add(&mut self, name: &str, overloads: Vec<OverloadSpec>) -> Result<(), RegisterError> {
254        if name.is_empty() {
255            return Err(RegisterError::EmptyFunctionName);
256        }
257        if is_special_form(name) {
258            return Err(RegisterError::SpecialForm(name.to_owned()));
259        }
260        if self.by_name.contains_key(name) {
261            return Err(RegisterError::Duplicate(name.to_owned()));
262        }
263        if overloads.is_empty() || overloads.len() > usize::from(u8::MAX) + 1 {
264            return Err(RegisterError::OverloadCount(name.to_owned()));
265        }
266        // Parsing parses the arguments for the one overload that takes as many
267        // as it finds, so two of one arity would leave the second unreachable.
268        for (i, a) in overloads.iter().enumerate() {
269            if overloads[..i].iter().any(|b| a.params.overlaps(&b.params)) {
270                return Err(RegisterError::AmbiguousArity(name.to_owned()));
271            }
272        }
273        if overloads.iter().any(|overload| !overload.eval.matches(&overload.result)) {
274            return Err(RegisterError::EvalMismatch(name.to_owned()));
275        }
276        for role in [Role::Zoom, Role::GlobalState] {
277            let claims = |def: &FunctionDef| def.overloads.iter().any(|overload| overload.role == role);
278            if overloads.iter().any(|overload| overload.role == role) && self.defs.iter().any(claims) {
279                return Err(RegisterError::RoleTaken(name.to_owned()));
280            }
281        }
282        let name: Arc<str> = Arc::from(name);
283        let overloads = (0u8..=u8::MAX)
284            .zip(overloads)
285            .map(|(index, spec)| {
286                Arc::new(Overload {
287                    name: Arc::clone(&name),
288                    index,
289                    result: spec.result,
290                    params: spec.params,
291                    dependencies: spec.dependencies,
292                    role: spec.role,
293                    eval: spec.eval,
294                })
295            })
296            .collect();
297        self.by_name.insert(Arc::clone(&name), self.defs.len());
298        self.defs.push(FunctionDef { name, overloads });
299        Ok(())
300    }
301
302    #[must_use]
303    pub fn get(&self, name: &str) -> Option<&FunctionDef> {
304        self.by_name.get(name).map(|&index| &self.defs[index])
305    }
306
307    #[must_use]
308    pub fn contains(&self, name: &str) -> bool {
309        self.by_name.contains_key(name)
310    }
311
312    /// Names of all registered functions, in registration order.
313    pub fn names(&self) -> impl Iterator<Item = &str> + '_ {
314        self.defs.iter().map(|def| def.name.as_ref())
315    }
316}
317
318/// A context in which reading an [`Expr`] from the worker codec resolves
319/// compound expressions against these functions.
320impl mln_wire::Context for &Functions {
321    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
322        request.give::<Functions>(self);
323    }
324}
325
326/// The overload `index` of `name` among the functions in `r`'s context.
327pub(crate) fn decoding_overload(
328    r: &mut mln_wire::Reader<'_>,
329    name: &str,
330    index: u8,
331) -> Result<Arc<Overload>, &'static str> {
332    match r.context::<Functions>() {
333        None => Err("an expression function without functions to resolve it against"),
334        Some(functions) => match functions.get(name) {
335            None => Err("unknown expression function"),
336            Some(def) => def.overloads.get(usize::from(index)).cloned().ok_or("no such overload of a function"),
337        },
338    }
339}
340
341#[cfg(test)]
342mod tests;