mln_style/expression/functions/
mod.rs1pub(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#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Params {
31 Fixed(Vec<Type>),
32 Varargs(Type),
33}
34
35impl Params {
36 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub(crate) enum Role {
50 Plain,
51 FeatureProperty,
54 FeatureId,
56 GeometryType,
58 Zoom,
61 GlobalState,
64}
65
66pub trait DynamicEvaluator: Send + Sync + std::fmt::Debug {
73 fn evaluate(&self, args: &[Expr], cx: &EvaluationContext<'_>) -> EvaluationResult;
74}
75
76#[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#[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#[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 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#[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#[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#[derive(Debug, Default)]
192pub struct Functions {
193 defs: Vec<FunctionDef>,
194 by_name: HashMap<Arc<str>, usize>,
195}
196
197impl Functions {
198 #[must_use]
200 pub fn new() -> Self {
201 Functions::default()
202 }
203
204 #[must_use]
207 pub fn with_builtins() -> Arc<Functions> {
208 static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
209 let mut functions = Functions::new();
210 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 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 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 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 pub fn names(&self) -> impl Iterator<Item = &str> + '_ {
314 self.defs.iter().map(|def| def.name.as_ref())
315 }
316}
317
318impl 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
326pub(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;