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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
#![allow(clippy::missing_docs_in_private_items)]
use indexmap::IndexMap;
use rust_decimal::Decimal;
use std::collections::HashMap;
use crate::ast::*;
use crate::convert::fel_to_json;
use crate::error::{Diagnostic, MissingTimezoneContextError};
use crate::extensions::{ExtensionCallOutcome, ExtensionFunctions, call_extension};
use crate::trace::{Trace, TraceStep};
use crate::types::*;
use super::budget::{BudgetExceededKind, EvalBudget};
use super::util::{binary_op_symbol, dec, is_eager_traceable_function, render_field_path};
/// Maximum [`Evaluator::eval`] recursion depth (stack overflow guard; left-associative chains are deep).
///
/// Kept modest so evaluation stops before the OS thread stack overflows (well above stress tests
/// that use ~48-term chains; far below LibFuzzer inputs that nested thousands of operators).
const MAX_EVAL_DEPTH: usize = 128;
/// Diagnostic code for unregistered host context references.
pub const UNBOUND_CONTEXT_REF_CODE: &str = "FEL-UNBOUND-CONTEXT";
// ── Evaluation context ──────────────────────────────────────────
/// Resolves `$` field paths, `@` context, MIP queries, repeat navigation, and clock for FEL builtins.
pub trait Environment {
/// Resolve `$a.b` style path as segment list (`["a","b"]`); empty slice is bare `$`.
fn resolve_field(&self, segments: &[String]) -> Value;
/// Resolve `@name`, `@name('arg')`, `@name.tail`.
fn resolve_context(&self, name: &str, arg: Option<&str>, tail: &[String]) -> Value;
/// `valid($path)` — default `true` when not overridden.
fn mip_valid(&self, _path: &[String]) -> Value {
Value::Boolean(true)
}
/// `relevant($path)` — default `true`.
fn mip_relevant(&self, _path: &[String]) -> Value {
Value::Boolean(true)
}
/// `readonly($path)` — default `false`.
fn mip_readonly(&self, _path: &[String]) -> Value {
Value::Boolean(false)
}
/// `required($path)` — default `false`.
fn mip_required(&self, _path: &[String]) -> Value {
Value::Boolean(false)
}
/// `prev()` in repeat scope — default null.
fn repeat_prev(&self) -> Value {
Value::Null
}
/// `next()` in repeat scope — default null.
fn repeat_next(&self) -> Value {
Value::Null
}
/// `parent()` in repeat scope — default null.
fn repeat_parent(&self) -> Value {
Value::Null
}
/// Calendar date for `today()` per ADR 0069 D-6 — hosts MUST configure a
/// timezone-equivalent clock or return [`MissingTimezoneContextError`].
///
/// The default impl returns
/// [`MissingTimezoneContextError::not_configured`]; this is deliberate —
/// no implementation MAY return a silent UTC fallback. The evaluator
/// translates `Err(_)` into a [`crate::error::DiagnosticKind::MissingTimezoneContext`]
/// diagnostic on every call site.
fn current_date(&self) -> Result<Date, MissingTimezoneContextError> {
Err(MissingTimezoneContextError::not_configured())
}
/// Date-time for `now()` per ADR 0069 D-6 — see [`Self::current_date`] for
/// the contract. Hosts that override one method typically override both;
/// returning different timezone contexts from the two paths is a host bug.
fn current_datetime(&self) -> Result<Date, MissingTimezoneContextError> {
Err(MissingTimezoneContextError::not_configured())
}
/// Active locale code for `locale()` — default none (returns null).
fn locale(&self) -> Option<&str> {
None
}
/// The Locale document's pattern for a `formatDate` style (`short` … `full`), when the
/// active locale authored one (Locale spec §2.4). Default none: built-in rendering.
fn date_format(&self, _style: &str) -> Option<&str> {
None
}
/// Runtime metadata value for `runtimeMeta(key)` — default null.
fn runtime_meta(&self, _key: &str) -> Value {
Value::Null
}
}
/// Classifies a host context binding root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextBindingKind {
/// Scalar or otherwise indivisible value; dot traversal is rejected.
Value,
/// Object-like root; the evaluator owns dot-segment traversal.
Object,
/// Callable context binding; the catalog materializes its return value.
Function,
}
/// Materialized host context binding returned by a catalog.
#[derive(Debug, Clone, PartialEq)]
pub struct ContextBinding {
/// Binding kind declared by the host catalog.
pub kind: ContextBindingKind,
/// Root FEL value supplied by the host catalog.
pub value: Value,
}
impl ContextBinding {
/// Creates a value-kind host binding.
pub fn value(value: Value) -> Self {
Self {
kind: ContextBindingKind::Value,
value,
}
}
/// Creates an object-kind host binding.
pub fn object(value: Value) -> Self {
Self {
kind: ContextBindingKind::Object,
value,
}
}
/// Creates a function-kind host binding result.
pub fn function(value: Value) -> Self {
Self {
kind: ContextBindingKind::Function,
value,
}
}
}
/// Resolves host-supplied `@name` context bindings.
///
/// The catalog returns the binding root only. Dot-segment traversal is performed
/// by the evaluator so every host receives the same path behavior.
pub trait ContextBindingCatalog {
/// Returns the declared kind for `name`, or `None` when unregistered.
fn binding_kind(&self, name: &str) -> Option<ContextBindingKind>;
/// Resolves the binding root for `name`.
///
/// Function bindings receive the optional string literal from `@name('arg')`.
/// Value and object bindings receive `None`.
fn resolve(&self, name: &str, arg: Option<&str>) -> Option<Value>;
}
/// No-op host context binding catalog.
#[derive(Default, Debug, Clone, Copy)]
pub struct EmptyCatalog;
impl ContextBindingCatalog for EmptyCatalog {
fn binding_kind(&self, _name: &str) -> Option<ContextBindingKind> {
None
}
fn resolve(&self, _name: &str, _arg: Option<&str>) -> Option<Value> {
None
}
}
/// Flat `HashMap` environment for tests and simple hosts (no `@` context; fixed clock in default impl).
pub struct MapEnvironment {
/// Top-level and nested values (nested via object values); keys may be dotted.
pub fields: HashMap<String, Value>,
/// Clock source for `today()` / `now()` lookups.
pub current_datetime: Option<Date>,
}
impl MapEnvironment {
/// Empty field map.
pub fn new() -> Self {
Self {
fields: HashMap::new(),
current_datetime: Some(Date::DateTime {
year: 2026,
month: 3,
day: 20,
hour: 0,
minute: 0,
second: 0,
}),
}
}
/// Pre-populated field map.
pub fn with_fields(fields: HashMap<String, Value>) -> Self {
Self {
fields,
..Self::new()
}
}
/// Override the environment clock used by `today()` and `now()`.
///
/// Passing `None` removes the clock so calls to `today()` / `now()`
/// surface `MissingTimezoneContextError::NotConfigured`. Prefer the
/// readable [`MapEnvironment::without_clock`] constructor at call
/// sites that intend to exercise the no-clock contract.
pub fn with_current_datetime(mut self, current_datetime: Option<Date>) -> Self {
self.current_datetime = current_datetime;
self
}
/// Remove the environment clock so `today()` / `now()` produce the
/// `MissingTimezoneContext` diagnostic. Read-aloud companion to
/// [`MapEnvironment::with_current_datetime`] for the `None` case.
pub fn without_clock(self) -> Self {
self.with_current_datetime(None)
}
}
/// Empty `MapEnvironment` (delegates to [`MapEnvironment::new`]).
impl Default for MapEnvironment {
fn default() -> Self {
Self::new()
}
}
/// Default clock: pinned to 2026-03-20 for deterministic tests/examples; resolves nested fields by dotted key or object walk.
impl Environment for MapEnvironment {
fn resolve_field(&self, segments: &[String]) -> Value {
if segments.is_empty() {
return Value::Null;
}
let key = segments.join(".");
if let Some(val) = self.fields.get(&key) {
return val.clone();
}
// Walk nested objects
let mut current = match self.fields.get(&segments[0]) {
Some(v) => v.clone(),
None => return Value::Null,
};
for seg in &segments[1..] {
match ¤t {
Value::Object(entries) => match entries.get(seg.as_str()) {
Some(v) => current = v.clone(),
None => return Value::Null,
},
_ => return Value::Null,
}
}
current
}
fn resolve_context(&self, _name: &str, _arg: Option<&str>, _tail: &[String]) -> Value {
Value::Null
}
fn current_date(&self) -> Result<Date, MissingTimezoneContextError> {
match &self.current_datetime {
Some(Date::Date { year, month, day }) => Ok(Date::Date {
year: *year,
month: *month,
day: *day,
}),
Some(Date::DateTime {
year, month, day, ..
}) => Ok(Date::Date {
year: *year,
month: *month,
day: *day,
}),
None => Err(MissingTimezoneContextError::not_configured()),
}
}
fn current_datetime(&self) -> Result<Date, MissingTimezoneContextError> {
self.current_datetime
.clone()
.ok_or_else(MissingTimezoneContextError::not_configured)
}
}
/// Result of evaluation: a value plus any accumulated diagnostics.
#[derive(Debug, Clone)]
pub struct EvalResult {
/// Computed value (may be null after errors).
pub value: Value,
/// Non-fatal issues (undefined functions, type errors, etc.).
pub diagnostics: Vec<Diagnostic>,
}
/// Tree-walking evaluator with `let` scopes and diagnostic collection.
pub struct Evaluator<'a> {
pub(super) env: &'a dyn Environment,
pub(super) extensions: Option<&'a dyn ExtensionFunctions>,
pub(super) context_bindings: Option<&'a dyn ContextBindingCatalog>,
pub(super) diagnostics: Vec<Diagnostic>,
pub(super) let_scopes: Vec<HashMap<String, Value>>,
/// Optional evaluation trace. `None` on the hot path, `Some` when the
/// caller passed [`EvaluatorOptions::trace`] to [`evaluate_with`].
pub(super) trace: Option<Trace>,
/// Stack of per-call argument caches used by traceable eager functions.
call_arg_cache_stack: Vec<CallArgCache>,
/// Nesting depth for `eval` recursion (capped at [`MAX_EVAL_DEPTH`]).
eval_depth: usize,
/// Resource budget for this evaluation run.
budget: EvalBudget,
/// Incrementing step counter checked against [`EvalBudget::max_steps`].
step_count: u64,
/// Best-effort allocation counter checked against [`EvalBudget::max_alloc_bytes`].
alloc_bytes: u64,
/// Set on first budget breach to suppress redundant diagnostics.
budget_breached: bool,
}
/// Memoizes evaluated argument [`Value`]s for one traced eager builtin call.
///
/// [`Self::args_ptr`] equals [`slice::as_ptr`] on the `&[Expr]` argument slice passed into
/// `eval_function`. That slice is borrowed from the caller's [`Expr::FunctionCall`] and remains
/// stable for the whole call; the evaluator must not hold this cache across a point where that
/// `Vec` could reallocate. Teardown asserts the pointer still matches the slice being finalized.
#[derive(Debug)]
struct CallArgCache {
args_ptr: *const Expr,
values: Vec<Option<Value>>,
}
/// Configuration for an evaluation run.
pub struct EvaluatorOptions<'a> {
/// Optional trace sink — when `Some`, the evaluator records structured steps into this trace.
pub trace: Option<&'a mut Trace>,
/// Optional host extension functions (Core §3.12) for resolving unknown function names.
pub extensions: Option<&'a dyn ExtensionFunctions>,
/// Resource budget for this evaluation run.
pub budget: EvalBudget,
}
impl Default for EvaluatorOptions<'_> {
fn default() -> Self {
Self {
trace: None,
extensions: None,
budget: EvalBudget::unlimited(),
}
}
}
fn is_grammar_reserved_context(name: &str) -> bool {
matches!(name, "current" | "index" | "count" | "instance")
}
fn context_tail_path(tail: &[String]) -> Vec<PathSegment> {
tail.iter().cloned().map(PathSegment::Dot).collect()
}
fn split_context_env_path(path: &[PathSegment]) -> (Vec<String>, &[PathSegment]) {
for (index, segment) in path.iter().enumerate() {
if !matches!(segment, PathSegment::Dot(_)) {
let prefix = path[..index]
.iter()
.filter_map(|segment| match segment {
PathSegment::Dot(name) => Some(name.clone()),
_ => None,
})
.collect();
return (prefix, &path[index..]);
}
}
let prefix = path
.iter()
.filter_map(|segment| match segment {
PathSegment::Dot(name) => Some(name.clone()),
_ => None,
})
.collect();
(prefix, &[])
}
/// Evaluate an expression against an environment (no budget, no trace, no extensions).
pub fn evaluate(expr: &Expr, env: &dyn Environment) -> EvalResult {
evaluate_with(expr, env, EvaluatorOptions::default())
}
/// Evaluate with full configuration via [`EvaluatorOptions`].
pub fn evaluate_with(expr: &Expr, env: &dyn Environment, options: EvaluatorOptions) -> EvalResult {
evaluate_configured(expr, env, options, None)
}
/// Evaluate with a host-supplied context binding catalog.
///
/// This sibling entry point preserves the [`EvaluatorOptions`] struct shape for
/// existing callers while enabling FEL §6.3 catalog-aware evaluation.
pub fn evaluate_with_catalog<'a>(
expr: &Expr,
env: &dyn Environment,
options: EvaluatorOptions<'a>,
catalog: &'a dyn ContextBindingCatalog,
) -> EvalResult {
evaluate_configured(expr, env, options, Some(catalog))
}
fn evaluate_configured<'a>(
expr: &Expr,
env: &dyn Environment,
mut options: EvaluatorOptions<'a>,
context_bindings: Option<&'a dyn ContextBindingCatalog>,
) -> EvalResult {
let caller_trace = options.trace.take();
let wants_trace = caller_trace.is_some();
let mut evaluator = Evaluator {
env,
extensions: options.extensions,
context_bindings,
diagnostics: Vec::new(),
let_scopes: Vec::new(),
trace: if wants_trace {
Some(Trace::new())
} else {
None
},
call_arg_cache_stack: Vec::new(),
eval_depth: 0,
budget: options.budget,
step_count: 0,
alloc_bytes: 0,
budget_breached: false,
};
let raw_value = evaluator.eval(expr);
if let (Some(ev_trace), Some(caller)) = (evaluator.trace, caller_trace) {
*caller = ev_trace;
}
// When the budget was breached during evaluation, null out any partial
// result. Partial values alongside a "budget exceeded" diagnostic are
// an attractive nuisance — hosts looking only at value would see a
// plausible-but-incomplete number / array. The harness in
// fuzz/fuzz_targets/fel_budget.rs encodes this contract; libFuzzer
// surfaced inputs where the existing code leaked partial subexpression
// results past the budget breach.
let value = if evaluator.budget_breached {
Value::Null
} else {
raw_value
};
EvalResult {
value,
diagnostics: evaluator.diagnostics,
}
}
impl<'a> Evaluator<'a> {
pub(super) fn diag(&mut self, msg: impl Into<String>) {
self.diagnostics.push(Diagnostic::error(msg));
}
pub(super) fn diag_coded(&mut self, code: impl Into<String>, msg: impl Into<String>) {
self.diagnostics.push(Diagnostic::error_coded(code, msg));
}
pub(in crate::evaluator) fn make_string(&mut self, s: String) -> Value {
self.track_alloc(s.len() as u64);
if self.alloc_limit_breached() {
return Value::Null;
}
Value::String(s)
}
fn make_array(&mut self, elems: Vec<Value>) -> Value {
self.track_alloc(
(elems.len() * 16) as u64 + elems.iter().map(value_size_estimate).sum::<u64>(),
);
if self.alloc_limit_breached() {
return Value::Null;
}
Value::Array(elems)
}
fn make_object(&mut self, entries: IndexMap<String, Value>) -> Value {
self.track_alloc(
(entries.len() * 40) as u64
+ entries
.iter()
.map(|(k, v)| k.len() as u64 + value_size_estimate(v))
.sum::<u64>(),
);
if self.alloc_limit_breached() {
return Value::Null;
}
Value::Object(entries)
}
/// Bump step counter and check budget; when exceeded, emit diagnostic and return `true`.
/// Suppresses duplicate budget diagnostics via [`Self::budget_breached`].
#[inline]
fn check_budget(&mut self) -> bool {
self.step_count += 1;
if self.budget_breached {
return true;
}
match self.budget.check(self.step_count, self.alloc_bytes) {
Ok(()) => false,
Err(kind) => {
let label = match kind {
BudgetExceededKind::Steps => "steps",
BudgetExceededKind::Alloc => "alloc",
BudgetExceededKind::Deadline => "deadline",
};
self.diag(format!("budget exceeded ({label})"));
self.budget_breached = true;
true
}
}
}
/// Track an estimated allocation (best-effort, not byte-accurate).
/// Also checks the updated total against the budget, emitting a diagnostic if exceeded.
/// Suppresses duplicate budget diagnostics via [`Self::budget_breached`].
#[inline]
fn track_alloc(&mut self, bytes: u64) {
self.alloc_bytes = self.alloc_bytes.saturating_add(bytes);
if self.alloc_limit_breached() && !self.budget_breached {
self.diag("budget exceeded (alloc)");
self.budget_breached = true;
}
}
/// True after [`Self::track_alloc`] when estimated bytes exceed [`EvalBudget::max_alloc_bytes`].
#[inline]
fn alloc_limit_breached(&self) -> bool {
self.alloc_bytes > self.budget.max_alloc_bytes
}
/// Evaluates `pred` with `$` bound to `elem` for one let-scope frame.
pub(super) fn eval_under_dollar(&mut self, elem: &Value, pred: &Expr) -> Value {
self.let_scopes
.push(HashMap::from([("$".to_string(), elem.clone())]));
let out = self.eval(pred);
self.let_scopes.pop();
out
}
/// Records a structured type mismatch diagnostic (no [`Value`] returned).
pub(super) fn diag_expected_type(&mut self, fn_name: &str, expected: &str, got_type: &str) {
self.diagnostics
.push(Diagnostic::type_mismatch(fn_name, expected, got_type));
}
/// Records a type mismatch diagnostic and returns [`Value::Null`].
pub(super) fn reject_expected_type(
&mut self,
fn_name: &str,
expected: &str,
got: &Value,
) -> Value {
self.diag_expected_type(fn_name, expected, got.type_name());
Value::Null
}
/// True iff this evaluator is recording a trace. Cheap predictable branch.
#[inline]
pub(super) fn tracing(&self) -> bool {
self.trace.is_some()
}
/// Append a step, no-op when not tracing.
#[inline]
pub(super) fn trace_step(&mut self, step: TraceStep) {
if let Some(t) = self.trace.as_mut() {
t.push(step);
}
}
fn eval_context_ref(
&mut self,
name: &str,
called: bool,
arg: Option<&str>,
tail: &[String],
) -> Value {
let path = context_tail_path(tail);
self.eval_context_ref_path(name, called, arg, &path)
}
fn eval_context_ref_path(
&mut self,
name: &str,
called: bool,
arg: Option<&str>,
path: &[PathSegment],
) -> Value {
if is_grammar_reserved_context(name) || self.context_bindings.is_none() {
let (env_tail, remaining_path) = split_context_env_path(path);
let base = self.env.resolve_context(name, arg, &env_tail);
return if remaining_path.is_empty() {
base
} else {
self.access_path(base, remaining_path)
};
}
let Some(catalog) = self.context_bindings else {
let (env_tail, remaining_path) = split_context_env_path(path);
let base = self.env.resolve_context(name, arg, &env_tail);
return if remaining_path.is_empty() {
base
} else {
self.access_path(base, remaining_path)
};
};
let Some(kind) = catalog.binding_kind(name) else {
self.diag_coded(
UNBOUND_CONTEXT_REF_CODE,
format!("unbound context reference: @{name}"),
);
return Value::Null;
};
match kind {
ContextBindingKind::Value => {
if called {
self.diag_coded(
"FEL-CONTEXT-BINDING-NOT-CALLABLE",
format!("context binding @{name} is not callable"),
);
return Value::Null;
}
if !path.is_empty() {
self.diag_coded(
"FEL-CONTEXT-BINDING-PATH",
format!("context binding @{name} does not support postfix traversal"),
);
return Value::Null;
}
self.resolve_context_binding_value(catalog, name, None, path)
}
ContextBindingKind::Object => {
if called {
self.diag_coded(
"FEL-CONTEXT-BINDING-NOT-CALLABLE",
format!("context binding @{name} is not callable"),
);
return Value::Null;
}
self.resolve_context_binding_value(catalog, name, None, path)
}
ContextBindingKind::Function => {
if !called {
self.diag_coded(
"FEL-CONTEXT-BINDING-CALL-REQUIRED",
format!("context binding @{name} must be called"),
);
return Value::Null;
}
self.resolve_context_binding_value(catalog, name, arg, path)
}
}
}
fn resolve_context_binding_value(
&mut self,
catalog: &dyn ContextBindingCatalog,
name: &str,
arg: Option<&str>,
path: &[PathSegment],
) -> Value {
let Some(value) = catalog.resolve(name, arg) else {
self.diag_coded(
UNBOUND_CONTEXT_REF_CODE,
format!("unbound context reference: @{name}"),
);
return Value::Null;
};
self.access_path(value, path)
}
}
impl<'a> Evaluator<'a> {
pub(super) fn eval(&mut self, expr: &Expr) -> Value {
if self.eval_depth >= MAX_EVAL_DEPTH {
self.diag("expression evaluation depth exceeded");
return Value::Null;
}
if self.check_budget() {
return Value::Null;
}
self.eval_depth += 1;
let out = self.eval_impl(expr);
self.eval_depth -= 1;
out
}
fn eval_impl(&mut self, expr: &Expr) -> Value {
match expr {
Expr::Null => Value::Null,
Expr::Boolean(b) => Value::Boolean(*b),
Expr::Number(n) => Value::Number(*n),
Expr::String(s) => self.make_string(s.clone()),
Expr::DateLiteral(s) => match parse_date_literal(s) {
Some(d) => Value::Date(d),
None => {
self.diag(format!("invalid date literal '{s}'"));
Value::Null
}
},
Expr::DateTimeLiteral(s) => match parse_datetime_literal(s) {
Some(d) => Value::Date(d),
None => {
self.diag(format!("invalid datetime literal '{s}'"));
Value::Null
}
},
Expr::Array(elems) => {
let values: Vec<Value> = elems.iter().map(|e| self.eval(e)).collect();
self.make_array(values)
}
Expr::Object(entries) => {
let pairs: IndexMap<String, Value> = entries
.iter()
.map(|(k, v)| (k.clone(), self.eval(v)))
.collect();
self.make_object(pairs)
}
Expr::FieldRef { name, path } => {
let value = self.eval_field_ref(name, path);
if self.tracing() {
let rendered = render_field_path(name, path);
self.trace_step(TraceStep::FieldResolved {
path: rendered,
value: fel_to_json(&value),
});
}
value
}
Expr::VarRef { name, path } => {
let value = self.eval_field_ref(&Some(name.clone()), path);
if self.tracing() {
let rendered = render_field_path(&Some(name.clone()), path);
self.trace_step(TraceStep::FieldResolved {
path: rendered,
value: fel_to_json(&value),
});
}
value
}
Expr::ContextRef {
name,
called,
arg,
tail,
} => self.eval_context_ref(name, *called, arg.as_deref(), tail),
Expr::UnaryOp { op, operand, .. } => {
let val = self.eval(operand);
self.eval_unary(*op, val)
}
Expr::BinaryOp { op, left, right } => self.eval_binary(*op, left, right),
Expr::Ternary {
condition,
then_branch,
else_branch,
}
| Expr::IfThenElse {
condition,
then_branch,
else_branch,
} => {
let cond = self.eval(condition);
match cond {
Value::Null => {
self.diag("if: condition evaluated to null");
Value::Null
}
Value::Boolean(true) => {
if self.tracing() {
self.trace_step(TraceStep::IfBranch {
condition_value: serde_json::Value::Bool(true),
branch_taken: "then",
});
}
self.eval(then_branch)
}
Value::Boolean(false) => {
if self.tracing() {
self.trace_step(TraceStep::IfBranch {
condition_value: serde_json::Value::Bool(false),
branch_taken: "else",
});
}
self.eval(else_branch)
}
_ => self.reject_expected_type("if", "boolean", &cond),
}
}
Expr::Membership {
value,
container,
negated,
} => {
let val = self.eval(value);
let cont = self.eval(container);
self.eval_membership(val, cont, *negated)
}
Expr::NullCoalesce { left, right } => {
let l = self.eval(left);
if l.is_null() { self.eval(right) } else { l }
}
Expr::LetBinding { name, value, body } => {
let val = self.eval(value);
self.track_alloc(64);
if self.alloc_limit_breached() {
return Value::Null;
}
self.let_scopes.push(HashMap::from([(name.clone(), val)]));
let result = self.eval(body);
self.let_scopes.pop();
result
}
Expr::FunctionCall { name, args } => {
// Eager traceable builtins rely on per-call arg caching (see `CallArgCache`);
// only pure functions may remain on the eager trace list.
let should_trace_call = self.tracing() && is_eager_traceable_function(name);
if should_trace_call {
self.begin_call_arg_cache(args);
}
let result = self.eval_function(name, args);
if should_trace_call {
let arg_vals = self.finish_call_arg_cache_as_json(args);
self.trace_step(TraceStep::FunctionCalled {
name: name.clone(),
args: arg_vals,
result: fel_to_json(&result),
});
}
result
}
Expr::PostfixAccess { expr, path } => {
if let Expr::PostfixAccess {
expr: inner,
path: inner_path,
} = expr.as_ref()
{
let mut combined = Vec::with_capacity(inner_path.len() + path.len());
combined.extend(inner_path.iter().cloned());
combined.extend(path.iter().cloned());
if let Expr::ContextRef {
name,
called,
arg,
tail,
} = inner.as_ref()
{
let mut context_path = context_tail_path(tail);
context_path.extend(combined);
return self.eval_context_ref_path(
name,
*called,
arg.as_deref(),
&context_path,
);
}
let base = self.eval(inner);
return self.access_path(base, &combined);
}
if let Expr::FieldRef {
name: Some(name),
path: base_path,
} = expr.as_ref()
{
let mut segments = vec![name.clone()];
let mut combined = Vec::with_capacity(base_path.len() + path.len());
combined.extend(base_path.iter().cloned());
combined.extend(path.iter().cloned());
if combined
.iter()
.all(|segment| matches!(segment, PathSegment::Dot(_)))
{
// Let-bound identifiers resolve in `eval_field_ref` before the environment.
// Skipping `eval(expr)` would merge path segments and call `resolve_field`
// only, so e.g. `let x = {a: 1} in x.a` would wrongly yield null.
let bound_in_let =
self.let_scopes.iter().any(|scope| scope.contains_key(name));
if !bound_in_let {
for segment in &combined {
if let PathSegment::Dot(part) = segment {
segments.push(part.clone());
}
}
return self.env.resolve_field(&segments);
}
}
}
if let Expr::VarRef {
name,
path: base_path,
} = expr.as_ref()
{
let mut segments = vec![name.clone()];
let mut combined = Vec::with_capacity(base_path.len() + path.len());
combined.extend(base_path.iter().cloned());
combined.extend(path.iter().cloned());
if combined
.iter()
.all(|segment| matches!(segment, PathSegment::Dot(_)))
{
let bound_in_let =
self.let_scopes.iter().any(|scope| scope.contains_key(name));
if !bound_in_let {
for segment in &combined {
if let PathSegment::Dot(part) = segment {
segments.push(part.clone());
}
}
return self.env.resolve_field(&segments);
}
}
}
if let Expr::ContextRef {
name,
called,
arg,
tail,
} = expr.as_ref()
{
let mut context_path = context_tail_path(tail);
context_path.extend(path.iter().cloned());
return self.eval_context_ref_path(
name,
*called,
arg.as_deref(),
&context_path,
);
}
let base = self.eval(expr);
self.access_path(base, path)
}
}
}
// ── Field references ────────────────────────────────────────
fn eval_field_ref(&mut self, name: &Option<String>, path: &[PathSegment]) -> Value {
match name {
None => {
// Check let-scopes for bare `$` (predicate rebound in countWhere / every / some
// and in *Where helpers via filter_where).
for scope in self.let_scopes.iter().rev() {
if let Some(val) = scope.get("$") {
return if path.is_empty() {
val.clone()
} else {
self.access_path(val.clone(), path)
};
}
}
let base = self.env.resolve_field(&[]);
if path.is_empty() {
base
} else {
self.access_path(base, path)
}
}
Some(n) => {
// Check let-scopes first
for scope in self.let_scopes.iter().rev() {
if let Some(val) = scope.get(n) {
return if path.is_empty() {
val.clone()
} else {
self.access_path(val.clone(), path)
};
}
}
// Build segments for environment resolution
let mut segments = vec![n.clone()];
let mut remaining_path = Vec::new();
let mut hit_special = false;
for seg in path {
if hit_special {
remaining_path.push(seg.clone());
} else {
match seg {
PathSegment::Dot(name) => segments.push(name.clone()),
_ => {
hit_special = true;
remaining_path.push(seg.clone());
}
}
}
}
let base = self.env.resolve_field(&segments);
if matches!(base, Value::Null)
&& path.iter().any(|seg| matches!(seg, PathSegment::Index(_)))
{
let mut flat_segments = vec![n.clone()];
for seg in path {
match seg {
PathSegment::Dot(name) => flat_segments.push(name.clone()),
PathSegment::Index(idx) => {
if let Some(last) = flat_segments.last_mut() {
last.push_str(&format!("[{idx}]"));
}
}
PathSegment::Wildcard => {
if let Some(last) = flat_segments.last_mut() {
last.push_str("[*]");
}
}
}
}
let flat = self.env.resolve_field(&flat_segments);
if !matches!(flat, Value::Null) {
return flat;
}
}
if remaining_path.is_empty() {
base
} else {
self.access_path(base, &remaining_path)
}
}
}
}
fn access_path(&mut self, mut current: Value, path: &[PathSegment]) -> Value {
for (i, seg) in path.iter().enumerate() {
match seg {
PathSegment::Dot(name) => match ¤t {
Value::Object(entries) => {
current = entries.get(name.as_str()).cloned().unwrap_or(Value::Null);
}
Value::Null => return Value::Null,
_ => {
self.diag(format!("cannot access '{name}' on {}", current.type_name()));
return Value::Null;
}
},
PathSegment::Index(idx) => match ¤t {
Value::Array(arr) => {
// FEL indices are 1-based; guard above rejects 0 and OOB before subtracting.
if *idx == 0 || *idx > arr.len() {
self.diag(format!("index {idx} out of bounds (len {})", arr.len()));
return Value::Null;
}
current = arr.get(*idx - 1).cloned().unwrap_or(Value::Null);
}
Value::Null => return Value::Null,
_ => {
self.diag(format!("cannot index into {}", current.type_name()));
return Value::Null;
}
},
PathSegment::Wildcard => match ¤t {
Value::Array(arr) => {
let remaining = &path[i + 1..];
if remaining.is_empty() {
return current;
}
let elems: Vec<Value> = arr
.iter()
.map(|e| self.access_path(e.clone(), remaining))
.collect();
return self.make_array(elems);
}
Value::Null => return Value::Null,
_ => {
self.diag(format!("cannot wildcard on {}", current.type_name()));
return Value::Null;
}
},
}
}
current
}
// ── Unary operators ─────────────────────────────────────────
fn eval_unary(&mut self, op: UnaryOp, val: Value) -> Value {
match op {
UnaryOp::Not => match val {
Value::Null => Value::Null,
Value::Boolean(b) => Value::Boolean(!b),
_ => {
self.diag(format!("cannot apply 'not' to {}", val.type_name()));
Value::Null
}
},
UnaryOp::Neg => match &val {
Value::Null => Value::Null,
Value::Number(n) => Value::Number(-n),
Value::Array(arr) => {
let values: Vec<Value> =
arr.iter().map(|v| self.eval_unary(op, v.clone())).collect();
self.make_array(values)
}
_ => {
self.diag(format!("cannot negate {}", val.type_name()));
Value::Null
}
},
}
}
// ── Binary operators ────────────────────────────────────────
fn eval_binary(&mut self, op: BinaryOp, left_expr: &Expr, right_expr: &Expr) -> Value {
// Short-circuit for logical ops
match op {
BinaryOp::And => {
let left = self.eval(left_expr);
if left.is_null() {
return Value::Null;
}
let left_bool = match left {
Value::Boolean(b) => b,
other => {
self.diag(format!("cannot apply 'and' to {}", other.type_name()));
return Value::Null;
}
};
if !left_bool {
if self.tracing() {
self.trace_step(TraceStep::ShortCircuit {
op: "and".into(),
reason: "left of 'and' was false, skipped right".into(),
});
}
return Value::Boolean(false);
}
let right = self.eval(right_expr);
if right.is_null() {
return Value::Null;
}
return match right {
Value::Boolean(b) => {
if self.tracing() {
self.trace_step(TraceStep::BinaryOp {
op: "and".into(),
lhs: serde_json::Value::Bool(true),
rhs: serde_json::Value::Bool(b),
result: serde_json::Value::Bool(b),
});
}
Value::Boolean(b)
}
other => {
self.diag(format!("cannot apply 'and' to {}", other.type_name()));
Value::Null
}
};
}
BinaryOp::Or => {
let left = self.eval(left_expr);
if left.is_null() {
return Value::Null;
}
let left_bool = match left {
Value::Boolean(b) => b,
other => {
self.diag(format!("cannot apply 'or' to {}", other.type_name()));
return Value::Null;
}
};
if left_bool {
if self.tracing() {
self.trace_step(TraceStep::ShortCircuit {
op: "or".into(),
reason: "left of 'or' was true, skipped right".into(),
});
}
return Value::Boolean(true);
}
let right = self.eval(right_expr);
if right.is_null() {
return Value::Null;
}
return match right {
Value::Boolean(b) => {
if self.tracing() {
self.trace_step(TraceStep::BinaryOp {
op: "or".into(),
lhs: serde_json::Value::Bool(false),
rhs: serde_json::Value::Bool(b),
result: serde_json::Value::Bool(b),
});
}
Value::Boolean(b)
}
other => {
self.diag(format!("cannot apply 'or' to {}", other.type_name()));
Value::Null
}
};
}
_ => {}
}
let left = self.eval(left_expr);
let right = self.eval(right_expr);
// Equality does NOT propagate null
match op {
BinaryOp::Eq => {
let result = self.eval_equality(&left, &right);
if self.tracing()
&& !matches!(left, Value::Array(_))
&& !matches!(right, Value::Array(_))
{
self.trace_step(TraceStep::BinaryOp {
op: "==".into(),
lhs: fel_to_json(&left),
rhs: fel_to_json(&right),
result: fel_to_json(&result),
});
}
return result;
}
BinaryOp::NotEq => {
let eq = self.eval_equality(&left, &right);
let result = match eq {
Value::Boolean(b) => Value::Boolean(!b),
other => other,
};
if self.tracing()
&& !matches!(left, Value::Array(_))
&& !matches!(right, Value::Array(_))
{
self.trace_step(TraceStep::BinaryOp {
op: "!=".into(),
lhs: fel_to_json(&left),
rhs: fel_to_json(&right),
result: fel_to_json(&result),
});
}
return result;
}
_ => {}
}
// Array broadcasting
match (&left, &right) {
(Value::Array(la), Value::Array(ra)) => {
if la.len() != ra.len() {
self.diag(format!(
"array length mismatch: {} vs {}",
la.len(),
ra.len()
));
return Value::Null;
}
return {
let values: Vec<Value> = la
.iter()
.zip(ra.iter())
.map(|(l, r)| self.apply_binary(op, l, r))
.collect();
self.make_array(values)
};
}
(Value::Array(la), _) => {
return {
let values: Vec<Value> = la
.iter()
.map(|l| self.apply_binary(op, l, &right))
.collect();
self.make_array(values)
};
}
(_, Value::Array(ra)) => {
let values: Vec<Value> =
ra.iter().map(|r| self.apply_binary(op, &left, r)).collect();
return self.make_array(values);
}
_ => {}
}
let result = self.apply_binary(op, &left, &right);
if self.tracing() {
self.trace_step(TraceStep::BinaryOp {
op: binary_op_symbol(op).into(),
lhs: fel_to_json(&left),
rhs: fel_to_json(&right),
result: fel_to_json(&result),
});
}
result
}
fn apply_binary(&mut self, op: BinaryOp, left: &Value, right: &Value) -> Value {
if left.is_null() || right.is_null() {
return Value::Null;
}
match op {
BinaryOp::Add => self.num_op(left, right, "+"),
BinaryOp::Sub => self.num_op(left, right, "-"),
BinaryOp::Mul => self.num_op(left, right, "*"),
BinaryOp::Div => {
if let (Value::Number(a), Value::Number(b)) = (left, right) {
if b.is_zero() {
self.diag("division by zero");
Value::Null
} else {
match a.checked_div(*b) {
Some(q) => Value::Number(q),
None => {
self.diag("division overflow");
Value::Null
}
}
}
} else if let (Value::Money(m), Value::Number(n)) = (left, right) {
if n.is_zero() {
self.diag("division by zero");
Value::Null
} else {
match m.amount.checked_div(*n) {
Some(amount) => Value::Money(Money {
amount,
currency: m.currency,
}),
None => {
self.diag("division overflow");
Value::Null
}
}
}
} else if let (Value::Money(a), Value::Money(b)) = (left, right) {
if a.currency != b.currency {
self.diag(format!(
"currency mismatch: {} vs {}",
a.currency, b.currency
));
Value::Null
} else if b.amount.is_zero() {
self.diag("division by zero");
Value::Null
} else {
match a.amount.checked_div(b.amount) {
Some(q) => Value::Number(q),
None => {
self.diag("division overflow");
Value::Null
}
}
}
} else {
self.diag(format!(
"cannot divide {} by {}",
left.type_name(),
right.type_name()
));
Value::Null
}
}
BinaryOp::Mod => {
if let (Value::Number(a), Value::Number(b)) = (left, right) {
if b.is_zero() {
self.diag("modulo by zero");
Value::Null
} else {
match a.checked_rem(*b) {
Some(r) => Value::Number(r),
None => {
self.diag("modulo overflow");
Value::Null
}
}
}
} else if let (Value::Money(m), Value::Number(n)) = (left, right) {
if n.is_zero() {
self.diag("modulo by zero");
Value::Null
} else {
match m.amount.checked_rem(*n) {
Some(amount) => Value::Money(Money {
amount,
currency: m.currency,
}),
None => {
self.diag("modulo overflow");
Value::Null
}
}
}
} else {
self.diag(format!(
"cannot modulo {} by {}",
left.type_name(),
right.type_name()
));
Value::Null
}
}
BinaryOp::Concat => {
if let (Value::String(a), Value::String(b)) = (left, right) {
self.make_string(format!("{a}{b}"))
} else {
self.diag(format!(
"cannot concat {} and {}",
left.type_name(),
right.type_name()
));
Value::Null
}
}
BinaryOp::Lt => self.compare(left, right, |o| o.is_lt()),
BinaryOp::Gt => self.compare(left, right, |o| o.is_gt()),
BinaryOp::LtEq => self.compare(left, right, |o| o.is_le()),
BinaryOp::GtEq => self.compare(left, right, |o| o.is_ge()),
BinaryOp::Eq | BinaryOp::NotEq | BinaryOp::And | BinaryOp::Or => {
unreachable!("handled above")
}
}
}
fn num_op(&mut self, left: &Value, right: &Value, sym: &str) -> Value {
let combine = |a: Decimal, b: Decimal| -> Option<Decimal> {
match sym {
"+" => a.checked_add(b),
"-" => a.checked_sub(b),
"*" => a.checked_mul(b),
_ => None,
}
};
match (left, right) {
(Value::Number(a), Value::Number(b)) => match combine(*a, *b) {
Some(v) => Value::Number(v),
None => {
self.diag(format!("arithmetic overflow ({sym})"));
Value::Null
}
},
(Value::Money(a), Value::Money(b)) if sym == "+" || sym == "-" => {
if a.currency != b.currency {
self.diag(format!(
"currency mismatch: {} vs {}",
a.currency, b.currency
));
Value::Null
} else {
match combine(a.amount, b.amount) {
Some(amount) => Value::Money(Money {
amount,
currency: a.currency,
}),
None => {
self.diag(format!("arithmetic overflow ({sym})"));
Value::Null
}
}
}
}
(Value::Money(m), Value::Number(n)) if sym == "+" || sym == "-" => {
match combine(m.amount, *n) {
Some(amount) => Value::Money(Money {
amount,
currency: m.currency,
}),
None => {
self.diag(format!("arithmetic overflow ({sym})"));
Value::Null
}
}
}
(Value::Money(m), Value::Number(n)) if sym == "*" => match m.amount.checked_mul(*n) {
Some(amount) => Value::Money(Money {
amount,
currency: m.currency,
}),
None => {
self.diag("arithmetic overflow (*)");
Value::Null
}
},
(Value::Number(n), Value::Money(m)) if sym == "*" => match n.checked_mul(m.amount) {
Some(amount) => Value::Money(Money {
amount,
currency: m.currency,
}),
None => {
self.diag("arithmetic overflow (*)");
Value::Null
}
},
_ => {
self.diag(format!(
"cannot apply '{sym}' to {} and {}",
left.type_name(),
right.type_name()
));
Value::Null
}
}
}
pub(super) fn eval_equality(&mut self, left: &Value, right: &Value) -> Value {
match (left, right) {
(Value::Null, Value::Null) => Value::Boolean(true),
(Value::Null, _) | (_, Value::Null) => Value::Boolean(false),
(Value::Boolean(a), Value::Boolean(b)) => Value::Boolean(a == b),
(Value::Number(a), Value::Number(b)) => Value::Boolean(a == b),
(Value::String(a), Value::String(b)) => Value::Boolean(a == b),
(Value::Date(a), Value::Date(b)) => Value::Boolean(a == b),
(Value::Money(a), Value::Money(b)) => {
Value::Boolean(a.currency == b.currency && a.amount == b.amount)
}
(Value::Array(a), Value::Array(b)) => {
if a.len() != b.len() {
return Value::Boolean(false);
}
for (av, bv) in a.iter().zip(b.iter()) {
if !matches!(self.eval_equality(av, bv), Value::Boolean(true)) {
return Value::Boolean(false);
}
}
Value::Boolean(true)
}
(Value::Object(a), Value::Object(b)) => Value::Boolean(a == b),
_ => {
self.diag(format!(
"cannot compare {} with {}",
left.type_name(),
right.type_name()
));
Value::Null
}
}
}
fn compare(
&mut self,
left: &Value,
right: &Value,
check: fn(std::cmp::Ordering) -> bool,
) -> Value {
let ord = match (left, right) {
(Value::Number(a), Value::Number(b)) => a.cmp(b),
(Value::String(a), Value::String(b)) => a.cmp(b),
(Value::Date(a), Value::Date(b)) => a.ordinal().cmp(&b.ordinal()),
// 9f: Money vs Number comparison — specific diagnostic with fix suggestion
(Value::Money(_), Value::Number(_)) | (Value::Number(_), Value::Money(_)) => {
self.diag("Type error: cannot compare money with number directly. Use moneyAmount($field) to extract the numeric amount.");
return Value::Null;
}
// Money vs Money ordering — only equality is supported
(Value::Money(_), Value::Money(_)) => {
self.diag("Type error: cannot order money values directly. Use moneyAmount($field) to extract the numeric amount for ordering comparisons.");
return Value::Null;
}
_ => {
self.diag(format!(
"cannot compare {} with {}",
left.type_name(),
right.type_name()
));
return Value::Null;
}
};
Value::Boolean(check(ord))
}
fn eval_membership(&mut self, value: Value, container: Value, negated: bool) -> Value {
match &container {
Value::Array(arr) => {
let found = arr
.iter()
.any(|e| matches!(self.eval_equality(&value, e), Value::Boolean(true)));
Value::Boolean(if negated { !found } else { found })
}
Value::Null => Value::Null,
_ => {
self.diag(format!(
"membership requires array, got {}",
container.type_name()
));
Value::Null
}
}
}
// ── Standard library functions ──────────────────────────────
fn eval_function(&mut self, name: &str, args: &[Expr]) -> Value {
// Uniform catalog-driven arity gate (FUT-7). Every built-in's signature
// — `(min, max)` derived from `BuiltinFunctionCatalogEntry::arity` — is
// enforced before dispatch so handlers cannot silently accept too-few
// args (defaulting missing positions to null) or too-many args (ignoring
// tails). Unknown names skip this gate and fall through to the
// extension registry / undefined-function diagnostic at the bottom.
if let Some((min, max)) = crate::extensions::builtin_arity(name) {
let got = args.len();
let out_of_bounds = got < min || max.is_some_and(|m| got > m);
if out_of_bounds {
self.diagnostics
.push(Diagnostic::arity_mismatch(name, min, max, got));
return Value::Null;
}
}
match name {
// Aggregates
"sum" => self.fn_aggregate(args, "sum", |nums| nums.iter().copied().sum()),
"count" => {
let v = self.eval_arg(args, 0);
self.fn_count(&v)
}
"avg" => self.fn_aggregate(args, "avg", |nums| {
if nums.is_empty() {
Decimal::ZERO
} else {
nums.iter().copied().sum::<Decimal>() / Decimal::from(nums.len() as i64)
}
}),
"min" => self.fn_min_max(args, true),
"max" => self.fn_min_max(args, false),
"countWhere" => self.fn_count_where(args),
"every" => self.fn_every(args),
"some" => self.fn_some(args),
"sumWhere" => self.fn_sum_where(args),
"avgWhere" => self.fn_avg_where(args),
"minWhere" => self.fn_min_where(args),
"maxWhere" => self.fn_max_where(args),
// String
"length" => self.fn_length(args),
"contains" => self.fn_str2(args, "contains", |s, sub| Value::Boolean(s.contains(sub))),
"startsWith" => {
self.fn_str2(args, "startsWith", |s, p| Value::Boolean(s.starts_with(p)))
}
"endsWith" => self.fn_str2(args, "endsWith", |s, p| Value::Boolean(s.ends_with(p))),
"substring" => self.fn_substring(args),
"replace" => self.fn_replace(args),
"upper" => self.fn_str1(args, "upper", |s| s.to_uppercase()),
"lower" => self.fn_str1(args, "lower", |s| s.to_lowercase()),
"trim" => self.fn_str1(args, "trim", |s| s.trim().to_string()),
"matches" => self.fn_matches(args),
"format" => self.fn_format(args),
// Numeric
"round" => self.fn_round(args),
"floor" => self.fn_num1(args, "floor", |n| n.floor()),
"ceil" => self.fn_num1(args, "ceil", |n| n.ceil()),
"abs" => self.fn_num1(args, "abs", |n| n.abs()),
"power" => self.fn_power(args),
// Date
"today" => self.fn_today(),
"now" => self.fn_now(),
"year" => self.fn_date_part(args, "year", |d| dec(d.year() as i64)),
"month" => self.fn_date_part(args, "month", |d| dec(d.month() as i64)),
"day" => self.fn_date_part(args, "day", |d| dec(d.day() as i64)),
"hours" => self.fn_time_part(args, 0),
"minutes" => self.fn_time_part(args, 1),
"seconds" => self.fn_time_part(args, 2),
"time" => self.fn_time(args),
"timeDiff" => self.fn_time_diff(args),
"duration" => self.fn_duration(args),
"dateDiff" => self.fn_date_diff(args),
"dateAdd" => self.fn_date_add(args),
// Logical
"if" => self.fn_if(args),
"coalesce" => self.fn_coalesce(args),
"empty" => self.fn_empty(args),
"present" => self.fn_present(args),
"selected" => self.fn_selected(args),
// Type checking
"isNumber" => self.fn_is_type(args, "number"),
"isString" => self.fn_is_type(args, "string"),
"isDate" => self.fn_is_type(args, "date"),
"isNull" => {
let v = self.eval_arg(args, 0);
Value::Boolean(v.is_null())
}
"typeOf" => {
let v = self.eval_arg(args, 0);
self.make_string(v.type_name().to_string())
}
// Casting
"number" => self.fn_cast_number(args),
"string" => self.fn_cast_string(args),
"boolean" => self.fn_cast_boolean(args),
"date" => self.fn_cast_date(args),
// Money
"money" => self.fn_money(args),
"moneyAmount" => {
let v = self.eval_arg(args, 0);
match v {
Value::Money(m) => Value::Number(m.amount),
Value::Null => Value::Null,
other => self.reject_expected_type("moneyAmount", "money", &other),
}
}
"moneyCurrency" => {
let v = self.eval_arg(args, 0);
match v {
Value::Money(m) => self.make_string(m.currency.to_string()),
Value::Null => Value::Null,
other => self.reject_expected_type("moneyCurrency", "money", &other),
}
}
"moneyAdd" => self.fn_money_add(args),
"moneySum" => self.fn_money_sum(args),
"moneySumWhere" => self.fn_money_sum_where(args),
// MIP state queries
"valid" => self.fn_mip(args, "valid"),
"relevant" => self.fn_mip(args, "relevant"),
"readonly" => self.fn_mip(args, "readonly"),
"required" => self.fn_mip(args, "required"),
// Repeat navigation
"prev" => self.env.repeat_prev(),
"next" => self.env.repeat_next(),
"parent" => self.env.repeat_parent(),
"instance" => self.fn_instance(args),
// Locale
"locale" => self.fn_locale(),
"formatNumber" => self.fn_format_number(args),
"formatDate" => self.fn_format_date(args),
"runtimeMeta" => self.fn_runtime_meta(args),
"pluralCategory" => self.fn_plural_category(args),
_ => {
let evaluated_args: Vec<Value> = args.iter().map(|arg| self.eval(arg)).collect();
if let Some(extensions) = self.extensions {
match call_extension(extensions, name, &evaluated_args) {
ExtensionCallOutcome::Ok(result) => {
let result = match result {
Value::String(s) => self.make_string(s),
Value::Array(arr) => self.make_array(arr),
Value::Object(obj) => self.make_object(obj),
other => {
self.track_alloc(value_size_estimate(&other));
if self.alloc_limit_breached() {
return Value::Null;
}
other
}
};
if self.tracing() {
self.trace_step(TraceStep::FunctionCalled {
name: name.to_string(),
args: evaluated_args.iter().map(fel_to_json).collect(),
result: fel_to_json(&result),
});
}
return result;
}
ExtensionCallOutcome::ArityMismatch {
name,
min_args,
max_args,
got,
} => {
self.diagnostics
.push(Diagnostic::arity_mismatch(name, min_args, max_args, got));
return Value::Null;
}
ExtensionCallOutcome::Failed { name, message } => {
self.diagnostics
.push(Diagnostic::extension_failed(name, message));
return Value::Null;
}
ExtensionCallOutcome::NotFound => {}
}
}
self.diagnostics.push(Diagnostic::undefined_function(name));
Value::Null
}
}
}
pub(super) fn eval_arg(&mut self, args: &[Expr], idx: usize) -> Value {
let args_ptr = args.as_ptr();
if idx < args.len() {
let use_top_cache = self
.call_arg_cache_stack
.last()
.is_some_and(|cache| cache.args_ptr == args_ptr && idx < cache.values.len());
if use_top_cache {
if let Some(val) = self
.call_arg_cache_stack
.last()
.and_then(|cache| cache.values[idx].as_ref())
{
return val.clone();
}
let evaluated = self.eval(&args[idx]);
if let Some(cache) = self.call_arg_cache_stack.last_mut()
&& cache.args_ptr == args_ptr
&& idx < cache.values.len()
{
cache.values[idx] = Some(evaluated.clone());
}
return evaluated;
}
self.eval(&args[idx])
} else {
Value::Null
}
}
pub(super) fn get_array<'v>(&mut self, val: &'v Value, fn_name: &str) -> Option<&'v [Value]> {
match val {
Value::Array(a) => Some(a.as_slice()),
Value::Null => None,
_ => {
self.diag_expected_type(fn_name, "array", val.type_name());
None
}
}
}
fn begin_call_arg_cache(&mut self, args: &[Expr]) {
self.call_arg_cache_stack.push(CallArgCache {
args_ptr: args.as_ptr(),
values: vec![None; args.len()],
});
}
fn finish_call_arg_cache_as_json(&mut self, args: &[Expr]) -> Vec<serde_json::Value> {
let Some(mut cache) = self.call_arg_cache_stack.pop() else {
self.diag("internal: missing call arg cache frame");
return args.iter().map(|e| fel_to_json(&self.eval(e))).collect();
};
if cache.args_ptr != args.as_ptr() {
self.diag("internal: call arg cache pointer mismatch");
return args.iter().map(|e| fel_to_json(&self.eval(e))).collect();
}
cache
.values
.iter_mut()
.enumerate()
.map(|(idx, slot)| {
let value = slot.take().unwrap_or_else(|| self.eval(&args[idx]));
fel_to_json(&value)
})
.collect()
}
/// Filter array elements by predicate (shared by sumWhere / avgWhere / minWhere / maxWhere / moneySumWhere).
///
/// Arity is enforced upstream by the uniform pre-dispatch gate in `eval_function`;
/// callers are guaranteed `args.len() >= 2` and may index `args[0]`/`args[1]` directly.
pub(super) fn filter_where(&mut self, args: &[Expr], fn_name: &str) -> Option<Vec<Value>> {
let arr_val = self.eval(&args[0]);
let arr = self.get_array(&arr_val, fn_name)?;
let mut matched = Vec::new();
for elem in arr {
let pred = self.eval_under_dollar(elem, &args[1]);
if pred.is_truthy() {
matched.push(elem.clone());
}
}
Some(matched)
}
}