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 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/// An overload's evaluator, typed by its result so that a number, boolean,
67/// string or color evaluates without a [`Value`](crate::expression::Value) in between.
68/// `Value` is for every other result type.
69#[derive(Clone, Copy, Debug)]
70pub enum Eval {
71    Number(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<f64>),
72    Boolean(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<bool>),
73    String(for<'e> fn(&'e [Expr], &EvaluationContext<'_>) -> EvalResult<Cow<'e, str>>),
74    Color(fn(&[Expr], &EvaluationContext<'_>) -> EvalResult<Color>),
75    Value(fn(&[Expr], &EvaluationContext<'_>) -> EvaluationResult),
76}
77
78impl Eval {
79    fn matches(&self, result: &Type) -> bool {
80        match self {
81            Eval::Number(_) => *result == Type::Number,
82            Eval::Boolean(_) => *result == Type::Boolean,
83            Eval::String(_) => *result == Type::String,
84            Eval::Color(_) => *result == Type::Color,
85            Eval::Value(_) => !matches!(result, Type::Number | Type::Boolean | Type::String | Type::Color),
86        }
87    }
88}
89
90/// An overload as [`Functions::add`] takes it.
91#[doc(hidden)]
92#[derive(Clone, Debug)]
93pub struct OverloadSpec {
94    pub result: Type,
95    pub params: Params,
96    pub dependencies: Dependency,
97    pub role: Role,
98    pub eval: Eval,
99}
100
101#[derive(Debug)]
102pub struct Overload {
103    pub(crate) name: Arc<str>,
104    /// The overload's position among its name's.
105    pub(crate) index: u8,
106    pub result: Type,
107    pub params: Params,
108    pub dependencies: Dependency,
109    pub role: Role,
110    pub eval: Eval,
111}
112
113impl Overload {
114    #[must_use]
115    pub fn name(&self) -> &str {
116        &self.name
117    }
118}
119
120/// A function: its name and its overloads, in the order parsing tries them.
121#[derive(Debug)]
122pub struct FunctionDef {
123    name: Arc<str>,
124    overloads: Box<[Arc<Overload>]>,
125}
126
127impl FunctionDef {
128    #[must_use]
129    pub fn name(&self) -> &str {
130        &self.name
131    }
132
133    #[must_use]
134    pub fn overloads(&self) -> &[Arc<Overload>] {
135        &self.overloads
136    }
137}
138
139/// Why a registration was refused: a function by [`Functions::add`], or a
140/// layer type, a source type, an extension member or a projection by the
141/// runtime's registry.
142#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
143pub enum RegisterError {
144    #[error("\"{0}\" is already registered")]
145    Duplicate(String),
146    #[error("\"{0}\" is an expression form, not a function")]
147    SpecialForm(String),
148    #[error("\"{0}\" needs between 1 and 256 overloads")]
149    OverloadCount(String),
150    #[error("two overloads of \"{0}\" take the same number of arguments")]
151    AmbiguousArity(String),
152    #[error("an overload of \"{0}\" evaluates to another type than its result")]
153    EvalMismatch(String),
154    #[error("\"{0}\" claims a role that another function has")]
155    RoleTaken(String),
156    #[error(
157        "the projection name \"{0}\" needs a colon, like \"EPSG:2193\": names without one are kept for built-in \
158         projections"
159    )]
160    ProjectionName(String),
161    #[error("the projection \"{0}\" needs a tile matrix set with a finite origin and a positive, finite extent")]
162    TileMatrixSet(String),
163}
164
165/// The expression functions that parsing resolves names against.
166#[derive(Debug, Default)]
167pub struct Functions {
168    defs: Vec<FunctionDef>,
169    by_name: HashMap<Arc<str>, usize>,
170}
171
172impl Functions {
173    /// No functions.
174    #[must_use]
175    pub fn new() -> Self {
176        Functions::default()
177    }
178
179    /// The style specification's functions. Every call returns the same
180    /// value, built on the first: it never changes, so sharing it is a cache.
181    #[must_use]
182    pub fn with_builtins() -> Arc<Functions> {
183        static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
184            let mut functions = Functions::new();
185            // Into no functions, the built-ins register: no two share a name
186            // or a role, and none is an expression form.
187            let registered = register_builtin_functions(&mut functions);
188            debug_assert_eq!(registered, Ok(()));
189            Arc::new(functions)
190        });
191        Arc::clone(&BUILTINS)
192    }
193
194    /// Adds the function `name` with its overloads, in the order parsing
195    /// tries them. Fails for a name that is taken or is an expression form,
196    /// two overloads that take the same number of arguments, an evaluator of
197    /// another type than its overload's result, or a role that only one
198    /// function may have and another has.
199    #[doc(hidden)]
200    pub fn add(&mut self, name: &str, overloads: Vec<OverloadSpec>) -> Result<(), RegisterError> {
201        if is_special_form(name) {
202            return Err(RegisterError::SpecialForm(name.to_owned()));
203        }
204        if self.by_name.contains_key(name) {
205            return Err(RegisterError::Duplicate(name.to_owned()));
206        }
207        if overloads.is_empty() || overloads.len() > usize::from(u8::MAX) + 1 {
208            return Err(RegisterError::OverloadCount(name.to_owned()));
209        }
210        // Parsing parses the arguments for the one overload that takes as many
211        // as it finds, so two of one arity would leave the second unreachable.
212        for (i, a) in overloads.iter().enumerate() {
213            if overloads[..i].iter().any(|b| a.params.overlaps(&b.params)) {
214                return Err(RegisterError::AmbiguousArity(name.to_owned()));
215            }
216        }
217        if overloads.iter().any(|overload| !overload.eval.matches(&overload.result)) {
218            return Err(RegisterError::EvalMismatch(name.to_owned()));
219        }
220        for role in [Role::Zoom, Role::GlobalState] {
221            let claims = |def: &FunctionDef| def.overloads.iter().any(|overload| overload.role == role);
222            if overloads.iter().any(|overload| overload.role == role) && self.defs.iter().any(claims) {
223                return Err(RegisterError::RoleTaken(name.to_owned()));
224            }
225        }
226        let name: Arc<str> = Arc::from(name);
227        let overloads = (0u8..=u8::MAX)
228            .zip(overloads)
229            .map(|(index, spec)| {
230                Arc::new(Overload {
231                    name: Arc::clone(&name),
232                    index,
233                    result: spec.result,
234                    params: spec.params,
235                    dependencies: spec.dependencies,
236                    role: spec.role,
237                    eval: spec.eval,
238                })
239            })
240            .collect();
241        self.by_name.insert(Arc::clone(&name), self.defs.len());
242        self.defs.push(FunctionDef { name, overloads });
243        Ok(())
244    }
245
246    #[must_use]
247    pub fn get(&self, name: &str) -> Option<&FunctionDef> {
248        self.by_name.get(name).map(|&index| &self.defs[index])
249    }
250
251    pub(crate) fn contains(&self, name: &str) -> bool {
252        self.by_name.contains_key(name)
253    }
254}
255
256/// A context in which reading an [`Expr`] from the worker codec resolves
257/// compound expressions against these functions.
258impl mln_wire::Context for &Functions {
259    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
260        request.give::<Functions>(self);
261    }
262}
263
264/// The overload `index` of `name` among the functions in `r`'s context.
265pub(crate) fn decoding_overload(
266    r: &mut mln_wire::Reader<'_>,
267    name: &str,
268    index: u8,
269) -> Result<Arc<Overload>, &'static str> {
270    match r.context::<Functions>() {
271        None => Err("an expression function without functions to resolve it against"),
272        Some(functions) => match functions.get(name) {
273            None => Err("unknown expression function"),
274            Some(def) => def.overloads.get(usize::from(index)).cloned().ok_or("no such overload of a function"),
275        },
276    }
277}
278
279#[cfg(test)]
280mod tests;