rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! Typed expression engine for data-driven style evaluation.
//!
//! [`Expression<T>`] is the core type used by the style system to represent
//! values that may depend on zoom level, feature properties, feature state,
//! or combinations thereof.
//!
//! # Design
//!
//! Rather than interpreting JSON expression arrays at runtime (the MapLibre
//! approach, motivated by JavaScript's lack of a type system), Rustial uses a
//! **typed enum AST** that is:
//!
//! - **Compile-time checked** — invalid expressions cannot be constructed.
//! - **Zero-cost for constants** — `Expression::Constant(v)` is a plain value.
//! - **Branch-predictor friendly** — evaluation is a single `match` dispatch.
//! - **Rust-ergonomic** — users build expressions with constructors, not JSON.
//!
//! JSON-based style documents (MapLibre/Mapbox `.json`) are parsed into
//! `Expression<T>` by the `style-json` feature's deserialiser, making JSON
//! an input format rather than the core representation.
//!
//! # Backward compatibility
//!
//! [`StyleValue<T>`] is a type alias for `Expression<T>`, preserving all
//! existing API call-sites.

use crate::geometry::PropertyValue;
use crate::query::FeatureState;
use std::collections::HashMap;
use std::fmt;

// ---------------------------------------------------------------------------
// Evaluation contexts
// ---------------------------------------------------------------------------

/// Properties of a single feature being styled.
///
/// This is the same type as the `properties` map on [`Feature`](crate::Feature)
/// and the [`FeatureState`] map — a `HashMap<String, PropertyValue>`.
pub type FeatureProperties = HashMap<String, PropertyValue>;

/// Full evaluation context for expressions.
///
/// Carries zoom level, optional feature properties (for data-driven styling),
/// and optional feature state (for interactive hover/selection styling).
#[derive(Debug, Clone, Copy)]
pub struct ExprEvalContext<'a> {
    /// Current map zoom level (0–22+).
    pub zoom: f32,
    /// Current camera pitch in degrees.
    pub pitch: f32,
    /// Per-feature properties (from GeoJSON / MVT).
    ///
    /// `None` when evaluating at the layer level (no specific feature).
    pub properties: Option<&'a FeatureProperties>,
    /// Per-feature mutable state (hover, selected, etc.).
    ///
    /// `None` when feature state is not available.
    pub feature_state: Option<&'a FeatureState>,
}

impl<'a> ExprEvalContext<'a> {
    /// Create a zoom-only context.
    pub fn zoom_only(zoom: f32) -> Self {
        Self {
            zoom,
            pitch: 0.0,
            properties: None,
            feature_state: None,
        }
    }

    /// Create a context with feature properties for data-driven styling.
    pub fn with_feature(zoom: f32, properties: &'a FeatureProperties) -> Self {
        Self {
            zoom,
            pitch: 0.0,
            properties: Some(properties),
            feature_state: None,
        }
    }

    /// Add feature state to this context.
    pub fn and_state(mut self, state: &'a FeatureState) -> Self {
        self.feature_state = Some(state);
        self
    }

    /// Add pitch to this context.
    pub fn and_pitch(mut self, pitch: f32) -> Self {
        self.pitch = pitch;
        self
    }

    /// Look up a feature property by key.
    pub fn get_property(&self, key: &str) -> Option<&PropertyValue> {
        self.properties.and_then(|p| p.get(key))
    }

    /// Look up a feature-state value by key.
    pub fn get_state(&self, key: &str) -> Option<&PropertyValue> {
        self.feature_state.and_then(|s| s.get(key))
    }
}

// ---------------------------------------------------------------------------
// Expression<T> — the core typed AST
// ---------------------------------------------------------------------------

/// A typed expression that evaluates to a value of type `T`.
///
/// This is the core representation for all style property values. The
/// variants range from plain literals to data-driven expressions that
/// depend on feature properties, zoom level, and feature state.
///
/// # Backward compatibility
///
/// `StyleValue<T>` is a type alias for this type, so all existing code
/// that uses `StyleValue::Constant(...)`, `StyleValue::ZoomStops(...)`,
/// or `StyleValue::FeatureState { .. }` continues to work unchanged.
#[derive(Debug, Clone, PartialEq)]
pub enum Expression<T> {
    // =======================================================================
    // Original StyleValue variants (unchanged)
    // =======================================================================
    /// Constant literal value.
    Constant(T),

    /// Zoom-keyed stops with linear interpolation.
    ZoomStops(Vec<(f32, T)>),

    /// Value driven by a per-feature state key.
    FeatureState {
        /// Feature-state key to look up (e.g. `"hover"`, `"selected"`).
        key: String,
        /// Default value when the key is absent.
        fallback: T,
    },

    // =======================================================================
    // New data-driven expression variants
    // =======================================================================
    /// Read a feature property and convert to `T`.
    ///
    /// Equivalent to MapLibre `["get", "property_name"]`.
    /// Falls back to `fallback` when the property is missing or
    /// cannot be converted to `T`.
    GetProperty {
        /// Property key to read from feature properties.
        key: String,
        /// Value to use when the property is absent or incompatible.
        fallback: T,
    },

    /// Interpolate between stops based on a numeric input expression.
    ///
    /// Equivalent to MapLibre `["interpolate", ["linear"], input, z0, v0, z1, v1, ...]`.
    Interpolate {
        /// The numeric input value (typically `Expression::Zoom` or a property).
        input: Box<NumericExpression>,
        /// Ordered stop pairs `(input_value, output_value)`.
        stops: Vec<(f32, T)>,
    },

    /// Step function: returns the stop value for the greatest stop ≤ input.
    ///
    /// Equivalent to MapLibre `["step", input, default, z0, v0, z1, v1, ...]`.
    Step {
        /// The numeric input.
        input: Box<NumericExpression>,
        /// Default value when input is below all stops.
        default: T,
        /// Ordered stops `(threshold, output_value)`.
        stops: Vec<(f32, T)>,
    },

    /// Pattern match on a string input expression.
    ///
    /// Equivalent to MapLibre `["match", input, label1, val1, ..., fallback]`.
    Match {
        /// The string input to match against.
        input: Box<StringExpression>,
        /// Cases: `(label, output_value)`.
        cases: Vec<(String, T)>,
        /// Value when no case matches.
        fallback: T,
    },

    /// Conditional branches evaluated in order.
    ///
    /// Equivalent to MapLibre `["case", cond1, val1, cond2, val2, ..., fallback]`.
    Case {
        /// Branches: `(condition, output_value)`.
        branches: Vec<(BoolExpression, T)>,
        /// Value when no condition is true.
        fallback: T,
    },

    /// Return the first non-null result from a list of expressions.
    ///
    /// Equivalent to MapLibre `["coalesce", expr1, expr2, ...]`.
    Coalesce(Vec<Expression<T>>),
}

// ---------------------------------------------------------------------------
// Numeric sub-expression (untyped, evaluates to f64)
// ---------------------------------------------------------------------------

/// A numeric expression that evaluates to `f64`.
///
/// Used as the `input` for `Interpolate` and `Step` expressions, and as
/// operands for arithmetic and comparison operations.
#[derive(Debug, Clone, PartialEq)]
pub enum NumericExpression {
    /// A constant numeric literal.
    Literal(f64),
    /// The current map zoom level.
    Zoom,
    /// The current camera pitch in degrees.
    Pitch,
    /// Read a numeric feature property.
    GetProperty {
        /// Property key.
        key: String,
        /// Fallback when absent or non-numeric.
        fallback: f64,
    },
    /// Read a numeric feature-state value.
    GetState {
        /// State key.
        key: String,
        /// Fallback when absent or non-numeric.
        fallback: f64,
    },
    /// Addition: `a + b`.
    Add(Box<NumericExpression>, Box<NumericExpression>),
    /// Subtraction: `a - b`.
    Sub(Box<NumericExpression>, Box<NumericExpression>),
    /// Multiplication: `a * b`.
    Mul(Box<NumericExpression>, Box<NumericExpression>),
    /// Division: `a / b` (returns 0 on division by zero).
    Div(Box<NumericExpression>, Box<NumericExpression>),
    /// Remainder: `a % b`.
    Mod(Box<NumericExpression>, Box<NumericExpression>),
    /// Exponentiation: `a ^ b`.
    Pow(Box<NumericExpression>, Box<NumericExpression>),
    /// Absolute value.
    Abs(Box<NumericExpression>),
    /// Natural logarithm.
    Ln(Box<NumericExpression>),
    /// Square root.
    Sqrt(Box<NumericExpression>),
    /// Minimum of two values.
    Min(Box<NumericExpression>, Box<NumericExpression>),
    /// Maximum of two values.
    Max(Box<NumericExpression>, Box<NumericExpression>),
}

// ---------------------------------------------------------------------------
// String sub-expression
// ---------------------------------------------------------------------------

/// A string expression that evaluates to a `String`.
///
/// Used as the `input` for `Match` expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum StringExpression {
    /// A constant string literal.
    Literal(String),
    /// Read a string feature property.
    GetProperty {
        /// Property key.
        key: String,
        /// Fallback when absent or non-string.
        fallback: String,
    },
    /// Read a string feature-state value.
    GetState {
        /// State key.
        key: String,
        /// Fallback when absent or non-string.
        fallback: String,
    },
    /// Concatenate two strings.
    Concat(Box<StringExpression>, Box<StringExpression>),
    /// Uppercase.
    Upcase(Box<StringExpression>),
    /// Lowercase.
    Downcase(Box<StringExpression>),
}

// ---------------------------------------------------------------------------
// Boolean sub-expression
// ---------------------------------------------------------------------------

/// A boolean expression that evaluates to `bool`.
///
/// Used as the `condition` in `Case` branches.
#[derive(Debug, Clone, PartialEq)]
pub enum BoolExpression {
    /// A constant boolean literal.
    Literal(bool),
    /// Read a boolean feature property.
    GetProperty {
        /// Property key.
        key: String,
        /// Fallback when absent or non-boolean.
        fallback: bool,
    },
    /// Read a boolean feature-state value.
    GetState {
        /// State key.
        key: String,
        /// Fallback when absent or non-boolean.
        fallback: bool,
    },
    /// Check whether a feature property key exists.
    Has(String),
    /// Logical NOT.
    Not(Box<BoolExpression>),
    /// Logical AND (all must be true).
    All(Vec<BoolExpression>),
    /// Logical OR (any must be true).
    Any(Vec<BoolExpression>),
    /// Numeric equality: `a == b`.
    Eq(NumericExpression, NumericExpression),
    /// Numeric inequality: `a != b`.
    Neq(NumericExpression, NumericExpression),
    /// Greater than: `a > b`.
    Gt(NumericExpression, NumericExpression),
    /// Greater or equal: `a >= b`.
    Gte(NumericExpression, NumericExpression),
    /// Less than: `a < b`.
    Lt(NumericExpression, NumericExpression),
    /// Less or equal: `a <= b`.
    Lte(NumericExpression, NumericExpression),
    /// String equality.
    StrEq(StringExpression, StringExpression),
}

// ---------------------------------------------------------------------------
// Evaluation — NumericExpression
// ---------------------------------------------------------------------------

impl NumericExpression {
    /// Evaluate this numeric expression against a context.
    pub fn eval(&self, ctx: &ExprEvalContext<'_>) -> f64 {
        match self {
            NumericExpression::Literal(v) => *v,
            NumericExpression::Zoom => ctx.zoom as f64,
            NumericExpression::Pitch => ctx.pitch as f64,
            NumericExpression::GetProperty { key, fallback } => ctx
                .get_property(key)
                .and_then(PropertyValue::as_f64)
                .unwrap_or(*fallback),
            NumericExpression::GetState { key, fallback } => ctx
                .get_state(key)
                .and_then(PropertyValue::as_f64)
                .unwrap_or(*fallback),
            NumericExpression::Add(a, b) => a.eval(ctx) + b.eval(ctx),
            NumericExpression::Sub(a, b) => a.eval(ctx) - b.eval(ctx),
            NumericExpression::Mul(a, b) => a.eval(ctx) * b.eval(ctx),
            NumericExpression::Div(a, b) => {
                let denom = b.eval(ctx);
                if denom.abs() < f64::EPSILON {
                    0.0
                } else {
                    a.eval(ctx) / denom
                }
            }
            NumericExpression::Mod(a, b) => {
                let denom = b.eval(ctx);
                if denom.abs() < f64::EPSILON {
                    0.0
                } else {
                    a.eval(ctx) % denom
                }
            }
            NumericExpression::Pow(a, b) => a.eval(ctx).powf(b.eval(ctx)),
            NumericExpression::Abs(a) => a.eval(ctx).abs(),
            NumericExpression::Ln(a) => a.eval(ctx).ln(),
            NumericExpression::Sqrt(a) => a.eval(ctx).sqrt(),
            NumericExpression::Min(a, b) => a.eval(ctx).min(b.eval(ctx)),
            NumericExpression::Max(a, b) => a.eval(ctx).max(b.eval(ctx)),
        }
    }
}

// ---------------------------------------------------------------------------
// Evaluation — StringExpression
// ---------------------------------------------------------------------------

impl StringExpression {
    /// Evaluate this string expression against a context.
    pub fn eval(&self, ctx: &ExprEvalContext<'_>) -> String {
        match self {
            StringExpression::Literal(v) => v.clone(),
            StringExpression::GetProperty { key, fallback } => ctx
                .get_property(key)
                .and_then(PropertyValue::as_str)
                .map(|s| s.to_owned())
                .unwrap_or_else(|| fallback.clone()),
            StringExpression::GetState { key, fallback } => ctx
                .get_state(key)
                .and_then(PropertyValue::as_str)
                .map(|s| s.to_owned())
                .unwrap_or_else(|| fallback.clone()),
            StringExpression::Concat(a, b) => {
                let mut s = a.eval(ctx);
                s.push_str(&b.eval(ctx));
                s
            }
            StringExpression::Upcase(a) => a.eval(ctx).to_uppercase(),
            StringExpression::Downcase(a) => a.eval(ctx).to_lowercase(),
        }
    }
}

// ---------------------------------------------------------------------------
// Evaluation — BoolExpression
// ---------------------------------------------------------------------------

impl BoolExpression {
    /// Evaluate this boolean expression against a context.
    pub fn eval(&self, ctx: &ExprEvalContext<'_>) -> bool {
        match self {
            BoolExpression::Literal(v) => *v,
            BoolExpression::GetProperty { key, fallback } => ctx
                .get_property(key)
                .and_then(PropertyValue::as_bool)
                .unwrap_or(*fallback),
            BoolExpression::GetState { key, fallback } => ctx
                .get_state(key)
                .and_then(PropertyValue::as_bool)
                .unwrap_or(*fallback),
            BoolExpression::Has(key) => ctx
                .properties
                .map(|p| p.contains_key(key.as_str()))
                .unwrap_or(false),
            BoolExpression::Not(a) => !a.eval(ctx),
            BoolExpression::All(exprs) => exprs.iter().all(|e| e.eval(ctx)),
            BoolExpression::Any(exprs) => exprs.iter().any(|e| e.eval(ctx)),
            BoolExpression::Eq(a, b) => (a.eval(ctx) - b.eval(ctx)).abs() < f64::EPSILON,
            BoolExpression::Neq(a, b) => (a.eval(ctx) - b.eval(ctx)).abs() >= f64::EPSILON,
            BoolExpression::Gt(a, b) => a.eval(ctx) > b.eval(ctx),
            BoolExpression::Gte(a, b) => a.eval(ctx) >= b.eval(ctx),
            BoolExpression::Lt(a, b) => a.eval(ctx) < b.eval(ctx),
            BoolExpression::Lte(a, b) => a.eval(ctx) <= b.eval(ctx),
            BoolExpression::StrEq(a, b) => a.eval(ctx) == b.eval(ctx),
        }
    }
}

// ---------------------------------------------------------------------------
// Evaluation — Expression<T>
// ---------------------------------------------------------------------------

/// Helper: interpolate zoom stops using the `StyleInterpolatable` trait.
fn eval_stops<T: super::style::StyleInterpolatable>(stops: &[(f32, T)], input: f32) -> T {
    debug_assert!(!stops.is_empty(), "stop list must not be empty");
    let (first_input, first_value) = &stops[0];
    if input <= *first_input {
        return first_value.clone();
    }
    for pair in stops.windows(2) {
        let (i0, v0) = &pair[0];
        let (i1, v1) = &pair[1];
        if input <= *i1 {
            let span = (*i1 - *i0).max(f32::EPSILON);
            let t = (input - *i0) / span;
            return T::interpolate(v0, v1, t);
        }
    }
    stops.last().expect("non-empty stops").1.clone()
}

impl<T: super::style::StyleInterpolatable> Expression<T> {
    /// Evaluate with no context (uses defaults).
    pub fn evaluate(&self) -> T {
        self.eval_full(&ExprEvalContext::zoom_only(0.0))
    }

    /// Evaluate with a zoom-only legacy context.
    pub fn evaluate_with_context(&self, ctx: super::style::StyleEvalContext) -> T {
        self.eval_full(&ExprEvalContext::zoom_only(ctx.zoom))
    }

    /// Evaluate with a full legacy context (zoom + feature state).
    pub fn evaluate_with_full_context(&self, ctx: &super::style::StyleEvalContextFull<'_>) -> T {
        let expr_ctx = ExprEvalContext {
            zoom: ctx.zoom,
            pitch: 0.0,
            properties: None,
            feature_state: Some(ctx.feature_state),
        };
        self.eval_full(&expr_ctx)
    }

    /// Evaluate with feature properties for data-driven styling.
    pub fn evaluate_with_properties(&self, ctx: &ExprEvalContext<'_>) -> T {
        self.eval_full(ctx)
    }

    /// Core evaluation entry point.
    pub fn eval_full(&self, ctx: &ExprEvalContext<'_>) -> T {
        match self {
            // --- Original StyleValue variants (unchanged behavior) ---
            Expression::Constant(value) => value.clone(),

            Expression::ZoomStops(stops) => eval_stops(stops, ctx.zoom),

            Expression::FeatureState { key, fallback } => ctx
                .get_state(key)
                .and_then(|prop| T::from_feature_state_property(prop))
                .unwrap_or_else(|| fallback.clone()),

            // --- New data-driven variants ---
            Expression::GetProperty { key, fallback } => ctx
                .get_property(key)
                .and_then(|prop| T::from_feature_state_property(prop))
                .unwrap_or_else(|| fallback.clone()),

            Expression::Interpolate { input, stops } => {
                let input_val = input.eval(ctx) as f32;
                eval_stops(stops, input_val)
            }

            Expression::Step {
                input,
                default,
                stops,
            } => {
                let input_val = input.eval(ctx) as f32;
                if stops.is_empty() || input_val < stops[0].0 {
                    return default.clone();
                }
                // Find the greatest stop ≤ input_val.
                let mut result = default;
                for (threshold, value) in stops {
                    if input_val >= *threshold {
                        result = value;
                    } else {
                        break;
                    }
                }
                result.clone()
            }

            Expression::Match {
                input,
                cases,
                fallback,
            } => {
                let input_val = input.eval(ctx);
                for (label, value) in cases {
                    if *label == input_val {
                        return value.clone();
                    }
                }
                fallback.clone()
            }

            Expression::Case { branches, fallback } => {
                for (condition, value) in branches {
                    if condition.eval(ctx) {
                        return value.clone();
                    }
                }
                fallback.clone()
            }

            Expression::Coalesce(exprs) => {
                // Coalesce: for typed expressions, we evaluate each and return
                // the first result. Since all expressions always produce a
                // value (with fallbacks), we return the first one.
                // In practice, Coalesce is most useful when combined with
                // GetProperty where the fallback indicates "missing".
                if let Some(first) = exprs.first() {
                    first.eval_full(ctx)
                } else {
                    // Empty coalesce — this shouldn't happen, but return
                    // a reasonable default.
                    panic!("Expression::Coalesce requires at least one sub-expression");
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Convenience constructors
// ---------------------------------------------------------------------------

impl<T> Expression<T> {
    /// Create a feature-state-driven expression.
    pub fn feature_state_key(key: impl Into<String>, fallback: T) -> Self {
        Expression::FeatureState {
            key: key.into(),
            fallback,
        }
    }

    /// Whether this expression depends on per-feature mutable state.
    pub fn is_feature_state_driven(&self) -> bool {
        match self {
            Expression::FeatureState { .. } => true,
            Expression::Case { branches, .. } => {
                branches.iter().any(|(cond, _)| cond.uses_feature_state())
            }
            Expression::Coalesce(exprs) => exprs.iter().any(|e| e.is_feature_state_driven()),
            _ => false,
        }
    }

    /// Whether this expression depends on feature properties.
    pub fn is_data_driven(&self) -> bool {
        match self {
            Expression::GetProperty { .. } => true,
            Expression::Match { .. } => true,
            Expression::Interpolate { .. } => true,
            Expression::Step { .. } => true,
            Expression::Case { .. } => true,
            Expression::Coalesce(exprs) => exprs.iter().any(|e| e.is_data_driven()),
            _ => false,
        }
    }
}

impl<T> From<T> for Expression<T> {
    fn from(value: T) -> Self {
        Expression::Constant(value)
    }
}

impl BoolExpression {
    /// Whether this boolean expression references feature state.
    pub fn uses_feature_state(&self) -> bool {
        match self {
            BoolExpression::GetState { .. } => true,
            BoolExpression::Not(a) => a.uses_feature_state(),
            BoolExpression::All(exprs) => exprs.iter().any(|e| e.uses_feature_state()),
            BoolExpression::Any(exprs) => exprs.iter().any(|e| e.uses_feature_state()),
            _ => false,
        }
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl<T: fmt::Debug> fmt::Display for Expression<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expression::Constant(v) => write!(f, "{v:?}"),
            Expression::ZoomStops(stops) => {
                write!(f, "zoom_stops[")?;
                for (i, (z, v)) in stops.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{z}: {v:?}")?;
                }
                write!(f, "]")
            }
            Expression::FeatureState { key, fallback } => {
                write!(f, "feature_state(\"{key}\", {fallback:?})")
            }
            Expression::GetProperty { key, fallback } => {
                write!(f, "get(\"{key}\", {fallback:?})")
            }
            Expression::Interpolate { input, stops } => {
                write!(f, "interpolate({input:?}, [")?;
                for (i, (z, v)) in stops.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{z}: {v:?}")?;
                }
                write!(f, "])")
            }
            Expression::Step {
                input,
                default,
                stops,
            } => {
                write!(f, "step({input:?}, {default:?}, [")?;
                for (i, (z, v)) in stops.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{z}: {v:?}")?;
                }
                write!(f, "])")
            }
            Expression::Match {
                input,
                cases,
                fallback,
            } => {
                write!(f, "match({input:?}, [")?;
                for (i, (lbl, v)) in cases.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "\"{lbl}\": {v:?}")?;
                }
                write!(f, "], {fallback:?})")
            }
            Expression::Case { branches, fallback } => {
                write!(f, "case([")?;
                for (i, (cond, v)) in branches.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{cond:?} => {v:?}")?;
                }
                write!(f, "], {fallback:?})")
            }
            Expression::Coalesce(exprs) => {
                write!(f, "coalesce(")?;
                for (i, e) in exprs.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{e}")?;
                }
                write!(f, ")")
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Builder helpers for common patterns
// ---------------------------------------------------------------------------

impl Expression<f32> {
    /// Interpolate linearly on zoom: `["interpolate", ["linear"], ["zoom"], z0, v0, z1, v1, ...]`.
    pub fn zoom_interpolate(stops: Vec<(f32, f32)>) -> Self {
        Expression::Interpolate {
            input: Box::new(NumericExpression::Zoom),
            stops,
        }
    }

    /// Step on zoom: `["step", ["zoom"], default, z0, v0, z1, v1, ...]`.
    pub fn zoom_step(default: f32, stops: Vec<(f32, f32)>) -> Self {
        Expression::Step {
            input: Box::new(NumericExpression::Zoom),
            default,
            stops,
        }
    }

    /// Read a numeric property with fallback.
    pub fn property(key: impl Into<String>, fallback: f32) -> Self {
        Expression::GetProperty {
            key: key.into(),
            fallback,
        }
    }

    /// Interpolate linearly on a numeric feature property.
    pub fn property_interpolate(
        property: impl Into<String>,
        fallback: f64,
        stops: Vec<(f32, f32)>,
    ) -> Self {
        Expression::Interpolate {
            input: Box::new(NumericExpression::GetProperty {
                key: property.into(),
                fallback,
            }),
            stops,
        }
    }
}

impl Expression<[f32; 4]> {
    /// Interpolate colors linearly on zoom.
    pub fn zoom_interpolate(stops: Vec<(f32, [f32; 4])>) -> Self {
        Expression::Interpolate {
            input: Box::new(NumericExpression::Zoom),
            stops,
        }
    }

    /// Step on zoom for colors.
    pub fn zoom_step(default: [f32; 4], stops: Vec<(f32, [f32; 4])>) -> Self {
        Expression::Step {
            input: Box::new(NumericExpression::Zoom),
            default,
            stops,
        }
    }

    /// Match a string property to a color.
    pub fn property_match(
        property: impl Into<String>,
        cases: Vec<(String, [f32; 4])>,
        fallback: [f32; 4],
    ) -> Self {
        Expression::Match {
            input: Box::new(StringExpression::GetProperty {
                key: property.into(),
                fallback: String::new(),
            }),
            cases,
            fallback,
        }
    }
}

impl Expression<bool> {
    /// Read a boolean feature property.
    pub fn property(key: impl Into<String>, fallback: bool) -> Self {
        Expression::GetProperty {
            key: key.into(),
            fallback,
        }
    }
}

impl Expression<String> {
    /// Read a string feature property.
    pub fn property(key: impl Into<String>, fallback: impl Into<String>) -> Self {
        Expression::GetProperty {
            key: key.into(),
            fallback: fallback.into(),
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::PropertyValue;
    use crate::style::{StyleEvalContext, StyleEvalContextFull};

    // -- Backward compatibility: Constant --

    #[test]
    fn constant_evaluates_directly() {
        let expr: Expression<f32> = Expression::Constant(42.0);
        assert!((expr.evaluate() - 42.0).abs() < f32::EPSILON);
    }

    #[test]
    fn constant_via_into() {
        let expr: Expression<f32> = 42.0.into();
        assert!((expr.evaluate() - 42.0).abs() < f32::EPSILON);
    }

    // -- Backward compatibility: ZoomStops --

    #[test]
    fn zoom_stops_interpolates() {
        let expr = Expression::ZoomStops(vec![(0.0, 0.0_f32), (10.0, 100.0)]);
        let ctx = ExprEvalContext::zoom_only(5.0);
        let result = expr.eval_full(&ctx);
        assert!((result - 50.0).abs() < 0.1);
    }

    #[test]
    fn zoom_stops_clamps_below() {
        let expr = Expression::ZoomStops(vec![(5.0, 10.0_f32), (10.0, 20.0)]);
        let ctx = ExprEvalContext::zoom_only(0.0);
        assert!((expr.eval_full(&ctx) - 10.0).abs() < f32::EPSILON);
    }

    #[test]
    fn zoom_stops_clamps_above() {
        let expr = Expression::ZoomStops(vec![(5.0, 10.0_f32), (10.0, 20.0)]);
        let ctx = ExprEvalContext::zoom_only(99.0);
        assert!((expr.eval_full(&ctx) - 20.0).abs() < f32::EPSILON);
    }

    // -- Backward compatibility: FeatureState --

    #[test]
    fn feature_state_returns_fallback_without_state() {
        let expr = Expression::<f32>::feature_state_key("opacity", 0.5);
        let ctx = ExprEvalContext::zoom_only(10.0);
        assert!((expr.eval_full(&ctx) - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn feature_state_resolves_from_state_map() {
        let mut state = HashMap::new();
        state.insert("opacity".to_string(), PropertyValue::Number(0.8));
        let ctx = ExprEvalContext::zoom_only(10.0).and_state(&state);
        let expr = Expression::<f32>::feature_state_key("opacity", 0.5);
        assert!((expr.eval_full(&ctx) - 0.8).abs() < f32::EPSILON);
    }

    // -- Backward compatibility: legacy context wrappers --

    #[test]
    fn legacy_evaluate_with_context() {
        let expr = Expression::ZoomStops(vec![(0.0, 0.0_f32), (10.0, 100.0)]);
        let result = expr.evaluate_with_context(StyleEvalContext::new(5.0));
        assert!((result - 50.0).abs() < 0.1);
    }

    #[test]
    fn legacy_evaluate_with_full_context() {
        let mut state = HashMap::new();
        state.insert("opacity".to_string(), PropertyValue::Number(0.8));
        let ctx = StyleEvalContextFull::new(10.0, &state);
        let expr = Expression::<f32>::feature_state_key("opacity", 0.5);
        assert!((expr.evaluate_with_full_context(&ctx) - 0.8).abs() < f32::EPSILON);
    }

    // -- New: GetProperty --

    #[test]
    fn get_property_reads_feature_property() {
        let mut props = HashMap::new();
        props.insert("height".to_string(), PropertyValue::Number(50.0));
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr = Expression::<f32>::property("height", 0.0);
        assert!((expr.eval_full(&ctx) - 50.0).abs() < f32::EPSILON);
    }

    #[test]
    fn get_property_returns_fallback_when_missing() {
        let props = HashMap::new();
        let ctx = ExprEvalContext::with_feature(10.0, &props);
        let expr = Expression::<f32>::property("height", 10.0);
        assert!((expr.eval_full(&ctx) - 10.0).abs() < f32::EPSILON);
    }

    // -- New: Interpolate on property --

    #[test]
    fn interpolate_on_property() {
        let mut props = HashMap::new();
        props.insert("population".to_string(), PropertyValue::Number(500.0));
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr = Expression::<f32>::property_interpolate(
            "population",
            0.0,
            vec![(0.0, 2.0), (1000.0, 20.0)],
        );
        let result = expr.eval_full(&ctx);
        assert!((result - 11.0).abs() < 0.1);
    }

    // -- New: Interpolate on zoom (convenience) --

    #[test]
    fn zoom_interpolate_convenience() {
        let expr = Expression::<f32>::zoom_interpolate(vec![(0.0, 1.0), (20.0, 10.0)]);
        let ctx = ExprEvalContext::zoom_only(10.0);
        assert!((expr.eval_full(&ctx) - 5.5).abs() < 0.1);
    }

    // -- New: Step --

    #[test]
    fn step_below_first_returns_default() {
        let expr = Expression::Step {
            input: Box::new(NumericExpression::Zoom),
            default: 1.0_f32,
            stops: vec![(5.0, 2.0), (10.0, 3.0)],
        };
        let ctx = ExprEvalContext::zoom_only(3.0);
        assert!((expr.eval_full(&ctx) - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn step_between_stops() {
        let expr = Expression::Step {
            input: Box::new(NumericExpression::Zoom),
            default: 1.0_f32,
            stops: vec![(5.0, 2.0), (10.0, 3.0)],
        };
        let ctx = ExprEvalContext::zoom_only(7.0);
        assert!((expr.eval_full(&ctx) - 2.0).abs() < f32::EPSILON);
    }

    #[test]
    fn step_above_last() {
        let expr = Expression::Step {
            input: Box::new(NumericExpression::Zoom),
            default: 1.0_f32,
            stops: vec![(5.0, 2.0), (10.0, 3.0)],
        };
        let ctx = ExprEvalContext::zoom_only(15.0);
        assert!((expr.eval_full(&ctx) - 3.0).abs() < f32::EPSILON);
    }

    // -- New: Match --

    #[test]
    fn match_on_string_property() {
        let mut props = HashMap::new();
        props.insert(
            "type".to_string(),
            PropertyValue::String("residential".to_string()),
        );
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr: Expression<[f32; 4]> = Expression::property_match(
            "type",
            vec![
                ("residential".to_string(), [0.0, 0.0, 1.0, 1.0]),
                ("commercial".to_string(), [1.0, 0.0, 0.0, 1.0]),
            ],
            [0.5, 0.5, 0.5, 1.0],
        );
        let result = expr.eval_full(&ctx);
        assert_eq!(result, [0.0, 0.0, 1.0, 1.0]);
    }

    #[test]
    fn match_returns_fallback_when_no_case() {
        let mut props = HashMap::new();
        props.insert(
            "type".to_string(),
            PropertyValue::String("industrial".to_string()),
        );
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr: Expression<[f32; 4]> = Expression::property_match(
            "type",
            vec![("residential".to_string(), [0.0, 0.0, 1.0, 1.0])],
            [0.5, 0.5, 0.5, 1.0],
        );
        assert_eq!(expr.eval_full(&ctx), [0.5, 0.5, 0.5, 1.0]);
    }

    // -- New: Case --

    #[test]
    fn case_with_bool_conditions() {
        let mut props = HashMap::new();
        props.insert("height".to_string(), PropertyValue::Number(150.0));
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr: Expression<[f32; 4]> = Expression::Case {
            branches: vec![
                (
                    BoolExpression::Gt(
                        NumericExpression::GetProperty {
                            key: "height".to_string(),
                            fallback: 0.0,
                        },
                        NumericExpression::Literal(100.0),
                    ),
                    [1.0, 0.0, 0.0, 1.0], // red if height > 100
                ),
                (
                    BoolExpression::Gt(
                        NumericExpression::GetProperty {
                            key: "height".to_string(),
                            fallback: 0.0,
                        },
                        NumericExpression::Literal(50.0),
                    ),
                    [1.0, 1.0, 0.0, 1.0], // yellow if height > 50
                ),
            ],
            fallback: [0.0, 1.0, 0.0, 1.0], // green otherwise
        };
        assert_eq!(expr.eval_full(&ctx), [1.0, 0.0, 0.0, 1.0]);
    }

    #[test]
    fn case_fallback_when_no_branch_matches() {
        let props = HashMap::new();
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        let expr: Expression<f32> = Expression::Case {
            branches: vec![
                (BoolExpression::Literal(false), 10.0),
                (BoolExpression::Literal(false), 20.0),
            ],
            fallback: 99.0,
        };
        assert!((expr.eval_full(&ctx) - 99.0).abs() < f32::EPSILON);
    }

    // -- New: Numeric sub-expressions --

    #[test]
    fn numeric_arithmetic() {
        let ctx = ExprEvalContext::zoom_only(10.0);

        let add = NumericExpression::Add(
            Box::new(NumericExpression::Literal(3.0)),
            Box::new(NumericExpression::Literal(4.0)),
        );
        assert!((add.eval(&ctx) - 7.0).abs() < f64::EPSILON);

        let mul = NumericExpression::Mul(
            Box::new(NumericExpression::Zoom),
            Box::new(NumericExpression::Literal(2.0)),
        );
        assert!((mul.eval(&ctx) - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn numeric_division_by_zero() {
        let ctx = ExprEvalContext::zoom_only(10.0);
        let div = NumericExpression::Div(
            Box::new(NumericExpression::Literal(10.0)),
            Box::new(NumericExpression::Literal(0.0)),
        );
        assert!((div.eval(&ctx) - 0.0).abs() < f64::EPSILON);
    }

    // -- New: BoolExpression --

    #[test]
    fn bool_has_checks_property_existence() {
        let mut props = HashMap::new();
        props.insert(
            "name".to_string(),
            PropertyValue::String("test".to_string()),
        );
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        assert!(BoolExpression::Has("name".to_string()).eval(&ctx));
        assert!(!BoolExpression::Has("missing".to_string()).eval(&ctx));
    }

    #[test]
    fn bool_all_and_any() {
        let ctx = ExprEvalContext::zoom_only(10.0);

        assert!(BoolExpression::All(vec![
            BoolExpression::Literal(true),
            BoolExpression::Literal(true),
        ])
        .eval(&ctx));

        assert!(!BoolExpression::All(vec![
            BoolExpression::Literal(true),
            BoolExpression::Literal(false),
        ])
        .eval(&ctx));

        assert!(BoolExpression::Any(vec![
            BoolExpression::Literal(false),
            BoolExpression::Literal(true),
        ])
        .eval(&ctx));
    }

    // -- New: StringExpression --

    #[test]
    fn string_concat() {
        let ctx = ExprEvalContext::zoom_only(10.0);
        let concat = StringExpression::Concat(
            Box::new(StringExpression::Literal("hello ".to_string())),
            Box::new(StringExpression::Literal("world".to_string())),
        );
        assert_eq!(concat.eval(&ctx), "hello world");
    }

    #[test]
    fn string_upcase_downcase() {
        let ctx = ExprEvalContext::zoom_only(10.0);
        let up = StringExpression::Upcase(Box::new(StringExpression::Literal("hello".to_string())));
        assert_eq!(up.eval(&ctx), "HELLO");

        let down =
            StringExpression::Downcase(Box::new(StringExpression::Literal("HELLO".to_string())));
        assert_eq!(down.eval(&ctx), "hello");
    }

    // -- Trait flags --

    #[test]
    fn is_data_driven_flags() {
        let constant: Expression<f32> = Expression::Constant(1.0);
        assert!(!constant.is_data_driven());

        let get: Expression<f32> = Expression::GetProperty {
            key: "height".into(),
            fallback: 0.0,
        };
        assert!(get.is_data_driven());

        let interp = Expression::<f32>::zoom_interpolate(vec![(0.0, 1.0), (10.0, 5.0)]);
        assert!(interp.is_data_driven()); // has Interpolate variant
    }

    #[test]
    fn is_feature_state_driven_flags() {
        let constant: Expression<f32> = Expression::Constant(1.0);
        assert!(!constant.is_feature_state_driven());

        let driven: Expression<f32> = Expression::feature_state_key("opacity", 1.0);
        assert!(driven.is_feature_state_driven());
    }

    // -- Combined: data-driven + zoom = composite expression --

    #[test]
    fn composite_expression_zoom_and_property() {
        // Interpolate on zoom where the base value comes from a property.
        // This is equivalent to the MapLibre "composite" expression pattern.
        let mut props = HashMap::new();
        props.insert("rank".to_string(), PropertyValue::Number(5.0));
        let ctx = ExprEvalContext::with_feature(10.0, &props);

        // Step on property: rank < 3 → small, rank >= 3 → large.
        // Then the result is further modulated by a zoom interpolation.
        let expr: Expression<f32> = Expression::Case {
            branches: vec![(
                BoolExpression::Gte(
                    NumericExpression::GetProperty {
                        key: "rank".to_string(),
                        fallback: 0.0,
                    },
                    NumericExpression::Literal(3.0),
                ),
                20.0, // large text
            )],
            fallback: 10.0, // small text
        };
        assert!((expr.eval_full(&ctx) - 20.0).abs() < f32::EPSILON);
    }
}