Skip to main content

basemapper_core/vector/
expr.rs

1//! MapLibre style-spec values: colors, property functions, expressions, and
2//! filters (both legacy and expression syntax).
3//!
4//! Semantics follow `@maplibre/maplibre-gl-style-spec` so renders can match
5//! MapLibre GL JS pixel-for-pixel. Colors are stored premultiplied, as in the
6//! style-spec `Color` class, and are interpolated in premultiplied space.
7
8use super::mvt::{Feature, GeomType, Value};
9use serde_json::Value as Json;
10
11// ── Color ────────────────────────────────────────────────────────────────────
12
13/// Premultiplied RGBA in 0..=1, like the style-spec `Color`.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct Color {
16    pub r: f32,
17    pub g: f32,
18    pub b: f32,
19    pub a: f32,
20    /// Straight RGB of a fully transparent parsed color: the style-spec keeps
21    /// it so that interpolating from e.g. `rgba(0, 0, 255, 0)` stays blue.
22    zero_rgb: [f32; 3],
23}
24
25impl Color {
26    pub const TRANSPARENT: Color = Color::new(0.0, 0.0, 0.0, 0.0);
27    pub const BLACK: Color = Color::new(0.0, 0.0, 0.0, 1.0);
28
29    /// A color from premultiplied channels.
30    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Color {
31        Color { r, g, b, a, zero_rgb: [0.0; 3] }
32    }
33
34    pub fn parse(s: &str) -> Option<Color> {
35        let c = csscolorparser::parse(s.trim()).ok()?;
36        // Premultiply in double precision, as MapLibre's JS Color does,
37        // before the float32 conversion a uniform upload performs.
38        let a = c.a;
39        let mut out = Color::new((c.r * a) as f32, (c.g * a) as f32, (c.b * a) as f32, a as f32);
40        if a == 0.0 {
41            out.zero_rgb = [c.r as f32, c.g as f32, c.b as f32];
42        }
43        Some(out)
44    }
45
46    pub fn with_opacity(self, o: f32) -> Color {
47        Color::new(self.r * o, self.g * o, self.b * o, self.a * o)
48    }
49
50    /// Straight (unpremultiplied) RGB, as the style-spec `rgb` getter.
51    fn straight(self) -> [f64; 3] {
52        if self.a > 0.0 {
53            let a = self.a as f64;
54            [self.r as f64 / a, self.g as f64 / a, self.b as f64 / a]
55        } else {
56            self.zero_rgb.map(|v| v as f64)
57        }
58    }
59
60    /// `Color.interpolate` in `rgb` space: straight channels and alpha are
61    /// interpolated, then premultiplied.
62    fn lerp(a: Color, b: Color, t: f32) -> Color {
63        let t = t as f64;
64        let (x, y) = (a.straight(), b.straight());
65        let rgb = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * t);
66        let alpha = a.a as f64 + (b.a as f64 - a.a as f64) * t;
67        let mut out = Color::new((rgb[0] * alpha) as f32, (rgb[1] * alpha) as f32, (rgb[2] * alpha) as f32, alpha as f32);
68        if alpha == 0.0 {
69            out.zero_rgb = rgb.map(|v| v as f32);
70        }
71        out
72    }
73}
74
75// ── Values ───────────────────────────────────────────────────────────────────
76
77#[derive(Clone, Debug, PartialEq)]
78pub enum Val {
79    Null,
80    Bool(bool),
81    Num(f64),
82    Str(String),
83    Color(Color),
84    Array(Vec<Val>),
85}
86
87impl Val {
88    pub fn from_json(j: &Json) -> Val {
89        match j {
90            Json::Null => Val::Null,
91            Json::Bool(b) => Val::Bool(*b),
92            Json::Number(n) => Val::Num(n.as_f64().unwrap_or(0.0)),
93            Json::String(s) => Val::Str(s.clone()),
94            Json::Array(a) => Val::Array(a.iter().map(Val::from_json).collect()),
95            Json::Object(_) => Val::Null,
96        }
97    }
98
99    fn from_prop(v: &Value) -> Val {
100        match v {
101            Value::String(s) => Val::Str(s.clone()),
102            Value::Number(n) => Val::Num(*n),
103            Value::Bool(b) => Val::Bool(*b),
104        }
105    }
106
107    pub fn as_num(&self) -> Option<f64> {
108        match self {
109            Val::Num(n) => Some(*n),
110            _ => None,
111        }
112    }
113
114    pub fn as_str(&self) -> Option<&str> {
115        match self {
116            Val::Str(s) => Some(s),
117            _ => None,
118        }
119    }
120
121    /// Coerce to a color: Color values pass through, strings are parsed.
122    pub fn as_color(&self) -> Option<Color> {
123        match self {
124            Val::Color(c) => Some(*c),
125            Val::Str(s) => Color::parse(s),
126            _ => None,
127        }
128    }
129
130    pub fn as_num_array(&self) -> Option<Vec<f64>> {
131        match self {
132            Val::Array(a) => a.iter().map(|v| v.as_num()).collect(),
133            _ => None,
134        }
135    }
136
137    fn truthy(&self) -> bool {
138        matches!(self, Val::Bool(true))
139    }
140
141    fn to_string_val(&self) -> String {
142        match self {
143            Val::Null => String::new(),
144            Val::Bool(b) => b.to_string(),
145            Val::Num(n) => format_num(*n),
146            Val::Str(s) => s.clone(),
147            Val::Color(c) => {
148                let a = c.a.max(1e-9);
149                format!(
150                    "rgba({},{},{},{})",
151                    (c.r / a * 255.0).round(),
152                    (c.g / a * 255.0).round(),
153                    (c.b / a * 255.0).round(),
154                    c.a
155                )
156            }
157            Val::Array(_) => String::new(),
158        }
159    }
160}
161
162fn format_num(n: f64) -> String {
163    if n.fract() == 0.0 && n.abs() < 1e15 {
164        format!("{}", n as i64)
165    } else {
166        format!("{n}")
167    }
168}
169
170// ── Evaluation context ───────────────────────────────────────────────────────
171
172pub struct Ctx<'a> {
173    pub zoom: f64,
174    pub feature: Option<&'a Feature>,
175}
176
177impl Ctx<'_> {
178    fn prop(&self, key: &str) -> Val {
179        self.feature
180            .and_then(|f| f.properties.get(key))
181            .map(Val::from_prop)
182            .unwrap_or(Val::Null)
183    }
184
185    fn geom_type(&self) -> Val {
186        match self.feature.map(|f| f.geom_type) {
187            Some(GeomType::Point) => Val::Str("Point".into()),
188            Some(GeomType::LineString) => Val::Str("LineString".into()),
189            Some(GeomType::Polygon) => Val::Str("Polygon".into()),
190            None => Val::Null,
191        }
192    }
193
194    fn id(&self) -> Val {
195        self.feature.and_then(|f| f.id).map(|i| Val::Num(i as f64)).unwrap_or(Val::Null)
196    }
197}
198
199// ── Property values (constant | legacy function | expression) ───────────────
200
201/// Kind of value a property expects; affects legacy-function defaults and
202/// how string constants are coerced.
203#[derive(Clone, Copy, PartialEq, Eq, Debug)]
204pub enum Kind {
205    Number,
206    Color,
207    Array,
208    Enum,
209}
210
211/// Evaluate a paint/layout property value.
212pub fn eval_property(j: &Json, kind: Kind, ctx: &Ctx) -> Val {
213    let v = match j {
214        Json::Object(_) => eval_legacy_function(j, kind, ctx),
215        Json::Array(a) if a.first().map_or(false, |f| f.is_string()) && kind != Kind::Array => {
216            eval_expr(j, ctx)
217        }
218        Json::Array(a) if kind == Kind::Array && a.first().map_or(false, |f| f.is_string()) => {
219            // Array-valued properties: a string head means an expression
220            // (e.g. ["literal", [2, 1]] or ["step", ...]).
221            eval_expr(j, ctx)
222        }
223        _ => Val::from_json(j),
224    };
225    coerce(v, kind)
226}
227
228fn coerce(v: Val, kind: Kind) -> Val {
229    match (kind, &v) {
230        (Kind::Color, Val::Str(s)) => Color::parse(s).map(Val::Color).unwrap_or(Val::Null),
231        _ => v,
232    }
233}
234
235/// True if evaluating `j` requires feature data (so it can't be hoisted to
236/// once per layer).
237pub fn is_data_driven(j: &Json) -> bool {
238    match j {
239        Json::Object(o) => o.contains_key("property"),
240        Json::Array(a) => {
241            if let Some(Json::String(op)) = a.first() {
242                if matches!(
243                    op.as_str(),
244                    "get" | "has" | "!has" | "geometry-type" | "id" | "properties" | "feature-state"
245                ) {
246                    return true;
247                }
248            }
249            a.iter().any(is_data_driven)
250        }
251        _ => false,
252    }
253}
254
255fn interpolate_val(a: &Val, b: &Val, t: f64) -> Val {
256    match (a, b) {
257        (Val::Num(x), Val::Num(y)) => Val::Num(x + (y - x) * t),
258        (Val::Color(x), Val::Color(y)) => Val::Color(Color::lerp(*x, *y, t as f32)),
259        (Val::Str(_), _) | (_, Val::Str(_)) => {
260            match (a.as_color(), b.as_color()) {
261                (Some(x), Some(y)) => Val::Color(Color::lerp(x, y, t as f32)),
262                _ => a.clone(),
263            }
264        }
265        (Val::Array(x), Val::Array(y)) if x.len() == y.len() => {
266            Val::Array(x.iter().zip(y).map(|(p, q)| interpolate_val(p, q, t)).collect())
267        }
268        _ => a.clone(),
269    }
270}
271
272/// Exponential interpolation factor, as in the style spec.
273fn exp_factor(input: f64, base: f64, lower: f64, upper: f64) -> f64 {
274    let diff = upper - lower;
275    if diff == 0.0 {
276        return 0.0;
277    }
278    let progress = input - lower;
279    if base == 1.0 {
280        progress / diff
281    } else {
282        (base.powf(progress) - 1.0) / (base.powf(diff) - 1.0)
283    }
284}
285
286/// Unit cubic-bezier(x1, y1, x2, y2) solved for y at x = t.
287fn cubic_bezier(t: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
288    let (cx, cy) = (3.0 * x1, 3.0 * y1);
289    let (bx, by) = (3.0 * (x2 - x1) - cx, 3.0 * (y2 - y1) - cy);
290    let (ax, ay) = (1.0 - cx - bx, 1.0 - cy - by);
291    let sample_x = |s: f64| ((ax * s + bx) * s + cx) * s;
292    let sample_y = |s: f64| ((ay * s + by) * s + cy) * s;
293    let deriv_x = |s: f64| (3.0 * ax * s + 2.0 * bx) * s + cx;
294    let mut s = t;
295    for _ in 0..8 {
296        let x = sample_x(s) - t;
297        if x.abs() < 1e-6 {
298            return sample_y(s);
299        }
300        let d = deriv_x(s);
301        if d.abs() < 1e-6 {
302            break;
303        }
304        s -= x / d;
305    }
306    // Bisection fallback.
307    let (mut lo, mut hi) = (0.0, 1.0);
308    s = t;
309    for _ in 0..32 {
310        let x = sample_x(s);
311        if (x - t).abs() < 1e-6 {
312            break;
313        }
314        if t > x {
315            lo = s;
316        } else {
317            hi = s;
318        }
319        s = (lo + hi) / 2.0;
320    }
321    sample_y(s)
322}
323
324fn eval_legacy_function(j: &Json, kind: Kind, ctx: &Ctx) -> Val {
325    let stops = match j.get("stops").and_then(|s| s.as_array()) {
326        Some(s) if !s.is_empty() => s,
327        _ => return j.get("default").map(Val::from_json).unwrap_or(Val::Null),
328    };
329    let interpolatable = matches!(kind, Kind::Number | Kind::Color | Kind::Array);
330    let ftype = j
331        .get("type")
332        .and_then(|t| t.as_str())
333        .unwrap_or(if interpolatable { "exponential" } else { "interval" });
334    let base = j.get("base").and_then(|b| b.as_f64()).unwrap_or(1.0);
335
336    // Composite (zoom-and-property) functions: stop inputs are {zoom, value}.
337    let is_composite = stops[0].get(0).map_or(false, |s| s.is_object());
338    let input = if is_composite {
339        // Evaluate the property dimension per zoom stop, then interpolate on zoom.
340        let prop = j.get("property").and_then(|p| p.as_str()).unwrap_or("");
341        let pval = ctx.prop(prop);
342        let mut zooms: Vec<f64> = stops
343            .iter()
344            .filter_map(|s| s.get(0)?.get("zoom")?.as_f64())
345            .collect();
346        zooms.dedup();
347        let per_zoom: Vec<(f64, Val)> = zooms
348            .iter()
349            .map(|&z| {
350                let inner: Vec<Json> = stops
351                    .iter()
352                    .filter(|s| s.get(0).and_then(|i| i.get("zoom")).and_then(|v| v.as_f64()) == Some(z))
353                    .map(|s| Json::Array(vec![s[0]["value"].clone(), s[1].clone()]))
354                    .collect();
355                let f = serde_json::json!({ "type": ftype, "base": base, "stops": inner });
356                (z, eval_stops(&f, &pval, ftype, base, kind))
357            })
358            .collect();
359        return interpolate_stops(&per_zoom, ctx.zoom, "exponential", base);
360    } else if let Some(prop) = j.get("property").and_then(|p| p.as_str()) {
361        let v = ctx.prop(prop);
362        if ftype == "identity" {
363            return coerce(v, kind);
364        }
365        v
366    } else {
367        Val::Num(ctx.zoom)
368    };
369    let out = eval_stops(j, &input, ftype, base, kind);
370    if out == Val::Null {
371        j.get("default").map(Val::from_json).unwrap_or(Val::Null)
372    } else {
373        out
374    }
375}
376
377fn eval_stops(j: &Json, input: &Val, ftype: &str, base: f64, kind: Kind) -> Val {
378    let stops: Vec<(Val, Val)> = j["stops"]
379        .as_array()
380        .map(|a| {
381            a.iter()
382                .filter_map(|s| Some((Val::from_json(s.get(0)?), coerce(Val::from_json(s.get(1)?), kind))))
383                .collect()
384        })
385        .unwrap_or_default();
386    match ftype {
387        "categorical" => stops
388            .iter()
389            .find(|(k, _)| k == input)
390            .map(|(_, v)| v.clone())
391            .unwrap_or(Val::Null),
392        _ => {
393            let Some(x) = input.as_num() else { return Val::Null };
394            let numeric: Vec<(f64, Val)> =
395                stops.into_iter().filter_map(|(k, v)| Some((k.as_num()?, v))).collect();
396            interpolate_stops(&numeric, x, ftype, base)
397        }
398    }
399}
400
401fn interpolate_stops(stops: &[(f64, Val)], x: f64, ftype: &str, base: f64) -> Val {
402    if stops.is_empty() {
403        return Val::Null;
404    }
405    if x <= stops[0].0 {
406        return stops[0].1.clone();
407    }
408    let last = stops.len() - 1;
409    if x >= stops[last].0 {
410        return stops[last].1.clone();
411    }
412    let i = stops.iter().rposition(|(k, _)| *k <= x).unwrap_or(0);
413    if ftype == "interval" {
414        return stops[i].1.clone();
415    }
416    let (lo, hi) = (&stops[i], &stops[i + 1]);
417    let t = exp_factor(x, base, lo.0, hi.0);
418    interpolate_val(&lo.1, &hi.1, t)
419}
420
421// ── Expressions ──────────────────────────────────────────────────────────────
422
423/// An enum layout property (plain string or expression, e.g.
424/// ["step", ["zoom"], "point", 11, "line"]) evaluated at `zoom` (bucket
425/// layout properties use the tile zoom).
426pub fn layout_enum(layout: &Json, key: &str, zoom: f64) -> Option<String> {
427    match layout.get(key)? {
428        Json::String(s) => Some(s.clone()),
429        Json::Null => None,
430        j => match eval_property(j, Kind::Enum, &Ctx { zoom, feature: None }) {
431            Val::Str(s) => Some(s),
432            _ => None,
433        },
434    }
435}
436
437/// MapLibre's `typeof` names.
438fn type_name(v: &Val) -> String {
439    match v {
440        Val::Null => "null".into(),
441        Val::Bool(_) => "boolean".into(),
442        Val::Num(_) => "number".into(),
443        Val::Str(_) => "string".into(),
444        Val::Color(_) => "color".into(),
445        Val::Array(items) => {
446            let first = items.first().map(type_name);
447            match first {
448                Some(t) if items.iter().all(|x| type_name(x) == t) => format!("array<{t}, {}>", items.len()),
449                _ => "array".into(),
450            }
451        }
452    }
453}
454
455/// A value as a JSON literal expression (for `let` substitution).
456fn val_to_literal(v: &Val) -> Json {
457    match v {
458        Val::Null => Json::Null,
459        Val::Bool(b) => Json::Bool(*b),
460        Val::Num(n) => serde_json::json!(n),
461        Val::Str(s) => Json::String(s.clone()),
462        Val::Color(c) => {
463            let al = c.a.max(1e-9);
464            Json::String(format!(
465                "rgba({},{},{},{})",
466                c.r / al * 255.0,
467                c.g / al * 255.0,
468                c.b / al * 255.0,
469                c.a
470            ))
471        }
472        Val::Array(items) => serde_json::json!(["literal", Json::Array(items.iter().map(val_to_literal).collect())]),
473    }
474}
475
476/// `body` with every ["var", name] replaced by `value` (inner `let`s that
477/// rebind `name` are left alone).
478fn substitute_var(body: &Json, name: &str, value: &Json) -> Json {
479    match body {
480        Json::Array(a) => {
481            if a.len() == 2 && a[0] == "var" && a[1] == name {
482                return value.clone();
483            }
484            if a.first().map_or(false, |f| f == "let") && a[1..a.len().saturating_sub(1)].chunks(2).any(|p| p[0] == name) {
485                return body.clone();
486            }
487            Json::Array(a.iter().map(|x| substitute_var(x, name, value)).collect())
488        }
489        _ => body.clone(),
490    }
491}
492
493fn arg(a: &[Json], i: usize, ctx: &Ctx) -> Val {
494    a.get(i).map(|e| eval_expr(e, ctx)).unwrap_or(Val::Null)
495}
496
497fn num(a: &[Json], i: usize, ctx: &Ctx) -> f64 {
498    arg(a, i, ctx).as_num().unwrap_or(0.0)
499}
500
501/// Evaluate an expression. Non-array JSON evaluates to itself.
502pub fn eval_expr(j: &Json, ctx: &Ctx) -> Val {
503    let a = match j {
504        Json::Array(a) if a.first().map_or(false, |f| f.is_string()) => a,
505        _ => return Val::from_json(j),
506    };
507    let op = a[0].as_str().unwrap();
508    match op {
509        "literal" => a.get(1).map(Val::from_json).unwrap_or(Val::Null),
510        "zoom" => Val::Num(ctx.zoom),
511        "get" => {
512            if a.len() > 2 {
513                return Val::Null; // object-scoped get: not supported
514            }
515            match arg(a, 1, ctx) {
516                Val::Str(k) => ctx.prop(&k),
517                _ => Val::Null,
518            }
519        }
520        "has" => match arg(a, 1, ctx) {
521            Val::Str(k) => Val::Bool(ctx.feature.map_or(false, |f| f.properties.contains_key(&k))),
522            _ => Val::Bool(false),
523        },
524        "!has" => match arg(a, 1, ctx) {
525            Val::Str(k) => Val::Bool(!ctx.feature.map_or(false, |f| f.properties.contains_key(&k))),
526            _ => Val::Bool(true),
527        },
528        "geometry-type" => ctx.geom_type(),
529        "id" => ctx.id(),
530        "==" | "!=" => {
531            let eq = arg(a, 1, ctx) == arg(a, 2, ctx);
532            Val::Bool(if op == "==" { eq } else { !eq })
533        }
534        "<" | "<=" | ">" | ">=" => {
535            let (x, y) = (arg(a, 1, ctx), arg(a, 2, ctx));
536            let ord = match (&x, &y) {
537                (Val::Num(p), Val::Num(q)) => p.partial_cmp(q),
538                (Val::Str(p), Val::Str(q)) => Some(p.cmp(q)),
539                _ => None,
540            };
541            Val::Bool(match (op, ord) {
542                ("<", Some(o)) => o.is_lt(),
543                ("<=", Some(o)) => o.is_le(),
544                (">", Some(o)) => o.is_gt(),
545                (">=", Some(o)) => o.is_ge(),
546                _ => false,
547            })
548        }
549        "all" => Val::Bool(a[1..].iter().all(|e| eval_expr(e, ctx).truthy())),
550        "any" => Val::Bool(a[1..].iter().any(|e| eval_expr(e, ctx).truthy())),
551        "!" => Val::Bool(!arg(a, 1, ctx).truthy()),
552        "none" => Val::Bool(!a[1..].iter().any(|e| eval_expr(e, ctx).truthy())),
553        "in" => {
554            let needle = arg(a, 1, ctx);
555            match arg(a, 2, ctx) {
556                Val::Array(hay) => Val::Bool(hay.contains(&needle)),
557                Val::Str(hay) => Val::Bool(needle.as_str().map_or(false, |n| hay.contains(n))),
558                _ => Val::Bool(false),
559            }
560        }
561        "match" => {
562            let input = arg(a, 1, ctx);
563            let mut i = 2;
564            while i + 1 < a.len() {
565                let labels = &a[i];
566                let hit = match labels {
567                    Json::Array(ls) => ls.iter().any(|l| Val::from_json(l) == input),
568                    l => Val::from_json(l) == input,
569                };
570                if hit {
571                    return eval_expr(&a[i + 1], ctx);
572                }
573                i += 2;
574            }
575            a.last().map(|e| eval_expr(e, ctx)).unwrap_or(Val::Null)
576        }
577        "case" => {
578            let mut i = 1;
579            while i + 1 < a.len() {
580                if eval_expr(&a[i], ctx).truthy() {
581                    return eval_expr(&a[i + 1], ctx);
582                }
583                i += 2;
584            }
585            a.last().map(|e| eval_expr(e, ctx)).unwrap_or(Val::Null)
586        }
587        "coalesce" => a[1..]
588            .iter()
589            .map(|e| eval_expr(e, ctx))
590            .find(|v| *v != Val::Null)
591            .unwrap_or(Val::Null),
592        "step" => {
593            let x = num(a, 1, ctx);
594            let mut out = &a[2];
595            let mut i = 3;
596            while i + 1 < a.len() {
597                if a[i].as_f64().map_or(false, |s| x >= s) {
598                    out = &a[i + 1];
599                } else {
600                    break;
601                }
602                i += 2;
603            }
604            eval_expr(out, ctx)
605        }
606        "interpolate" | "interpolate-hcl" | "interpolate-lab" => {
607            let interp = a.get(1).and_then(|v| v.as_array());
608            let x = num(a, 2, ctx);
609            let stops: Vec<(f64, &Json)> = a[3..]
610                .chunks_exact(2)
611                .filter_map(|c| Some((c[0].as_f64()?, &c[1])))
612                .collect();
613            if stops.is_empty() {
614                return Val::Null;
615            }
616            if x <= stops[0].0 {
617                return eval_expr(stops[0].1, ctx);
618            }
619            let last = stops.len() - 1;
620            if x >= stops[last].0 {
621                return eval_expr(stops[last].1, ctx);
622            }
623            let i = stops.iter().rposition(|(k, _)| *k <= x).unwrap_or(0);
624            let (lo, hi) = (stops[i], stops[i + 1]);
625            let kind = interp.and_then(|v| v.first()).and_then(|v| v.as_str()).unwrap_or("linear");
626            let t = match kind {
627                "exponential" => {
628                    let base = interp.and_then(|v| v.get(1)).and_then(|v| v.as_f64()).unwrap_or(1.0);
629                    exp_factor(x, base, lo.0, hi.0)
630                }
631                "cubic-bezier" => {
632                    let c: Vec<f64> =
633                        interp.map(|v| v[1..].iter().filter_map(|n| n.as_f64()).collect()).unwrap_or_default();
634                    let lin = exp_factor(x, 1.0, lo.0, hi.0);
635                    if c.len() == 4 {
636                        cubic_bezier(lin, c[0], c[1], c[2], c[3])
637                    } else {
638                        lin
639                    }
640                }
641                _ => exp_factor(x, 1.0, lo.0, hi.0),
642            };
643            interpolate_val(&eval_expr(lo.1, ctx), &eval_expr(hi.1, ctx), t)
644        }
645        "+" => Val::Num(a[1..].iter().map(|e| eval_expr(e, ctx).as_num().unwrap_or(0.0)).sum()),
646        "*" => Val::Num(a[1..].iter().map(|e| eval_expr(e, ctx).as_num().unwrap_or(0.0)).product()),
647        "-" => {
648            if a.len() == 2 {
649                Val::Num(-num(a, 1, ctx))
650            } else {
651                Val::Num(num(a, 1, ctx) - num(a, 2, ctx))
652            }
653        }
654        "/" => Val::Num(num(a, 1, ctx) / num(a, 2, ctx)),
655        "%" => Val::Num(num(a, 1, ctx) % num(a, 2, ctx)),
656        "^" => Val::Num(num(a, 1, ctx).powf(num(a, 2, ctx))),
657        "min" => Val::Num(a[1..].iter().filter_map(|e| eval_expr(e, ctx).as_num()).fold(f64::INFINITY, f64::min)),
658        "max" => Val::Num(a[1..].iter().filter_map(|e| eval_expr(e, ctx).as_num()).fold(f64::NEG_INFINITY, f64::max)),
659        "abs" => Val::Num(num(a, 1, ctx).abs()),
660        "round" => Val::Num(num(a, 1, ctx).round()),
661        "floor" => Val::Num(num(a, 1, ctx).floor()),
662        "ceil" => Val::Num(num(a, 1, ctx).ceil()),
663        "sqrt" => Val::Num(num(a, 1, ctx).sqrt()),
664        "ln" => Val::Num(num(a, 1, ctx).ln()),
665        "log10" => Val::Num(num(a, 1, ctx).log10()),
666        "log2" => Val::Num(num(a, 1, ctx).log2()),
667        "pi" => Val::Num(std::f64::consts::PI),
668        "e" => Val::Num(std::f64::consts::E),
669        "to-number" => {
670            for e in &a[1..] {
671                match eval_expr(e, ctx) {
672                    Val::Num(n) => return Val::Num(n),
673                    Val::Str(s) => {
674                        if let Ok(n) = s.trim().parse() {
675                            return Val::Num(n);
676                        }
677                    }
678                    Val::Bool(b) => return Val::Num(if b { 1.0 } else { 0.0 }),
679                    Val::Null => return Val::Num(0.0),
680                    _ => {}
681                }
682            }
683            Val::Num(0.0)
684        }
685        "to-string" => Val::Str(arg(a, 1, ctx).to_string_val()),
686        "to-boolean" => Val::Bool(match arg(a, 1, ctx) {
687            Val::Bool(b) => b,
688            Val::Num(n) => n != 0.0 && !n.is_nan(),
689            Val::Str(s) => !s.is_empty(),
690            Val::Null => false,
691            _ => true,
692        }),
693        "to-color" => a[1..]
694            .iter()
695            .find_map(|e| eval_expr(e, ctx).as_color())
696            .map(Val::Color)
697            .unwrap_or(Val::Color(Color::BLACK)),
698        "rgb" | "rgba" => {
699            let alpha = if op == "rgba" { num(a, 4, ctx) as f32 } else { 1.0 };
700            Val::Color(Color::new(
701                num(a, 1, ctx) as f32 / 255.0 * alpha,
702                num(a, 2, ctx) as f32 / 255.0 * alpha,
703                num(a, 3, ctx) as f32 / 255.0 * alpha,
704                alpha,
705            ))
706        }
707        "concat" => Val::Str(a[1..].iter().map(|e| eval_expr(e, ctx).to_string_val()).collect()),
708        "downcase" => Val::Str(arg(a, 1, ctx).to_string_val().to_lowercase()),
709        "upcase" => Val::Str(arg(a, 1, ctx).to_string_val().to_uppercase()),
710        "length" => match arg(a, 1, ctx) {
711            Val::Str(s) => Val::Num(s.chars().count() as f64),
712            Val::Array(v) => Val::Num(v.len() as f64),
713            _ => Val::Null,
714        },
715        "number" | "string" | "boolean" | "array" | "object" => {
716            // Type assertions: pass through the first argument.
717            arg(a, if op == "array" && a.len() > 2 { a.len() - 1 } else { 1 }, ctx)
718        }
719        // ["let", name, value, ..., body]: bind by substituting the values
720        // (as literals) for ["var", name] in the body.
721        "let" if a.len() >= 2 && a.len() % 2 == 0 => {
722            let mut body = a[a.len() - 1].clone();
723            for pair in a[1..a.len() - 1].chunks(2) {
724                if let Some(name) = pair[0].as_str() {
725                    let v = val_to_literal(&eval_expr(&pair[1], ctx));
726                    body = substitute_var(&body, name, &v);
727                }
728            }
729            eval_expr(&body, ctx)
730        }
731        "let" | "var" => Val::Null, // unbound var
732        "typeof" => Val::Str(type_name(&arg(a, 1, ctx))),
733        "at" => match (arg(a, 1, ctx), arg(a, 2, ctx)) {
734            (Val::Num(i), Val::Array(v)) if i >= 0.0 => v.get(i as usize).cloned().unwrap_or(Val::Null),
735            _ => Val::Null,
736        },
737        "index-of" => {
738            let needle = arg(a, 1, ctx);
739            let from = a.get(3).map_or(0.0, |_| num(a, 3, ctx)).max(0.0) as usize;
740            match arg(a, 2, ctx) {
741                Val::Str(hay) => match &needle {
742                    Val::Str(n) => {
743                        let chars: Vec<char> = hay.chars().collect();
744                        let n: Vec<char> = n.chars().collect();
745                        let pos = (from..=chars.len().saturating_sub(n.len().max(1)))
746                            .find(|&i| chars.get(i..i + n.len()) == Some(&n[..]));
747                        Val::Num(pos.map_or(-1.0, |p| p as f64))
748                    }
749                    _ => Val::Num(-1.0),
750                },
751                Val::Array(v) => Val::Num(v.iter().skip(from).position(|x| x == &needle).map_or(-1.0, |p| (p + from) as f64)),
752                _ => Val::Num(-1.0),
753            }
754        }
755        "slice" => {
756            let start = num(a, 2, ctx);
757            let end = a.get(3).map(|_| num(a, 3, ctx));
758            let range = |len: usize| {
759                let norm = |i: f64| if i < 0.0 { (len as f64 + i).max(0.0) as usize } else { (i as usize).min(len) };
760                let (s0, e0) = (norm(start), end.map_or(len, norm));
761                (s0, e0.max(s0))
762            };
763            match arg(a, 1, ctx) {
764                Val::Str(st) => {
765                    let chars: Vec<char> = st.chars().collect();
766                    let (s0, e0) = range(chars.len());
767                    Val::Str(chars[s0..e0].iter().collect())
768                }
769                Val::Array(v) => {
770                    let (s0, e0) = range(v.len());
771                    Val::Array(v[s0..e0].to_vec())
772                }
773                _ => Val::Null,
774            }
775        }
776        "sin" => Val::Num(num(a, 1, ctx).sin()),
777        "cos" => Val::Num(num(a, 1, ctx).cos()),
778        "tan" => Val::Num(num(a, 1, ctx).tan()),
779        "asin" => Val::Num(num(a, 1, ctx).asin()),
780        "acos" => Val::Num(num(a, 1, ctx).acos()),
781        "atan" => Val::Num(num(a, 1, ctx).atan()),
782        "to-rgba" => match arg(a, 1, ctx).as_color() {
783            Some(c) => {
784                let al = c.a.max(1e-9);
785                let ch = |v: f32| Val::Num((v / al * 255.0) as f64);
786                Val::Array(vec![ch(c.r), ch(c.g), ch(c.b), Val::Num(c.a as f64)])
787            }
788            None => Val::Null,
789        },
790        "properties" => Val::Array(Vec::new()), // object values are not modelled
791        "feature-state" => Val::Null,             // no feature state in static renders
792        "image" => arg(a, 1, ctx),                // the image name
793        "format" => {
794            // Text sections concatenated (section options ignored here).
795            let mut out = String::new();
796            for e in &a[1..] {
797                if e.is_object() {
798                    continue;
799                }
800                out.push_str(&eval_expr(e, ctx).to_string_val());
801            }
802            Val::Str(out)
803        }
804        "number-format" => {
805            let n = num(a, 1, ctx);
806            let opts = a.get(2).cloned().unwrap_or(Json::Null);
807            let min = opts["min-fraction-digits"].as_u64();
808            let max = opts["max-fraction-digits"].as_u64();
809            let digits = max.or(min).unwrap_or(3) as usize;
810            let mut t = format!("{n:.digits$}");
811            if t.contains('.') {
812                let keep = min.unwrap_or(0) as usize;
813                while t.ends_with('0') && t.split('.').nth(1).map_or(0, |f| f.len()) > keep {
814                    t.pop();
815                }
816                if t.ends_with('.') {
817                    t.pop();
818                }
819            }
820            Val::Str(t)
821        }
822        "is-supported-script" => Val::Bool(true),
823        "resolved-locale" => Val::Str("en".into()),
824        "collator" => Val::Null,
825        _ => {
826            log::debug!("unsupported expression operator: {op}");
827            Val::Null
828        }
829    }
830}
831
832// ── Filters ──────────────────────────────────────────────────────────────────
833
834/// MapLibre's `isExpressionFilter`: decides legacy vs expression syntax.
835pub fn is_expression_filter(f: &Json) -> bool {
836    match f {
837        Json::Bool(_) => true,
838        Json::Array(a) if !a.is_empty() => match a[0].as_str() {
839            Some("has") => a.len() >= 2 && a[1] != "$id" && a[1] != "$type",
840            Some("in") => a.len() >= 3 && (!a[1].is_string() || a[2].is_array()),
841            Some("!in") | Some("!has") | Some("none") => false,
842            Some("==") | Some("!=") | Some(">") | Some(">=") | Some("<") | Some("<=") => {
843                a.len() != 3 || a[1].is_array() || a[2].is_array()
844            }
845            Some("any") | Some("all") => {
846                a[1..].iter().all(|x| is_expression_filter(x) || x.is_boolean())
847            }
848            _ => true,
849        },
850        _ => false,
851    }
852}
853
854/// Evaluate a layer filter (legacy or expression) against a feature.
855pub fn eval_filter(f: &Json, ctx: &Ctx) -> bool {
856    if is_expression_filter(f) {
857        eval_expr(f, ctx).truthy()
858    } else {
859        eval_legacy_filter(f, ctx)
860    }
861}
862
863fn legacy_key(key: &Json, ctx: &Ctx) -> Val {
864    match key.as_str() {
865        Some("$type") => ctx.geom_type(),
866        Some("$id") => ctx.id(),
867        Some(k) => ctx.prop(k),
868        None => Val::Null,
869    }
870}
871
872fn eval_legacy_filter(f: &Json, ctx: &Ctx) -> bool {
873    let Some(a) = f.as_array() else { return true };
874    let Some(op) = a.first().and_then(|o| o.as_str()) else { return true };
875    match op {
876        "all" => a[1..].iter().all(|x| eval_legacy_filter(x, ctx)),
877        "any" => a[1..].iter().any(|x| eval_legacy_filter(x, ctx)),
878        "none" => !a[1..].iter().any(|x| eval_legacy_filter(x, ctx)),
879        "has" => a.get(1).map_or(false, |k| legacy_key(k, ctx) != Val::Null),
880        "!has" => a.get(1).map_or(true, |k| legacy_key(k, ctx) == Val::Null),
881        "in" | "!in" => {
882            let v = a.get(1).map(|k| legacy_key(k, ctx)).unwrap_or(Val::Null);
883            let found = a[2..].iter().any(|x| Val::from_json(x) == v);
884            if op == "in" { found } else { !found }
885        }
886        "==" | "!=" | "<" | "<=" | ">" | ">=" => {
887            let v = a.get(1).map(|k| legacy_key(k, ctx)).unwrap_or(Val::Null);
888            let w = a.get(2).map(Val::from_json).unwrap_or(Val::Null);
889            match op {
890                "==" => v == w,
891                "!=" => v != w,
892                _ => {
893                    let ord = match (&v, &w) {
894                        (Val::Num(p), Val::Num(q)) => p.partial_cmp(q),
895                        (Val::Str(p), Val::Str(q)) => Some(p.cmp(q)),
896                        _ => None,
897                    };
898                    match (op, ord) {
899                        ("<", Some(o)) => o.is_lt(),
900                        ("<=", Some(o)) => o.is_le(),
901                        (">", Some(o)) => o.is_gt(),
902                        (">=", Some(o)) => o.is_ge(),
903                        _ => false,
904                    }
905                }
906            }
907        }
908        _ => true,
909    }
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915    use serde_json::json;
916    use std::collections::HashMap;
917
918    fn feat(props: &[(&str, Value)], t: GeomType) -> Feature {
919        Feature {
920            id: Some(7),
921            geom_type: t,
922            properties: props.iter().map(|(k, v)| (k.to_string(), v.clone())).collect::<HashMap<_, _>>(),
923            geometry: super::super::mvt::Geometry::Points(vec![]),
924        }
925    }
926
927    #[test]
928    fn color_parse_premultiplies() {
929        let c = Color::parse("rgba(206,217,184,0.5)").unwrap();
930        assert!((c.a - 0.5).abs() < 1e-6);
931        assert!((c.r - 206.0 / 255.0 * 0.5).abs() < 1e-4);
932        assert_eq!(Color::parse("#fff").unwrap(), Color::new(1.0, 1.0, 1.0, 1.0));
933    }
934
935    #[test]
936    fn legacy_filter_symbol_equality() {
937        let f = feat(&[("_symbol", Value::Number(0.0))], GeomType::Polygon);
938        let ctx = Ctx { zoom: 13.0, feature: Some(&f) };
939        let filt = json!(["==", "_symbol", 0]);
940        assert!(!is_expression_filter(&filt));
941        assert!(eval_filter(&filt, &ctx));
942        assert!(!eval_filter(&json!(["==", "_symbol", 1]), &ctx));
943        assert!(eval_filter(&json!(["==", "$type", "Polygon"]), &ctx));
944        assert!(eval_filter(&json!(["all", ["==", "_symbol", 0], ["!in", "x", 1, 2]]), &ctx));
945    }
946
947    #[test]
948    fn expression_filter_and_match() {
949        let f = feat(&[("class", Value::String("motorway".into()))], GeomType::LineString);
950        let ctx = Ctx { zoom: 13.0, feature: Some(&f) };
951        let filt = json!(["match", ["get", "class"], ["motorway", "trunk"], true, false]);
952        assert!(is_expression_filter(&filt));
953        assert!(eval_filter(&filt, &ctx));
954        assert!(eval_filter(&json!(["==", ["geometry-type"], "LineString"]), &ctx));
955    }
956
957    #[test]
958    fn interpolate_and_legacy_stops() {
959        let ctx = Ctx { zoom: 12.5, feature: None };
960        let e = json!(["interpolate", ["linear"], ["zoom"], 12, 1, 13, 3]);
961        assert_eq!(eval_property(&e, Kind::Number, &ctx), Val::Num(2.0));
962        let lf = json!({"stops": [[12, 1], [13, 3]]});
963        assert_eq!(eval_property(&lf, Kind::Number, &ctx), Val::Num(2.0));
964        let base2 = json!({"base": 2, "stops": [[12, 0], [13, 3]]});
965        let v = eval_property(&base2, Kind::Number, &ctx).as_num().unwrap();
966        assert!((v - 3.0 * (2f64.sqrt() - 1.0)).abs() < 1e-9);
967        let step = json!(["step", ["zoom"], 0, 12, 5, 14, 9]);
968        assert_eq!(eval_property(&step, Kind::Number, &ctx), Val::Num(5.0));
969    }
970
971    #[test]
972    fn color_interpolation_is_straight_alpha() {
973        // Transparent blue to opaque royalblue: the straight color stays
974        // between blue and royalblue (not royalblue faded).
975        let ctx = Ctx { zoom: 0.5, feature: None };
976        let e = json!(["interpolate", ["linear"], ["zoom"], 0, "rgba(0, 0, 255, 0)", 1, "rgb(64, 104, 224)"]);
977        let c = eval_property(&e, Kind::Color, &ctx).as_color().unwrap();
978        assert!((c.a - 0.5).abs() < 1e-6);
979        assert!((c.r / c.a - 32.0 / 255.0).abs() < 1e-5 && (c.b / c.a - (255.0 + 224.0) / 2.0 / 255.0).abs() < 1e-5, "{c:?}");
980    }
981
982    #[test]
983    fn color_interpolation_of_same_hue_alpha() {
984        let ctx = Ctx { zoom: 1.0, feature: None };
985        let e = json!(["interpolate", ["linear"], ["zoom"], 0, "rgba(255,0,0,0)", 2, "rgba(255,0,0,1)"]);
986        let c = eval_property(&e, Kind::Color, &ctx).as_color().unwrap();
987        assert!((c.a - 0.5).abs() < 1e-6 && (c.r - 0.5).abs() < 1e-6);
988    }
989
990    #[test]
991    fn newer_expression_operators() {
992        let f = feat(&[("admin_level", Value::Number(4.0)), ("name", Value::String("Salt Lake".into()))], GeomType::LineString);
993        let ctx = Ctx { zoom: 5.0, feature: Some(&f) };
994        let e = |j: serde_json::Value| eval_expr(&j, &ctx);
995        assert_eq!(e(json!(["typeof", ["get", "admin_level"]])), Val::Str("number".into()));
996        assert_eq!(e(json!(["typeof", ["get", "missing"]])), Val::Str("null".into()));
997        assert!(eval_filter(&json!(["==", ["typeof", ["get", "admin_level"]], "number"]), &ctx));
998        assert_eq!(e(json!(["let", "x", 2, "y", 3, ["*", ["var", "x"], ["var", "y"]]])), Val::Num(6.0));
999        assert_eq!(e(json!(["slice", ["get", "name"], 0, 4])), Val::Str("Salt".into()));
1000        assert_eq!(e(json!(["slice", ["get", "name"], -4])), Val::Str("Lake".into()));
1001        assert_eq!(e(json!(["index-of", "Lake", ["get", "name"]])), Val::Num(5.0));
1002        assert_eq!(e(json!(["at", 1, ["literal", [10, 20, 30]]])), Val::Num(20.0));
1003        assert_eq!(e(json!(["number-format", 3.14159, {"max-fraction-digits": 2}])), Val::Str("3.14".into()));
1004    }
1005}