| 1 | //! Tree-walking evaluator for the parsed AST. |
| 2 | //! |
| 3 | //! FEEL is null-friendly: most type errors (arithmetic on non-numbers, |
| 4 | //! comparing incomparable types, division by zero, a non-boolean condition, |
| 5 | //! …) evaluate to `null` rather than raising — this is the three-valued |
| 6 | //! (Kleene) logic the language is built on (see DECISIONS.md). `FeelError` is |
| 7 | //! therefore reserved for parse failures; evaluation here essentially always |
| 8 | //! produces a `Value`. |
| 9 | |
| 10 | use std::cell::Cell; |
| 11 | use std::cmp::Ordering; |
| 12 | use std::collections::{BTreeMap, HashSet}; |
| 13 | use std::sync::Arc; |
| 14 | |
| 15 | use crate::ast::{ArithOp, CallArgs, CmpOp, Expr, FeelType, IterSource, Quantifier, UnaryTest}; |
| 16 | use crate::builtins::resolve_index; |
| 17 | use crate::function::{Applier, Args, Closure, Func}; |
| 18 | use crate::{temporal, Context, EvalEnv, FeelError, Value}; |
| 19 | |
| 20 | type EvalResult = Result<Value, FeelError>; |
| 21 | |
| 22 | /// Maximum nested user-defined-function call depth (ADR-23). Closures and host |
| 23 | /// callables can call one another, so this bounds runaway recursion to an |
| 24 | /// error-null instead of a stack overflow — the same defensive spirit as the |
| 25 | /// `for`-range cap and the equality depth cap. Kept deliberately conservative so |
| 26 | /// the guard fires *before* the native stack is exhausted, even on hosts with a |
| 27 | /// small thread stack (a deeply nested tree-walk costs several native frames per |
| 28 | /// FEEL call). |
| 29 | const MAX_CALL_DEPTH: usize = 64; |
| 30 | |
| 31 | /// Recursion cap for the descendant traversal (`e ... name`, DMN §10.3.2.7). The |
| 32 | /// primary cycle guard is the visited-set of `Foreign` identities in |
| 33 | /// [`descendant_collect`]; this depth cap is a secondary backstop against |
| 34 | /// pathologically deep (but acyclic) data — the same defensive spirit as |
| 35 | /// `EQ_MAX_DEPTH`. |
| 36 | const DESCENDANT_MAX_DEPTH: usize = 1024; |
| 37 | |
| 38 | /// A tree-walking evaluator carrying the evaluation environment (host regex |
| 39 | /// provider + `now()`/`today()` instant + host function registry; |
| 40 | /// ADR-16/ADR-18/ADR-23). The env is held by reference and is **not** part of |
| 41 | /// [`Context`] (which is cloned per loop iteration and compared with `PartialEq`), |
| 42 | /// so threading it here keeps those cheap. |
| 43 | pub(crate) struct Evaluator<'a> { |
| 44 | pub(crate) env: &'a EvalEnv<'a>, |
| 45 | /// Current nested function-call depth, for the recursion guard (ADR-23). |
| 46 | call_depth: Cell<usize>, |
| 47 | } |
| 48 | |
| 49 | impl<'a> Evaluator<'a> { |
| 50 | /// Build an evaluator for an environment, with the call-depth counter reset. |
| 51 | pub(crate) fn new(env: &'a EvalEnv<'a>) -> Self { |
| 52 | Self { |
| 53 | env, |
| 54 | call_depth: Cell::new(0), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl Evaluator<'_> { |
| 60 | /// Evaluate an AST node against a context. |
| 61 | pub(crate) fn eval(&self, expr: &Expr, ctx: &Context) -> EvalResult { |
| 62 | match expr { |
| 63 | // --- literals --- |
| 64 | Expr::Number(n) => Ok(Value::Number(*n)), |
| 65 | Expr::Str(s) => Ok(Value::String(s.clone())), |
| 66 | // A malformed temporal literal is a type/domain error -> error-null. |
| 67 | // A named-zone literal is vetted away under the IMMUTABLE policy (RD-10). |
| 68 | Expr::TemporalLit(s) => { |
| 69 | let v = crate::temporal::parse_at_literal(s).unwrap_or(Value::Error); |
| 70 | Ok(self.env.vet_named_zone(v)) |
| 71 | } |
| 72 | Expr::Bool(b) => Ok(Value::Boolean(*b)), |
| 73 | Expr::Null => Ok(Value::Null), |
| 74 | Expr::List(items) => { |
| 75 | let mut out = Vec::with_capacity(items.len()); |
| 76 | for item in items { |
| 77 | out.push(self.eval(item, ctx)?); |
| 78 | } |
| 79 | Ok(Value::List(out)) |
| 80 | } |
| 81 | // A range literal in value position (DMN §10.3.4.6): evaluate both |
| 82 | // endpoints and box them into a `Value::Range`. Unlike the `range(string)` |
| 83 | // built-in, a *literal* is taken at face value — no ordering/type check — |
| 84 | // mirroring the interval *test* form, which also evaluates endpoints lazily. |
| 85 | Expr::RangeLit(iv) => { |
| 86 | // An omitted endpoint stays `None` (unbounded, ±∞; ADR-31) — distinct |
| 87 | // from a present `null` bound, which evaluates to `Some(Value::Null)`. |
| 88 | let start = self.eval_opt_endpoint(&iv.start, ctx)?; |
| 89 | let end = self.eval_opt_endpoint(&iv.end, ctx)?; |
| 90 | Ok(Value::Range(Box::new(crate::value::RangeVal { |
| 91 | start, |
| 92 | end, |
| 93 | start_open: iv.start_open, |
| 94 | end_open: iv.end_open, |
| 95 | }))) |
| 96 | } |
| 97 | // A parenthesised comparison-test value `(< 10)` (DMN §10.3.4.6; ADR-32): |
| 98 | // evaluate the endpoint and wrap it in an opaque `Value::UnaryTestVal`. It is |
| 99 | // NOT a range — its equality is structural and range-incompatible (see below). |
| 100 | Expr::UnaryTestVal(op, e) => Ok(Value::UnaryTestVal(Box::new( |
| 101 | crate::value::UnaryTestVal { |
| 102 | op: *op, |
| 103 | endpoint: self.eval(e, ctx)?.forced(), |
| 104 | }, |
| 105 | ))), |
| 106 | // Variable reference: (1) a context binding, (2) a known built-in name |
| 107 | // → a first-class function value (ADR-36), (3) an unbound name → null. |
| 108 | Expr::Var(name) => Ok(if let Some(v) = ctx.get(name) { |
| 109 | v.clone() |
| 110 | } else if crate::builtins::is_builtin(name) { |
| 111 | Func::Builtin(name.clone()).into_value() |
| 112 | } else { |
| 113 | Value::Null |
| 114 | }), |
| 115 | Expr::ContextLit(entries) => self.eval_context_lit(entries, ctx), |
| 116 | Expr::Path(target, name) => Ok(match self.eval(target, ctx)? { |
| 117 | // Selection on a list of contexts maps over the list and returns a |
| 118 | // list of selections (DMN §10.3.2.5): `[{x:1},{x:2}].x = [1, 2]`, |
| 119 | // a missing key in an element yielding a value-null in that slot. |
| 120 | // The list is *not* `forced()` first, so a `Foreign` left intact |
| 121 | // here keeps the single-object lazy path below (ADR-21). |
| 122 | Value::List(items) => { |
| 123 | Value::List(items.into_iter().map(|it| member_access(it, name)).collect()) |
| 124 | } |
| 125 | other => member_access(other, name), |
| 126 | }), |
| 127 | // Descendant `e ... name` (DMN §10.3.2.7, grammar rule 68): collect every |
| 128 | // value bound to `name` in `e` and all nested contexts/lists, depth-first, |
| 129 | // into a list. A null/error target propagates; a non-navigable scalar is |
| 130 | // null (the `.` operator behaves the same). The recursive walk is the |
| 131 | // engine's first *unbounded* collection, so a cyclic host graph behind |
| 132 | // `Value::Foreign` needs a visited-set guard — see [`descendant_collect`]. |
| 133 | Expr::Descendant(target, name) => { |
| 134 | let v = self.eval(target, ctx)?.forced(); |
| 135 | Ok(match &v { |
| 136 | Value::Null => Value::Null, |
| 137 | Value::Error => Value::Error, |
| 138 | Value::Context(_) | Value::List(_) | Value::Foreign(_) => { |
| 139 | let mut out = Vec::new(); |
| 140 | let mut seen = HashSet::new(); |
| 141 | descendant_collect(&v, name, &mut seen, &mut out, 0); |
| 142 | Value::List(out) |
| 143 | } |
| 144 | // A non-navigable scalar/range/function: applicability "type e is |
| 145 | // a context" fails -> null (mirrors `.` on a non-context). |
| 146 | _ => Value::Null, |
| 147 | }) |
| 148 | } |
| 149 | Expr::Filter(source, bracket) => self.eval_filter(source, bracket, ctx), |
| 150 | // A function literal captures the current scope (lexical closure, ADR-23). |
| 151 | Expr::FnDef { params, body } => Ok(Func::Closure(Closure { |
| 152 | params: params.clone(), |
| 153 | body: Arc::new((**body).clone()), |
| 154 | captured: ctx.clone(), |
| 155 | }) |
| 156 | .into_value()), |
| 157 | Expr::FnCall(name, args) => self.eval_call(name, args, ctx), |
| 158 | // Value-invocation: evaluate the callee, invoke if it is a function, else |
| 159 | // error-null (DMN §10.3.2.13.2; ADR-38). Args are skipped for non-functions |
| 160 | // — FEEL has no side-effects, so this is observably identical to evaluating |
| 161 | // them. |
| 162 | Expr::Invoke(callee, args) => match self.eval(callee, ctx)?.forced() { |
| 163 | Value::Function(f) => { |
| 164 | let a = self.eval_args(args, ctx)?; |
| 165 | self.invoke(&f, a) |
| 166 | } |
| 167 | _ => Ok(Value::Error), |
| 168 | }, |
| 169 | |
| 170 | // --- arithmetic --- |
| 171 | // Operands are `forced()` so a lazy host value is materialised before |
| 172 | // any non-path use (ADR-21); this is a no-op for every non-`Foreign`. |
| 173 | Expr::Neg(e) => Ok(match self.eval(e, ctx)?.forced() { |
| 174 | Value::Number(n) => Value::Number(-n), |
| 175 | // Negating a duration flips its sign (ADR-18). |
| 176 | v if temporal::is_temporal(&v) => temporal::negate(&v).unwrap_or(Value::Error), |
| 177 | _ => Value::Error, // negation of a non-number/non-duration -> error-null |
| 178 | }), |
| 179 | Expr::Arith(op, l, r) => eval_arith( |
| 180 | *op, |
| 181 | self.eval(l, ctx)?.forced(), |
| 182 | self.eval(r, ctx)?.forced(), |
| 183 | ), |
| 184 | |
| 185 | // --- comparison --- |
| 186 | Expr::Compare(op, l, r) => Ok(eval_compare( |
| 187 | *op, |
| 188 | &self.eval(l, ctx)?.forced(), |
| 189 | &self.eval(r, ctx)?.forced(), |
| 190 | )), |
| 191 | Expr::Between(v, lo, hi) => { |
| 192 | let v = self.eval(v, ctx)?.forced(); |
| 193 | let lo = self.eval(lo, ctx)?.forced(); |
| 194 | let hi = self.eval(hi, ctx)?.forced(); |
| 195 | // low <= v and v <= high (three-valued) |
| 196 | Ok(and3( |
| 197 | eval_compare(CmpOp::Le, &lo, &v), |
| 198 | eval_compare(CmpOp::Le, &v, &hi), |
| 199 | )) |
| 200 | } |
| 201 | Expr::In(value, tests) => self.eval_in(value, tests, ctx), |
| 202 | // Type predicate (DMN §10.3.2.9, rule 51). An unmappable type → null; a |
| 203 | // null/error value is an instance only of `Null`; any other value is |
| 204 | // checked structurally against the target type (ADR-26). |
| 205 | Expr::InstanceOf(e, ty) => { |
| 206 | if !ty.is_mappable() { |
| 207 | return Ok(Value::Null); |
| 208 | } |
| 209 | Ok(match self.eval(e, ctx)?.forced() { |
| 210 | Value::Null | Value::Error => Value::Boolean(matches!(ty, FeelType::Null)), |
| 211 | other => Value::Boolean(crate::types::value_conforms_to(&other, ty)), |
| 212 | }) |
| 213 | } |
| 214 | |
| 215 | // --- three-valued logic --- |
| 216 | Expr::And(l, r) => Ok(and3( |
| 217 | self.eval(l, ctx)?.forced(), |
| 218 | self.eval(r, ctx)?.forced(), |
| 219 | )), |
| 220 | Expr::Or(l, r) => Ok(or3( |
| 221 | self.eval(l, ctx)?.forced(), |
| 222 | self.eval(r, ctx)?.forced(), |
| 223 | )), |
| 224 | Expr::Not(e) => Ok(match self.eval(e, ctx)?.forced() { |
| 225 | Value::Boolean(b) => Value::Boolean(!b), |
| 226 | // `not` of a value-null is the Kleene "not unknown = unknown". |
| 227 | Value::Null => Value::Null, |
| 228 | _ => Value::Error, // not of a non-boolean (or error) -> error-null |
| 229 | }), |
| 230 | |
| 231 | // --- control flow --- |
| 232 | // `if` keys on the *provenance* of its condition (ADR-13/ADR-14): |
| 233 | // true -> then |
| 234 | // false / value-null -> else (null is a value meaning "not true", |
| 235 | // per DMN-TCK 0032) |
| 236 | // error-null / wrong type -> error-null (a type error escalates; |
| 237 | // it does not silently take `else`) |
| 238 | Expr::If(c, t, e) => match self.eval(c, ctx)?.forced() { |
| 239 | Value::Boolean(true) => self.eval(t, ctx), |
| 240 | Value::Boolean(false) | Value::Null => self.eval(e, ctx), |
| 241 | _ => Ok(Value::Error), |
| 242 | }, |
| 243 | Expr::For { bindings, body } => self.eval_for(bindings, body, ctx), |
| 244 | Expr::Quantified { |
| 245 | kind, |
| 246 | bindings, |
| 247 | predicate, |
| 248 | } => self.eval_quantified(*kind, bindings, predicate, ctx), |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | // ----------------------------------------------------------------------- // |
| 253 | // Context literal |
| 254 | // ----------------------------------------------------------------------- // |
| 255 | |
| 256 | /// Evaluate `{a: 1, b: a + 1}`. Entries are bound progressively: each value is |
| 257 | /// evaluated against the outer context extended with the entries seen so far, |
| 258 | /// so a later entry can reference an earlier one. |
| 259 | fn eval_context_lit(&self, entries: &[(String, Box<Expr>)], ctx: &Context) -> EvalResult { |
| 260 | let mut map = BTreeMap::new(); |
| 261 | let mut scope = ctx.clone(); |
| 262 | for (key, value_expr) in entries { |
| 263 | let value = self.eval(value_expr, &scope)?; |
| 264 | scope.insert(key.clone(), value.clone()); |
| 265 | if map.insert(key.clone(), value).is_some() { |
| 266 | // A context literal with duplicate keys is invalid (DMN-TCK 0057) -> |
| 267 | // error-null; we cannot keep "all specified entries". |
| 268 | return Ok(Value::Error); |
| 269 | } |
| 270 | } |
| 271 | Ok(Value::Context(map)) |
| 272 | } |
| 273 | |
| 274 | // ----------------------------------------------------------------------- // |
| 275 | // Function calls (ADR-23) |
| 276 | // ----------------------------------------------------------------------- // |
| 277 | |
| 278 | /// Evaluate a call `name(args)`, resolving the callee with this precedence: |
| 279 | /// 1. a function value bound in scope (a closure or a host callable) — this |
| 280 | /// lets a binding shadow a built-in (host override), and is how the FEEL |
| 281 | /// `function(…)` literal is invoked; |
| 282 | /// 2. a built-in (the reorder shim handles named arguments; ADR-23); |
| 283 | /// 3. an ambient host function from the [`FunctionRegistry`](crate::FunctionRegistry); |
| 284 | /// 4. otherwise an error-null (unknown function). |
| 285 | /// |
| 286 | /// Arguments are evaluated **unforced** (no `.forced()`), so path laziness flows |
| 287 | /// through the call exactly like a `for`/quantifier variable (ADR-21). Built-ins |
| 288 | /// force them internally; closures and host callables receive them lazy. |
| 289 | fn eval_call(&self, name: &str, args: &CallArgs, ctx: &Context) -> EvalResult { |
| 290 | // 1. A function-valued binding shadows everything else. |
| 291 | if let Some(Value::Function(f)) = ctx.get(name) { |
| 292 | let f = f.clone(); |
| 293 | let args = self.eval_args(args, ctx)?; |
| 294 | return self.invoke(&f, args); |
| 295 | } |
| 296 | // 2. A built-in. `builtins::call` returns `None` for a name it does not |
| 297 | // implement, so the call can fall through to the host registry. |
| 298 | let evaluated = self.eval_args(args, ctx)?; |
| 299 | if let Some(result) = crate::builtins::call(name, evaluated, self.env, self) { |
| 300 | return Ok(result); |
| 301 | } |
| 302 | // 3. An ambient host function (the arguments were consumed by the built-in |
| 303 | // probe above, so re-evaluate them — kept unforced for the host). |
| 304 | if let Some(host_fn) = self.env.functions.get(name) { |
| 305 | let args = self.eval_args(args, ctx)?; |
| 306 | return Ok(host_fn.call(args)); |
| 307 | } |
| 308 | // 4. Unknown function. |
| 309 | Ok(Value::Error) |
| 310 | } |
| 311 | |
| 312 | /// Evaluate the positional and named argument expressions, unforced. |
| 313 | fn eval_args(&self, args: &CallArgs, ctx: &Context) -> Result<Args, FeelError> { |
| 314 | let mut positional = Vec::with_capacity(args.positional.len()); |
| 315 | for arg in &args.positional { |
| 316 | positional.push(self.eval(arg, ctx)?); |
| 317 | } |
| 318 | let mut named = Vec::with_capacity(args.named.len()); |
| 319 | for (name, arg) in &args.named { |
| 320 | named.push((name.clone(), self.eval(arg, ctx)?)); |
| 321 | } |
| 322 | Ok(Args { positional, named }) |
| 323 | } |
| 324 | |
| 325 | /// Invoke a function value (native closure, host callable, or built-in ref) with |
| 326 | /// evaluated args. |
| 327 | fn invoke(&self, f: &Func, args: Args) -> EvalResult { |
| 328 | match f { |
| 329 | // A host callable owns its own arity/defaults (ADR-23): pass the args |
| 330 | // straight through, no checking here. |
| 331 | Func::Foreign(host_fn) => Ok(host_fn.call(args)), |
| 332 | Func::Closure(closure) => self.invoke_closure(closure, args), |
| 333 | // A first-class built-in reference: dispatch through the normal built-in |
| 334 | // table. `call` returns `None` only for names not in the table — which |
| 335 | // cannot happen here (the name was validated by `is_builtin` when the |
| 336 | // value was created) — so `unwrap_or(Error)` is a safety net (ADR-36). |
| 337 | Func::Builtin(name) => Ok(crate::builtins::call(name, args, self.env, self) |
| 338 | .unwrap_or(Value::Error)), |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | /// Invoke a FEEL closure: bind the arguments to its formal parameters in the |
| 343 | /// captured (lexical) scope, then evaluate the body there. Binding is lenient |
| 344 | /// vs. spec §10.3.2.13.5 — an unsupplied parameter is bound to value-null |
| 345 | /// rather than rejecting the call — but a genuine non-conformance (an unknown |
| 346 | /// parameter name, a parameter bound both positionally and by name, or too many |
| 347 | /// positional arguments) is an error-null. The recursion guard bounds nested |
| 348 | /// calls (ADR-23). |
| 349 | fn invoke_closure(&self, closure: &Closure, args: Args) -> EvalResult { |
| 350 | let depth = self.call_depth.get(); |
| 351 | if depth >= MAX_CALL_DEPTH { |
| 352 | return Ok(Value::Error); |
| 353 | } |
| 354 | let scope = match bind_params(&closure.captured, &closure.params, args) { |
| 355 | Ok(scope) => scope, |
| 356 | Err(()) => return Ok(Value::Error), // arguments do not conform |
| 357 | }; |
| 358 | self.call_depth.set(depth + 1); |
| 359 | let result = self.eval(&closure.body, &scope); |
| 360 | self.call_depth.set(depth); |
| 361 | result |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /// Wire up the `Applier` seam so higher-order built-ins can invoke a |
| 366 | /// function-valued argument through the same path as a direct FEEL call — |
| 367 | /// including the recursion-depth guard (ADR-37). |
| 368 | impl Applier for Evaluator<'_> { |
| 369 | fn apply(&self, f: &Func, args: Args) -> Value { |
| 370 | // `invoke` returns `EvalResult = Result<Value, FeelError>`. A genuine |
| 371 | // `FeelError` (parse failure) cannot occur here — we are already inside |
| 372 | // the evaluator — so `unwrap_or(Error)` is purely a type-level safety net. |
| 373 | self.invoke(f, args).unwrap_or(Value::Error) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// Bind call arguments to a closure's formal parameters, returning the body scope |
| 378 | /// (the captured scope extended with the bindings). `Err(())` signals |
| 379 | /// non-conformance: an unknown named parameter, a parameter supplied both |
| 380 | /// positionally and by name, more positional arguments than parameters, or a |
| 381 | /// typed parameter whose actual argument fails §10.3.2.9.4 implicit conversion. |
| 382 | /// An unsupplied parameter is bound to value-null (spec §10.3.2.13.5). |
| 383 | fn bind_params( |
| 384 | captured: &Context, |
| 385 | params: &[(String, Option<FeelType>)], |
| 386 | args: Args, |
| 387 | ) -> Result<Context, ()> { |
| 388 | if args.positional.len() > params.len() { |
| 389 | return Err(()); // too many positional arguments |
| 390 | } |
| 391 | let mut scope = captured.clone(); |
| 392 | let mut bound = vec![false; params.len()]; |
| 393 | for (i, value) in args.positional.into_iter().enumerate() { |
| 394 | scope.insert(params[i].0.clone(), value); |
| 395 | bound[i] = true; |
| 396 | } |
| 397 | for (name, value) in args.named { |
| 398 | match params.iter().position(|(p, _)| p == &name) { |
| 399 | Some(i) if !bound[i] => { |
| 400 | scope.insert(name, value); |
| 401 | bound[i] = true; |
| 402 | } |
| 403 | Some(_) => return Err(()), // already bound positionally |
| 404 | None => return Err(()), // unknown parameter name |
| 405 | } |
| 406 | } |
| 407 | for (i, (param, _)) in params.iter().enumerate() { |
| 408 | if !bound[i] { |
| 409 | scope.insert(param.clone(), Value::Null); // unsupplied -> value-null |
| 410 | } |
| 411 | } |
| 412 | // Apply invocation-context implicit conversions (§10.3.2.9.4): for each |
| 413 | // typed formal parameter, coerce the actual argument. A null argument has |
| 414 | // type `Null <: T` and is left as-is; a coercion failure (non-conforming |
| 415 | // actual) aborts the entire call → error-null (`decision_bkm_002`, `fd_002`). |
| 416 | for (name, ty) in params { |
| 417 | if let Some(t) = ty { |
| 418 | if let Some(v) = scope.get(name) { |
| 419 | if !matches!(v, Value::Null) { |
| 420 | let coerced = crate::types::coerce(v.clone(), t); |
| 421 | if matches!(coerced, Value::Null) { |
| 422 | return Err(()); |
| 423 | } |
| 424 | scope.insert(name.clone(), coerced); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | Ok(scope) |
| 430 | } |
| 431 | |
| 432 | // --------------------------------------------------------------------------- // |
| 433 | // Arithmetic |
| 434 | // --------------------------------------------------------------------------- // |
| 435 | |
| 436 | fn eval_arith(op: ArithOp, lhs: Value, rhs: Value) -> EvalResult { |
| 437 | // Numeric path: both operands are numbers. |
| 438 | if let (Some(a), Some(b)) = (as_number(&lhs), as_number(&rhs)) { |
| 439 | let out = match op { |
| 440 | ArithOp::Add => a + b, |
| 441 | ArithOp::Sub => a - b, |
| 442 | ArithOp::Mul => a * b, |
| 443 | ArithOp::Div => { |
| 444 | if b == 0.0 { |
| 445 | return Ok(Value::Error); // division by zero -> error-null |
| 446 | } |
| 447 | a / b |
| 448 | } |
| 449 | ArithOp::Pow => a.powf(b), |
| 450 | }; |
| 451 | // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) are a domain error; |
| 452 | // this also keeps every Number JSON-representable at the wrappers. |
| 453 | return Ok(if out.is_finite() { |
| 454 | Value::Number(out) |
| 455 | } else { |
| 456 | Value::Error |
| 457 | }); |
| 458 | } |
| 459 | // String concatenation: `"foo" + "bar" = "foobar"` (FEEL defines `+` on strings). |
| 460 | if let (ArithOp::Add, Value::String(a), Value::String(b)) = (op, &lhs, &rhs) { |
| 461 | return Ok(Value::String(format!("{a}{b}"))); |
| 462 | } |
| 463 | // Temporal path: date/time/duration arithmetic (ADR-18). Anything not defined |
| 464 | // (incl. a number mixed with a non-duration) is an error-null. |
| 465 | Ok(temporal::arith(op, &lhs, &rhs).unwrap_or(Value::Error)) |
| 466 | } |
| 467 | |
| 468 | // --------------------------------------------------------------------------- // |
| 469 | // Comparison & equality (three-valued, cross-type) |
| 470 | // --------------------------------------------------------------------------- // |
| 471 | |
| 472 | fn eval_compare(op: CmpOp, a: &Value, b: &Value) -> Value { |
| 473 | match op { |
| 474 | // Equality is defined for null (null = null -> true), so it does not |
| 475 | // propagate null; only a type mismatch (`None`) is an error. |
| 476 | CmpOp::Eq => eq_result(feel_equal(a, b)), |
| 477 | CmpOp::Ne => eq_result(feel_equal(a, b).map(|eq| !eq)), |
| 478 | CmpOp::Lt => order_compare(a, b, |o| o == Ordering::Less), |
| 479 | CmpOp::Le => order_compare(a, b, |o| o != Ordering::Greater), |
| 480 | CmpOp::Gt => order_compare(a, b, |o| o == Ordering::Greater), |
| 481 | CmpOp::Ge => order_compare(a, b, |o| o != Ordering::Less), |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /// FEEL equality, three-valued: |
| 486 | /// * both null-ish -> Some(true) (error-null equals value-null) |
| 487 | /// * exactly one null-ish -> Some(false) |
| 488 | /// * same type -> Some(value comparison) (lists compared elementwise) |
| 489 | /// * different non-null -> None (-> error-null at the call site) |
| 490 | fn feel_equal(a: &Value, b: &Value) -> Option<bool> { |
| 491 | feel_equal_depth(a, b, 0) |
| 492 | } |
| 493 | |
| 494 | /// Recursion cap for structural equality. Legitimate FEEL data never nests this |
| 495 | /// deep; the cap only bites when two *distinct* cyclic foreign graphs (ADR-21) |
| 496 | /// are compared structurally — which would otherwise diverge — degrading that one |
| 497 | /// pathological case to error-null (`None`). |
| 498 | const EQ_MAX_DEPTH: usize = 1024; |
| 499 | |
| 500 | fn feel_equal_depth(a: &Value, b: &Value, depth: usize) -> Option<bool> { |
| 501 | use Value::{Error, Null}; |
| 502 | // Foreign (ADR-21): identical handles are equal without forcing (this also |
| 503 | // makes `a = a` on a cyclic graph terminate); otherwise force one level and |
| 504 | // recurse, bounded by the depth cap. |
| 505 | if matches!(a, Value::Foreign(_)) || matches!(b, Value::Foreign(_)) { |
| 506 | if let (Value::Foreign(x), Value::Foreign(y)) = (a, b) { |
| 507 | if std::sync::Arc::ptr_eq(&x.0, &y.0) { |
| 508 | return Some(true); |
| 509 | } |
| 510 | } |
| 511 | if depth >= EQ_MAX_DEPTH { |
| 512 | return None; |
| 513 | } |
| 514 | return feel_equal_depth(&a.clone().forced(), &b.clone().forced(), depth + 1); |
| 515 | } |
| 516 | // Functions (ADR-23): equal only if they are the *same* value (same `Arc`); |
| 517 | // two distinct functions are incomparable -> error-null. A function compared to |
| 518 | // a non-function is a type mismatch -> error-null (the final `_` arm). |
| 519 | if let (Value::Function(x), Value::Function(y)) = (a, b) { |
| 520 | return if std::sync::Arc::ptr_eq(x, y) { |
| 521 | Some(true) |
| 522 | } else { |
| 523 | None |
| 524 | }; |
| 525 | } |
| 526 | match (a, b) { |
| 527 | (Null | Error, Null | Error) => Some(true), |
| 528 | (Null | Error, _) | (_, Null | Error) => Some(false), |
| 529 | (Value::Number(x), Value::Number(y)) => Some(x == y), |
| 530 | (Value::Boolean(x), Value::Boolean(y)) => Some(x == y), |
| 531 | (Value::String(x), Value::String(y)) => Some(x == y), |
| 532 | (Value::List(xs), Value::List(ys)) => { |
| 533 | if xs.len() != ys.len() { |
| 534 | return Some(false); |
| 535 | } |
| 536 | let mut result = Some(true); |
| 537 | for (x, y) in xs.iter().zip(ys) { |
| 538 | match feel_equal_depth(x, y, depth + 1) { |
| 539 | Some(false) => return Some(false), |
| 540 | None => result = None, // type-mismatched element -> null (unless a later false) |
| 541 | Some(true) => {} |
| 542 | } |
| 543 | } |
| 544 | result |
| 545 | } |
| 546 | (Value::Context(xs), Value::Context(ys)) => { |
| 547 | if xs.len() != ys.len() { |
| 548 | return Some(false); |
| 549 | } |
| 550 | let mut result = Some(true); |
| 551 | for ((xk, xv), (yk, yv)) in xs.iter().zip(ys) { |
| 552 | // BTreeMap iterates in key order, so a key mismatch means the |
| 553 | // key sets differ -> not equal. |
| 554 | if xk != yk { |
| 555 | return Some(false); |
| 556 | } |
| 557 | match feel_equal_depth(xv, yv, depth + 1) { |
| 558 | Some(false) => return Some(false), |
| 559 | None => result = None, // type-mismatched member -> null (unless a later false) |
| 560 | Some(true) => {} |
| 561 | } |
| 562 | } |
| 563 | result |
| 564 | } |
| 565 | // Ranges are equal iff each *side* matches: same boundedness, same openness |
| 566 | // (only where the side is bounded), and FEEL-equal endpoints (DMN §10.3.4.6). |
| 567 | // An unbounded side ignores the openness flag (only an open bracket is even |
| 568 | // writable there), and differs from a bounded side — `[1..)` ≠ `[1..10]` (ADR-31). A |
| 569 | // type-mismatched endpoint makes the whole comparison error-null (`None`), |
| 570 | // unless a definite difference has already made it `false`. |
| 571 | (Value::Range(x), Value::Range(y)) => { |
| 572 | match ( |
| 573 | range_side_eq(&x.start, x.start_open, &y.start, y.start_open, depth + 1), |
| 574 | range_side_eq(&x.end, x.end_open, &y.end, y.end_open, depth + 1), |
| 575 | ) { |
| 576 | (Some(false), _) | (_, Some(false)) => Some(false), |
| 577 | (None, _) | (_, None) => None, |
| 578 | (Some(true), Some(true)) => Some(true), |
| 579 | } |
| 580 | } |
| 581 | // An opaque parenthesised comparison-test value `(< 10)` (ADR-32). It equals |
| 582 | // ONLY a structurally identical test — same operator AND FEEL-equal endpoint — |
| 583 | // reflexively (`(<10) = (<10)`, `(=10) = (=10)`, `(!=10) = (!=10)` → true). A |
| 584 | // differing operator is a definite `false`; the endpoint comparison three-values |
| 585 | // through (an endpoint type mismatch is the usual error-null). |
| 586 | (Value::UnaryTestVal(x), Value::UnaryTestVal(y)) => { |
| 587 | if x.op != y.op { |
| 588 | Some(false) |
| 589 | } else { |
| 590 | feel_equal_depth(&x.endpoint, &y.endpoint, depth + 1) |
| 591 | } |
| 592 | } |
| 593 | // …but it is NEVER equal to a `Range` or anything else: `(<10) = (null..10)` and |
| 594 | // `(=10) = [10..10]` are a definite `false` (the measured 0068 semantics that |
| 595 | // falsified the desugar-to-range hypothesis), not a type-mismatch error-null. |
| 596 | // (Null/error on either side was already settled above.) |
| 597 | (Value::UnaryTestVal(_), _) | (_, Value::UnaryTestVal(_)) => Some(false), |
| 598 | // Temporal: same-type -> Some(bool); cross temporal type -> None (-> error-null). |
| 599 | (x, y) if temporal::is_temporal(x) && temporal::is_temporal(y) => temporal::equal(x, y), |
| 600 | _ => None, // different, non-null types |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | /// Three-valued equality of one *side* (start or end) of two ranges (ADR-31). Both |
| 605 | /// unbounded → equal (openness ignored, `±∞` has none); exactly one unbounded → |
| 606 | /// `false`; both bounded → openness must match *and* the endpoints be FEEL-equal. |
| 607 | fn range_side_eq( |
| 608 | xa: &Option<Value>, |
| 609 | xo: bool, |
| 610 | ya: &Option<Value>, |
| 611 | yo: bool, |
| 612 | depth: usize, |
| 613 | ) -> Option<bool> { |
| 614 | match (xa, ya) { |
| 615 | (None, None) => Some(true), |
| 616 | (Some(_), None) | (None, Some(_)) => Some(false), |
| 617 | (Some(a), Some(b)) => { |
| 618 | if xo != yo { |
| 619 | Some(false) |
| 620 | } else { |
| 621 | feel_equal_depth(a, b, depth) |
| 622 | } |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | /// FEEL ordering of two comparable, non-null values. Only numbers and strings |
| 628 | /// are ordered; any other pairing is a type mismatch (`None`). Null/error |
| 629 | /// operands are handled by [`order_compare`] before this is reached. |
| 630 | pub(crate) fn feel_order(a: &Value, b: &Value) -> Option<Ordering> { |
| 631 | match (a, b) { |
| 632 | (Value::Number(x), Value::Number(y)) => x.partial_cmp(y), |
| 633 | (Value::String(x), Value::String(y)) => Some(x.cmp(y)), |
| 634 | // Temporal values order within their own type (ADR-18); cross-type -> None. |
| 635 | (x, y) if temporal::is_temporal(x) && temporal::is_temporal(y) => temporal::compare(x, y), |
| 636 | _ => None, |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | /// Map an equality outcome to a value. `None` (different non-null types) is a |
| 641 | /// type mismatch -> error-null. |
| 642 | fn eq_result(b: Option<bool>) -> Value { |
| 643 | match b { |
| 644 | Some(b) => Value::Boolean(b), |
| 645 | None => Value::Error, |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | /// Ordering comparison (`< <= > >=`) with provenance: |
| 650 | /// * an error operand -> error-null (propagated); |
| 651 | /// * a value-null operand -> value-null (the order is unknown, like Kleene); |
| 652 | /// * two comparable values -> the boolean; |
| 653 | /// * incomparable non-null types -> error-null (type mismatch). |
| 654 | fn order_compare(a: &Value, b: &Value, pred: impl Fn(Ordering) -> bool) -> Value { |
| 655 | if is_error(a) || is_error(b) { |
| 656 | return Value::Error; |
| 657 | } |
| 658 | if matches!(a, Value::Null) || matches!(b, Value::Null) { |
| 659 | return Value::Null; |
| 660 | } |
| 661 | match feel_order(a, b) { |
| 662 | Some(o) => Value::Boolean(pred(o)), |
| 663 | None => Value::Error, // incomparable non-null types |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | impl Evaluator<'_> { |
| 668 | /// Evaluate an interval endpoint that may be omitted: `None` (unbounded, ±∞; |
| 669 | /// ADR-31) passes straight through, a present endpoint is evaluated and `forced` |
| 670 | /// (a present `null` bound becomes `Some(Value::Null)`, which downstream keeps |
| 671 | /// three-valued). |
| 672 | fn eval_opt_endpoint( |
| 673 | &self, |
| 674 | e: &Option<Box<Expr>>, |
| 675 | ctx: &Context, |
| 676 | ) -> Result<Option<Value>, FeelError> { |
| 677 | match e { |
| 678 | Some(e) => Ok(Some(self.eval(e, ctx)?.forced())), |
| 679 | None => Ok(None), |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /// Membership test, interval inclusivity exactly per S-FEEL: |
| 684 | /// [a..b] -> a <= o <= b ; (a..b] -> a < o <= b ; [a..b) -> a <= o < b ; |
| 685 | /// (a..b) -> a < o < b |
| 686 | fn eval_in(&self, value: &Expr, tests: &[UnaryTest], ctx: &Context) -> EvalResult { |
| 687 | let o = self.eval(value, ctx)?.forced(); |
| 688 | // The input satisfies the membership if it satisfies ANY test (Kleene OR, |
| 689 | // so a null/error from one test only sticks if no test is a definite true). |
| 690 | let mut acc = Value::Boolean(false); |
| 691 | for test in tests { |
| 692 | acc = or3(acc, self.eval_unary_test(&o, test, ctx)?); |
| 693 | } |
| 694 | Ok(acc) |
| 695 | } |
| 696 | |
| 697 | /// Evaluate one positive unary test against the already-evaluated input `o`. |
| 698 | fn eval_unary_test(&self, o: &Value, test: &UnaryTest, ctx: &Context) -> EvalResult { |
| 699 | Ok(match test { |
| 700 | UnaryTest::Compare(op, e) => eval_compare(*op, o, &self.eval(e, ctx)?.forced()), |
| 701 | // A *written* interval literal `[a..b]`: evaluate its endpoints in the |
| 702 | // test context and check containment. An omitted endpoint is unbounded |
| 703 | // (`5 in [1..)`, `5 in (..10]`), satisfying that side unconditionally |
| 704 | // (ADR-31); a present `null` bound keeps three-valued membership. |
| 705 | UnaryTest::Interval(iv) => { |
| 706 | let start = self.eval_opt_endpoint(&iv.start, ctx)?; |
| 707 | let end = self.eval_opt_endpoint(&iv.end, ctx)?; |
| 708 | range_contains(o, start.as_ref(), iv.start_open, end.as_ref(), iv.end_open) |
| 709 | } |
| 710 | // A bare endpoint expression `x in e`: range *membership* when `e` is a |
| 711 | // range value (e.g. `range("[1..3]")`), otherwise equality `x = e`. |
| 712 | UnaryTest::Endpoint(e) => match self.eval(e, ctx)?.forced() { |
| 713 | Value::Range(r) => range_contains( |
| 714 | o, |
| 715 | r.start.as_ref(), |
| 716 | r.start_open, |
| 717 | r.end.as_ref(), |
| 718 | r.end_open, |
| 719 | ), |
| 720 | t => eval_compare(CmpOp::Eq, o, &t), |
| 721 | }, |
| 722 | // `x in not(t1, …)`: negate the OR-fold of the inner tests, three-valued |
| 723 | // (Kleene). `not(true) = false`, `not(false) = true`, `not(null) = null`; |
| 724 | // an error in an inner test stays an error-null through `not3` (so the |
| 725 | // negation never manufactures a definite truth from an unknown). |
| 726 | UnaryTest::Not(tests) => { |
| 727 | let mut acc = Value::Boolean(false); |
| 728 | for test in tests { |
| 729 | acc = or3(acc, self.eval_unary_test(o, test, ctx)?); |
| 730 | } |
| 731 | not3(acc) |
| 732 | } |
| 733 | }) |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | /// Kleene negation used by `x in not(…)` test negation: `not(true) = false`, |
| 738 | /// `not(false) = true`, `not(null) = null`. A tainted unknown (error-null or a |
| 739 | /// wrong-typed operand) stays an error-null, mirroring `and3`/`or3` provenance, so |
| 740 | /// negating an unknown never produces a definite truth. |
| 741 | fn not3(v: Value) -> Value { |
| 742 | match v { |
| 743 | Value::Boolean(b) => Value::Boolean(!b), |
| 744 | other => nullish(taints(&other)), |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | /// S-FEEL interval inclusivity for an input `o` against a `[start..end]` range: |
| 749 | /// `[a..b]` -> a <= o <= b ; `(a..b]` -> a < o <= b ; `[a..b)` -> a <= o < b ; |
| 750 | /// `(a..b)` -> a < o < b. Three-valued: a null/error endpoint makes the side it |
| 751 | /// bounds unknown, and `and3` combines the two sides with sticky error provenance. |
| 752 | /// |
| 753 | /// A `None` endpoint is *unbounded* (`±∞`; ADR-31): that side is satisfied |
| 754 | /// unconditionally (`true`), so `5 in [1..)` and `5 in (..10]` are `true`, while a |
| 755 | /// *present* `null` bound (`5 in [null..10]`) still yields the three-valued `null`. |
| 756 | fn range_contains( |
| 757 | o: &Value, |
| 758 | start: Option<&Value>, |
| 759 | start_open: bool, |
| 760 | end: Option<&Value>, |
| 761 | end_open: bool, |
| 762 | ) -> Value { |
| 763 | let lower = match start { |
| 764 | Some(s) => eval_compare(if start_open { CmpOp::Lt } else { CmpOp::Le }, s, o), |
| 765 | None => Value::Boolean(true), |
| 766 | }; |
| 767 | let upper = match end { |
| 768 | Some(e) => eval_compare(if end_open { CmpOp::Lt } else { CmpOp::Le }, o, e), |
| 769 | None => Value::Boolean(true), |
| 770 | }; |
| 771 | and3(lower, upper) |
| 772 | } |
| 773 | |
| 774 | // --------------------------------------------------------------------------- // |
| 775 | // Kleene logic |
| 776 | // --------------------------------------------------------------------------- // |
| 777 | |
| 778 | // Strong Kleene with sticky error provenance (Design 1, ADR-14): the truth |
| 779 | // value is exactly strong three-valued logic — a dominating `false` (and) or |
| 780 | // `true` (or) wins regardless of the other operand — so the TCK stays green. |
| 781 | // Provenance only matters when the result is the "unknown" null: then it is an |
| 782 | // error-null iff a contributing operand was tainted. A value-null operand is |
| 783 | // untainted (it is a legitimate unknown); a wrong-typed or error operand taints. |
| 784 | |
| 785 | /// `and`: false if either operand is `false`, true if both are `true`, else |
| 786 | /// null (error-null iff an unknown operand was tainted). |
| 787 | fn and3(a: Value, b: Value) -> Value { |
| 788 | if is_false(&a) || is_false(&b) { |
| 789 | Value::Boolean(false) |
| 790 | } else if is_true(&a) && is_true(&b) { |
| 791 | Value::Boolean(true) |
| 792 | } else { |
| 793 | nullish(taints(&a) || taints(&b)) |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | /// `or`: true if either operand is `true`, false if both are `false`, else |
| 798 | /// null (error-null iff an unknown operand was tainted). |
| 799 | fn or3(a: Value, b: Value) -> Value { |
| 800 | if is_true(&a) || is_true(&b) { |
| 801 | Value::Boolean(true) |
| 802 | } else if is_false(&a) && is_false(&b) { |
| 803 | Value::Boolean(false) |
| 804 | } else { |
| 805 | nullish(taints(&a) || taints(&b)) |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | fn is_true(v: &Value) -> bool { |
| 810 | matches!(v, Value::Boolean(true)) |
| 811 | } |
| 812 | |
| 813 | fn is_false(v: &Value) -> bool { |
| 814 | matches!(v, Value::Boolean(false)) |
| 815 | } |
| 816 | |
| 817 | fn is_error(v: &Value) -> bool { |
| 818 | matches!(v, Value::Error) |
| 819 | } |
| 820 | |
| 821 | /// An "unknown" operand taints the result with an error iff it is an error-null |
| 822 | /// or a wrong-typed value (a non-boolean, non-(value-null) value is a type error |
| 823 | /// as a logic operand). A plain value-null is a legitimate unknown -> untainted. |
| 824 | fn taints(v: &Value) -> bool { |
| 825 | !matches!(v, Value::Boolean(_) | Value::Null) |
| 826 | } |
| 827 | |
| 828 | /// The "unknown" result of a three-valued operation: error-null if tainted, |
| 829 | /// else value-null. |
| 830 | fn nullish(tainted: bool) -> Value { |
| 831 | if tainted { |
| 832 | Value::Error |
| 833 | } else { |
| 834 | Value::Null |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | // --------------------------------------------------------------------------- // |
| 839 | // Iteration: for / some / every |
| 840 | // --------------------------------------------------------------------------- // |
| 841 | |
| 842 | impl Evaluator<'_> { |
| 843 | /// Resolve a `for`/`some`/`every` source to the list it iterates over. |
| 844 | /// Returns `None` when the source is not iterable (e.g. a range with |
| 845 | /// non-numeric bounds) — the caller maps that to `null`. |
| 846 | fn iter_values( |
| 847 | &self, |
| 848 | source: &IterSource, |
| 849 | ctx: &Context, |
| 850 | ) -> Result<Option<Vec<Value>>, FeelError> { |
| 851 | match source { |
| 852 | // The source list is `forced()`; its *elements* stay as produced |
| 853 | // (possibly `Foreign`) and are bound to the loop variable unforced, |
| 854 | // so iterating a host collection is lazy element-by-element (ADR-21). |
| 855 | IterSource::Expr(e) => Ok(match self.eval(e, ctx)?.forced() { |
| 856 | Value::List(items) => Some(items), |
| 857 | _ => None, |
| 858 | }), |
| 859 | IterSource::Range(lo, hi) => { |
| 860 | let lo = self.eval(lo, ctx)?.forced(); |
| 861 | let hi = self.eval(hi, ctx)?.forced(); |
| 862 | match (as_number(&lo), as_number(&hi)) { |
| 863 | (Some(lo), Some(hi)) => Ok(Some(int_range(lo, hi))), |
| 864 | _ => Ok(None), |
| 865 | } |
| 866 | } |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | /// Evaluate a `for` over one or more iteration contexts (FEEL rule 44). The |
| 871 | /// body runs over the Cartesian product of the sources, in declaration order |
| 872 | /// with the rightmost context varying fastest; each source is resolved in the |
| 873 | /// scope of the contexts to its left. A non-iterable source (at any level) |
| 874 | /// makes the whole expression an error-null, matching the single-context rule. |
| 875 | fn eval_for(&self, bindings: &[(String, IterSource)], body: &Expr, ctx: &Context) -> EvalResult { |
| 876 | let mut out = Vec::new(); |
| 877 | if self.for_product(bindings, body, ctx, &mut out)? { |
| 878 | Ok(Value::List(out)) |
| 879 | } else { |
| 880 | Ok(Value::Error) // a (nested) source was non-iterable |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | /// Walk the Cartesian product of `bindings`, pushing one body result per tuple |
| 885 | /// into `out`. Returns `Ok(false)` (aborting) if a source was non-iterable. |
| 886 | fn for_product( |
| 887 | &self, |
| 888 | bindings: &[(String, IterSource)], |
| 889 | body: &Expr, |
| 890 | ctx: &Context, |
| 891 | out: &mut Vec<Value>, |
| 892 | ) -> Result<bool, FeelError> { |
| 893 | let Some(((var, source), rest)) = bindings.split_first() else { |
| 894 | out.push(self.eval(body, ctx)?); |
| 895 | return Ok(true); |
| 896 | }; |
| 897 | let Some(items) = self.iter_values(source, ctx)? else { |
| 898 | return Ok(false); |
| 899 | }; |
| 900 | for item in items { |
| 901 | if !self.for_product(rest, body, &ctx.with(var, item), out)? { |
| 902 | return Ok(false); |
| 903 | } |
| 904 | } |
| 905 | Ok(true) |
| 906 | } |
| 907 | |
| 908 | /// Evaluate a postfix filter / index `source[bracket]` (DMN §10.3.2.5). |
| 909 | /// |
| 910 | /// The source is coerced to a list: a non-list, non-null value becomes a |
| 911 | /// singleton (implicit conversion §10.3.2.9.4); `null` and error-null |
| 912 | /// short-circuit. The bracket is then disambiguated by its value type — a |
| 913 | /// number is a 1-based positional index (negative-from-end, out of range → |
| 914 | /// value-null); anything else is a boolean filter, re-evaluated per element |
| 915 | /// with the element bound as `item` (see [`filter_scope`]), keeping only the |
| 916 | /// elements whose result is `true`. The disambiguation evaluates the bracket |
| 917 | /// in the *outer* scope, where `item` is unbound, so a genuine predicate like |
| 918 | /// `item > 2` is null there and correctly falls through to the filter path. |
| 919 | fn eval_filter(&self, source: &Expr, bracket: &Expr, ctx: &Context) -> EvalResult { |
| 920 | let items = match self.eval(source, ctx)?.forced() { |
| 921 | Value::Null => return Ok(Value::Null), |
| 922 | Value::Error => return Ok(Value::Error), |
| 923 | Value::List(items) => items, |
| 924 | other => vec![other], |
| 925 | }; |
| 926 | if let Value::Number(n) = self.eval(bracket, ctx)?.forced() { |
| 927 | return Ok(index_into(&items, n)); |
| 928 | } |
| 929 | let mut out = Vec::new(); |
| 930 | for item in items { |
| 931 | if let Value::Boolean(true) = self.eval(bracket, &filter_scope(ctx, &item))?.forced() { |
| 932 | out.push(item); |
| 933 | } |
| 934 | } |
| 935 | Ok(Value::List(out)) |
| 936 | } |
| 937 | |
| 938 | /// Evaluate `some`/`every` over one or more iteration contexts (FEEL rule 46). |
| 939 | /// The predicate ranges over the Cartesian product of the (left-to-right |
| 940 | /// scoped) sources — see [`Self::eval_for`] for the iteration order — with |
| 941 | /// short-circuit on the first dominating result (`some`→true / `every`→false). |
| 942 | fn eval_quantified( |
| 943 | &self, |
| 944 | kind: Quantifier, |
| 945 | bindings: &[(String, IterSource)], |
| 946 | predicate: &Expr, |
| 947 | ctx: &Context, |
| 948 | ) -> EvalResult { |
| 949 | // A quantifier is a folded and/or, so it carries the same sticky-provenance |
| 950 | // rule (Design 1): a dominating result short-circuits; otherwise the unknown |
| 951 | // result is an error-null iff a non-boolean predicate result tainted it. |
| 952 | let mut saw_unknown = false; |
| 953 | let mut tainted = false; |
| 954 | match self.quant_product(kind, bindings, predicate, ctx, &mut saw_unknown, &mut tainted)? { |
| 955 | QuantOutcome::Short(v) => Ok(v), |
| 956 | QuantOutcome::NonIterable => Ok(Value::Error), // type error |
| 957 | QuantOutcome::Exhausted => Ok(if saw_unknown { |
| 958 | nullish(tainted) |
| 959 | } else { |
| 960 | match kind { |
| 961 | Quantifier::Some => Value::Boolean(false), |
| 962 | Quantifier::Every => Value::Boolean(true), |
| 963 | } |
| 964 | }), |
| 965 | } |
| 966 | } |
| 967 | |
| 968 | /// Walk the Cartesian product of `bindings` for a quantifier, threading the |
| 969 | /// sticky-provenance flags. Short-circuits on the first dominating boolean and |
| 970 | /// aborts on a non-iterable source. |
| 971 | fn quant_product( |
| 972 | &self, |
| 973 | kind: Quantifier, |
| 974 | bindings: &[(String, IterSource)], |
| 975 | predicate: &Expr, |
| 976 | ctx: &Context, |
| 977 | saw_unknown: &mut bool, |
| 978 | tainted: &mut bool, |
| 979 | ) -> Result<QuantOutcome, FeelError> { |
| 980 | let Some(((var, source), rest)) = bindings.split_first() else { |
| 981 | return Ok(match self.eval(predicate, ctx)? { |
| 982 | Value::Boolean(true) if kind == Quantifier::Some => { |
| 983 | QuantOutcome::Short(Value::Boolean(true)) |
| 984 | } |
| 985 | Value::Boolean(false) if kind == Quantifier::Every => { |
| 986 | QuantOutcome::Short(Value::Boolean(false)) |
| 987 | } |
| 988 | Value::Boolean(_) => QuantOutcome::Exhausted, |
| 989 | other => { |
| 990 | *saw_unknown = true; |
| 991 | *tainted |= taints(&other); |
| 992 | QuantOutcome::Exhausted |
| 993 | } |
| 994 | }); |
| 995 | }; |
| 996 | let Some(items) = self.iter_values(source, ctx)? else { |
| 997 | return Ok(QuantOutcome::NonIterable); |
| 998 | }; |
| 999 | for item in items { |
| 1000 | match self.quant_product( |
| 1001 | kind, |
| 1002 | rest, |
| 1003 | predicate, |
| 1004 | &ctx.with(var, item), |
| 1005 | saw_unknown, |
| 1006 | tainted, |
| 1007 | )? { |
| 1008 | QuantOutcome::Exhausted => {} |
| 1009 | short_or_abort => return Ok(short_or_abort), |
| 1010 | } |
| 1011 | } |
| 1012 | Ok(QuantOutcome::Exhausted) |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | /// Outcome of walking a (sub-)product for a quantifier ([`Evaluator::quant_product`]). |
| 1017 | enum QuantOutcome { |
| 1018 | /// A dominating boolean ended iteration early (`some`→true / `every`→false). |
| 1019 | Short(Value), |
| 1020 | /// A (nested) source was non-iterable: the whole quantifier is an error-null. |
| 1021 | NonIterable, |
| 1022 | /// This sub-product was exhausted without short-circuiting. |
| 1023 | Exhausted, |
| 1024 | } |
| 1025 | |
| 1026 | /// Select member `name` from one value — the per-element rule shared by scalar |
| 1027 | /// path access and list projection (DMN §10.3.2.5). A missing context key is a |
| 1028 | /// value-null (like an unbound variable); a `Foreign` resolves the dot lazily |
| 1029 | /// (ADR-21); a temporal value exposes its components (ADR-18); anything else is a |
| 1030 | /// type error (error-null). |
| 1031 | fn member_access(value: Value, name: &str) -> Value { |
| 1032 | match value { |
| 1033 | Value::Context(map) => map.get(name).cloned().unwrap_or(Value::Null), |
| 1034 | Value::Foreign(f) => f.0.get(name), |
| 1035 | // Range properties (DMN §10.3.2.6 / TCK 0074): the two endpoint values and |
| 1036 | // their inclusivity. `start included`/`end included` arrive as single joined |
| 1037 | // names (ADR-17). An *unbounded* endpoint (`None`; ADR-31) has no value — its |
| 1038 | // `start`/`end` is `null` and it is never `included` (`±∞` is no member), so |
| 1039 | // `[1..).end` is `null` and `[1..).end included` is `false` regardless of the |
| 1040 | // (meaningless) bracket. An unknown property is a value-null, mirroring |
| 1041 | // `temporal::get_property` (a range *has* properties). |
| 1042 | Value::Range(r) => match name { |
| 1043 | "start" => r.start.clone().unwrap_or(Value::Null), |
| 1044 | "end" => r.end.clone().unwrap_or(Value::Null), |
| 1045 | "start included" => Value::Boolean(r.start.is_some() && !r.start_open), |
| 1046 | "end included" => Value::Boolean(r.end.is_some() && !r.end_open), |
| 1047 | _ => Value::Null, |
| 1048 | }, |
| 1049 | // A comparison-test value `(< 10)` (ADR-32) is a range-typed value for the |
| 1050 | // purpose of these projections (DMN §10.3.2.7 / Table 42, TCK 0074 |
| 1051 | // `range_006`–`011`): the single-endpoint-operator form leaves the *other* |
| 1052 | // endpoint **undefined** (property `null`, never `included`), while the |
| 1053 | // present endpoint's inclusivity follows the operator (`<=`/`>=`/`=` are |
| 1054 | // included, the strict `<`/`>`/`!=` are not). Only these projections are |
| 1055 | // range-shaped — its *equality* stays OPAQUE (ADR-32, `feel_equal_depth`): |
| 1056 | // `(=10).start`/`.end` are `10`/`10` even though `(=10) ≠ [10..10]`. |
| 1057 | Value::UnaryTestVal(u) => { |
| 1058 | use crate::ast::CmpOp; |
| 1059 | let e = &u.endpoint; |
| 1060 | // (start, start included, end, end included) per Table 42. |
| 1061 | let (start, start_incl, end, end_incl): (Option<&Value>, bool, Option<&Value>, bool) = |
| 1062 | match u.op { |
| 1063 | CmpOp::Lt => (None, false, Some(e), false), |
| 1064 | CmpOp::Le => (None, false, Some(e), true), |
| 1065 | CmpOp::Gt => (Some(e), false, None, false), |
| 1066 | CmpOp::Ge => (Some(e), true, None, false), |
| 1067 | CmpOp::Eq => (Some(e), true, Some(e), true), |
| 1068 | CmpOp::Ne => (Some(e), false, Some(e), false), |
| 1069 | }; |
| 1070 | match name { |
| 1071 | "start" => start.cloned().unwrap_or(Value::Null), |
| 1072 | "end" => end.cloned().unwrap_or(Value::Null), |
| 1073 | "start included" => Value::Boolean(start_incl), |
| 1074 | "end included" => Value::Boolean(end_incl), |
| 1075 | _ => Value::Null, |
| 1076 | } |
| 1077 | } |
| 1078 | v if temporal::is_temporal(&v) => temporal::get_property(&v, name), |
| 1079 | _ => Value::Error, |
| 1080 | } |
| 1081 | } |
| 1082 | |
| 1083 | /// Recursively collect every value bound to `name` in `root` and all nested |
| 1084 | /// contexts/lists, depth-first, appending to `out` (DMN §10.3.2.7, the descendant |
| 1085 | /// `e ... name` operator). Pre-order: at each context the match for `name` is |
| 1086 | /// collected *before* descending into its children, so |
| 1087 | /// `{a:{b:{b:1}}} ... b` → `[{b:1}, 1]`. |
| 1088 | /// |
| 1089 | /// **Cycle guard / DAG de-dup.** `seen` is a *global* visited-set — threaded |
| 1090 | /// through the whole traversal, never cleared — keyed on |
| 1091 | /// [`ForeignObject::identity`](crate::foreign::ForeignObject::identity), the *host |
| 1092 | /// object's* identity (not the Rust allocation address). Only an `Arc`-backed |
| 1093 | /// [`Value::Foreign`] is keyed; pure-Rust values are owned trees and never |
| 1094 | /// `Foreign`, so a pure-FEEL context is traversed in full (exact multiset |
| 1095 | /// semantics, per spec). A host that mints a fresh `Arc` per `force`/`get` |
| 1096 | /// (feel-py/lua/wasm) still has a back-edge broken once its `identity()` override |
| 1097 | /// returns a stable value (feel-pg is exempt: `jsonb` cannot cycle). |
| 1098 | /// |
| 1099 | /// Because the set is global and never cleared, it also **de-duplicates shared |
| 1100 | /// *acyclic* host sub-objects** (a diamond/DAG): a host object reachable via two |
| 1101 | /// distinct paths is collected once, not once per path. Host object graphs are out |
| 1102 | /// of DMN spec (spec defines descendant only over value-tree contexts), so there is |
| 1103 | /// no spec answer; the global set is chosen over a path-scoped set (insert on entry, |
| 1104 | /// remove on exit) to prevent *exponential blowup* on diamond-heavy DAGs, accepting |
| 1105 | /// per-path multiset semantics for shared host data as the trade-off. See ADR-46. |
| 1106 | /// [`DESCENDANT_MAX_DEPTH`] is a secondary backstop. |
| 1107 | fn descendant_collect( |
| 1108 | root: &Value, |
| 1109 | name: &str, |
| 1110 | seen: &mut HashSet<usize>, |
| 1111 | out: &mut Vec<Value>, |
| 1112 | depth: usize, |
| 1113 | ) { |
| 1114 | if depth >= DESCENDANT_MAX_DEPTH { |
| 1115 | return; |
| 1116 | } |
| 1117 | match root { |
| 1118 | Value::Context(map) => { |
| 1119 | if let Some(val) = map.get(name) { |
| 1120 | out.push(val.clone()); |
| 1121 | } |
| 1122 | for child in map.values() { |
| 1123 | descendant_collect(child, name, seen, out, depth + 1); |
| 1124 | } |
| 1125 | } |
| 1126 | Value::List(items) => { |
| 1127 | for child in items { |
| 1128 | descendant_collect(child, name, seen, out, depth + 1); |
| 1129 | } |
| 1130 | } |
| 1131 | Value::Foreign(f) => { |
| 1132 | // Break a back-edge into an already-visited host object: the cycle's |
| 1133 | // duplicate is skipped, leaving the finite DAG unfolding. |
| 1134 | if !seen.insert(f.0.identity()) { |
| 1135 | return; |
| 1136 | } |
| 1137 | // Force one level and continue the descent (its own members are collected |
| 1138 | // by the Context/List arms; nested Foreigns re-check `seen`). |
| 1139 | descendant_collect(&f.0.force(), name, seen, out, depth + 1); |
| 1140 | } |
| 1141 | _ => {} // scalars, ranges, functions: nothing to descend into |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | /// 1-based positional index into `items` (DMN §10.3.2.5): a positive `n` counts |
| 1146 | /// from the front, a negative `n` from the end. A non-integer or out-of-range |
| 1147 | /// `n` is a value-null. Reuses [`resolve_index`] — the same 1-based / negative |
| 1148 | /// resolution the list built-ins use (`out` of `[0, len]`, so guard `< len`). |
| 1149 | fn index_into(items: &[Value], n: f64) -> Value { |
| 1150 | if n.fract() != 0.0 { |
| 1151 | return Value::Null; |
| 1152 | } |
| 1153 | match resolve_index(n as i64, items.len() as i64) { |
| 1154 | Some(idx) if (idx as usize) < items.len() => items[idx as usize].clone(), |
| 1155 | _ => Value::Null, |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | /// Build the scope a filter predicate is evaluated in for one element. The element |
| 1160 | /// is bound as `item`; if it is a context, its entries are also spread into scope |
| 1161 | /// so they can be referenced without an `item.` prefix — but a context that |
| 1162 | /// already carries an `item` key keeps that key as `item` (DMN §10.3.2.5). The |
| 1163 | /// element is forced first so a lazy host context's entries are visible, while the |
| 1164 | /// `item` binding stays the original value (preserving `Foreign` identity, ADR-21). |
| 1165 | fn filter_scope(ctx: &Context, item: &Value) -> Context { |
| 1166 | let mut scope = ctx.clone(); |
| 1167 | if let Value::Context(map) = item.clone().forced() { |
| 1168 | let has_item = map.contains_key("item"); |
| 1169 | for (k, v) in map { |
| 1170 | scope.insert(k, v); |
| 1171 | } |
| 1172 | if !has_item { |
| 1173 | scope.insert("item", item.clone()); |
| 1174 | } |
| 1175 | } else { |
| 1176 | scope.insert("item", item.clone()); |
| 1177 | } |
| 1178 | scope |
| 1179 | } |
| 1180 | |
| 1181 | /// Inclusive integer range with a ±1 step: `2..4` -> [2,3,4], `4..2` -> [4,3,2]. |
| 1182 | fn int_range(lo: f64, hi: f64) -> Vec<Value> { |
| 1183 | // Guard against pathological/non-integer bounds producing huge or endless |
| 1184 | // loops; this slice only ever sees small ranges. |
| 1185 | const CAP: usize = 1_000_000; |
| 1186 | let mut out = Vec::new(); |
| 1187 | let step = if lo <= hi { 1.0 } else { -1.0 }; |
| 1188 | let mut x = lo; |
| 1189 | while (step > 0.0 && x <= hi) || (step < 0.0 && x >= hi) { |
| 1190 | out.push(Value::Number(x)); |
| 1191 | if out.len() >= CAP { |
| 1192 | break; |
| 1193 | } |
| 1194 | x += step; |
| 1195 | } |
| 1196 | out |
| 1197 | } |
| 1198 | |
| 1199 | // --------------------------------------------------------------------------- // |
| 1200 | |
| 1201 | pub(crate) fn as_number(v: &Value) -> Option<f64> { |
| 1202 | match v { |
| 1203 | Value::Number(n) => Some(*n), |
| 1204 | _ => None, |
| 1205 | } |
| 1206 | } |