Skip to main content

fel_core/evaluator/
core.rs

1#![allow(clippy::missing_docs_in_private_items)]
2use indexmap::IndexMap;
3use rust_decimal::Decimal;
4use std::collections::HashMap;
5
6use crate::ast::*;
7use crate::convert::fel_to_json;
8use crate::error::{Diagnostic, MissingTimezoneContextError};
9use crate::extensions::{ExtensionCallOutcome, ExtensionFunctions, call_extension};
10use crate::trace::{Trace, TraceStep};
11use crate::types::*;
12
13use super::budget::{BudgetExceededKind, EvalBudget};
14use super::util::{binary_op_symbol, dec, is_eager_traceable_function, render_field_path};
15
16/// Maximum [`Evaluator::eval`] recursion depth (stack overflow guard; left-associative chains are deep).
17///
18/// Kept modest so evaluation stops before the OS thread stack overflows (well above stress tests
19/// that use ~48-term chains; far below LibFuzzer inputs that nested thousands of operators).
20const MAX_EVAL_DEPTH: usize = 128;
21
22/// Diagnostic code for unregistered host context references.
23pub const UNBOUND_CONTEXT_REF_CODE: &str = "FEL-UNBOUND-CONTEXT";
24
25// ── Evaluation context ──────────────────────────────────────────
26
27/// Resolves `$` field paths, `@` context, MIP queries, repeat navigation, and clock for FEL builtins.
28pub trait Environment {
29    /// Resolve `$a.b` style path as segment list (`["a","b"]`); empty slice is bare `$`.
30    fn resolve_field(&self, segments: &[String]) -> Value;
31    /// Resolve `@name`, `@name('arg')`, `@name.tail`.
32    fn resolve_context(&self, name: &str, arg: Option<&str>, tail: &[String]) -> Value;
33
34    /// `valid($path)` — default `true` when not overridden.
35    fn mip_valid(&self, _path: &[String]) -> Value {
36        Value::Boolean(true)
37    }
38    /// `relevant($path)` — default `true`.
39    fn mip_relevant(&self, _path: &[String]) -> Value {
40        Value::Boolean(true)
41    }
42    /// `readonly($path)` — default `false`.
43    fn mip_readonly(&self, _path: &[String]) -> Value {
44        Value::Boolean(false)
45    }
46    /// `required($path)` — default `false`.
47    fn mip_required(&self, _path: &[String]) -> Value {
48        Value::Boolean(false)
49    }
50
51    /// `prev()` in repeat scope — default null.
52    fn repeat_prev(&self) -> Value {
53        Value::Null
54    }
55    /// `next()` in repeat scope — default null.
56    fn repeat_next(&self) -> Value {
57        Value::Null
58    }
59    /// `parent()` in repeat scope — default null.
60    fn repeat_parent(&self) -> Value {
61        Value::Null
62    }
63    /// Calendar date for `today()` per ADR 0069 D-6 — hosts MUST configure a
64    /// timezone-equivalent clock or return [`MissingTimezoneContextError`].
65    ///
66    /// The default impl returns
67    /// [`MissingTimezoneContextError::not_configured`]; this is deliberate —
68    /// no implementation MAY return a silent UTC fallback. The evaluator
69    /// translates `Err(_)` into a [`crate::error::DiagnosticKind::MissingTimezoneContext`]
70    /// diagnostic on every call site.
71    fn current_date(&self) -> Result<Date, MissingTimezoneContextError> {
72        Err(MissingTimezoneContextError::not_configured())
73    }
74    /// Date-time for `now()` per ADR 0069 D-6 — see [`Self::current_date`] for
75    /// the contract. Hosts that override one method typically override both;
76    /// returning different timezone contexts from the two paths is a host bug.
77    fn current_datetime(&self) -> Result<Date, MissingTimezoneContextError> {
78        Err(MissingTimezoneContextError::not_configured())
79    }
80    /// Active locale code for `locale()` — default none (returns null).
81    fn locale(&self) -> Option<&str> {
82        None
83    }
84    /// The Locale document's pattern for a `formatDate` style (`short` … `full`), when the
85    /// active locale authored one (Locale spec §2.4). Default none: built-in rendering.
86    fn date_format(&self, _style: &str) -> Option<&str> {
87        None
88    }
89    /// Runtime metadata value for `runtimeMeta(key)` — default null.
90    fn runtime_meta(&self, _key: &str) -> Value {
91        Value::Null
92    }
93}
94
95/// Classifies a host context binding root.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum ContextBindingKind {
98    /// Scalar or otherwise indivisible value; dot traversal is rejected.
99    Value,
100    /// Object-like root; the evaluator owns dot-segment traversal.
101    Object,
102    /// Callable context binding; the catalog materializes its return value.
103    Function,
104}
105
106/// Materialized host context binding returned by a catalog.
107#[derive(Debug, Clone, PartialEq)]
108pub struct ContextBinding {
109    /// Binding kind declared by the host catalog.
110    pub kind: ContextBindingKind,
111    /// Root FEL value supplied by the host catalog.
112    pub value: Value,
113}
114
115impl ContextBinding {
116    /// Creates a value-kind host binding.
117    pub fn value(value: Value) -> Self {
118        Self {
119            kind: ContextBindingKind::Value,
120            value,
121        }
122    }
123
124    /// Creates an object-kind host binding.
125    pub fn object(value: Value) -> Self {
126        Self {
127            kind: ContextBindingKind::Object,
128            value,
129        }
130    }
131
132    /// Creates a function-kind host binding result.
133    pub fn function(value: Value) -> Self {
134        Self {
135            kind: ContextBindingKind::Function,
136            value,
137        }
138    }
139}
140
141/// Resolves host-supplied `@name` context bindings.
142///
143/// The catalog returns the binding root only. Dot-segment traversal is performed
144/// by the evaluator so every host receives the same path behavior.
145pub trait ContextBindingCatalog {
146    /// Returns the declared kind for `name`, or `None` when unregistered.
147    fn binding_kind(&self, name: &str) -> Option<ContextBindingKind>;
148
149    /// Resolves the binding root for `name`.
150    ///
151    /// Function bindings receive the optional string literal from `@name('arg')`.
152    /// Value and object bindings receive `None`.
153    fn resolve(&self, name: &str, arg: Option<&str>) -> Option<Value>;
154}
155
156/// No-op host context binding catalog.
157#[derive(Default, Debug, Clone, Copy)]
158pub struct EmptyCatalog;
159
160impl ContextBindingCatalog for EmptyCatalog {
161    fn binding_kind(&self, _name: &str) -> Option<ContextBindingKind> {
162        None
163    }
164
165    fn resolve(&self, _name: &str, _arg: Option<&str>) -> Option<Value> {
166        None
167    }
168}
169
170/// Flat `HashMap` environment for tests and simple hosts (no `@` context; fixed clock in default impl).
171pub struct MapEnvironment {
172    /// Top-level and nested values (nested via object values); keys may be dotted.
173    pub fields: HashMap<String, Value>,
174    /// Clock source for `today()` / `now()` lookups.
175    pub current_datetime: Option<Date>,
176}
177
178impl MapEnvironment {
179    /// Empty field map.
180    pub fn new() -> Self {
181        Self {
182            fields: HashMap::new(),
183            current_datetime: Some(Date::DateTime {
184                year: 2026,
185                month: 3,
186                day: 20,
187                hour: 0,
188                minute: 0,
189                second: 0,
190            }),
191        }
192    }
193
194    /// Pre-populated field map.
195    pub fn with_fields(fields: HashMap<String, Value>) -> Self {
196        Self {
197            fields,
198            ..Self::new()
199        }
200    }
201
202    /// Override the environment clock used by `today()` and `now()`.
203    ///
204    /// Passing `None` removes the clock so calls to `today()` / `now()`
205    /// surface `MissingTimezoneContextError::NotConfigured`. Prefer the
206    /// readable [`MapEnvironment::without_clock`] constructor at call
207    /// sites that intend to exercise the no-clock contract.
208    pub fn with_current_datetime(mut self, current_datetime: Option<Date>) -> Self {
209        self.current_datetime = current_datetime;
210        self
211    }
212
213    /// Remove the environment clock so `today()` / `now()` produce the
214    /// `MissingTimezoneContext` diagnostic. Read-aloud companion to
215    /// [`MapEnvironment::with_current_datetime`] for the `None` case.
216    pub fn without_clock(self) -> Self {
217        self.with_current_datetime(None)
218    }
219}
220
221/// Empty `MapEnvironment` (delegates to [`MapEnvironment::new`]).
222impl Default for MapEnvironment {
223    fn default() -> Self {
224        Self::new()
225    }
226}
227
228/// Default clock: pinned to 2026-03-20 for deterministic tests/examples; resolves nested fields by dotted key or object walk.
229impl Environment for MapEnvironment {
230    fn resolve_field(&self, segments: &[String]) -> Value {
231        if segments.is_empty() {
232            return Value::Null;
233        }
234        let key = segments.join(".");
235        if let Some(val) = self.fields.get(&key) {
236            return val.clone();
237        }
238        // Walk nested objects
239        let mut current = match self.fields.get(&segments[0]) {
240            Some(v) => v.clone(),
241            None => return Value::Null,
242        };
243        for seg in &segments[1..] {
244            match &current {
245                Value::Object(entries) => match entries.get(seg.as_str()) {
246                    Some(v) => current = v.clone(),
247                    None => return Value::Null,
248                },
249                _ => return Value::Null,
250            }
251        }
252        current
253    }
254
255    fn resolve_context(&self, _name: &str, _arg: Option<&str>, _tail: &[String]) -> Value {
256        Value::Null
257    }
258
259    fn current_date(&self) -> Result<Date, MissingTimezoneContextError> {
260        match &self.current_datetime {
261            Some(Date::Date { year, month, day }) => Ok(Date::Date {
262                year: *year,
263                month: *month,
264                day: *day,
265            }),
266            Some(Date::DateTime {
267                year, month, day, ..
268            }) => Ok(Date::Date {
269                year: *year,
270                month: *month,
271                day: *day,
272            }),
273            None => Err(MissingTimezoneContextError::not_configured()),
274        }
275    }
276
277    fn current_datetime(&self) -> Result<Date, MissingTimezoneContextError> {
278        self.current_datetime
279            .clone()
280            .ok_or_else(MissingTimezoneContextError::not_configured)
281    }
282}
283
284/// Result of evaluation: a value plus any accumulated diagnostics.
285#[derive(Debug, Clone)]
286pub struct EvalResult {
287    /// Computed value (may be null after errors).
288    pub value: Value,
289    /// Non-fatal issues (undefined functions, type errors, etc.).
290    pub diagnostics: Vec<Diagnostic>,
291}
292
293/// Tree-walking evaluator with `let` scopes and diagnostic collection.
294pub struct Evaluator<'a> {
295    pub(super) env: &'a dyn Environment,
296    pub(super) extensions: Option<&'a dyn ExtensionFunctions>,
297    pub(super) context_bindings: Option<&'a dyn ContextBindingCatalog>,
298    pub(super) diagnostics: Vec<Diagnostic>,
299    pub(super) let_scopes: Vec<HashMap<String, Value>>,
300    /// Optional evaluation trace. `None` on the hot path, `Some` when the
301    /// caller passed [`EvaluatorOptions::trace`] to [`evaluate_with`].
302    pub(super) trace: Option<Trace>,
303    /// Stack of per-call argument caches used by traceable eager functions.
304    call_arg_cache_stack: Vec<CallArgCache>,
305    /// Nesting depth for `eval` recursion (capped at [`MAX_EVAL_DEPTH`]).
306    eval_depth: usize,
307    /// Resource budget for this evaluation run.
308    budget: EvalBudget,
309    /// Incrementing step counter checked against [`EvalBudget::max_steps`].
310    step_count: u64,
311    /// Best-effort allocation counter checked against [`EvalBudget::max_alloc_bytes`].
312    alloc_bytes: u64,
313    /// Set on first budget breach to suppress redundant diagnostics.
314    budget_breached: bool,
315}
316
317/// Memoizes evaluated argument [`Value`]s for one traced eager builtin call.
318///
319/// [`Self::args_ptr`] equals [`slice::as_ptr`] on the `&[Expr]` argument slice passed into
320/// `eval_function`. That slice is borrowed from the caller's [`Expr::FunctionCall`] and remains
321/// stable for the whole call; the evaluator must not hold this cache across a point where that
322/// `Vec` could reallocate. Teardown asserts the pointer still matches the slice being finalized.
323#[derive(Debug)]
324struct CallArgCache {
325    args_ptr: *const Expr,
326    values: Vec<Option<Value>>,
327}
328
329/// Configuration for an evaluation run.
330pub struct EvaluatorOptions<'a> {
331    /// Optional trace sink — when `Some`, the evaluator records structured steps into this trace.
332    pub trace: Option<&'a mut Trace>,
333    /// Optional host extension functions (Core §3.12) for resolving unknown function names.
334    pub extensions: Option<&'a dyn ExtensionFunctions>,
335    /// Resource budget for this evaluation run.
336    pub budget: EvalBudget,
337}
338
339impl Default for EvaluatorOptions<'_> {
340    fn default() -> Self {
341        Self {
342            trace: None,
343            extensions: None,
344            budget: EvalBudget::unlimited(),
345        }
346    }
347}
348
349fn is_grammar_reserved_context(name: &str) -> bool {
350    matches!(name, "current" | "index" | "count" | "instance")
351}
352
353fn context_tail_path(tail: &[String]) -> Vec<PathSegment> {
354    tail.iter().cloned().map(PathSegment::Dot).collect()
355}
356
357fn split_context_env_path(path: &[PathSegment]) -> (Vec<String>, &[PathSegment]) {
358    for (index, segment) in path.iter().enumerate() {
359        if !matches!(segment, PathSegment::Dot(_)) {
360            let prefix = path[..index]
361                .iter()
362                .filter_map(|segment| match segment {
363                    PathSegment::Dot(name) => Some(name.clone()),
364                    _ => None,
365                })
366                .collect();
367            return (prefix, &path[index..]);
368        }
369    }
370    let prefix = path
371        .iter()
372        .filter_map(|segment| match segment {
373            PathSegment::Dot(name) => Some(name.clone()),
374            _ => None,
375        })
376        .collect();
377    (prefix, &[])
378}
379
380/// Evaluate an expression against an environment (no budget, no trace, no extensions).
381pub fn evaluate(expr: &Expr, env: &dyn Environment) -> EvalResult {
382    evaluate_with(expr, env, EvaluatorOptions::default())
383}
384
385/// Evaluate with full configuration via [`EvaluatorOptions`].
386pub fn evaluate_with(expr: &Expr, env: &dyn Environment, options: EvaluatorOptions) -> EvalResult {
387    evaluate_configured(expr, env, options, None)
388}
389
390/// Evaluate with a host-supplied context binding catalog.
391///
392/// This sibling entry point preserves the [`EvaluatorOptions`] struct shape for
393/// existing callers while enabling FEL §6.3 catalog-aware evaluation.
394pub fn evaluate_with_catalog<'a>(
395    expr: &Expr,
396    env: &dyn Environment,
397    options: EvaluatorOptions<'a>,
398    catalog: &'a dyn ContextBindingCatalog,
399) -> EvalResult {
400    evaluate_configured(expr, env, options, Some(catalog))
401}
402
403fn evaluate_configured<'a>(
404    expr: &Expr,
405    env: &dyn Environment,
406    mut options: EvaluatorOptions<'a>,
407    context_bindings: Option<&'a dyn ContextBindingCatalog>,
408) -> EvalResult {
409    let caller_trace = options.trace.take();
410    let wants_trace = caller_trace.is_some();
411    let mut evaluator = Evaluator {
412        env,
413        extensions: options.extensions,
414        context_bindings,
415        diagnostics: Vec::new(),
416        let_scopes: Vec::new(),
417        trace: if wants_trace {
418            Some(Trace::new())
419        } else {
420            None
421        },
422        call_arg_cache_stack: Vec::new(),
423        eval_depth: 0,
424        budget: options.budget,
425        step_count: 0,
426        alloc_bytes: 0,
427        budget_breached: false,
428    };
429    let raw_value = evaluator.eval(expr);
430    if let (Some(ev_trace), Some(caller)) = (evaluator.trace, caller_trace) {
431        *caller = ev_trace;
432    }
433    // When the budget was breached during evaluation, null out any partial
434    // result. Partial values alongside a "budget exceeded" diagnostic are
435    // an attractive nuisance — hosts looking only at value would see a
436    // plausible-but-incomplete number / array. The harness in
437    // fuzz/fuzz_targets/fel_budget.rs encodes this contract; libFuzzer
438    // surfaced inputs where the existing code leaked partial subexpression
439    // results past the budget breach.
440    let value = if evaluator.budget_breached {
441        Value::Null
442    } else {
443        raw_value
444    };
445    EvalResult {
446        value,
447        diagnostics: evaluator.diagnostics,
448    }
449}
450
451impl<'a> Evaluator<'a> {
452    pub(super) fn diag(&mut self, msg: impl Into<String>) {
453        self.diagnostics.push(Diagnostic::error(msg));
454    }
455
456    pub(super) fn diag_coded(&mut self, code: impl Into<String>, msg: impl Into<String>) {
457        self.diagnostics.push(Diagnostic::error_coded(code, msg));
458    }
459
460    pub(in crate::evaluator) fn make_string(&mut self, s: String) -> Value {
461        self.track_alloc(s.len() as u64);
462        if self.alloc_limit_breached() {
463            return Value::Null;
464        }
465        Value::String(s)
466    }
467
468    fn make_array(&mut self, elems: Vec<Value>) -> Value {
469        self.track_alloc(
470            (elems.len() * 16) as u64 + elems.iter().map(value_size_estimate).sum::<u64>(),
471        );
472        if self.alloc_limit_breached() {
473            return Value::Null;
474        }
475        Value::Array(elems)
476    }
477
478    fn make_object(&mut self, entries: IndexMap<String, Value>) -> Value {
479        self.track_alloc(
480            (entries.len() * 40) as u64
481                + entries
482                    .iter()
483                    .map(|(k, v)| k.len() as u64 + value_size_estimate(v))
484                    .sum::<u64>(),
485        );
486        if self.alloc_limit_breached() {
487            return Value::Null;
488        }
489        Value::Object(entries)
490    }
491
492    /// Bump step counter and check budget; when exceeded, emit diagnostic and return `true`.
493    /// Suppresses duplicate budget diagnostics via [`Self::budget_breached`].
494    #[inline]
495    fn check_budget(&mut self) -> bool {
496        self.step_count += 1;
497        if self.budget_breached {
498            return true;
499        }
500        match self.budget.check(self.step_count, self.alloc_bytes) {
501            Ok(()) => false,
502            Err(kind) => {
503                let label = match kind {
504                    BudgetExceededKind::Steps => "steps",
505                    BudgetExceededKind::Alloc => "alloc",
506                    BudgetExceededKind::Deadline => "deadline",
507                };
508                self.diag(format!("budget exceeded ({label})"));
509                self.budget_breached = true;
510                true
511            }
512        }
513    }
514
515    /// Track an estimated allocation (best-effort, not byte-accurate).
516    /// Also checks the updated total against the budget, emitting a diagnostic if exceeded.
517    /// Suppresses duplicate budget diagnostics via [`Self::budget_breached`].
518    #[inline]
519    fn track_alloc(&mut self, bytes: u64) {
520        self.alloc_bytes = self.alloc_bytes.saturating_add(bytes);
521        if self.alloc_limit_breached() && !self.budget_breached {
522            self.diag("budget exceeded (alloc)");
523            self.budget_breached = true;
524        }
525    }
526
527    /// True after [`Self::track_alloc`] when estimated bytes exceed [`EvalBudget::max_alloc_bytes`].
528    #[inline]
529    fn alloc_limit_breached(&self) -> bool {
530        self.alloc_bytes > self.budget.max_alloc_bytes
531    }
532
533    /// Evaluates `pred` with `$` bound to `elem` for one let-scope frame.
534    pub(super) fn eval_under_dollar(&mut self, elem: &Value, pred: &Expr) -> Value {
535        self.let_scopes
536            .push(HashMap::from([("$".to_string(), elem.clone())]));
537        let out = self.eval(pred);
538        self.let_scopes.pop();
539        out
540    }
541
542    /// Records a structured type mismatch diagnostic (no [`Value`] returned).
543    pub(super) fn diag_expected_type(&mut self, fn_name: &str, expected: &str, got_type: &str) {
544        self.diagnostics
545            .push(Diagnostic::type_mismatch(fn_name, expected, got_type));
546    }
547
548    /// Records a type mismatch diagnostic and returns [`Value::Null`].
549    pub(super) fn reject_expected_type(
550        &mut self,
551        fn_name: &str,
552        expected: &str,
553        got: &Value,
554    ) -> Value {
555        self.diag_expected_type(fn_name, expected, got.type_name());
556        Value::Null
557    }
558
559    /// True iff this evaluator is recording a trace. Cheap predictable branch.
560    #[inline]
561    pub(super) fn tracing(&self) -> bool {
562        self.trace.is_some()
563    }
564
565    /// Append a step, no-op when not tracing.
566    #[inline]
567    pub(super) fn trace_step(&mut self, step: TraceStep) {
568        if let Some(t) = self.trace.as_mut() {
569            t.push(step);
570        }
571    }
572
573    fn eval_context_ref(
574        &mut self,
575        name: &str,
576        called: bool,
577        arg: Option<&str>,
578        tail: &[String],
579    ) -> Value {
580        let path = context_tail_path(tail);
581        self.eval_context_ref_path(name, called, arg, &path)
582    }
583
584    fn eval_context_ref_path(
585        &mut self,
586        name: &str,
587        called: bool,
588        arg: Option<&str>,
589        path: &[PathSegment],
590    ) -> Value {
591        if is_grammar_reserved_context(name) || self.context_bindings.is_none() {
592            let (env_tail, remaining_path) = split_context_env_path(path);
593            let base = self.env.resolve_context(name, arg, &env_tail);
594            return if remaining_path.is_empty() {
595                base
596            } else {
597                self.access_path(base, remaining_path)
598            };
599        }
600
601        let Some(catalog) = self.context_bindings else {
602            let (env_tail, remaining_path) = split_context_env_path(path);
603            let base = self.env.resolve_context(name, arg, &env_tail);
604            return if remaining_path.is_empty() {
605                base
606            } else {
607                self.access_path(base, remaining_path)
608            };
609        };
610        let Some(kind) = catalog.binding_kind(name) else {
611            self.diag_coded(
612                UNBOUND_CONTEXT_REF_CODE,
613                format!("unbound context reference: @{name}"),
614            );
615            return Value::Null;
616        };
617
618        match kind {
619            ContextBindingKind::Value => {
620                if called {
621                    self.diag_coded(
622                        "FEL-CONTEXT-BINDING-NOT-CALLABLE",
623                        format!("context binding @{name} is not callable"),
624                    );
625                    return Value::Null;
626                }
627                if !path.is_empty() {
628                    self.diag_coded(
629                        "FEL-CONTEXT-BINDING-PATH",
630                        format!("context binding @{name} does not support postfix traversal"),
631                    );
632                    return Value::Null;
633                }
634                self.resolve_context_binding_value(catalog, name, None, path)
635            }
636            ContextBindingKind::Object => {
637                if called {
638                    self.diag_coded(
639                        "FEL-CONTEXT-BINDING-NOT-CALLABLE",
640                        format!("context binding @{name} is not callable"),
641                    );
642                    return Value::Null;
643                }
644                self.resolve_context_binding_value(catalog, name, None, path)
645            }
646            ContextBindingKind::Function => {
647                if !called {
648                    self.diag_coded(
649                        "FEL-CONTEXT-BINDING-CALL-REQUIRED",
650                        format!("context binding @{name} must be called"),
651                    );
652                    return Value::Null;
653                }
654                self.resolve_context_binding_value(catalog, name, arg, path)
655            }
656        }
657    }
658
659    fn resolve_context_binding_value(
660        &mut self,
661        catalog: &dyn ContextBindingCatalog,
662        name: &str,
663        arg: Option<&str>,
664        path: &[PathSegment],
665    ) -> Value {
666        let Some(value) = catalog.resolve(name, arg) else {
667            self.diag_coded(
668                UNBOUND_CONTEXT_REF_CODE,
669                format!("unbound context reference: @{name}"),
670            );
671            return Value::Null;
672        };
673        self.access_path(value, path)
674    }
675}
676
677impl<'a> Evaluator<'a> {
678    pub(super) fn eval(&mut self, expr: &Expr) -> Value {
679        if self.eval_depth >= MAX_EVAL_DEPTH {
680            self.diag("expression evaluation depth exceeded");
681            return Value::Null;
682        }
683        if self.check_budget() {
684            return Value::Null;
685        }
686        self.eval_depth += 1;
687        let out = self.eval_impl(expr);
688        self.eval_depth -= 1;
689        out
690    }
691
692    fn eval_impl(&mut self, expr: &Expr) -> Value {
693        match expr {
694            Expr::Null => Value::Null,
695            Expr::Boolean(b) => Value::Boolean(*b),
696            Expr::Number(n) => Value::Number(*n),
697            Expr::String(s) => self.make_string(s.clone()),
698            Expr::DateLiteral(s) => match parse_date_literal(s) {
699                Some(d) => Value::Date(d),
700                None => {
701                    self.diag(format!("invalid date literal '{s}'"));
702                    Value::Null
703                }
704            },
705            Expr::DateTimeLiteral(s) => match parse_datetime_literal(s) {
706                Some(d) => Value::Date(d),
707                None => {
708                    self.diag(format!("invalid datetime literal '{s}'"));
709                    Value::Null
710                }
711            },
712            Expr::Array(elems) => {
713                let values: Vec<Value> = elems.iter().map(|e| self.eval(e)).collect();
714                self.make_array(values)
715            }
716            Expr::Object(entries) => {
717                let pairs: IndexMap<String, Value> = entries
718                    .iter()
719                    .map(|(k, v)| (k.clone(), self.eval(v)))
720                    .collect();
721                self.make_object(pairs)
722            }
723            Expr::FieldRef { name, path } => {
724                let value = self.eval_field_ref(name, path);
725                if self.tracing() {
726                    let rendered = render_field_path(name, path);
727                    self.trace_step(TraceStep::FieldResolved {
728                        path: rendered,
729                        value: fel_to_json(&value),
730                    });
731                }
732                value
733            }
734            Expr::VarRef { name, path } => {
735                let value = self.eval_field_ref(&Some(name.clone()), path);
736                if self.tracing() {
737                    let rendered = render_field_path(&Some(name.clone()), path);
738                    self.trace_step(TraceStep::FieldResolved {
739                        path: rendered,
740                        value: fel_to_json(&value),
741                    });
742                }
743                value
744            }
745            Expr::ContextRef {
746                name,
747                called,
748                arg,
749                tail,
750            } => self.eval_context_ref(name, *called, arg.as_deref(), tail),
751            Expr::UnaryOp { op, operand, .. } => {
752                let val = self.eval(operand);
753                self.eval_unary(*op, val)
754            }
755            Expr::BinaryOp { op, left, right } => self.eval_binary(*op, left, right),
756            Expr::Ternary {
757                condition,
758                then_branch,
759                else_branch,
760            }
761            | Expr::IfThenElse {
762                condition,
763                then_branch,
764                else_branch,
765            } => {
766                let cond = self.eval(condition);
767                match cond {
768                    Value::Null => {
769                        self.diag("if: condition evaluated to null");
770                        Value::Null
771                    }
772                    Value::Boolean(true) => {
773                        if self.tracing() {
774                            self.trace_step(TraceStep::IfBranch {
775                                condition_value: serde_json::Value::Bool(true),
776                                branch_taken: "then",
777                            });
778                        }
779                        self.eval(then_branch)
780                    }
781                    Value::Boolean(false) => {
782                        if self.tracing() {
783                            self.trace_step(TraceStep::IfBranch {
784                                condition_value: serde_json::Value::Bool(false),
785                                branch_taken: "else",
786                            });
787                        }
788                        self.eval(else_branch)
789                    }
790                    _ => self.reject_expected_type("if", "boolean", &cond),
791                }
792            }
793            Expr::Membership {
794                value,
795                container,
796                negated,
797            } => {
798                let val = self.eval(value);
799                let cont = self.eval(container);
800                self.eval_membership(val, cont, *negated)
801            }
802            Expr::NullCoalesce { left, right } => {
803                let l = self.eval(left);
804                if l.is_null() { self.eval(right) } else { l }
805            }
806            Expr::LetBinding { name, value, body } => {
807                let val = self.eval(value);
808                self.track_alloc(64);
809                if self.alloc_limit_breached() {
810                    return Value::Null;
811                }
812                self.let_scopes.push(HashMap::from([(name.clone(), val)]));
813                let result = self.eval(body);
814                self.let_scopes.pop();
815                result
816            }
817            Expr::FunctionCall { name, args } => {
818                // Eager traceable builtins rely on per-call arg caching (see `CallArgCache`);
819                // only pure functions may remain on the eager trace list.
820                let should_trace_call = self.tracing() && is_eager_traceable_function(name);
821                if should_trace_call {
822                    self.begin_call_arg_cache(args);
823                }
824                let result = self.eval_function(name, args);
825                if should_trace_call {
826                    let arg_vals = self.finish_call_arg_cache_as_json(args);
827                    self.trace_step(TraceStep::FunctionCalled {
828                        name: name.clone(),
829                        args: arg_vals,
830                        result: fel_to_json(&result),
831                    });
832                }
833                result
834            }
835            Expr::PostfixAccess { expr, path } => {
836                if let Expr::PostfixAccess {
837                    expr: inner,
838                    path: inner_path,
839                } = expr.as_ref()
840                {
841                    let mut combined = Vec::with_capacity(inner_path.len() + path.len());
842                    combined.extend(inner_path.iter().cloned());
843                    combined.extend(path.iter().cloned());
844                    if let Expr::ContextRef {
845                        name,
846                        called,
847                        arg,
848                        tail,
849                    } = inner.as_ref()
850                    {
851                        let mut context_path = context_tail_path(tail);
852                        context_path.extend(combined);
853                        return self.eval_context_ref_path(
854                            name,
855                            *called,
856                            arg.as_deref(),
857                            &context_path,
858                        );
859                    }
860                    let base = self.eval(inner);
861                    return self.access_path(base, &combined);
862                }
863                if let Expr::FieldRef {
864                    name: Some(name),
865                    path: base_path,
866                } = expr.as_ref()
867                {
868                    let mut segments = vec![name.clone()];
869                    let mut combined = Vec::with_capacity(base_path.len() + path.len());
870                    combined.extend(base_path.iter().cloned());
871                    combined.extend(path.iter().cloned());
872                    if combined
873                        .iter()
874                        .all(|segment| matches!(segment, PathSegment::Dot(_)))
875                    {
876                        // Let-bound identifiers resolve in `eval_field_ref` before the environment.
877                        // Skipping `eval(expr)` would merge path segments and call `resolve_field`
878                        // only, so e.g. `let x = {a: 1} in x.a` would wrongly yield null.
879                        let bound_in_let =
880                            self.let_scopes.iter().any(|scope| scope.contains_key(name));
881                        if !bound_in_let {
882                            for segment in &combined {
883                                if let PathSegment::Dot(part) = segment {
884                                    segments.push(part.clone());
885                                }
886                            }
887                            return self.env.resolve_field(&segments);
888                        }
889                    }
890                }
891                if let Expr::VarRef {
892                    name,
893                    path: base_path,
894                } = expr.as_ref()
895                {
896                    let mut segments = vec![name.clone()];
897                    let mut combined = Vec::with_capacity(base_path.len() + path.len());
898                    combined.extend(base_path.iter().cloned());
899                    combined.extend(path.iter().cloned());
900                    if combined
901                        .iter()
902                        .all(|segment| matches!(segment, PathSegment::Dot(_)))
903                    {
904                        let bound_in_let =
905                            self.let_scopes.iter().any(|scope| scope.contains_key(name));
906                        if !bound_in_let {
907                            for segment in &combined {
908                                if let PathSegment::Dot(part) = segment {
909                                    segments.push(part.clone());
910                                }
911                            }
912                            return self.env.resolve_field(&segments);
913                        }
914                    }
915                }
916                if let Expr::ContextRef {
917                    name,
918                    called,
919                    arg,
920                    tail,
921                } = expr.as_ref()
922                {
923                    let mut context_path = context_tail_path(tail);
924                    context_path.extend(path.iter().cloned());
925                    return self.eval_context_ref_path(
926                        name,
927                        *called,
928                        arg.as_deref(),
929                        &context_path,
930                    );
931                }
932                let base = self.eval(expr);
933                self.access_path(base, path)
934            }
935        }
936    }
937
938    // ── Field references ────────────────────────────────────────
939
940    fn eval_field_ref(&mut self, name: &Option<String>, path: &[PathSegment]) -> Value {
941        match name {
942            None => {
943                // Check let-scopes for bare `$` (predicate rebound in countWhere / every / some
944                // and in *Where helpers via filter_where).
945                for scope in self.let_scopes.iter().rev() {
946                    if let Some(val) = scope.get("$") {
947                        return if path.is_empty() {
948                            val.clone()
949                        } else {
950                            self.access_path(val.clone(), path)
951                        };
952                    }
953                }
954                let base = self.env.resolve_field(&[]);
955                if path.is_empty() {
956                    base
957                } else {
958                    self.access_path(base, path)
959                }
960            }
961            Some(n) => {
962                // Check let-scopes first
963                for scope in self.let_scopes.iter().rev() {
964                    if let Some(val) = scope.get(n) {
965                        return if path.is_empty() {
966                            val.clone()
967                        } else {
968                            self.access_path(val.clone(), path)
969                        };
970                    }
971                }
972                // Build segments for environment resolution
973                let mut segments = vec![n.clone()];
974                let mut remaining_path = Vec::new();
975                let mut hit_special = false;
976                for seg in path {
977                    if hit_special {
978                        remaining_path.push(seg.clone());
979                    } else {
980                        match seg {
981                            PathSegment::Dot(name) => segments.push(name.clone()),
982                            _ => {
983                                hit_special = true;
984                                remaining_path.push(seg.clone());
985                            }
986                        }
987                    }
988                }
989                let base = self.env.resolve_field(&segments);
990                if matches!(base, Value::Null)
991                    && path.iter().any(|seg| matches!(seg, PathSegment::Index(_)))
992                {
993                    let mut flat_segments = vec![n.clone()];
994                    for seg in path {
995                        match seg {
996                            PathSegment::Dot(name) => flat_segments.push(name.clone()),
997                            PathSegment::Index(idx) => {
998                                if let Some(last) = flat_segments.last_mut() {
999                                    last.push_str(&format!("[{idx}]"));
1000                                }
1001                            }
1002                            PathSegment::Wildcard => {
1003                                if let Some(last) = flat_segments.last_mut() {
1004                                    last.push_str("[*]");
1005                                }
1006                            }
1007                        }
1008                    }
1009                    let flat = self.env.resolve_field(&flat_segments);
1010                    if !matches!(flat, Value::Null) {
1011                        return flat;
1012                    }
1013                }
1014                if remaining_path.is_empty() {
1015                    base
1016                } else {
1017                    self.access_path(base, &remaining_path)
1018                }
1019            }
1020        }
1021    }
1022
1023    fn access_path(&mut self, mut current: Value, path: &[PathSegment]) -> Value {
1024        for (i, seg) in path.iter().enumerate() {
1025            match seg {
1026                PathSegment::Dot(name) => match &current {
1027                    Value::Object(entries) => {
1028                        current = entries.get(name.as_str()).cloned().unwrap_or(Value::Null);
1029                    }
1030                    Value::Null => return Value::Null,
1031                    _ => {
1032                        self.diag(format!("cannot access '{name}' on {}", current.type_name()));
1033                        return Value::Null;
1034                    }
1035                },
1036                PathSegment::Index(idx) => match &current {
1037                    Value::Array(arr) => {
1038                        // FEL indices are 1-based; guard above rejects 0 and OOB before subtracting.
1039                        if *idx == 0 || *idx > arr.len() {
1040                            self.diag(format!("index {idx} out of bounds (len {})", arr.len()));
1041                            return Value::Null;
1042                        }
1043                        current = arr.get(*idx - 1).cloned().unwrap_or(Value::Null);
1044                    }
1045                    Value::Null => return Value::Null,
1046                    _ => {
1047                        self.diag(format!("cannot index into {}", current.type_name()));
1048                        return Value::Null;
1049                    }
1050                },
1051                PathSegment::Wildcard => match &current {
1052                    Value::Array(arr) => {
1053                        let remaining = &path[i + 1..];
1054                        if remaining.is_empty() {
1055                            return current;
1056                        }
1057                        let elems: Vec<Value> = arr
1058                            .iter()
1059                            .map(|e| self.access_path(e.clone(), remaining))
1060                            .collect();
1061                        return self.make_array(elems);
1062                    }
1063                    Value::Null => return Value::Null,
1064                    _ => {
1065                        self.diag(format!("cannot wildcard on {}", current.type_name()));
1066                        return Value::Null;
1067                    }
1068                },
1069            }
1070        }
1071        current
1072    }
1073
1074    // ── Unary operators ─────────────────────────────────────────
1075
1076    fn eval_unary(&mut self, op: UnaryOp, val: Value) -> Value {
1077        match op {
1078            UnaryOp::Not => match val {
1079                Value::Null => Value::Null,
1080                Value::Boolean(b) => Value::Boolean(!b),
1081                _ => {
1082                    self.diag(format!("cannot apply 'not' to {}", val.type_name()));
1083                    Value::Null
1084                }
1085            },
1086            UnaryOp::Neg => match &val {
1087                Value::Null => Value::Null,
1088                Value::Number(n) => Value::Number(-n),
1089                Value::Array(arr) => {
1090                    let values: Vec<Value> =
1091                        arr.iter().map(|v| self.eval_unary(op, v.clone())).collect();
1092                    self.make_array(values)
1093                }
1094                _ => {
1095                    self.diag(format!("cannot negate {}", val.type_name()));
1096                    Value::Null
1097                }
1098            },
1099        }
1100    }
1101
1102    // ── Binary operators ────────────────────────────────────────
1103
1104    fn eval_binary(&mut self, op: BinaryOp, left_expr: &Expr, right_expr: &Expr) -> Value {
1105        // Short-circuit for logical ops
1106        match op {
1107            BinaryOp::And => {
1108                let left = self.eval(left_expr);
1109                if left.is_null() {
1110                    return Value::Null;
1111                }
1112                let left_bool = match left {
1113                    Value::Boolean(b) => b,
1114                    other => {
1115                        self.diag(format!("cannot apply 'and' to {}", other.type_name()));
1116                        return Value::Null;
1117                    }
1118                };
1119                if !left_bool {
1120                    if self.tracing() {
1121                        self.trace_step(TraceStep::ShortCircuit {
1122                            op: "and".into(),
1123                            reason: "left of 'and' was false, skipped right".into(),
1124                        });
1125                    }
1126                    return Value::Boolean(false);
1127                }
1128                let right = self.eval(right_expr);
1129                if right.is_null() {
1130                    return Value::Null;
1131                }
1132                return match right {
1133                    Value::Boolean(b) => {
1134                        if self.tracing() {
1135                            self.trace_step(TraceStep::BinaryOp {
1136                                op: "and".into(),
1137                                lhs: serde_json::Value::Bool(true),
1138                                rhs: serde_json::Value::Bool(b),
1139                                result: serde_json::Value::Bool(b),
1140                            });
1141                        }
1142                        Value::Boolean(b)
1143                    }
1144                    other => {
1145                        self.diag(format!("cannot apply 'and' to {}", other.type_name()));
1146                        Value::Null
1147                    }
1148                };
1149            }
1150            BinaryOp::Or => {
1151                let left = self.eval(left_expr);
1152                if left.is_null() {
1153                    return Value::Null;
1154                }
1155                let left_bool = match left {
1156                    Value::Boolean(b) => b,
1157                    other => {
1158                        self.diag(format!("cannot apply 'or' to {}", other.type_name()));
1159                        return Value::Null;
1160                    }
1161                };
1162                if left_bool {
1163                    if self.tracing() {
1164                        self.trace_step(TraceStep::ShortCircuit {
1165                            op: "or".into(),
1166                            reason: "left of 'or' was true, skipped right".into(),
1167                        });
1168                    }
1169                    return Value::Boolean(true);
1170                }
1171                let right = self.eval(right_expr);
1172                if right.is_null() {
1173                    return Value::Null;
1174                }
1175                return match right {
1176                    Value::Boolean(b) => {
1177                        if self.tracing() {
1178                            self.trace_step(TraceStep::BinaryOp {
1179                                op: "or".into(),
1180                                lhs: serde_json::Value::Bool(false),
1181                                rhs: serde_json::Value::Bool(b),
1182                                result: serde_json::Value::Bool(b),
1183                            });
1184                        }
1185                        Value::Boolean(b)
1186                    }
1187                    other => {
1188                        self.diag(format!("cannot apply 'or' to {}", other.type_name()));
1189                        Value::Null
1190                    }
1191                };
1192            }
1193            _ => {}
1194        }
1195
1196        let left = self.eval(left_expr);
1197        let right = self.eval(right_expr);
1198
1199        // Equality does NOT propagate null
1200        match op {
1201            BinaryOp::Eq => {
1202                let result = self.eval_equality(&left, &right);
1203                if self.tracing()
1204                    && !matches!(left, Value::Array(_))
1205                    && !matches!(right, Value::Array(_))
1206                {
1207                    self.trace_step(TraceStep::BinaryOp {
1208                        op: "==".into(),
1209                        lhs: fel_to_json(&left),
1210                        rhs: fel_to_json(&right),
1211                        result: fel_to_json(&result),
1212                    });
1213                }
1214                return result;
1215            }
1216            BinaryOp::NotEq => {
1217                let eq = self.eval_equality(&left, &right);
1218                let result = match eq {
1219                    Value::Boolean(b) => Value::Boolean(!b),
1220                    other => other,
1221                };
1222                if self.tracing()
1223                    && !matches!(left, Value::Array(_))
1224                    && !matches!(right, Value::Array(_))
1225                {
1226                    self.trace_step(TraceStep::BinaryOp {
1227                        op: "!=".into(),
1228                        lhs: fel_to_json(&left),
1229                        rhs: fel_to_json(&right),
1230                        result: fel_to_json(&result),
1231                    });
1232                }
1233                return result;
1234            }
1235            _ => {}
1236        }
1237
1238        // Array broadcasting
1239        match (&left, &right) {
1240            (Value::Array(la), Value::Array(ra)) => {
1241                if la.len() != ra.len() {
1242                    self.diag(format!(
1243                        "array length mismatch: {} vs {}",
1244                        la.len(),
1245                        ra.len()
1246                    ));
1247                    return Value::Null;
1248                }
1249                return {
1250                    let values: Vec<Value> = la
1251                        .iter()
1252                        .zip(ra.iter())
1253                        .map(|(l, r)| self.apply_binary(op, l, r))
1254                        .collect();
1255                    self.make_array(values)
1256                };
1257            }
1258            (Value::Array(la), _) => {
1259                return {
1260                    let values: Vec<Value> = la
1261                        .iter()
1262                        .map(|l| self.apply_binary(op, l, &right))
1263                        .collect();
1264                    self.make_array(values)
1265                };
1266            }
1267            (_, Value::Array(ra)) => {
1268                let values: Vec<Value> =
1269                    ra.iter().map(|r| self.apply_binary(op, &left, r)).collect();
1270                return self.make_array(values);
1271            }
1272            _ => {}
1273        }
1274
1275        let result = self.apply_binary(op, &left, &right);
1276        if self.tracing() {
1277            self.trace_step(TraceStep::BinaryOp {
1278                op: binary_op_symbol(op).into(),
1279                lhs: fel_to_json(&left),
1280                rhs: fel_to_json(&right),
1281                result: fel_to_json(&result),
1282            });
1283        }
1284        result
1285    }
1286
1287    fn apply_binary(&mut self, op: BinaryOp, left: &Value, right: &Value) -> Value {
1288        if left.is_null() || right.is_null() {
1289            return Value::Null;
1290        }
1291
1292        match op {
1293            BinaryOp::Add => self.num_op(left, right, "+"),
1294            BinaryOp::Sub => self.num_op(left, right, "-"),
1295            BinaryOp::Mul => self.num_op(left, right, "*"),
1296            BinaryOp::Div => {
1297                if let (Value::Number(a), Value::Number(b)) = (left, right) {
1298                    if b.is_zero() {
1299                        self.diag("division by zero");
1300                        Value::Null
1301                    } else {
1302                        match a.checked_div(*b) {
1303                            Some(q) => Value::Number(q),
1304                            None => {
1305                                self.diag("division overflow");
1306                                Value::Null
1307                            }
1308                        }
1309                    }
1310                } else if let (Value::Money(m), Value::Number(n)) = (left, right) {
1311                    if n.is_zero() {
1312                        self.diag("division by zero");
1313                        Value::Null
1314                    } else {
1315                        match m.amount.checked_div(*n) {
1316                            Some(amount) => Value::Money(Money {
1317                                amount,
1318                                currency: m.currency,
1319                            }),
1320                            None => {
1321                                self.diag("division overflow");
1322                                Value::Null
1323                            }
1324                        }
1325                    }
1326                } else if let (Value::Money(a), Value::Money(b)) = (left, right) {
1327                    if a.currency != b.currency {
1328                        self.diag(format!(
1329                            "currency mismatch: {} vs {}",
1330                            a.currency, b.currency
1331                        ));
1332                        Value::Null
1333                    } else if b.amount.is_zero() {
1334                        self.diag("division by zero");
1335                        Value::Null
1336                    } else {
1337                        match a.amount.checked_div(b.amount) {
1338                            Some(q) => Value::Number(q),
1339                            None => {
1340                                self.diag("division overflow");
1341                                Value::Null
1342                            }
1343                        }
1344                    }
1345                } else {
1346                    self.diag(format!(
1347                        "cannot divide {} by {}",
1348                        left.type_name(),
1349                        right.type_name()
1350                    ));
1351                    Value::Null
1352                }
1353            }
1354            BinaryOp::Mod => {
1355                if let (Value::Number(a), Value::Number(b)) = (left, right) {
1356                    if b.is_zero() {
1357                        self.diag("modulo by zero");
1358                        Value::Null
1359                    } else {
1360                        match a.checked_rem(*b) {
1361                            Some(r) => Value::Number(r),
1362                            None => {
1363                                self.diag("modulo overflow");
1364                                Value::Null
1365                            }
1366                        }
1367                    }
1368                } else if let (Value::Money(m), Value::Number(n)) = (left, right) {
1369                    if n.is_zero() {
1370                        self.diag("modulo by zero");
1371                        Value::Null
1372                    } else {
1373                        match m.amount.checked_rem(*n) {
1374                            Some(amount) => Value::Money(Money {
1375                                amount,
1376                                currency: m.currency,
1377                            }),
1378                            None => {
1379                                self.diag("modulo overflow");
1380                                Value::Null
1381                            }
1382                        }
1383                    }
1384                } else {
1385                    self.diag(format!(
1386                        "cannot modulo {} by {}",
1387                        left.type_name(),
1388                        right.type_name()
1389                    ));
1390                    Value::Null
1391                }
1392            }
1393            BinaryOp::Concat => {
1394                if let (Value::String(a), Value::String(b)) = (left, right) {
1395                    self.make_string(format!("{a}{b}"))
1396                } else {
1397                    self.diag(format!(
1398                        "cannot concat {} and {}",
1399                        left.type_name(),
1400                        right.type_name()
1401                    ));
1402                    Value::Null
1403                }
1404            }
1405            BinaryOp::Lt => self.compare(left, right, |o| o.is_lt()),
1406            BinaryOp::Gt => self.compare(left, right, |o| o.is_gt()),
1407            BinaryOp::LtEq => self.compare(left, right, |o| o.is_le()),
1408            BinaryOp::GtEq => self.compare(left, right, |o| o.is_ge()),
1409            BinaryOp::Eq | BinaryOp::NotEq | BinaryOp::And | BinaryOp::Or => {
1410                unreachable!("handled above")
1411            }
1412        }
1413    }
1414
1415    fn num_op(&mut self, left: &Value, right: &Value, sym: &str) -> Value {
1416        let combine = |a: Decimal, b: Decimal| -> Option<Decimal> {
1417            match sym {
1418                "+" => a.checked_add(b),
1419                "-" => a.checked_sub(b),
1420                "*" => a.checked_mul(b),
1421                _ => None,
1422            }
1423        };
1424
1425        match (left, right) {
1426            (Value::Number(a), Value::Number(b)) => match combine(*a, *b) {
1427                Some(v) => Value::Number(v),
1428                None => {
1429                    self.diag(format!("arithmetic overflow ({sym})"));
1430                    Value::Null
1431                }
1432            },
1433            (Value::Money(a), Value::Money(b)) if sym == "+" || sym == "-" => {
1434                if a.currency != b.currency {
1435                    self.diag(format!(
1436                        "currency mismatch: {} vs {}",
1437                        a.currency, b.currency
1438                    ));
1439                    Value::Null
1440                } else {
1441                    match combine(a.amount, b.amount) {
1442                        Some(amount) => Value::Money(Money {
1443                            amount,
1444                            currency: a.currency,
1445                        }),
1446                        None => {
1447                            self.diag(format!("arithmetic overflow ({sym})"));
1448                            Value::Null
1449                        }
1450                    }
1451                }
1452            }
1453            (Value::Money(m), Value::Number(n)) if sym == "+" || sym == "-" => {
1454                match combine(m.amount, *n) {
1455                    Some(amount) => Value::Money(Money {
1456                        amount,
1457                        currency: m.currency,
1458                    }),
1459                    None => {
1460                        self.diag(format!("arithmetic overflow ({sym})"));
1461                        Value::Null
1462                    }
1463                }
1464            }
1465            (Value::Money(m), Value::Number(n)) if sym == "*" => match m.amount.checked_mul(*n) {
1466                Some(amount) => Value::Money(Money {
1467                    amount,
1468                    currency: m.currency,
1469                }),
1470                None => {
1471                    self.diag("arithmetic overflow (*)");
1472                    Value::Null
1473                }
1474            },
1475            (Value::Number(n), Value::Money(m)) if sym == "*" => match n.checked_mul(m.amount) {
1476                Some(amount) => Value::Money(Money {
1477                    amount,
1478                    currency: m.currency,
1479                }),
1480                None => {
1481                    self.diag("arithmetic overflow (*)");
1482                    Value::Null
1483                }
1484            },
1485            _ => {
1486                self.diag(format!(
1487                    "cannot apply '{sym}' to {} and {}",
1488                    left.type_name(),
1489                    right.type_name()
1490                ));
1491                Value::Null
1492            }
1493        }
1494    }
1495
1496    pub(super) fn eval_equality(&mut self, left: &Value, right: &Value) -> Value {
1497        match (left, right) {
1498            (Value::Null, Value::Null) => Value::Boolean(true),
1499            (Value::Null, _) | (_, Value::Null) => Value::Boolean(false),
1500            (Value::Boolean(a), Value::Boolean(b)) => Value::Boolean(a == b),
1501            (Value::Number(a), Value::Number(b)) => Value::Boolean(a == b),
1502            (Value::String(a), Value::String(b)) => Value::Boolean(a == b),
1503            (Value::Date(a), Value::Date(b)) => Value::Boolean(a == b),
1504            (Value::Money(a), Value::Money(b)) => {
1505                Value::Boolean(a.currency == b.currency && a.amount == b.amount)
1506            }
1507            (Value::Array(a), Value::Array(b)) => {
1508                if a.len() != b.len() {
1509                    return Value::Boolean(false);
1510                }
1511                for (av, bv) in a.iter().zip(b.iter()) {
1512                    if !matches!(self.eval_equality(av, bv), Value::Boolean(true)) {
1513                        return Value::Boolean(false);
1514                    }
1515                }
1516                Value::Boolean(true)
1517            }
1518            (Value::Object(a), Value::Object(b)) => Value::Boolean(a == b),
1519            _ => {
1520                self.diag(format!(
1521                    "cannot compare {} with {}",
1522                    left.type_name(),
1523                    right.type_name()
1524                ));
1525                Value::Null
1526            }
1527        }
1528    }
1529
1530    fn compare(
1531        &mut self,
1532        left: &Value,
1533        right: &Value,
1534        check: fn(std::cmp::Ordering) -> bool,
1535    ) -> Value {
1536        let ord = match (left, right) {
1537            (Value::Number(a), Value::Number(b)) => a.cmp(b),
1538            (Value::String(a), Value::String(b)) => a.cmp(b),
1539            (Value::Date(a), Value::Date(b)) => a.ordinal().cmp(&b.ordinal()),
1540            // 9f: Money vs Number comparison — specific diagnostic with fix suggestion
1541            (Value::Money(_), Value::Number(_)) | (Value::Number(_), Value::Money(_)) => {
1542                self.diag("Type error: cannot compare money with number directly. Use moneyAmount($field) to extract the numeric amount.");
1543                return Value::Null;
1544            }
1545            // Money vs Money ordering — only equality is supported
1546            (Value::Money(_), Value::Money(_)) => {
1547                self.diag("Type error: cannot order money values directly. Use moneyAmount($field) to extract the numeric amount for ordering comparisons.");
1548                return Value::Null;
1549            }
1550            _ => {
1551                self.diag(format!(
1552                    "cannot compare {} with {}",
1553                    left.type_name(),
1554                    right.type_name()
1555                ));
1556                return Value::Null;
1557            }
1558        };
1559        Value::Boolean(check(ord))
1560    }
1561
1562    fn eval_membership(&mut self, value: Value, container: Value, negated: bool) -> Value {
1563        match &container {
1564            Value::Array(arr) => {
1565                let found = arr
1566                    .iter()
1567                    .any(|e| matches!(self.eval_equality(&value, e), Value::Boolean(true)));
1568                Value::Boolean(if negated { !found } else { found })
1569            }
1570            Value::Null => Value::Null,
1571            _ => {
1572                self.diag(format!(
1573                    "membership requires array, got {}",
1574                    container.type_name()
1575                ));
1576                Value::Null
1577            }
1578        }
1579    }
1580
1581    // ── Standard library functions ──────────────────────────────
1582
1583    fn eval_function(&mut self, name: &str, args: &[Expr]) -> Value {
1584        // Uniform catalog-driven arity gate (FUT-7). Every built-in's signature
1585        // — `(min, max)` derived from `BuiltinFunctionCatalogEntry::arity` — is
1586        // enforced before dispatch so handlers cannot silently accept too-few
1587        // args (defaulting missing positions to null) or too-many args (ignoring
1588        // tails). Unknown names skip this gate and fall through to the
1589        // extension registry / undefined-function diagnostic at the bottom.
1590        if let Some((min, max)) = crate::extensions::builtin_arity(name) {
1591            let got = args.len();
1592            let out_of_bounds = got < min || max.is_some_and(|m| got > m);
1593            if out_of_bounds {
1594                self.diagnostics
1595                    .push(Diagnostic::arity_mismatch(name, min, max, got));
1596                return Value::Null;
1597            }
1598        }
1599        match name {
1600            // Aggregates
1601            "sum" => self.fn_aggregate(args, "sum", |nums| nums.iter().copied().sum()),
1602            "count" => {
1603                let v = self.eval_arg(args, 0);
1604                self.fn_count(&v)
1605            }
1606            "avg" => self.fn_aggregate(args, "avg", |nums| {
1607                if nums.is_empty() {
1608                    Decimal::ZERO
1609                } else {
1610                    nums.iter().copied().sum::<Decimal>() / Decimal::from(nums.len() as i64)
1611                }
1612            }),
1613            "min" => self.fn_min_max(args, true),
1614            "max" => self.fn_min_max(args, false),
1615            "countWhere" => self.fn_count_where(args),
1616            "every" => self.fn_every(args),
1617            "some" => self.fn_some(args),
1618            "sumWhere" => self.fn_sum_where(args),
1619            "avgWhere" => self.fn_avg_where(args),
1620            "minWhere" => self.fn_min_where(args),
1621            "maxWhere" => self.fn_max_where(args),
1622
1623            // String
1624            "length" => self.fn_length(args),
1625            "contains" => self.fn_str2(args, "contains", |s, sub| Value::Boolean(s.contains(sub))),
1626            "startsWith" => {
1627                self.fn_str2(args, "startsWith", |s, p| Value::Boolean(s.starts_with(p)))
1628            }
1629            "endsWith" => self.fn_str2(args, "endsWith", |s, p| Value::Boolean(s.ends_with(p))),
1630            "substring" => self.fn_substring(args),
1631            "replace" => self.fn_replace(args),
1632            "upper" => self.fn_str1(args, "upper", |s| s.to_uppercase()),
1633            "lower" => self.fn_str1(args, "lower", |s| s.to_lowercase()),
1634            "trim" => self.fn_str1(args, "trim", |s| s.trim().to_string()),
1635            "matches" => self.fn_matches(args),
1636            "format" => self.fn_format(args),
1637
1638            // Numeric
1639            "round" => self.fn_round(args),
1640            "floor" => self.fn_num1(args, "floor", |n| n.floor()),
1641            "ceil" => self.fn_num1(args, "ceil", |n| n.ceil()),
1642            "abs" => self.fn_num1(args, "abs", |n| n.abs()),
1643            "power" => self.fn_power(args),
1644
1645            // Date
1646            "today" => self.fn_today(),
1647            "now" => self.fn_now(),
1648            "year" => self.fn_date_part(args, "year", |d| dec(d.year() as i64)),
1649            "month" => self.fn_date_part(args, "month", |d| dec(d.month() as i64)),
1650            "day" => self.fn_date_part(args, "day", |d| dec(d.day() as i64)),
1651            "hours" => self.fn_time_part(args, 0),
1652            "minutes" => self.fn_time_part(args, 1),
1653            "seconds" => self.fn_time_part(args, 2),
1654            "time" => self.fn_time(args),
1655            "timeDiff" => self.fn_time_diff(args),
1656            "duration" => self.fn_duration(args),
1657            "dateDiff" => self.fn_date_diff(args),
1658            "dateAdd" => self.fn_date_add(args),
1659
1660            // Logical
1661            "if" => self.fn_if(args),
1662            "coalesce" => self.fn_coalesce(args),
1663            "empty" => self.fn_empty(args),
1664            "present" => self.fn_present(args),
1665            "selected" => self.fn_selected(args),
1666
1667            // Type checking
1668            "isNumber" => self.fn_is_type(args, "number"),
1669            "isString" => self.fn_is_type(args, "string"),
1670            "isDate" => self.fn_is_type(args, "date"),
1671            "isNull" => {
1672                let v = self.eval_arg(args, 0);
1673                Value::Boolean(v.is_null())
1674            }
1675            "typeOf" => {
1676                let v = self.eval_arg(args, 0);
1677                self.make_string(v.type_name().to_string())
1678            }
1679
1680            // Casting
1681            "number" => self.fn_cast_number(args),
1682            "string" => self.fn_cast_string(args),
1683            "boolean" => self.fn_cast_boolean(args),
1684            "date" => self.fn_cast_date(args),
1685
1686            // Money
1687            "money" => self.fn_money(args),
1688            "moneyAmount" => {
1689                let v = self.eval_arg(args, 0);
1690                match v {
1691                    Value::Money(m) => Value::Number(m.amount),
1692                    Value::Null => Value::Null,
1693                    other => self.reject_expected_type("moneyAmount", "money", &other),
1694                }
1695            }
1696            "moneyCurrency" => {
1697                let v = self.eval_arg(args, 0);
1698                match v {
1699                    Value::Money(m) => self.make_string(m.currency.to_string()),
1700                    Value::Null => Value::Null,
1701                    other => self.reject_expected_type("moneyCurrency", "money", &other),
1702                }
1703            }
1704            "moneyAdd" => self.fn_money_add(args),
1705            "moneySum" => self.fn_money_sum(args),
1706            "moneySumWhere" => self.fn_money_sum_where(args),
1707
1708            // MIP state queries
1709            "valid" => self.fn_mip(args, "valid"),
1710            "relevant" => self.fn_mip(args, "relevant"),
1711            "readonly" => self.fn_mip(args, "readonly"),
1712            "required" => self.fn_mip(args, "required"),
1713
1714            // Repeat navigation
1715            "prev" => self.env.repeat_prev(),
1716            "next" => self.env.repeat_next(),
1717            "parent" => self.env.repeat_parent(),
1718            "instance" => self.fn_instance(args),
1719
1720            // Locale
1721            "locale" => self.fn_locale(),
1722            "formatNumber" => self.fn_format_number(args),
1723            "formatDate" => self.fn_format_date(args),
1724            "runtimeMeta" => self.fn_runtime_meta(args),
1725            "pluralCategory" => self.fn_plural_category(args),
1726
1727            _ => {
1728                let evaluated_args: Vec<Value> = args.iter().map(|arg| self.eval(arg)).collect();
1729                if let Some(extensions) = self.extensions {
1730                    match call_extension(extensions, name, &evaluated_args) {
1731                        ExtensionCallOutcome::Ok(result) => {
1732                            let result = match result {
1733                                Value::String(s) => self.make_string(s),
1734                                Value::Array(arr) => self.make_array(arr),
1735                                Value::Object(obj) => self.make_object(obj),
1736                                other => {
1737                                    self.track_alloc(value_size_estimate(&other));
1738                                    if self.alloc_limit_breached() {
1739                                        return Value::Null;
1740                                    }
1741                                    other
1742                                }
1743                            };
1744                            if self.tracing() {
1745                                self.trace_step(TraceStep::FunctionCalled {
1746                                    name: name.to_string(),
1747                                    args: evaluated_args.iter().map(fel_to_json).collect(),
1748                                    result: fel_to_json(&result),
1749                                });
1750                            }
1751                            return result;
1752                        }
1753                        ExtensionCallOutcome::ArityMismatch {
1754                            name,
1755                            min_args,
1756                            max_args,
1757                            got,
1758                        } => {
1759                            self.diagnostics
1760                                .push(Diagnostic::arity_mismatch(name, min_args, max_args, got));
1761                            return Value::Null;
1762                        }
1763                        ExtensionCallOutcome::Failed { name, message } => {
1764                            self.diagnostics
1765                                .push(Diagnostic::extension_failed(name, message));
1766                            return Value::Null;
1767                        }
1768                        ExtensionCallOutcome::NotFound => {}
1769                    }
1770                }
1771                self.diagnostics.push(Diagnostic::undefined_function(name));
1772                Value::Null
1773            }
1774        }
1775    }
1776
1777    pub(super) fn eval_arg(&mut self, args: &[Expr], idx: usize) -> Value {
1778        let args_ptr = args.as_ptr();
1779        if idx < args.len() {
1780            let use_top_cache = self
1781                .call_arg_cache_stack
1782                .last()
1783                .is_some_and(|cache| cache.args_ptr == args_ptr && idx < cache.values.len());
1784            if use_top_cache {
1785                if let Some(val) = self
1786                    .call_arg_cache_stack
1787                    .last()
1788                    .and_then(|cache| cache.values[idx].as_ref())
1789                {
1790                    return val.clone();
1791                }
1792                let evaluated = self.eval(&args[idx]);
1793                if let Some(cache) = self.call_arg_cache_stack.last_mut()
1794                    && cache.args_ptr == args_ptr
1795                    && idx < cache.values.len()
1796                {
1797                    cache.values[idx] = Some(evaluated.clone());
1798                }
1799                return evaluated;
1800            }
1801            self.eval(&args[idx])
1802        } else {
1803            Value::Null
1804        }
1805    }
1806
1807    pub(super) fn get_array<'v>(&mut self, val: &'v Value, fn_name: &str) -> Option<&'v [Value]> {
1808        match val {
1809            Value::Array(a) => Some(a.as_slice()),
1810            Value::Null => None,
1811            _ => {
1812                self.diag_expected_type(fn_name, "array", val.type_name());
1813                None
1814            }
1815        }
1816    }
1817
1818    fn begin_call_arg_cache(&mut self, args: &[Expr]) {
1819        self.call_arg_cache_stack.push(CallArgCache {
1820            args_ptr: args.as_ptr(),
1821            values: vec![None; args.len()],
1822        });
1823    }
1824
1825    fn finish_call_arg_cache_as_json(&mut self, args: &[Expr]) -> Vec<serde_json::Value> {
1826        let Some(mut cache) = self.call_arg_cache_stack.pop() else {
1827            self.diag("internal: missing call arg cache frame");
1828            return args.iter().map(|e| fel_to_json(&self.eval(e))).collect();
1829        };
1830        if cache.args_ptr != args.as_ptr() {
1831            self.diag("internal: call arg cache pointer mismatch");
1832            return args.iter().map(|e| fel_to_json(&self.eval(e))).collect();
1833        }
1834        cache
1835            .values
1836            .iter_mut()
1837            .enumerate()
1838            .map(|(idx, slot)| {
1839                let value = slot.take().unwrap_or_else(|| self.eval(&args[idx]));
1840                fel_to_json(&value)
1841            })
1842            .collect()
1843    }
1844
1845    /// Filter array elements by predicate (shared by sumWhere / avgWhere / minWhere / maxWhere / moneySumWhere).
1846    ///
1847    /// Arity is enforced upstream by the uniform pre-dispatch gate in `eval_function`;
1848    /// callers are guaranteed `args.len() >= 2` and may index `args[0]`/`args[1]` directly.
1849    pub(super) fn filter_where(&mut self, args: &[Expr], fn_name: &str) -> Option<Vec<Value>> {
1850        let arr_val = self.eval(&args[0]);
1851        let arr = self.get_array(&arr_val, fn_name)?;
1852        let mut matched = Vec::new();
1853        for elem in arr {
1854            let pred = self.eval_under_dollar(elem, &args[1]);
1855            if pred.is_truthy() {
1856                matched.push(elem.clone());
1857            }
1858        }
1859        Some(matched)
1860    }
1861}