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 enum Role {
50 Plain,
51 FeatureProperty,
54 FeatureId,
56 GeometryType,
58 Zoom,
61 GlobalState,
64}
65
66#[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#[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 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#[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#[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#[derive(Debug, Default)]
167pub struct Functions {
168 defs: Vec<FunctionDef>,
169 by_name: HashMap<Arc<str>, usize>,
170}
171
172impl Functions {
173 #[must_use]
175 pub fn new() -> Self {
176 Functions::default()
177 }
178
179 #[must_use]
182 pub fn with_builtins() -> Arc<Functions> {
183 static BUILTINS: LazyLock<Arc<Functions>> = LazyLock::new(|| {
184 let mut functions = Functions::new();
185 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 #[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 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
256impl 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
264pub(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;