Skip to main content

mln_expression/
compound_expression.rs

1// Ports include/mln/style/expression/compound_expression.hpp and
2// src/mln/style/expression/compound_expression.cpp.
3//
4// C++ derives each signature's parameter and result types from the C++
5// types of a lambda (`Signature<R(Params...)>`). Here each definition states
6// its `type::Type`s explicitly and its `apply` function evaluates the
7// arguments and unpacks the values the way `fromExpressionValue<T>` does.
8// The registry keeps the C++ definition order, which is the overload order.
9
10use crate::check_subtype::check_subtype;
11use crate::collator::Collator;
12use crate::expression::{
13    Dependency, EvaluationContext, EvaluationError, EvaluationResult, Expression, ExpressionBase,
14    Kind, children_equal, collect_dependencies, downcast, mbgl_to_expression_value,
15};
16use crate::parsing_context::{ParseResult, ParsingContext};
17use crate::type_::{self, Type};
18use crate::utf8_op_helpers::{
19    get_unicode_character_offset_on_validated_utf8, unicode_length_on_validated_utf8,
20};
21use crate::util::rgba;
22use crate::value::{ObjectType, Value, to_string, type_of};
23use maplibre_native_base::{Identifier as FeatureIdentifier, Value as MbglValue};
24use mln_conversion::Convertible;
25use mln_util::geometry::FeatureType;
26use std::sync::LazyLock;
27
28/// The parameter list of a signature: fixed types or `VarargsType`.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Params {
31    Fixed(Vec<Type>),
32    Varargs(Type),
33}
34
35type ApplyFn = fn(&EvaluationContext<'_>, &[Box<dyn Expression>]) -> EvaluationResult;
36
37/// `detail::SignatureBase`.
38pub struct SignatureBase {
39    pub result: Type,
40    pub params: Params,
41    pub name: &'static str,
42    pub dependencies: Dependency,
43    apply: ApplyFn,
44}
45
46impl SignatureBase {
47    pub fn apply(&self, params: &EvaluationContext<'_>, args: &[Box<dyn Expression>]) -> EvaluationResult {
48        (self.apply)(params, args)
49    }
50}
51
52/// Evaluates the arguments in order, stopping at the first error (both
53/// `Signature::applyImpl` and the varargs `apply`).
54fn eval_args(
55    params: &EvaluationContext<'_>,
56    args: &[Box<dyn Expression>],
57) -> Result<Vec<Value>, EvaluationError> {
58    args.iter().map(|arg| arg.evaluate(params)).collect()
59}
60
61// `*fromExpressionValue<T>(value)`: the type checker guarantees the
62// alternative.
63fn num(v: &Value) -> f64 {
64    v.as_number().expect("number argument")
65}
66fn boolean(v: &Value) -> bool {
67    v.as_bool().expect("boolean argument")
68}
69fn string(v: &Value) -> &str {
70    v.as_str().expect("string argument")
71}
72
73fn sig(
74    name: &'static str,
75    result: Type,
76    params: Params,
77    dependencies: Dependency,
78    apply: ApplyFn,
79) -> SignatureBase {
80    SignatureBase {
81        result,
82        params,
83        name,
84        dependencies,
85        apply,
86    }
87}
88
89fn fixed(types: &[Type]) -> Params {
90    Params::Fixed(types.to_vec())
91}
92
93fn feature_id_as_expression_value(params: &EvaluationContext<'_>) -> Value {
94    let feature = params.feature.expect("feature");
95    let id = feature.get_id();
96    if let FeatureIdentifier::Null = id {
97        return Value::Null;
98    }
99    identifier_to_expression_value(&id)
100}
101
102/// `toExpressionValue(mln::Value(identifier))`.
103fn identifier_to_expression_value(id: &FeatureIdentifier) -> Value {
104    match id {
105        FeatureIdentifier::Null => Value::Null,
106        FeatureIdentifier::Uint(v) => Value::Number(*v as f64),
107        FeatureIdentifier::Int(v) => Value::Number(*v as f64),
108        FeatureIdentifier::Double(v) => Value::Number(*v),
109        FeatureIdentifier::String(v) => Value::String(v.clone()),
110    }
111}
112
113fn feature_property_as_expression_value(params: &EvaluationContext<'_>, key: &str) -> Option<Value> {
114    let feature = params.feature.expect("feature");
115    feature.get_value(key).map(|p| mbgl_to_expression_value(&p))
116}
117
118fn feature_type_as_string(t: FeatureType) -> Option<String> {
119    Some(
120        match t {
121            FeatureType::Point => "Point",
122            FeatureType::LineString => "LineString",
123            FeatureType::Polygon => "Polygon",
124            FeatureType::Unknown => "Unknown",
125        }
126        .to_owned(),
127    )
128}
129
130fn feature_property_as_double(params: &EvaluationContext<'_>, key: &str) -> Option<f64> {
131    let feature = params.feature.expect("feature");
132    match feature.get_value(key)? {
133        MbglValue::Double(v) => Some(v),
134        MbglValue::Uint(v) => Some(v as f64),
135        MbglValue::Int(v) => Some(v as f64),
136        _ => None,
137    }
138}
139
140fn feature_property_as_string(params: &EvaluationContext<'_>, key: &str) -> Option<String> {
141    let feature = params.feature.expect("feature");
142    match feature.get_value(key)? {
143        MbglValue::String(v) => Some(v),
144        _ => None,
145    }
146}
147
148fn feature_id_as_double(params: &EvaluationContext<'_>) -> Option<f64> {
149    let feature = params.feature.expect("feature");
150    match feature.get_id() {
151        FeatureIdentifier::Double(v) => Some(v),
152        FeatureIdentifier::Uint(v) => Some(v as f64),
153        FeatureIdentifier::Int(v) => Some(v as f64),
154        _ => None,
155    }
156}
157
158fn feature_id_as_string(params: &EvaluationContext<'_>) -> Option<String> {
159    let feature = params.feature.expect("feature");
160    match feature.get_id() {
161        FeatureIdentifier::String(v) => Some(v),
162        _ => None,
163    }
164}
165
166fn feature_unavailable() -> EvaluationError {
167    EvaluationError::new("Feature data is unavailable in the current evaluation context.")
168}
169
170use mln_math::{fmax, fmin};
171
172/// `util::i18n::isStringInSupportedScript` (src/mln/util/i18n.cpp).
173fn is_string_in_supported_script(input: &str) -> bool {
174    fn char_in_supported_script(chr: u16) -> bool {
175        // These blocks cover common scripts that require complex text
176        // shaping, based on unicode script metadata.
177        !((0x0900..=0x0DFF).contains(&chr)
178            // Main blocks for Indic scripts and Sinhala
179            || (0x0F00..=0x109F).contains(&chr)
180            // Main blocks for Tibetan and Myanmar
181            || (0x1780..=0x17FF).contains(&chr)) // isInKhmer
182    }
183    input.encode_utf16().all(char_in_supported_script)
184}
185
186/// `platform::uppercase` / `platform::lowercase` (platform/default
187/// string_stdlib.cpp, nunicode case mapping). nunicode writes invalid UTF-8
188/// for some 4-byte results; a Rust String holds U+FFFD there (see
189/// DEVIATIONS.md).
190fn uppercase(s: &str) -> String {
191    nunicode::uppercase(s)
192}
193fn lowercase(s: &str) -> String {
194    nunicode::lowercase(s)
195}
196
197fn filter_property_number(
198    params: &EvaluationContext<'_>,
199    args: &[Box<dyn Expression>],
200    cmp: fn(f64, f64) -> bool,
201) -> EvaluationResult {
202    let a = eval_args(params, args)?;
203    let rhs = feature_property_as_double(params, string(&a[0]));
204    Ok(Value::Bool(rhs.is_some_and(|rhs| cmp(rhs, num(&a[1])))))
205}
206
207fn filter_property_string(
208    params: &EvaluationContext<'_>,
209    args: &[Box<dyn Expression>],
210    cmp: fn(&str, &str) -> bool,
211) -> EvaluationResult {
212    let a = eval_args(params, args)?;
213    let rhs = feature_property_as_string(params, string(&a[0]));
214    Ok(Value::Bool(rhs.is_some_and(|rhs| cmp(&rhs, string(&a[1])))))
215}
216
217fn filter_id_number(
218    params: &EvaluationContext<'_>,
219    args: &[Box<dyn Expression>],
220    cmp: fn(f64, f64) -> bool,
221) -> EvaluationResult {
222    let a = eval_args(params, args)?;
223    let rhs = feature_id_as_double(params);
224    Ok(Value::Bool(rhs.is_some_and(|rhs| cmp(rhs, num(&a[0])))))
225}
226
227fn filter_id_string(
228    params: &EvaluationContext<'_>,
229    args: &[Box<dyn Expression>],
230    cmp: fn(&str, &str) -> bool,
231) -> EvaluationResult {
232    let a = eval_args(params, args)?;
233    let rhs = feature_id_as_string(params);
234    Ok(Value::Bool(rhs.is_some_and(|rhs| cmp(&rhs, string(&a[0])))))
235}
236
237fn math1(
238    params: &EvaluationContext<'_>,
239    args: &[Box<dyn Expression>],
240    f: fn(f64) -> f64,
241) -> EvaluationResult {
242    let a = eval_args(params, args)?;
243    Ok(Value::Number(f(num(&a[0]))))
244}
245
246static REGISTRY: LazyLock<Vec<SignatureBase>> = LazyLock::new(|| {
247    use Dependency as D;
248    use Type as T;
249    let s = T::String;
250    let n = T::Number;
251    vec![
252        sig("e", n.clone(), fixed(&[]), D::NONE, |_, _| Ok(Value::Number(std::f64::consts::E))),
253        sig("pi", n.clone(), fixed(&[]), D::NONE, |_, _| Ok(Value::Number(std::f64::consts::PI))),
254        sig("ln2", n.clone(), fixed(&[]), D::NONE, |_, _| Ok(Value::Number(std::f64::consts::LN_2))),
255        sig("typeof", s.clone(), fixed(&[T::Value]), D::NONE, |p, args| {
256            let a = eval_args(p, args)?;
257            Ok(Value::String(type_::to_string(&type_of(&a[0]))))
258        }),
259        sig("to-rgba", T::array_n(T::Number, 4), fixed(&[T::Color]), D::NONE, |p, args| {
260            let a = eval_args(p, args)?;
261            let Value::Color(color) = &a[0] else { panic!("color argument") };
262            Ok(Value::Array(color.to_array().iter().map(|v| Value::Number(*v)).collect()))
263        }),
264        sig("rgba", T::Color, fixed(&[n.clone(), n.clone(), n.clone(), n.clone()]), D::NONE, |p, args| {
265            let a = eval_args(p, args)?;
266            Ok(Value::Color(rgba(num(&a[0]), num(&a[1]), num(&a[2]), num(&a[3]))?))
267        }),
268        sig("rgb", T::Color, fixed(&[n.clone(), n.clone(), n.clone()]), D::NONE, |p, args| {
269            let a = eval_args(p, args)?;
270            Ok(Value::Color(rgba(num(&a[0]), num(&a[1]), num(&a[2]), 1.0f32 as f64)?))
271        }),
272        sig("zoom", n.clone(), fixed(&[]), D::ZOOM, |p, _| match p.zoom {
273            None => Err(EvaluationError::new(
274                "The 'zoom' expression is unavailable in the current evaluation context.",
275            )),
276            Some(zoom) => Ok(Value::Number(zoom as f64)),
277        }),
278        sig("heatmap-density", n.clone(), fixed(&[]), D::NONE, |p, _| match p.color_ramp_parameter {
279            None => Err(EvaluationError::new(
280                "The 'heatmap-density' expression is unavailable in the current evaluation context.",
281            )),
282            Some(v) => Ok(Value::Number(v)),
283        }),
284        sig("elevation", n.clone(), fixed(&[]), D::ELEVATION, |p, _| {
285            // For color-relief, elevation is passed via colorRampParameter
286            if let Some(v) = p.color_ramp_parameter {
287                return Ok(Value::Number(v));
288            }
289            // For 3D terrain, elevation is passed directly
290            if let Some(v) = p.elevation {
291                return Ok(Value::Number(v as f64));
292            }
293            // During parsing/validation, return a valid value to allow
294            // parsing to succeed. The Dependency::Elevation flag prevents
295            // this from being optimized to a constant.
296            Ok(Value::Number(0.0))
297        }),
298        sig("line-progress", n.clone(), fixed(&[]), D::NONE, |p, _| match p.color_ramp_parameter {
299            None => Err(EvaluationError::new(
300                "The 'line-progress' expression is unavailable in the current evaluation context.",
301            )),
302            Some(v) => Ok(Value::Number(v)),
303        }),
304        sig("accumulated", T::Value, fixed(&[]), D::NONE, |p, _| match p.accumulated {
305            None => Err(EvaluationError::new(
306                "The 'accumulated' expression is unavailable in the current evaluation context.",
307            )),
308            Some(v) => Ok(mbgl_to_expression_value(v)),
309        }),
310        sig("has", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
311            let a = eval_args(p, args)?;
312            let Some(feature) = p.feature else {
313                return Err(feature_unavailable());
314            };
315            Ok(Value::Bool(feature.get_value(string(&a[0])).is_some()))
316        }),
317        sig("has", T::Boolean, fixed(&[s.clone(), T::Object]), D::FEATURE, |p, args| {
318            let a = eval_args(p, args)?;
319            let Value::Object(object) = &a[1] else { panic!("object argument") };
320            Ok(Value::Bool(object.contains_key(string(&a[0]))))
321        }),
322        sig("get", T::Value, fixed(&[s.clone()]), D::FEATURE, |p, args| {
323            let a = eval_args(p, args)?;
324            let Some(feature) = p.feature else {
325                return Err(feature_unavailable());
326            };
327            match feature.get_value(string(&a[0])) {
328                None => Ok(Value::Null),
329                Some(v) => Ok(mbgl_to_expression_value(&v)),
330            }
331        }),
332        sig("get", T::Value, fixed(&[s.clone(), T::Object]), D::FEATURE, |p, args| {
333            let a = eval_args(p, args)?;
334            let Value::Object(object) = &a[1] else { panic!("object argument") };
335            Ok(object.get(string(&a[0])).cloned().unwrap_or(Value::Null))
336        }),
337        sig("properties", T::Object, fixed(&[]), D::FEATURE, |p, _| {
338            let Some(feature) = p.feature else {
339                return Err(feature_unavailable());
340            };
341            let mut result = ObjectType::new();
342            for (k, v) in feature.get_properties() {
343                result.insert(k.clone(), mbgl_to_expression_value(v));
344            }
345            Ok(Value::Object(result))
346        }),
347        sig("geometry-type", s.clone(), fixed(&[]), D::FEATURE, |p, _| {
348            let Some(feature) = p.feature else {
349                return Err(feature_unavailable());
350            };
351            Ok(Value::String(
352                match feature.get_type() {
353                    FeatureType::Point => "Point",
354                    FeatureType::LineString => "LineString",
355                    FeatureType::Polygon => "Polygon",
356                    FeatureType::Unknown => "Unknown",
357                }
358                .to_owned(),
359            ))
360        }),
361        sig("id", T::Value, fixed(&[]), D::FEATURE, |p, _| {
362            let Some(feature) = p.feature else {
363                return Err(feature_unavailable());
364            };
365            Ok(identifier_to_expression_value(&feature.get_id()))
366        }),
367        sig("+", n.clone(), Params::Varargs(n.clone()), D::NONE, |p, args| {
368            let a = eval_args(p, args)?;
369            let mut sum = 0.0f32 as f64;
370            for arg in &a {
371                sum += num(arg);
372            }
373            Ok(Value::Number(sum))
374        }),
375        sig("-", n.clone(), fixed(&[n.clone(), n.clone()]), D::NONE, |p, args| {
376            let a = eval_args(p, args)?;
377            Ok(Value::Number(num(&a[0]) - num(&a[1])))
378        }),
379        sig("-", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| {
380            let a = eval_args(p, args)?;
381            Ok(Value::Number(-num(&a[0])))
382        }),
383        sig("*", n.clone(), Params::Varargs(n.clone()), D::NONE, |p, args| {
384            let a = eval_args(p, args)?;
385            let mut prod = 1.0f32 as f64;
386            for arg in &a {
387                prod *= num(arg);
388            }
389            Ok(Value::Number(prod))
390        }),
391        sig("/", n.clone(), fixed(&[n.clone(), n.clone()]), D::NONE, |p, args| {
392            let a = eval_args(p, args)?;
393            let (x, y) = (num(&a[0]), num(&a[1]));
394            if y == 0.0 {
395                if x == 0.0 {
396                    return Ok(Value::Number(f64::NAN));
397                }
398                if x > 0.0 {
399                    return Ok(Value::Number(f64::INFINITY));
400                }
401                if x < 0.0 {
402                    return Ok(Value::Number(f64::NEG_INFINITY));
403                }
404            }
405            Ok(Value::Number(x / y))
406        }),
407        sig("%", n.clone(), fixed(&[n.clone(), n.clone()]), D::NONE, |p, args| {
408            let a = eval_args(p, args)?;
409            // Rust's float `%` is C fmod.
410            Ok(Value::Number(num(&a[0]) % num(&a[1])))
411        }),
412        sig("^", n.clone(), fixed(&[n.clone(), n.clone()]), D::NONE, |p, args| {
413            let a = eval_args(p, args)?;
414            Ok(Value::Number(num(&a[0]).powf(num(&a[1]))))
415        }),
416        sig("sqrt", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::sqrt)),
417        sig("log10", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::log10)),
418        sig("ln", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::ln)),
419        sig("log2", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::log2)),
420        sig("sin", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::sin)),
421        sig("cos", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::cos)),
422        sig("tan", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::tan)),
423        sig("asin", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::asin)),
424        sig("acos", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::acos)),
425        sig("atan", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::atan)),
426        sig("min", n.clone(), Params::Varargs(n.clone()), D::NONE, |p, args| {
427            let a = eval_args(p, args)?;
428            let mut result = f64::INFINITY;
429            for arg in &a {
430                result = fmin(num(arg), result);
431            }
432            Ok(Value::Number(result))
433        }),
434        sig("max", n.clone(), Params::Varargs(n.clone()), D::NONE, |p, args| {
435            let a = eval_args(p, args)?;
436            let mut result = f64::NEG_INFINITY;
437            for arg in &a {
438                result = fmax(num(arg), result);
439            }
440            Ok(Value::Number(result))
441        }),
442        // C `round` rounds half away from zero, as f64::round does.
443        sig("round", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::round)),
444        sig("floor", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::floor)),
445        sig("ceil", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::ceil)),
446        sig("abs", n.clone(), fixed(&[n.clone()]), D::NONE, |p, args| math1(p, args, f64::abs)),
447        sig("!", T::Boolean, fixed(&[T::Boolean]), D::NONE, |p, args| {
448            let a = eval_args(p, args)?;
449            Ok(Value::Bool(!boolean(&a[0])))
450        }),
451        sig("is-supported-script", T::Boolean, fixed(&[s.clone()]), D::NONE, |p, args| {
452            let a = eval_args(p, args)?;
453            Ok(Value::Bool(is_string_in_supported_script(string(&a[0]))))
454        }),
455        sig("upcase", s.clone(), fixed(&[s.clone()]), D::NONE, |p, args| {
456            let a = eval_args(p, args)?;
457            Ok(Value::String(uppercase(string(&a[0]))))
458        }),
459        sig("downcase", s.clone(), fixed(&[s.clone()]), D::NONE, |p, args| {
460            let a = eval_args(p, args)?;
461            Ok(Value::String(lowercase(string(&a[0]))))
462        }),
463        sig("concat", s.clone(), Params::Varargs(T::Value), D::NONE, |p, args| {
464            let a = eval_args(p, args)?;
465            let mut s = String::new();
466            for arg in &a {
467                s += &to_string(arg);
468            }
469            Ok(Value::String(s))
470        }),
471        sig("split", T::array(s.clone()), fixed(&[s.clone(), s.clone()]), D::NONE, |p, args| {
472            let a = eval_args(p, args)?;
473            let (input, delimiter) = (string(&a[0]), string(&a[1]));
474            let mut result = Vec::new();
475
476            if delimiter.is_empty() {
477                let mut remaining = input;
478                while !remaining.is_empty() {
479                    let character_length = get_unicode_character_offset_on_validated_utf8(remaining, 1);
480                    result.push(Value::String(remaining[..character_length].to_owned()));
481                    remaining = &remaining[character_length..];
482                }
483                let _ = unicode_length_on_validated_utf8(input);
484                return Ok(Value::Array(result));
485            }
486
487            let mut start = 0;
488            loop {
489                match input[start..].find(delimiter) {
490                    None => {
491                        result.push(Value::String(input[start..].to_owned()));
492                        break;
493                    }
494                    Some(offset) => {
495                        let position = start + offset;
496                        result.push(Value::String(input[start..position].to_owned()));
497                        start = position + delimiter.len();
498                    }
499                }
500            }
501            Ok(Value::Array(result))
502        }),
503        sig("join", s.clone(), fixed(&[T::array(s.clone()), s.clone()]), D::NONE, |p, args| {
504            let a = eval_args(p, args)?;
505            let Value::Array(input) = &a[0] else { panic!("array argument") };
506            let input: Vec<&str> = input.iter().map(string).collect();
507            Ok(Value::String(input.join(string(&a[1]))))
508        }),
509        sig("resolved-locale", s.clone(), fixed(&[T::Collator]), D::NONE, |p, args| {
510            let a = eval_args(p, args)?;
511            let Value::Collator(collator) = &a[0] else { panic!("collator argument") };
512            Ok(Value::String(Collator::resolved_locale(collator)))
513        }),
514        sig("error", T::Error, fixed(&[s.clone()]), D::NONE, |p, args| {
515            let a = eval_args(p, args)?;
516            Err(EvaluationError::new(string(&a[0])))
517        }),
518        sig("feature-state", T::Value, fixed(&[s.clone()]), D::FEATURE, |p, args| {
519            let a = eval_args(p, args)?;
520            let mut state = MbglValue::Null;
521            if let Some(feature_state) = p.feature_state {
522                if let Some(v) = feature_state.get(string(&a[0])) {
523                    state = v.clone();
524                }
525            }
526            Ok(mbgl_to_expression_value(&state))
527        }),
528        sig("global-state", T::Value, fixed(&[s.clone()]), D::GLOBAL_STATE, |p, args| {
529            let a = eval_args(p, args)?;
530            let mut state = MbglValue::Null;
531            if let Some(global_state) = p.global_state {
532                if let Some(v) = global_state.get(string(&a[0])) {
533                    state = v.clone();
534                }
535            }
536            Ok(mbgl_to_expression_value(&state))
537        }),
538        // Legacy Filters
539        sig("filter-==", T::Boolean, fixed(&[s.clone(), T::Value]), D::FEATURE, |p, args| {
540            let a = eval_args(p, args)?;
541            let rhs = feature_property_as_expression_value(p, string(&a[0]));
542            Ok(Value::Bool(rhs.is_some_and(|rhs| a[1] == rhs)))
543        }),
544        sig("filter-id-==", T::Boolean, fixed(&[T::Value]), D::FEATURE, |p, args| {
545            let a = eval_args(p, args)?;
546            Ok(Value::Bool(a[0] == feature_id_as_expression_value(p)))
547        }),
548        sig("filter-type-==", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
549            let a = eval_args(p, args)?;
550            let Some(feature) = p.feature else {
551                return Ok(Value::Bool(false));
552            };
553            Ok(Value::Bool(
554                feature_type_as_string(feature.get_type()).as_deref() == Some(string(&a[0])),
555            ))
556        }),
557        sig("filter-<", T::Boolean, fixed(&[s.clone(), n.clone()]), D::FEATURE, |p, args| {
558            filter_property_number(p, args, |a, b| a < b)
559        }),
560        sig("filter-<", T::Boolean, fixed(&[s.clone(), s.clone()]), D::FEATURE, |p, args| {
561            filter_property_string(p, args, |a, b| a < b)
562        }),
563        sig("filter-id-<", T::Boolean, fixed(&[n.clone()]), D::FEATURE, |p, args| {
564            filter_id_number(p, args, |a, b| a < b)
565        }),
566        sig("filter-id-<", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
567            filter_id_string(p, args, |a, b| a < b)
568        }),
569        sig("filter->", T::Boolean, fixed(&[s.clone(), n.clone()]), D::FEATURE, |p, args| {
570            filter_property_number(p, args, |a, b| a > b)
571        }),
572        sig("filter->", T::Boolean, fixed(&[s.clone(), s.clone()]), D::FEATURE, |p, args| {
573            filter_property_string(p, args, |a, b| a > b)
574        }),
575        sig("filter-id->", T::Boolean, fixed(&[n.clone()]), D::FEATURE, |p, args| {
576            filter_id_number(p, args, |a, b| a > b)
577        }),
578        sig("filter-id->", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
579            filter_id_string(p, args, |a, b| a > b)
580        }),
581        sig("filter-<=", T::Boolean, fixed(&[s.clone(), n.clone()]), D::FEATURE, |p, args| {
582            filter_property_number(p, args, |a, b| a <= b)
583        }),
584        sig("filter-<=", T::Boolean, fixed(&[s.clone(), s.clone()]), D::FEATURE, |p, args| {
585            filter_property_string(p, args, |a, b| a <= b)
586        }),
587        sig("filter-id-<=", T::Boolean, fixed(&[n.clone()]), D::FEATURE, |p, args| {
588            filter_id_number(p, args, |a, b| a <= b)
589        }),
590        sig("filter-id-<=", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
591            filter_id_string(p, args, |a, b| a <= b)
592        }),
593        sig("filter->=", T::Boolean, fixed(&[s.clone(), n.clone()]), D::FEATURE, |p, args| {
594            filter_property_number(p, args, |a, b| a >= b)
595        }),
596        sig("filter->=", T::Boolean, fixed(&[s.clone(), s.clone()]), D::FEATURE, |p, args| {
597            filter_property_string(p, args, |a, b| a >= b)
598        }),
599        sig("filter-id->=", T::Boolean, fixed(&[n.clone()]), D::FEATURE, |p, args| {
600            filter_id_number(p, args, |a, b| a >= b)
601        }),
602        sig("filter-id->=", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
603            filter_id_string(p, args, |a, b| a >= b)
604        }),
605        sig("filter-has", T::Boolean, fixed(&[s.clone()]), D::FEATURE, |p, args| {
606            let a = eval_args(p, args)?;
607            let feature = p.feature.expect("feature");
608            Ok(Value::Bool(feature.get_value(string(&a[0])).is_some()))
609        }),
610        sig("filter-has-id", T::Boolean, fixed(&[]), D::FEATURE, |p, _| {
611            let feature = p.feature.expect("feature");
612            Ok(Value::Bool(!matches!(feature.get_id(), FeatureIdentifier::Null)))
613        }),
614        sig("filter-type-in", T::Boolean, Params::Varargs(s.clone()), D::FEATURE, |p, args| {
615            let a = eval_args(p, args)?;
616            let feature = p.feature.expect("feature");
617            let t = feature_type_as_string(feature.get_type());
618            Ok(Value::Bool(a.iter().any(|v| t.as_deref() == Some(string(v)))))
619        }),
620        sig("filter-id-in", T::Boolean, Params::Varargs(T::Value), D::FEATURE, |p, args| {
621            let a = eval_args(p, args)?;
622            let id = feature_id_as_expression_value(p);
623            Ok(Value::Bool(a.contains(&id)))
624        }),
625        sig("filter-in", T::Boolean, Params::Varargs(T::Value), D::FEATURE, |p, args| {
626            let a = eval_args(p, args)?;
627            if a.len() < 2 {
628                return Ok(Value::Bool(false));
629            }
630            let value = feature_property_as_expression_value(p, string(&a[0]));
631            Ok(Value::Bool(value.is_some_and(|value| a[1..].contains(&value))))
632        }),
633    ]
634});
635
636/// `compoundExpressionRegistry.equal_range(name)`, in definition order.
637fn definitions(name: &str) -> Vec<&'static SignatureBase> {
638    REGISTRY.iter().filter(|s| s.name == name).collect()
639}
640
641pub struct CompoundExpression {
642    base: ExpressionBase,
643    signature: &'static SignatureBase,
644    args: Vec<Box<dyn Expression>>,
645}
646
647impl CompoundExpression {
648    pub fn new(signature: &'static SignatureBase, args: Vec<Box<dyn Expression>>) -> Self {
649        CompoundExpression {
650            base: ExpressionBase::new(
651                Kind::CompoundExpression,
652                signature.result.clone(),
653                signature.dependencies | collect_dependencies(&args),
654            ),
655            signature,
656            args,
657        }
658    }
659
660    pub fn get_parameter_count(&self) -> Option<usize> {
661        match &self.signature.params {
662            Params::Varargs(_) => None,
663            Params::Fixed(p) => Some(p.len()),
664        }
665    }
666
667    pub fn exists(name: &str) -> bool {
668        REGISTRY.iter().any(|s| s.name == name)
669    }
670}
671
672impl Expression for CompoundExpression {
673    fn base(&self) -> &ExpressionBase {
674        &self.base
675    }
676
677    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
678        self.signature.apply(params, &self.args)
679    }
680
681    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
682        for e in &self.args {
683            visit(&**e);
684        }
685    }
686
687    fn equals(&self, e: &dyn Expression) -> bool {
688        if e.get_kind() == Kind::CompoundExpression {
689            let rhs = downcast::<CompoundExpression>(e).expect("CompoundExpression");
690            return self.signature.name == rhs.signature.name
691                && self.signature.result == rhs.signature.result
692                && self.signature.params == rhs.signature.params
693                && children_equal(&self.args, &rhs.args);
694        }
695        false
696    }
697
698    fn possible_outputs(&self) -> Vec<Option<Value>> {
699        vec![None]
700    }
701
702    fn get_operator(&self) -> String {
703        self.signature.name.to_owned()
704    }
705}
706
707fn expected_types_error(definitions: &[&'static SignatureBase], args: &[Box<dyn Expression>]) -> String {
708    // Only used if there are no overloads with matching number of args
709    let mut available_overloads: Vec<String> = Vec::new();
710    let mut overloads: Vec<String> = Vec::new();
711    for signature in definitions {
712        match &signature.params {
713            Params::Varargs(t) => {
714                overloads.push(format!("({})", type_::to_string(t)));
715            }
716            Params::Fixed(params) => {
717                let overload = format!(
718                    "({})",
719                    params.iter().map(type_::to_string).collect::<Vec<_>>().join(", ")
720                );
721                if params.len() == args.len() {
722                    overloads.push(overload);
723                } else {
724                    available_overloads.push(overload);
725                }
726            }
727        }
728    }
729
730    let signatures = if overloads.is_empty() {
731        available_overloads.join(" | ")
732    } else {
733        overloads.join(" | ")
734    };
735
736    let actual_types = args
737        .iter()
738        .map(|arg| type_::to_string(arg.get_type()))
739        .collect::<Vec<_>>()
740        .join(", ");
741
742    format!("Expected arguments of type {signatures}, but found ({actual_types}) instead.")
743}
744
745fn create_compound_expression_from(
746    definitions: &[&'static SignatureBase],
747    args: Vec<Box<dyn Expression>>,
748    ctx: &mut ParsingContext,
749) -> ParseResult {
750    let mut signature_context = ParsingContext::with_key(ctx.get_key());
751
752    for signature in definitions {
753        signature_context.clear_errors();
754
755        match &signature.params {
756            Params::Fixed(params) => {
757                if params.len() != args.len() {
758                    signature_context.error(format!(
759                        "Expected {} arguments, but found {} instead.",
760                        params.len(),
761                        args.len()
762                    ));
763                    continue;
764                }
765
766                for (i, arg) in args.iter().enumerate() {
767                    if let Some(err) = check_subtype(&params[i], arg.get_type()) {
768                        signature_context.error_at(err, i + 1);
769                    }
770                }
771            }
772            Params::Varargs(param_type) => {
773                for (i, arg) in args.iter().enumerate() {
774                    if let Some(err) = check_subtype(param_type, arg.get_type()) {
775                        signature_context.error_at(err, i + 1);
776                    }
777                }
778            }
779        }
780
781        if !signature_context.has_errors() {
782            return Some(Box::new(CompoundExpression::new(signature, args)));
783        }
784    }
785
786    if definitions.len() == 1 {
787        ctx.append_errors(signature_context);
788    } else {
789        ctx.error(expected_types_error(definitions, &args));
790    }
791
792    None
793}
794
795pub fn parse_compound_expression(name: &str, value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
796    debug_assert!(value.is_array() && value.array_length() > 0);
797
798    let definitions = definitions(name);
799    if definitions.is_empty() {
800        ctx.error_at(
801            format!(r#"Unknown expression "{name}". If you wanted a literal array, use ["literal", [...]]."#),
802            0,
803        );
804        return None;
805    }
806
807    let length = value.array_length();
808
809    // Per the style specification, the "global-state" property name must be
810    // a string literal, not the result of a sub-expression.
811    if name == "global-state" && length == 2 && value.array_member(1).to_string().is_none() {
812        ctx.error_at("Global state property must be a string literal.".to_owned(), 1);
813        return None;
814    }
815
816    for signature in &definitions {
817        let matches = match &signature.params {
818            Params::Varargs(_) => true,
819            Params::Fixed(p) => p.len() == length - 1,
820        };
821        if matches {
822            // First parse all the args, potentially coercing to the types
823            // expected by this overload.
824            ctx.clear_errors();
825            let mut arg_parse_failed = false;
826            let mut args = Vec::with_capacity(length - 1);
827
828            for i in 1..length {
829                let expected = match &signature.params {
830                    Params::Varargs(t) => t.clone(),
831                    Params::Fixed(params) => params[i - 1].clone(),
832                };
833
834                let Some(parsed) = ctx.parse(&value.array_member(i), i, Some(expected), None) else {
835                    arg_parse_failed = true;
836                    break;
837                };
838                args.push(parsed);
839            }
840            if arg_parse_failed {
841                // Couldn't coerce args of this overload to expected type,
842                // move on to next one.
843                continue;
844            } else {
845                let parse_with_args = create_compound_expression_from(&definitions, args, ctx);
846                if parse_with_args.is_some() {
847                    return parse_with_args;
848                }
849            }
850        }
851    }
852    // The args couldn't be coerced to any of the expected types. Parse the
853    // arguments again without expected types just for the error message
854    ctx.clear_errors();
855    let mut args = Vec::with_capacity(length - 1);
856
857    for i in 1..length {
858        let parsed = ctx.parse(&value.array_member(i), i, None, None)?;
859        args.push(parsed);
860    }
861
862    ctx.error(expected_types_error(&definitions, &args));
863
864    None
865}
866
867pub fn create_compound_expression(
868    name: &str,
869    args: Vec<Box<dyn Expression>>,
870    ctx: &mut ParsingContext,
871) -> ParseResult {
872    create_compound_expression_from(&definitions(name), args, ctx)
873}