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 [`Functions::add`] refused a function.
140#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
141pub enum RegisterError {
142    #[error("\"{0}\" is already registered")]
143    Duplicate(String),
144    #[error("\"{0}\" is an expression form, not a function")]
145    SpecialForm(String),
146    #[error("\"{0}\" needs between 1 and 256 overloads")]
147    OverloadCount(String),
148    #[error("two overloads of \"{0}\" take the same number of arguments")]
149    AmbiguousArity(String),
150    #[error("an overload of \"{0}\" evaluates to another type than its result")]
151    EvalMismatch(String),
152    #[error("\"{0}\" claims a role that another function has")]
153    RoleTaken(String),
154}
155
156/// The expression functions that parsing resolves names against.
157#[derive(Debug, Default)]
158pub struct Functions {
159    defs: Vec<FunctionDef>,
160    by_name: HashMap<Arc<str>, usize>,
161}
162
163impl Functions {
164    /// No functions.
165    #[must_use]
166    pub fn new() -> Self {
167        Functions::default()
168    }
169
170    /// The style specification's functions. Every call returns the same
171    /// value, built on the first: it never changes, so sharing it is a cache.
172    #[must_use]
173    pub fn with_builtins() -> Arc<Functions> {
174        static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
175            let mut functions = Functions::new();
176            // Into no functions, the built-ins register: no two share a name
177            // or a role, and none is an expression form.
178            let registered = register_builtin_functions(&mut functions);
179            debug_assert_eq!(registered, Ok(()));
180            Arc::new(functions)
181        });
182        Arc::clone(&BUILTINS)
183    }
184
185    /// Adds the function `name` with its overloads, in the order parsing
186    /// tries them. Fails for a name that is taken or is an expression form,
187    /// two overloads that take the same number of arguments, an evaluator of
188    /// another type than its overload's result, or a role that only one
189    /// function may have and another has.
190    #[doc(hidden)]
191    pub fn add(&mut self, name: &str, overloads: Vec<OverloadSpec>) -> Result<(), RegisterError> {
192        if is_special_form(name) {
193            return Err(RegisterError::SpecialForm(name.to_owned()));
194        }
195        if self.by_name.contains_key(name) {
196            return Err(RegisterError::Duplicate(name.to_owned()));
197        }
198        if overloads.is_empty() || overloads.len() > usize::from(u8::MAX) + 1 {
199            return Err(RegisterError::OverloadCount(name.to_owned()));
200        }
201        // Parsing parses the arguments for the one overload that takes as many
202        // as it finds, so two of one arity would leave the second unreachable.
203        for (i, a) in overloads.iter().enumerate() {
204            if overloads[..i].iter().any(|b| a.params.overlaps(&b.params)) {
205                return Err(RegisterError::AmbiguousArity(name.to_owned()));
206            }
207        }
208        if overloads.iter().any(|overload| !overload.eval.matches(&overload.result)) {
209            return Err(RegisterError::EvalMismatch(name.to_owned()));
210        }
211        for role in [Role::Zoom, Role::GlobalState] {
212            let claims = |def: &FunctionDef| def.overloads.iter().any(|overload| overload.role == role);
213            if overloads.iter().any(|overload| overload.role == role) && self.defs.iter().any(claims) {
214                return Err(RegisterError::RoleTaken(name.to_owned()));
215            }
216        }
217        let name: Arc<str> = Arc::from(name);
218        let overloads = (0u8..=u8::MAX)
219            .zip(overloads)
220            .map(|(index, spec)| {
221                Arc::new(Overload {
222                    name: Arc::clone(&name),
223                    index,
224                    result: spec.result,
225                    params: spec.params,
226                    dependencies: spec.dependencies,
227                    role: spec.role,
228                    eval: spec.eval,
229                })
230            })
231            .collect();
232        self.by_name.insert(Arc::clone(&name), self.defs.len());
233        self.defs.push(FunctionDef { name, overloads });
234        Ok(())
235    }
236
237    #[must_use]
238    pub fn get(&self, name: &str) -> Option<&FunctionDef> {
239        self.by_name.get(name).map(|&index| &self.defs[index])
240    }
241
242    pub(crate) fn contains(&self, name: &str) -> bool {
243        self.by_name.contains_key(name)
244    }
245}
246
247/// A context in which reading an [`Expr`] from the worker codec resolves
248/// compound expressions against these functions.
249impl mln_wire::Context for &Functions {
250    fn provide<'a>(&'a mut self, request: &mut mln_wire::Request<'a>) {
251        request.give::<Functions>(self);
252    }
253}
254
255/// The overload `index` of `name` among the functions in `r`'s context.
256pub(crate) fn decoding_overload(
257    r: &mut mln_wire::Reader<'_>,
258    name: &str,
259    index: u8,
260) -> Result<Arc<Overload>, &'static str> {
261    match r.context::<Functions>() {
262        None => Err("an expression function without functions to resolve it against"),
263        Some(functions) => match functions.get(name) {
264            None => Err("unknown expression function"),
265            Some(def) => def.overloads.get(usize::from(index)).cloned().ok_or("no such overload of a function"),
266        },
267    }
268}