Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feel / crates / feel-core / src / lib.rs · 142.3 KB · at 93b43c1c833b · raw

Outline: 181 definitions
1
//! `feel-core` — a pure (S-)FEEL expression engine.
2
//!
3
//! Cardinal rule: this crate has **no** target-specific dependency (no pgrx,
4
//! no wasm-bindgen). Target glue lives only in the wrapper crates.
5
6
mod ast;
7
mod builtins;
8
mod error;
9
mod eval;
10
pub mod foreign;
11
pub mod function;
12
mod lexer;
13
mod regex_provider;
14
pub mod temporal;
15
mod types;
16
mod value;
17
18
pub use ast::FeelType;
19
pub use error::FeelError;
20
pub use foreign::{Foreign, ForeignObject};
21
pub use function::{Args, ForeignFunction, Func};
22
pub use regex_provider::FeelRegex;
23
pub use temporal::temporal_from_iso;
24
pub use value::Value;
25
// `EvalEnv` is defined below; re-stated here for discoverability via the crate root.
26
27
/// The Rust `regex` engine as a [`FeelRegex`] provider (available when the
28
/// default `rust-regex` feature is on). Wrappers that bring their own host engine
29
/// can still opt back into it — e.g. `feel-wasm`'s `xpath-regex` feature uses it
30
/// for cross-target consistency at the cost of bundle size (ADR-16).
31
#[cfg(feature = "rust-regex")]
32
pub use regex_provider::RustRegex;
33
34
use std::collections::HashMap;
35
36
use lalrpop_util::lalrpop_mod;
37
38
// Pull in the parser generated from `src/feel.lalrpop` by `build.rs`.
39
lalrpop_mod!(
40
    #[allow(clippy::all, dead_code, unused_imports)]
41
    feel
42
);
43
44
/// Evaluation context: a thin wrapper around a variable map.
45
///
46
/// The grammar slice does not reference variables yet, so this is usually
47
/// empty; it exists so the public API is stable as the engine grows and so the
48
/// wrapper crates have a place to map their JSON boundary input into.
49
#[derive(Debug, Default, Clone, PartialEq)]
50
pub struct Context {
51
    vars: HashMap<String, Value>,
52
}
53
54
impl Context {
55
    /// An empty context.
56
    pub fn new() -> Self {
57
        Self::default()
58
    }
59
60
    /// Alias for [`Context::new`], reads nicely in tests.
61
    pub fn empty() -> Self {
62
        Self::default()
63
    }
64
65
    /// Bind a name to a value.
66
    pub fn insert(&mut self, name: impl Into<String>, value: Value) {
67
        self.vars.insert(name.into(), value);
68
    }
69
70
    /// Look up a bound value.
71
    pub fn get(&self, name: &str) -> Option<&Value> {
72
        self.vars.get(name)
73
    }
74
75
    /// Return a child context with `name` additionally bound to `value`, leaving
76
    /// `self` unchanged. Used to scope `for`/`some`/`every` loop variables.
77
    pub fn with(&self, name: impl Into<String>, value: Value) -> Context {
78
        let mut child = self.clone();
79
        child.insert(name, value);
80
        child
81
    }
82
}
83
84
/// The parse-time "name oracle" for special-character names (§10.3.1.6, ADR-47):
85
/// decides which candidate names are in scope, so the lexer can fuse FEEL's
86
/// additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names.
87
///
88
/// std-only (ADR-1), like the other host seams. The canonical implementation is
89
/// [`Context`] itself — parse and eval must agree on what "in scope" means, so
90
/// the impl mirrors `Expr::Var` resolution exactly: a context binding or a
91
/// built-in function name. A host that parses before its context exists can
92
/// implement this against its own root-key view (e.g. a jsonb row's top-level
93
/// keys — feel-pg just builds the `Context` first, which is already cheap).
94
pub trait ScopeProbe {
95
    /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would
96
    /// find a value (a context binding or a built-in function name).
97
    fn contains(&self, name: &str) -> bool;
98
}
99
100
impl ScopeProbe for Context {
101
    fn contains(&self, name: &str) -> bool {
102
        // Mirrors `Expr::Var` (eval.rs): a context binding wins, then a built-in
103
        // name (a first-class function value, ADR-36), then null — the probe asks
104
        // about the first two.
105
        self.get(name).is_some() || crate::builtins::is_builtin(name)
106
    }
107
}
108
109
/// A [`Context`] plus an ambient [`FunctionRegistry`] (ADR-23) as one parse-time
110
/// scope (ADR-47): a call head resolves against context, built-ins and — third —
111
/// the registry (`eval_call`), so a hyphen-named host function (`my-fn(1)`) must
112
/// be in scope for the fusion too. The wrappers' one-shot `evaluate` parses
113
/// against this when a `functions` registry is supplied.
114
///
115
/// Slightly wider than `Expr::Var` (which never consults the registry): a bare,
116
/// uncalled `my-fn` fuses to a name that evaluates to null — the same null the
117
/// arithmetic reading `my - fn` would give.
118
pub struct ScopeWithFunctions<'a> {
119
    /// The root-level bindings.
120
    pub context: &'a Context,
121
    /// The ambient host functions.
122
    pub functions: &'a dyn FunctionRegistry,
123
}
124
125
impl ScopeProbe for ScopeWithFunctions<'_> {
126
    fn contains(&self, name: &str) -> bool {
127
        self.context.contains(name) || self.functions.get(name).is_some()
128
    }
129
}
130
131
/// A parsed FEEL expression, ready to be evaluated repeatedly.
132
///
133
/// Parsing is the per-call cost that does not depend on the context, so callers
134
/// that evaluate the same expression against many contexts (e.g. one decision
135
/// over many rows) should [`compile`] once and reuse the result. The wrapped AST
136
/// is fully owning, so a `CompiledExpr` carries no borrow of the source string.
137
///
138
/// ```
139
/// use feel_core::{compile, Context, Value};
140
/// let prog = compile("a + 1").unwrap();
141
/// let mut ctx = Context::empty();
142
/// ctx.insert("a", Value::Number(1.0));
143
/// assert_eq!(prog.evaluate(&ctx).unwrap(), Value::Number(2.0));
144
/// ```
145
#[derive(Debug, Clone)]
146
pub struct CompiledExpr {
147
    /// The parsed program.
148
    expr: ast::Expr,
149
    /// Whether the parse consulted a scope probe on a special-character name
150
    /// run (`a-b`, `Date-Time`, …) — i.e. is **scope-dependent**: another scope
151
    /// could fuse the same text differently (ADR-47). Only a probe-aware parse
152
    /// (`compile_with_probe`/`evaluate`) sets it; `compile` is probe-free and
153
    /// reports `false`.
154
    name_runs: bool,
155
}
156
157
impl CompiledExpr {
158
    /// Evaluate this already-parsed expression against a context, using the
159
    /// default regex provider (`RustRegex` with the `rust-regex` feature on,
160
    /// otherwise a no-op provider whose regex builtins yield an error-null) and
161
    /// the wall-clock instant for `now()`/`today()`.
162
    ///
163
    /// Use [`CompiledExpr::evaluate_with_env`] to control the regex provider or
164
    /// the `now()`/`today()` instant (the wrappers inject their host's there).
165
    pub fn evaluate(&self, context: &Context) -> Result<Value, FeelError> {
166
        self.evaluate_with_env(
167
            context,
168
            &EvalEnv::new(&regex_provider::DEFAULT, default_now()),
169
        )
170
    }
171
172
    /// Evaluate against a context using a fully caller-supplied [`EvalEnv`] —
173
    /// the single general entry point the wrappers use. The env carries both
174
    /// seams: the host regex provider (ADR-16: only `matches`/`replace`/`split`
175
    /// consult it; every other result is provider-independent) and the instant
176
    /// `now()`/`today()` read (ADR-18). The wrappers inject their host's clock
177
    /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()`
178
    /// deterministic in tests.
179
    pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> {
180
        eval::Evaluator::new(env).eval(&self.expr, context)
181
    }
182
183
    /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a
184
    /// freshly-parsed range literal's *shape* (its endpoints must be literals, not
185
    /// arbitrary expressions — DMN §10.3.4.6) before evaluating it.
186
    pub(crate) fn ast(&self) -> &ast::Expr {
187
        &self.expr
188
    }
189
190
    /// `true` if this expression never reads the wall clock — it calls neither
191
    /// `now()` nor `today()` anywhere (ADR-18). Wrappers exposing a deterministic,
192
    /// IMMUTABLE evaluation surface (e.g. feel-pg's `feel_eval_immutable`, for
193
    /// expression indexes; RD-10) gate on this: a non-clock-free expression cannot
194
    /// be IMMUTABLE because `now()`/`today()` vary over time.
195
    ///
196
    /// This is the *static* half. The runtime half — forbidding *named* time zones,
197
    /// whose offsets depend on the updatable IANA tzdb — is
198
    /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope
199
    /// here (the embedder's concern; feel-pg has no host-function seam).
200
    pub fn is_clock_free(&self) -> bool {
201
        self.expr.is_clock_free()
202
    }
203
204
    /// `true` if parsing consulted a scope probe on a special-character name run
205
    /// (`a-b`, `Date-Time`, …; §10.3.1.6, ADR-47): this parse is
206
    /// **scope-dependent** — the same text could parse differently under another
207
    /// scope. Only a probe-aware parse sets it; [`compile`] is probe-free and
208
    /// reports `false`. Hosts that cache parses across contexts can instead check
209
    /// [`name_run_candidates`] against each context, which distinguishes "could
210
    /// be ambiguous" from "this scope actually changes the parse".
211
    pub fn has_name_runs(&self) -> bool {
212
        self.name_runs
213
    }
214
}
215
216
/// A registry of host-provided ("ambient") functions, looked up by name when a
217
/// call resolves to neither a context-bound function value nor a built-in (ADR-23).
218
/// This is the second way a host injects callables — the first is binding a
219
/// [`Value::Function`] directly in the [`Context`]. Implemented per target
220
/// (feel-py's `PyFunctionRegistry`, feel-wasm's `JsFunctionRegistry`); the default
221
/// is empty, so a pure-Rust embedder pays nothing.
222
pub trait FunctionRegistry {
223
    /// Resolve a host function by name. Absent -> `None` (the call is then a
224
    /// built-in or, failing that, an error-null).
225
    fn get(&self, name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>>;
226
}
227
228
/// The empty registry: no ambient host functions. Used as the default in
229
/// [`EvalEnv::new`] so existing callers (and pure-Rust embedders) are unaffected.
230
struct EmptyRegistry;
231
impl FunctionRegistry for EmptyRegistry {
232
    fn get(&self, _name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>> {
233
        None
234
    }
235
}
236
static EMPTY_REGISTRY: EmptyRegistry = EmptyRegistry;
237
238
/// The evaluation environment threaded through the engine: the host regex
239
/// provider (ADR-16), the instant `now()`/`today()` read (ADR-18), and the host
240
/// function registry (ADR-23). Held by reference during evaluation (never cloned
241
/// per loop iteration), so building one is cheap and the clock is fixed for the
242
/// whole evaluation.
243
pub struct EvalEnv<'a> {
244
    /// The host regex provider consulted by `matches`/`replace`/`split`.
245
    pub regex: &'a dyn FeelRegex,
246
    /// The instant `now()` returns (and whose date `today()` returns).
247
    pub now: jiff::Zoned,
248
    /// Ambient host functions, consulted after context bindings and built-ins.
249
    pub functions: &'a dyn FunctionRegistry,
250
    /// When set, constructing a temporal value with a *named* IANA zone (e.g.
251
    /// `time("09:00:00@Europe/Berlin")`) yields an error-null instead; fixed
252
    /// offsets (`+02:00`) and `Z` are unaffected. Hosts needing tzdb-independent,
253
    /// IMMUTABLE-safe evaluation turn it on via [`EvalEnv::forbidding_named_zones`]
254
    /// (feel-pg's `feel_eval_immutable`; RD-10). Default `false`.
255
    pub reject_named_zones: bool,
256
}
257
258
impl<'a> EvalEnv<'a> {
259
    /// Build an environment from a regex provider and an evaluation instant, with
260
    /// no ambient host functions.
261
    pub fn new(regex: &'a dyn FeelRegex, now: jiff::Zoned) -> Self {
262
        Self {
263
            regex,
264
            now,
265
            functions: &EMPTY_REGISTRY,
266
            reject_named_zones: false,
267
        }
268
    }
269
270
    /// Build an environment that also exposes a host [`FunctionRegistry`] (ADR-23).
271
    pub fn with_functions(
272
        regex: &'a dyn FeelRegex,
273
        now: jiff::Zoned,
274
        functions: &'a dyn FunctionRegistry,
275
    ) -> Self {
276
        Self {
277
            regex,
278
            now,
279
            functions,
280
            reject_named_zones: false,
281
        }
282
    }
283
284
    /// Return this env with the *named*-zone policy on: any temporal value carrying
285
    /// a named IANA zone becomes an error-null during evaluation, while fixed
286
    /// offsets and `Z` pass through. Used for IMMUTABLE evaluation, where a named
287
    /// zone's offset would depend on the updatable IANA tzdb (RD-10). Pair it with
288
    /// [`CompiledExpr::is_clock_free`] for a fully deterministic surface.
289
    pub fn forbidding_named_zones(mut self) -> Self {
290
        self.reject_named_zones = true;
291
        self
292
    }
293
294
    /// Apply the named-zone policy to a freshly-constructed temporal value: a
295
    /// named-zone `time`/`date and time` becomes an error-null when the policy is
296
    /// on; everything else passes through unchanged. A single tag test when the
297
    /// policy is off, so the default path pays nothing.
298
    pub(crate) fn vet_named_zone(&self, v: Value) -> Value {
299
        if self.reject_named_zones && temporal::has_named_zone(&v) {
300
            Value::Error
301
        } else {
302
            v
303
        }
304
    }
305
}
306
307
/// The default evaluation instant: the system wall clock in the system zone.
308
fn default_now() -> jiff::Zoned {
309
    jiff::Zoned::now()
310
}
311
312
/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it.
313
///
314
/// Returns [`FeelError::Parse`] if the expression is syntactically invalid.
315
///
316
/// **Probe-free** (ADR-47): special-character name runs (`a-b`, `Date-Time`)
317
/// parse as arithmetic here — a compiled program must not pin one scope. Use
318
/// [`compile_with_probe`] when the scope is known at parse time, or the one-shot
319
/// [`evaluate`], which uses the context as the probe (§10.3.1.6).
320
///
321
/// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime
322
/// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the
323
/// per-call parse itself, which [`CompiledExpr`] lets callers pay once.
324
pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> {
325
    feel::ExprParser::new()
326
        .parse(lexer::lex(expr))
327
        .map(|expr| CompiledExpr { expr, name_runs: false })
328
        .map_err(|e| FeelError::Parse(e.to_string()))
329
}
330
331
/// Parse a FEEL expression with scope-dependent name resolution (§10.3.1.6,
332
/// ADR-47): special-character name runs (`a-b`, `Date-Time`, `x.y`) are fused
333
/// into single names when — and only when — the joined candidate is in scope
334
/// per `probe`, longest in-scope match preferred, left to right. Spaces are not
335
/// part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces
336
/// the operator reading.
337
///
338
/// The result's [`CompiledExpr::has_name_runs`] tells whether the parse
339
/// consulted the scope at all. For expressions with no name-run *pattern*
340
/// (see [`name_run_candidates`]), this is byte-identical to [`compile`].
341
pub fn compile_with_probe(
342
    expr: &str,
343
    probe: &dyn ScopeProbe,
344
) -> Result<CompiledExpr, FeelError> {
345
    let (toks, name_runs) = lexer::lex_with_probe(expr, probe);
346
    feel::ExprParser::new()
347
        .parse(toks)
348
        .map(|expr| CompiledExpr { expr, name_runs })
349
        .map_err(|e| FeelError::Parse(e.to_string()))
350
}
351
352
/// Parse and evaluate a FEEL expression against a context.
353
///
354
/// Convenience for `compile_with_probe(expr, context)?.evaluate(context)`;
355
/// prefer [`compile_with_probe`] when evaluating the same expression more than
356
/// once against the same scope. The context **is** the scope for §10.3.1.6
357
/// name resolution (ADR-47): a name like `a-b` resolves to the context binding
358
/// when one exists, and to subtraction otherwise.
359
///
360
/// ```
361
/// use feel_core::{evaluate, Context, Value};
362
/// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0));
363
/// ```
364
pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> {
365
    compile_with_probe(expr, context)?.evaluate(context)
366
}
367
368
/// Every special-character name candidate `expr` could fuse under *some* scope
369
/// (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, `a-b`, `b-c`. Probe-free
370
/// and cheap; the use case is a host that caches a probe-free parse across
371
/// contexts (feel-pg's `fn_extra` slot): if none of the candidates is bound in
372
/// a given context, the cached parse is already scope-correct; if any is bound,
373
/// re-parse that context with [`compile_with_probe`]. An empty result means the
374
/// expression's parse is scope-independent for every possible context.
375
pub fn name_run_candidates(expr: &str) -> Vec<String> {
376
    lexer::name_run_candidates(expr)
377
}
378
379
/// Parse a structural FEEL type expression (`number`, `list<string>`,
380
/// `context<a: number, b: string>`, `function<number> -> boolean`, …) into a
381
/// [`FeelType`].  Returns `None` if the input is syntactically invalid or
382
/// contains an unmappable name (one that maps to [`FeelType::Unknown`]).
383
pub fn parse_type(s: &str) -> Option<FeelType> {
384
    feel::TypeParser::new()
385
        .parse(lexer::lex(s))
386
        .ok()
387
        .filter(|t| t.is_mappable())
388
}
389
390
/// Apply the §10.3.2.9.4 implicit conversion from `v` toward target type `t`.
391
///
392
/// Returns `Value::Null` when the conversion is mandatory but cannot be
393
/// performed (type mismatch, null input, or unknown target type).  The five
394
/// rules — null/error pass-through, from-singleton-list, to-singleton-list,
395
/// and conforms-to — are documented on [`types::coerce`].
396
pub fn coerce(v: Value, t: &FeelType) -> Value {
397
    types::coerce(v, t)
398
}
399
400
#[cfg(test)]
401
mod tests {
402
    use super::*;
403
404
    /// Evaluate against an empty context, panicking on error, and collapse error
405
    /// provenance — this is the lenient/observable view, so these tests assert
406
    /// plain FEEL value semantics where an error-null and a value-null coincide.
407
    /// (See `error_provenance` for the raw, provenance-aware assertions.)
408
    fn ev(src: &str) -> Value {
409
        evaluate(src, &Context::empty())
410
            .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
411
            .into_lenient()
412
    }
413
414
    fn num(n: f64) -> Value {
415
        Value::Number(n)
416
    }
417
    fn b(v: bool) -> Value {
418
        Value::Boolean(v)
419
    }
420
    fn list(items: Vec<Value>) -> Value {
421
        Value::List(items)
422
    }
423
424
    #[test]
425
    fn compile_matches_evaluate() {
426
        // The compiled path and the one-shot path must agree.
427
        for src in ["1 + 1", "5 in [1..10]", "if 1 < 2 then 10 else 20"] {
428
            let one_shot = evaluate(src, &Context::empty()).unwrap();
429
            let compiled = compile(src).unwrap().evaluate(&Context::empty()).unwrap();
430
            assert_eq!(one_shot, compiled, "mismatch for `{src}`");
431
        }
432
    }
433
434
    #[test]
435
    fn compiled_expr_reused_across_contexts() {
436
        // One parse, evaluated against two different contexts.
437
        let prog = compile("a + 1").unwrap();
438
        let mut c1 = Context::empty();
439
        c1.insert("a", num(1.0));
440
        let mut c2 = Context::empty();
441
        c2.insert("a", num(41.0));
442
        assert_eq!(prog.evaluate(&c1).unwrap().into_lenient(), num(2.0));
443
        assert_eq!(prog.evaluate(&c2).unwrap().into_lenient(), num(42.0));
444
    }
445
446
    #[test]
447
    fn compile_reports_parse_error() {
448
        assert!(matches!(compile("1 +"), Err(FeelError::Parse(_))));
449
    }
450
451
    // ----------------------------------------------------------------------- //
452
    // Special-character names (§10.3.1.6, ADR-47)
453
    // ----------------------------------------------------------------------- //
454
455
    fn ctx_of(pairs: &[(&str, Value)]) -> Context {
456
        let mut c = Context::empty();
457
        for (k, v) in pairs {
458
            c.insert(*k, v.clone());
459
        }
460
        c
461
    }
462
463
    /// A FEEL context value from `(key, value)` pairs.
464
    fn ctx_value(pairs: &[(&str, Value)]) -> Value {
465
        Value::Context(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect())
466
    }
467
468
    /// One-shot evaluation against a scope built from `(name, value)` pairs —
469
    /// the §10.3.1.6 stance: the context is the name oracle.
470
    fn eval_in(src: &str, pairs: &[(&str, Value)]) -> Value {
471
        evaluate(src, &ctx_of(pairs))
472
            .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
473
            .into_lenient()
474
    }
475
476
    #[test]
477
    fn special_char_names_resolve_against_scope() {
478
        // `a-b` is the in-scope NAME when bound, subtraction otherwise — and
479
        // `a - b` is the same candidate: spaces are not part of the name.
480
        assert_eq!(eval_in("a-b", &[("a-b", num(10.0))]), num(10.0));
481
        assert_eq!(eval_in("a - b", &[("a-b", num(10.0))]), num(10.0));
482
        assert_eq!(eval_in("a-b", &[]), Value::Null); // unbound: subtraction of two nulls
483
        // All five additional name symbols (grammar rule 30).
484
        assert_eq!(eval_in("a+b", &[("a+b", num(1.0))]), num(1.0));
485
        assert_eq!(eval_in("a*b", &[("a*b", num(2.0))]), num(2.0));
486
        assert_eq!(eval_in("a/b", &[("a/b", num(3.0))]), num(3.0));
487
        assert_eq!(eval_in("a.b", &[("a.b", num(4.0))]), num(4.0));
488
        // Keywords are legal name PARTS in symbol runs (`x-in`; unfused, `in`
489
        // would make it a membership test) — but never a name START (§10.3.1.4).
490
        assert_eq!(eval_in("x-in", &[("x-in", b(true))]), b(true));
491
        // A multi-word name part joins before fusion (`total price-total`).
492
        assert_eq!(
493
            eval_in("total price-total", &[("total price-total", num(5.0))]),
494
            num(5.0)
495
        );
496
        // Fusion reaches every reference slot — call arguments:
497
        assert_eq!(eval_in("not(x-y)", &[("x-y", b(true))]), b(false));
498
    }
499
500
    #[test]
501
    fn special_char_name_longest_match_left_to_right() {
502
        // Longest in-scope prefix wins: with `a-b-c` also bound, the whole run
503
        // is one name.
504
        assert_eq!(
505
            eval_in("a-b-c", &[("a-b", num(1.0)), ("a-b-c", num(2.0))]),
506
            num(2.0)
507
        );
508
        // With only `a-b` bound, the run fuses `a-b` and subtracts the rest.
509
        assert_eq!(
510
            eval_in("a-b-c", &[("a-b", num(10.0)), ("c", num(4.0))]),
511
            num(6.0)
512
        );
513
        // The scan resumes after a fused name: `Date-Time - Date-Time2` fuses
514
        // BOTH names and keeps the minus an operator — the TCK 0007 expectation
515
        // (subtraction), reproduced by longest-match at each position.
516
        let dt = &[("Date-Time", num(100.0)), ("Date-Time2", num(58.0))];
517
        assert_eq!(eval_in("Date-Time - Date-Time2", dt), num(42.0));
518
        // ... and after a miss the scan continues INSIDE the run: `b-c` bound
519
        // in `a-b-c` parses as `a - b-c`.
520
        assert_eq!(
521
            eval_in("a-b-c", &[("a", num(8.0)), ("b-c", num(3.0))]),
522
            num(5.0)
523
        );
524
        // `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name.
525
        let esc = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))];
526
        assert_eq!(eval_in("(a)-(b)", esc), num(4.0));
527
    }
528
529
    #[test]
530
    fn special_char_name_vs_path_and_members() {
531
        // `x.y` is ambiguous between one name and a path (§10.3.1.6): the
532
        // in-scope name wins when bound; otherwise the path stands.
533
        let nested = &[("x", ctx_value(&[("y", num(5.0))]))];
534
        assert_eq!(eval_in("x.y", nested), num(5.0)); // path
535
        assert_eq!(eval_in("x.y", &[("x.y", num(9.0))]), num(9.0)); // name
536
        // A hyphen name as a PATH BASE: the whole-run candidate `Date-Time2.hour`
537
        // is not in scope, so `Date-Time2` fuses and `.hour` stays a member.
538
        let dt2 = &[("Date-Time2", ctx_value(&[("hour", num(3.0))]))];
539
        assert_eq!(eval_in("Date-Time2.hour", dt2), num(3.0));
540
        // A multi-word member stays a member: `Date-Time2.time offset`.
541
        let off = &[("Date-Time2", ctx_value(&[("time offset", num(2.0))]))];
542
        assert_eq!(eval_in("Date-Time2.time offset", off), num(2.0));
543
        // But a bound name of the WHOLE dotted run wins over the path (longest
544
        // match at the run start).
545
        let whole = &[
546
            ("Date-Time2", ctx_value(&[("hour", num(3.0))])),
547
            ("Date-Time2.hour", num(7.0)),
548
        ];
549
        assert_eq!(eval_in("Date-Time2.hour", whole), num(7.0));
550
    }
551
552
    #[test]
553
    fn compile_is_probe_free_and_reports_name_runs() {
554
        // `compile` never fuses: `a-b` stays subtraction even when bound in the
555
        // context it is later evaluated against (a compiled program pins no
556
        // scope — the documented compile-once policy, ADR-47).
557
        let bound = ctx_of(&[("a-b", num(10.0))]);
558
        assert_eq!(
559
            compile("a-b").unwrap().evaluate(&bound).unwrap().into_lenient(),
560
            Value::Null
561
        );
562
        assert_eq!(
563
            compile_with_probe("a-b", &bound)
564
                .unwrap()
565
                .evaluate(&bound)
566
                .unwrap()
567
                .into_lenient(),
568
            num(10.0)
569
        );
570
571
        // `has_name_runs`: set when a probe-aware parse SAW a run (fused or
572
        // not) — the parse consulted the scope; false without a run pattern.
573
        let empty = Context::empty();
574
        assert!(compile_with_probe("a-b", &empty).unwrap().has_name_runs());
575
        assert!(!compile_with_probe("a + 1", &empty).unwrap().has_name_runs()); // `1` is no word
576
        assert!(!compile("a-b").unwrap().has_name_runs()); // probe-free parse never consults
577
        // Adjacency never forms a run (`a and b`, `for x in y` are untouched).
578
        assert!(!compile_with_probe("a and b", &empty).unwrap().has_name_runs());
579
        assert!(!compile_with_probe("for x in y return x", &empty).unwrap().has_name_runs());
580
581
        // `name_run_candidates`: every fusable candidate, from every unit
582
        // position — the probe-free "could this parse be scope-dependent" set
583
        // (feel-pg's cache check). Empty for run-free texts.
584
        assert_eq!(name_run_candidates("a-b-c"), vec!["a-b-c", "a-b", "b-c"]);
585
        assert!(name_run_candidates("1 + 1").is_empty());
586
        assert!(name_run_candidates("a and b").is_empty());
587
        assert_eq!(name_run_candidates("x.y"), vec!["x.y"]);
588
        assert_eq!(name_run_candidates("x-in"), vec!["x-in"]);
589
        assert!(name_run_candidates("if-then").is_empty()); // keyword start
590
        assert_eq!(
591
            name_run_candidates("Date-Time - Date-Time2"),
592
            vec![
593
                "Date-Time-Date-Time2",
594
                "Date-Time-Date",
595
                "Date-Time",
596
                "Time-Date-Time2",
597
                "Time-Date",
598
                "Date-Time2"
599
            ]
600
        );
601
    }
602
603
    #[test]
604
    fn special_char_name_run_free_shapes_stay_untouched() {
605
        // No candidate in scope: every one of these keeps its operator reading.
606
        let empty = Context::empty();
607
        let ev0 = |src: &str| {
608
            evaluate(src, &empty)
609
                .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
610
                .into_lenient()
611
        };
612
        // Numeric operands never form runs (a name part cannot start with a digit).
613
        assert_eq!(ev0("1 + 1"), num(2.0));
614
        assert_eq!(ev0("3 - 1"), num(2.0));
615
        assert_eq!(ev0("a - 1"), Value::Null); // unbound `a`, minus 1
616
        assert_eq!(ev0("x and y"), Value::Null); // adjacency: boolean and of nulls
617
        // Range/descendant/exponent separators are not name symbols.
618
        assert_eq!(ev0("5 in [1..10]"), b(true));
619
        assert_eq!(ev0("2 ** 3"), num(8.0));
620
        assert_eq!(ev0("for i in [1,2] return i"), list(vec![num(1.0), num(2.0)]));
621
        assert_eq!(
622
            ev0("for i in [2, 3] return i - 1"),
623
            list(vec![num(1.0), num(2.0)])
624
        );
625
        // Declaration slots are deferred (ADR-47): `for a-b in …` declares no
626
        // hyphen loop variable — it stays a parse error.
627
        assert!(compile("for a-b in [1] return a-b").is_err());
628
    }
629
630
    #[test]
631
    fn path_member_word_never_fuses_against_outer_scope() {
632
        // A word directly after an unfused `.` is a MEMBER position, not a
633
        // variable reference: it must never start a name run. A root key may not
634
        // change how a member access parses (ADR-47; the base of the path still
635
        // forms legitimate run candidates, so a root key `x.y` keeps beating the
636
        // path by longest-match — see `special_char_name_vs_path_and_members`).
637
        let ctx = ctx_of(&[
638
            ("x", ctx_value(&[("y", num(10.0))])),
639
            ("z", num(3.0)),
640
            ("y-z", num(1.0)),
641
        ]);
642
        // `x.y-z` is (x.y) - z = 7 — even though the root binds `y-z`.
643
        assert_eq!(evaluate("x.y-z", &ctx).unwrap().into_lenient(), num(7.0));
644
        // And identically without the root key (the two parses agree again).
645
        let no_key = ctx_of(&[("x", ctx_value(&[("y", num(10.0))])), ("z", num(3.0))]);
646
        assert_eq!(evaluate("x.y-z", &no_key).unwrap().into_lenient(), num(7.0));
647
        // The member-position rule also holds after a fused path base: the
648
        // `hour` in `Date-Time2.hour - z` never starts a run.
649
        let dt = ctx_of(&[
650
            ("Date-Time2", ctx_value(&[("hour", num(3.0))])),
651
            ("z", num(4.0)),
652
            ("hour-z", num(99.0)),
653
        ]);
654
        assert_eq!(
655
            evaluate("Date-Time2.hour - z", &dt).unwrap().into_lenient(),
656
            num(-1.0)
657
        );
658
        // Deeper chains: only the base is a variable position (`p.q - s`).
659
        let deep = ctx_of(&[
660
            ("p", ctx_value(&[("q", ctx_value(&[("r", num(2.0))]))])),
661
            ("s", num(5.0)),
662
            ("r-s", num(1.0)),
663
        ]);
664
        assert_eq!(evaluate("p.q.r-s", &deep).unwrap().into_lenient(), num(-3.0));
665
        // Pinned v1 gap (ADR-47 deviation "names in inner scopes"): only the root
666
        // level is probed, so a nested hyphen KEY is not reachable as a member —
667
        // `applicant.first-name` stays `applicant.first - name`.
668
        let nested = ctx_of(&[(
669
            "applicant",
670
            ctx_value(&[("first-name", Value::String("Ada".into()))]),
671
        )]);
672
        assert_eq!(
673
            evaluate("applicant.first-name", &nested).unwrap().into_lenient(),
674
            Value::Null
675
        );
676
    }
677
678
    #[test]
679
    fn keywords_never_start_name_runs() {
680
        // A run must start at a Name: §10.3.1.4 — "A name start SHALL NOT be a
681
        // literal terminal symbol", so no keyword starts a run. `return -i`
682
        // must not produce the candidate `return-i` (which, if bound, would
683
        // corrupt the loop parse; and in feel-pg would force per-row
684
        // re-parses / IMMUTABLE errors).
685
        assert!(name_run_candidates("for i in [1,2] return -i").is_empty());
686
        assert!(name_run_candidates("if a then -b else -c").is_empty());
687
        assert!(name_run_candidates("some i in xs satisfies -i > 0").is_empty());
688
        // A bound `return-i` changes nothing (the candidate no longer exists).
689
        let ctx = ctx_of(&[("return-i", num(100.0))]);
690
        assert_eq!(
691
            evaluate("for i in [1,2] return -i", &ctx)
692
                .unwrap()
693
                .into_lenient(),
694
            list(vec![num(-1.0), num(-2.0)])
695
        );
696
        assert!(
697
            !compile_with_probe("for i in [1,2] return -i", &ctx)
698
                .unwrap()
699
                .has_name_runs()
700
        );
701
        // Value keywords do not start runs either: a bound `if-then` is not a
702
        // name (it stays the — invalid — `if - then`), nor is `true-x`.
703
        let if_then = ctx_of(&[("if-then", b(true))]);
704
        assert!(evaluate("if-then", &if_then).is_err());
705
        assert_eq!(eval_in("true-x", &[("true-x", num(1.0))]), Value::Null);
706
        // Keywords stay legal as NON-starting run words (`x-in`, `a-if`).
707
        assert_eq!(eval_in("x-in", &[("x-in", num(4.0))]), num(4.0));
708
        assert_eq!(eval_in("a-if", &[("a-if", num(5.0))]), num(5.0));
709
    }
710
711
    #[test]
712
    fn is_clock_free_finds_now_and_today_anywhere() {
713
        // Pure expressions are clock-free, including temporal constructors and
714
        // named-zone literals (the clock check is orthogonal to zones).
715
        for src in [
716
            "1 + 1",
717
            "date(2020, 1, 1)",
718
            r#"time("09:00:00@Europe/Berlin")"#,
719
            "for x in [1, 2, 3] return x + 1",
720
        ] {
721
            assert!(
722
                compile(src).unwrap().is_clock_free(),
723
                "expected clock-free: {src}"
724
            );
725
        }
726
        // `now()`/`today()` make it not clock-free, however deeply nested.
727
        for src in [
728
            "now()",
729
            "today()",
730
            "1 + now()",
731
            "if a then 1 else today()",
732
            "[1, now(), 3]",
733
            "{ a: now() }",
734
            "some x in [1, 2] satisfies x > today()",
735
        ] {
736
            assert!(
737
                !compile(src).unwrap().is_clock_free(),
738
                "expected clock-reading: {src}"
739
            );
740
        }
741
    }
742
743
    #[test]
744
    fn forbidding_named_zones_rejects_named_keeps_offsets() {
745
        let forbid =
746
            EvalEnv::new(&crate::regex_provider::DEFAULT, default_now()).forbidding_named_zones();
747
        let eval =
748
            |src: &str, ctx: &Context| compile(src).unwrap().evaluate_with_env(ctx, &forbid).unwrap();
749
        let empty = Context::empty();
750
751
        // Fixed offsets and `Z` are tzdb-independent -> always allowed.
752
        assert!(matches!(eval(r#"time("09:00:00+02:00")"#, &empty), Value::Time(_)));
753
        assert!(matches!(eval(r#"time("09:00:00Z")"#, &empty), Value::Time(_)));
754
755
        // A named zone is allowed by the default env (no policy) ...
756
        assert!(matches!(
757
            compile(r#"time("09:00:00@Europe/Berlin")"#)
758
                .unwrap()
759
                .evaluate(&empty)
760
                .unwrap(),
761
            Value::Time(_)
762
        ));
763
        // ... but becomes an error-null under the policy — whether the named zone
764
        // comes from a constructor literal, an `@"…"` literal, or runtime data.
765
        assert_eq!(eval(r#"time("09:00:00@Europe/Berlin")"#, &empty), Value::Error);
766
        assert_eq!(eval(r#"@"2017-08-10T12:00:00@Europe/Berlin""#, &empty), Value::Error);
767
        let mut ctx = Context::empty();
768
        ctx.insert("s", Value::String("2017-08-10T12:00:00@Europe/Berlin".into()));
769
        assert_eq!(eval("date and time(s)", &ctx), Value::Error);
770
    }
771
772
    #[test]
773
    fn literals() {
774
        assert_eq!(ev("42"), num(42.0));
775
        assert_eq!(ev("3.5"), num(3.5));
776
        assert_eq!(ev(r#""foo""#), Value::String("foo".into()));
777
        assert_eq!(ev("true"), b(true));
778
        assert_eq!(ev("false"), b(false));
779
        assert_eq!(ev("null"), Value::Null);
780
        assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)]));
781
        assert_eq!(ev("[]"), list(vec![]));
782
    }
783
784
    // FEEL grammar rule 35 / §10.3.2.3.1: leading-dot mantissa and exponent forms.
785
    // These are exercised by the 0101-feel-constants TCK suite and checked here
786
    // directly so the lexer widening has coverage independent of the fixtures.
787
    #[test]
788
    fn number_literals_rule35() {
789
        // leading-dot mantissa (.digits)
790
        assert_eq!(ev(".872"), num(0.872));
791
        assert_eq!(ev("-.872"), num(-0.872));
792
        // exponent forms
793
        assert_eq!(ev("1.2e3"), num(1200.0));
794
        assert_eq!(ev("1.2E3"), num(1200.0));
795
        assert_eq!(ev("1E-3"), num(0.001));
796
        assert_eq!(ev("1e+2"), num(100.0));
797
        // leading-dot + exponent
798
        assert_eq!(ev(".5e2"), num(50.0));
799
        // unchanged: digit-led mantissa still works
800
        assert_eq!(ev("3.5"), num(3.5));
801
    }
802
803
    #[test]
804
    fn comments() {
805
        assert_eq!(ev("1 + /* 1 + */ 1"), num(2.0));
806
        assert_eq!(ev("1 + // eol\n 1"), num(2.0));
807
        assert_eq!(ev("/* intro */ 1 + 1 // trailing"), num(2.0));
808
        assert_eq!(ev("6 / 3"), num(2.0)); // lone slash stays division
809
    }
810
811
    #[test]
812
    fn first_class_range_literals() {
813
        // A range literal in value position is a first-class value, equal to itself.
814
        assert_eq!(ev("[1..10] = [1..10]"), b(true));
815
        assert_eq!(ev("(1..10] = (1..10]"), b(true));
816
        assert_eq!(ev("[1..10) = [1..10)"), b(true));
817
        // Openness and endpoints are part of identity.
818
        assert_eq!(ev("[1..10] = [1..10)"), b(false));
819
        assert_eq!(ev("[1..10] = (1..10]"), b(false));
820
        assert_eq!(ev("[1..10] = [1..11]"), b(false));
821
        // Endpoints of any orderable type.
822
        assert_eq!(ev(r#"["a".."c"] = ["a".."c"]"#), b(true));
823
        // `instance of range<T>` checks both endpoints' type.
824
        assert_eq!(ev("[1..10] instance of range<number>"), b(true));
825
        assert_eq!(ev(r#"["a".."c"] instance of range<string>"#), b(true));
826
        assert_eq!(ev("[1..10] instance of range<string>"), b(false));
827
        // A range literal nests as a list element (list of ranges).
828
        assert_eq!(ev("[[1..2], [3..4]] = [[1..2], [3..4]]"), b(true));
829
        // The `in` membership *test* form is unchanged (regression).
830
        assert_eq!(ev("5 in [1..10]"), b(true));
831
        assert_eq!(ev("15 in [1..10]"), b(false));
832
        // A plain list literal is still a list, not a range.
833
        assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)]));
834
    }
835
836
    #[test]
837
    fn reverse_open_bracket_intervals() {
838
        // `]a..b]` is FEEL's exclusive-lower spelling of `(a..b]` — identical value.
839
        assert_eq!(ev("]1..10] = (1..10]"), b(true));
840
        assert_eq!(ev("]1..10] = [1..10]"), b(false)); // start openness differs
841
        assert_eq!(ev("]1..10) = (1..10)"), b(true)); // reverse-open + open upper
842
        // Value position: a reverse-open literal nests as a list element.
843
        assert_eq!(ev("[]1..2], (1..2]] = [(1..2], (1..2]]"), b(true));
844
        // Membership-test position: `x in ]a..b]` excludes the open lower bound.
845
        assert_eq!(ev("5 in ]1..10]"), b(true));
846
        assert_eq!(ev("1 in ]1..10]"), b(false)); // open lower excludes
847
        assert_eq!(ev("10 in ]1..10]"), b(true)); // closed upper includes
848
        // The empty list `[]` is untouched by the opener retag (no `..` follows).
849
        assert_eq!(ev("[]"), list(vec![]));
850
    }
851
852
    #[test]
853
    fn reverse_close_bracket_intervals() {
854
        // `[a..b[` is FEEL's exclusive-upper spelling of `[a..b)` — identical value.
855
        assert_eq!(ev("[1..10[ = [1..10)"), b(true));
856
        assert_eq!(ev("[1..10[ = [1..10]"), b(false)); // end openness differs
857
        assert_eq!(ev("(1..10[ = (1..10)"), b(true)); // open lower + reverse-close
858
        // Both reverse brackets at once: `]a..b[` ≡ `(a..b)`.
859
        assert_eq!(ev("]1..10[ = (1..10)"), b(true));
860
        // Membership-test position: `x in [a..b[` excludes the open upper bound.
861
        assert_eq!(ev("9 in [1..10["), b(true));
862
        assert_eq!(ev("10 in [1..10["), b(false)); // open upper excludes
863
        assert_eq!(ev("1 in [1..10["), b(true)); // closed lower includes
864
        // Arithmetic still works in the (filter-free) high endpoint.
865
        assert_eq!(ev("9 in [1..5+5["), b(true));
866
        // Regression: a `[` after a completed value is still a filter subscript.
867
        assert_eq!(ev("[10, 20, 30][2]"), num(20.0));
868
    }
869
870
    #[test]
871
    fn unbounded_ranges() {
872
        // An omitted endpoint is UNBOUNDED (±∞; ADR-31), satisfying its side of a
873
        // membership test unconditionally. Per FEEL grammar rule 66 an omitted endpoint
874
        // requires an OPEN bracket on that side: `[1..)` / `(..10]`, never `[1..]` /
875
        // `[..10]` (a closed bracket with no value is a parse error; see
876
        // `unbounded_closed_bracket_is_a_parse_error`).
877
        assert_eq!(ev("5 in [1..)"), b(true)); // everything ≥ 1
878
        assert_eq!(ev("0 in [1..)"), b(false));
879
        assert_eq!(ev("1 in [1..)"), b(true)); // closed lower includes
880
        assert_eq!(ev("1 in (1..)"), b(false)); // open lower excludes
881
        assert_eq!(ev("5 in (..10]"), b(true)); // everything ≤ 10
882
        assert_eq!(ev("11 in (..10]"), b(false));
883
        assert_eq!(ev("10 in (..10)"), b(false)); // open upper excludes
884
885
        // The crux: UNBOUNDED is NOT a `null` bound. `(..10]` includes everything ≤ 10;
886
        // `[null..10]` is a *present* null bound, so membership is three-valued unknown
887
        // (per DMN-TCK 0072) — they must stay distinct.
888
        assert_eq!(ev("5 in (..10]"), b(true));
889
        assert_eq!(ev("5 in [null..10]"), Value::Null);
890
        assert_eq!(ev("5 in [1..)"), b(true));
891
        assert_eq!(ev("5 in [1..null]"), Value::Null);
892
893
        // Value-position literals: a first-class unbounded range, equal to itself and
894
        // distinct from a bounded range.
895
        assert_eq!(ev("[1..) = [1..)"), b(true));
896
        assert_eq!(ev("(..10] = (..10]"), b(true));
897
        assert_eq!(ev("(..10] = ]..10]"), b(true)); // unbounded lower: spelling irrelevant
898
        assert_eq!(ev("[1..) = [1..10]"), b(false)); // unbounded ≠ bounded
899
        assert_eq!(ev("[1..) = [2..)"), b(false)); // different lower bound
900
        assert_eq!(ev("(..10] = (..11]"), b(false));
901
        // UNBOUNDED ≠ a present `null` bound, even structurally.
902
        assert_eq!(ev("(..10] = [null..10]"), b(false));
903
904
        // Range properties: an unbounded endpoint has no value and is never included.
905
        assert_eq!(ev("[1..).start"), num(1.0));
906
        assert_eq!(ev("[1..).end"), Value::Null);
907
        assert_eq!(ev("[1..).end included"), b(false));
908
        assert_eq!(ev("(..10].start"), Value::Null);
909
        assert_eq!(ev("(..10].start included"), b(false));
910
        assert_eq!(ev("(..10].end"), num(10.0));
911
912
        // `instance of`: the bounded side types the range; the unbounded side is vacuous.
913
        assert_eq!(ev("[1..) instance of range<number>"), b(true));
914
        assert_eq!(ev("[1..) instance of range<string>"), b(false));
915
        assert_eq!(ev(r#"["a"..) instance of range<string>"#), b(true));
916
917
        // string() echoes the written bracket, rendering an unbounded side as nothing.
918
        assert_eq!(ev("string([1..))"), Value::String("[1..)".into()));
919
        assert_eq!(ev("string((..10))"), Value::String("(..10)".into()));
920
921
        // Allen relations (§10.3.4.6) over unbounded operands.
922
        assert_eq!(ev("before( (..5], [10..) )"), b(true)); // (-∞,5] before [10,+∞)
923
        assert_eq!(ev("before( (..5], [3..) )"), b(false)); // they overlap
924
        assert_eq!(ev("includes( (..7], [3..7] )"), b(true)); // unbounded-below includes all ≤ 7
925
        assert_eq!(ev("includes( [1..), [3..7] )"), b(true));
926
        assert_eq!(ev("includes( [1..), [0..7] )"), b(false)); // 0 < 1, escapes below
927
        assert_eq!(ev("during( 5, [1..) )"), b(true));
928
        assert_eq!(ev("during( 5, (..10] )"), b(true));
929
        assert_eq!(ev("coincides( (..5], (..5] )"), b(true));
930
        assert_eq!(ev("coincides( (..5], ]..5] )"), b(true)); // unbounded lower: spelling ignored
931
        assert_eq!(ev("overlaps( (..5], [3..) )"), b(true));
932
    }
933
934
    #[test]
935
    fn unbounded_closed_bracket_is_a_parse_error() {
936
        // Rule 66: an omitted endpoint behind a CLOSED bracket is invalid, and AT MOST
937
        // one endpoint may be omitted — these do not parse (a hard error, not a silent
938
        // misparse), consistent with `range("[1..]")` / `range("(..)")` being null. The
939
        // valid spellings are `[1..)` / `(..10]` (ADR-31). `(..)` (both omitted) has no
940
        // rule-66 alternative, so it is rejected too.
941
        for src in [
942
            "[1..]", "[..10]", "[..10)", "[..]", "5 in [1..]", "5 in [..10]", "(..)",
943
            "5 in (..)", "(..)= (..)",
944
        ] {
945
            assert!(
946
                compile(src).is_err(),
947
                "expected a parse error for closed-bracket unbounded `{src}`"
948
            );
949
        }
950
    }
951
952
    #[test]
953
    fn value_position_comparison_test() {
954
        // A parenthesised comparison test in VALUE position — `(< 10)`, `(= 10)`,
955
        // `(!= 10)` — is an OPAQUE unary-test value (ADR-32), not a boolean and not a
956
        // promoted range. The measured TCK semantics (0068): it equals a *structurally
957
        // identical* test reflexively, but is NEVER equal to a `Range`.
958
        assert_eq!(ev("(<10) = (<10)"), b(true));
959
        assert_eq!(ev("(=10) = (=10)"), b(true));
960
        assert_eq!(ev("(!=10) = (!=10)"), b(true));
961
        // Whitespace inside the parens is irrelevant; every operator spelling works.
962
        assert_eq!(ev("(<= 10) = (<= 10)"), b(true));
963
        assert_eq!(ev("(>= 10) = (>= 10)"), b(true));
964
        assert_eq!(ev("(> 10) = (> 10)"), b(true));
965
966
        // Range-INCOMPATIBLE: equal to no `Range`, whatever the spelling — the crux that
967
        // falsified the desugar-to-range hypothesis (ADR-28). A definite `false`.
968
        assert_eq!(ev("(<10) = (null..10)"), b(false));
969
        assert_eq!(ev("(=10) = [10..10]"), b(false));
970
        assert_eq!(ev("(<10) = (..10)"), b(false)); // not even the unbounded `(..10)`
971
972
        // Structural, not loose: a different operator or endpoint is `false`.
973
        assert_eq!(ev("(<10) = (>10)"), b(false));
974
        assert_eq!(ev("(<10) = (<=10)"), b(false));
975
        assert_eq!(ev("(<10) = (<11)"), b(false));
976
        // …and against anything else (a plain number, a list) it is `false`, not error.
977
        assert_eq!(ev("(<10) = 10"), b(false));
978
        assert_eq!(ev("(=10) = [10]"), b(false));
979
980
        // string() renders the written parenthesised form (endpoint quoted as a member).
981
        assert_eq!(ev("string((<10))"), Value::String("(< 10)".into()));
982
        assert_eq!(ev("string((!=10))"), Value::String("(!= 10)".into()));
983
        assert_eq!(ev(r#"string((="x"))"#), Value::String("(= \"x\")".into()));
984
985
        // REGRESSION: the `in`-position forms (ADR-28) are a *test*, unchanged — they
986
        // still membership-test, never construct an opaque value.
987
        assert_eq!(ev("10 in (=10)"), b(true));
988
        assert_eq!(ev("5 in (=10)"), b(false));
989
        assert_eq!(ev("5 in (!=10)"), b(true));
990
        assert_eq!(ev("10 in (!=10)"), b(false));
991
        assert_eq!(ev("5 in (<10)"), b(true));
992
        assert_eq!(ev("15 in (<10)"), b(false));
993
    }
994
995
    #[test]
996
    fn range_properties() {
997
        // The four range properties (DMN §10.3.2.6 / TCK 0074): endpoints + inclusivity.
998
        assert_eq!(ev("[1..10].start"), num(1.0));
999
        assert_eq!(ev("[1..10].end"), num(10.0));
1000
        assert_eq!(ev("[1..10].start included"), b(true));
1001
        assert_eq!(ev("[1..10].end included"), b(true));
1002
        // Openness flows through to `start/end included`, across every bracket form.
1003
        assert_eq!(ev("(1..10].start included"), b(false));
1004
        assert_eq!(ev("[1..10).end included"), b(false));
1005
        assert_eq!(ev("]1..10].start included"), b(false)); // reverse-open lower
1006
        assert_eq!(ev("[1..10[.end included"), b(false)); // reverse-close upper
1007
        assert_eq!(ev("]1..10].start"), num(1.0));
1008
        assert_eq!(ev("[1..10[.end"), num(10.0));
1009
        // Endpoints of any orderable type.
1010
        assert_eq!(ev(r#"["a".."c"].end"#), Value::String("c".into()));
1011
        // An unknown property of a range is a value-null (a range has properties).
1012
        assert_eq!(ev("[1..10].foo"), Value::Null);
1013
1014
        // A comparison-test value `(< 10)` (ADR-32, ADR-33) is range-typed for these
1015
        // projections (§10.3.2.7 / Table 42, TCK 0074 range_006-011): the operator's
1016
        // missing endpoint is `null` and never included; the present endpoint's
1017
        // inclusivity follows the operator. Despite identical properties to a range,
1018
        // its equality stays OPAQUE — see `value_position_comparison_test`.
1019
        assert_eq!(ev("(<10).start"), Value::Null); // range_006: (<10)
1020
        assert_eq!(ev("(<10).end"), num(10.0));
1021
        assert_eq!(ev("(<10).start included"), b(false));
1022
        assert_eq!(ev("(<10).end included"), b(false));
1023
        assert_eq!(ev("(<=10).end included"), b(true)); // range_007: (<=10)
1024
        assert_eq!(ev("(>10).start"), num(10.0)); // range_009: (>10)
1025
        assert_eq!(ev("(>10).end"), Value::Null);
1026
        assert_eq!(ev("(>10).start included"), b(false));
1027
        assert_eq!(ev("(>=10).start included"), b(true)); // range_010: (>=10)
1028
        assert_eq!(ev("(=10).start"), num(10.0)); // range_011: (=10) ≡ [10..10] properties
1029
        assert_eq!(ev("(=10).end"), num(10.0));
1030
        assert_eq!(ev("(=10).start included"), b(true));
1031
        assert_eq!(ev("(=10).end included"), b(true));
1032
        assert_eq!(ev("(!=10).start included"), b(false)); // (!=10): bare endpoint, open
1033
        assert_eq!(ev("(!=10).end included"), b(false));
1034
        // An unknown property is still a value-null (it has range properties).
1035
        assert_eq!(ev("(<10).foo"), Value::Null);
1036
1037
        // `(< 10)` is "a typed instance of the range type" (§10.3.2.7), so it conforms
1038
        // to `range<T>` on its endpoint type — even though it is never *equal* to a range.
1039
        assert_eq!(ev("(<10) instance of range<number>"), b(true));
1040
        assert_eq!(ev("(>=10) instance of range<number>"), b(true));
1041
        assert_eq!(ev(r#"(<"x") instance of range<string>"#), b(true));
1042
        assert_eq!(ev("(<10) instance of range<string>"), b(false)); // wrong endpoint type
1043
    }
1044
1045
    #[test]
1046
    fn range_builtin() {
1047
        // Representative cases from DMN-TCK 1156-range-function.
1048
        // --- construction + equality with a literal / membership / instance of ---
1049
        assert_eq!(ev(r#"range("[18..21]") = [18..21]"#), b(true));
1050
        assert_eq!(ev(r#"range("(18..21]") = (18..21]"#), b(true));
1051
        assert_eq!(ev(r#"range("[18..21)") = [18..21)"#), b(true));
1052
        assert_eq!(ev(r#"range(" [ 1 .. 3 ] ") = [1..3]"#), b(true)); // whitespace tolerant
1053
        assert_eq!(ev(r#"2 in range("[1..3]")"#), b(true));
1054
        assert_eq!(ev(r#"range("[1..3]") instance of range<number>"#), b(true));
1055
        assert_eq!(ev(r#"range(string("[1..3]")) instance of range<number>"#), b(true));
1056
        assert_eq!(ev(r#"range("[\"a\"..\"c\"]") instance of range<string>"#), b(true));
1057
        assert_eq!(ev(r#"range(from: "[1..3]") = [1..3]"#), b(true));
1058
        // temporal endpoints (via `@"…"` and direct constructors on string literals)
1059
        assert_eq!(
1060
            ev(r#"range("[date(\"1970-01-01\")..date(\"1970-01-02\")]") = [date("1970-01-01")..date("1970-01-02")]"#),
1061
            b(true)
1062
        );
1063
        assert_eq!(ev(r#"range("[@\"P1D\"..@\"P2D\"]") instance of range<days and time duration>"#), b(true));
1064
        // Unbounded via the OPEN-bracket spelling is valid per FEEL grammar rule 66
1065
        // (b)/(c): `range("[2..)")` ≡ `>=2`, `range("(..2)")` ≡ `<2` (spec §10.3.4.6
1066
        // examples). A CLOSED bracket on the omitted side is invalid (the null cases
1067
        // below). See ADR-31.
1068
        assert_eq!(ev(r#"range("[2..)") = [2..)"#), b(true));
1069
        assert_eq!(ev(r#"range("(..2)") = (..2)"#), b(true));
1070
        assert_eq!(ev(r#"5 in range("[2..)")"#), b(true));
1071
        assert_eq!(ev(r#"5 in range("(..2)")"#), b(false));
1072
1073
        // --- error/null cases (lenient view collapses error-null to null) ---
1074
        for src in [
1075
            r#"range("")"#,
1076
            r#"range(" ")"#,
1077
            r#"range()"#,
1078
            r#"range("[1..3]", "foo")"#,
1079
            r#"range([1..3])"#,                  // argument is a range value, not a string
1080
            r#"range(">=10")"#,                  // not a range literal
1081
            r#"range("[1..\"b\"]")"#,            // mismatched endpoint types
1082
            r#"range("[3..1]")"#,                // reversed
1083
            r#"range("[null..null]")"#,          // null endpoints
1084
            // Omitted endpoint with a CLOSED bracket is invalid (rule 66 needs an OPEN
1085
            // bracket on the unbounded side); both-omitted has no rule-66 alternative.
1086
            // Unlike the lenient unbounded *literal* `[..2]` (ADR-31, in
1087
            // `unbounded_ranges`), the `range()` string is strict here.
1088
            r#"range("[..2]")"#,                 // closed start, no value → null (TCK 004_e)
1089
            r#"range("[1..]")"#,                 // closed end, no value → null (TCK 004_f)
1090
            r#"range("[..]")"#,                  // both omitted, both closed → null
1091
            r#"range("(..)")"#,                  // both omitted → null (no rule-66 case)
1092
            r#"range("[null..)")"#,              // present null lower bound → null
1093
            r#"range("[date(string(\"1970-01-01\"))..date(\"1970-01-02\")]")"#, // non-literal endpoint
1094
            r#"range(fron: "[1..3]")"#,          // unknown named parameter
1095
        ] {
1096
            assert_eq!(ev(src), Value::Null, "expected null for `{src}`");
1097
        }
1098
    }
1099
1100
    #[test]
1101
    fn range_relations_tck_1130() {
1102
        // The complete truth table of DMN-TCK 1130-feel-interval (every openness
1103
        // edge case for the §10.3.4.6 Allen relations). 1130's decisions are boxed
1104
        // contexts the fixture ingester does not read, so the suite is exercised here.
1105
        let cases: &[(&str, bool)] = &[
1106
            ("before( 1, 10 )", true),
1107
            ("before( 10, 1 )", false),
1108
            ("before( 1, [1..10] )", false),
1109
            ("before( 1, (1..10] )", true),
1110
            ("before( 1, [5..10] )", true),
1111
            ("before( [1..10], 10 )", false),
1112
            ("before( [1..10), 10 )", true),
1113
            ("before( [1..10], 15 )", true),
1114
            ("before( [1..10], [15..20] )", true),
1115
            ("before( [1..10], [10..20] )", false),
1116
            ("before( [1..10), [10..20] )", true),
1117
            ("before( [1..10], (10..20] )", true),
1118
            ("after( 10, 5 )", true),
1119
            ("after( 5, 10 )", false),
1120
            ("after( 12, [1..10] )", true),
1121
            ("after( 10, [1..10) )", true),
1122
            ("after( 10, [1..10] )", false),
1123
            ("after( [11..20], 12 )", false),
1124
            ("after( [11..20], 10 )", true),
1125
            ("after( (11..20], 11 )", true),
1126
            ("after( [11..20], 11 )", false),
1127
            ("after( [11..20], [1..10] )", true),
1128
            ("after( [1..10], [11..20] )", false),
1129
            ("after( [11..20], [1..11) )", true),
1130
            ("after( (11..20], [1..11] )", true),
1131
            ("meets( [1..5], [5..10] )", true),
1132
            ("meets( [1..5), [5..10] )", false),
1133
            ("meets( [1..5], (5..10] )", false),
1134
            ("meets( [1..5], [6..10] )", false),
1135
            ("met by( [5..10], [1..5] )", true),
1136
            ("met by( [5..10],  [1..5) )", false),
1137
            ("met by( (5..10], [1..5] )", false),
1138
            ("met by( [6..10], [1..5] )", false),
1139
            ("overlaps before( [1..5], [3..8] )", true),
1140
            ("overlaps before( [1..5], [6..8] )", false),
1141
            ("overlaps before( [1..5], [5..8] )", true),
1142
            ("overlaps before( [1..5], (5..8] )", false),
1143
            ("overlaps before( [1..5), [5..8] )", false),
1144
            ("overlaps before( [1..5), (1..5] )", true),
1145
            ("overlaps before( [1..5], (1..5] )", true),
1146
            ("overlaps before( [1..5), [1..5] )", false),
1147
            ("overlaps before( [1..5], [1..5] )", false),
1148
            ("overlaps after( [3..8], [1..5])", true),
1149
            ("overlaps after( [6..8], [1..5])", false),
1150
            ("overlaps after( [5..8], [1..5])", true),
1151
            ("overlaps after( (5..8], [1..5])", false),
1152
            ("overlaps after( [5..8], [1..5))", false),
1153
            ("overlaps after( (1..5], [1..5) )", true),
1154
            ("overlaps after( (1..5], [1..5] )", true),
1155
            ("overlaps after( [1..5], [1..5) )", false),
1156
            ("overlaps after( [1..5], [1..5] )", false),
1157
            ("finishes( 10, [1..10] )", true),
1158
            ("finishes( 10, [1..10) )", false),
1159
            ("finishes( [5..10], [1..10] )", true),
1160
            ("finishes( [5..10), [1..10] )", false),
1161
            ("finishes( [5..10), [1..10) )", true),
1162
            ("finishes( [1..10], [1..10] )", true),
1163
            ("finishes( (1..10], [1..10] )", true),
1164
            ("finished by( [1..10], 10 )", true),
1165
            ("finished by( [1..10), 10 )", false),
1166
            ("finished by( [1..10], [5..10] )", true),
1167
            ("finished by( [1..10], [5..10) )", false),
1168
            ("finished by( [1..10), [5..10) )", true),
1169
            ("finished by( [1..10], (1..10] )", true),
1170
            ("finished by( [1..10], [1..10] )", true),
1171
            ("includes( [1..10], 5 )", true),
1172
            ("includes( [1..10], 12 )", false),
1173
            ("includes( [1..10], 1 )", true),
1174
            ("includes( [1..10], 10 )", true),
1175
            ("includes( (1..10], 1 )", false),
1176
            ("includes( [1..10), 10 )", false),
1177
            ("includes( [1..10], [4..6] )", true),
1178
            ("includes( [1..10], [1..5] )", true),
1179
            ("includes( (1..10], (1..5] )", true),
1180
            ("includes( [1..10], (1..10) )", true),
1181
            ("includes( [1..10), [5..10) )", true),
1182
            ("includes( [1..10], [1..10) )", true),
1183
            ("includes( [1..10], (1..10] )", true),
1184
            ("includes( [1..10], [1..10] )", true),
1185
            ("during( 5, [1..10] )", true),
1186
            ("during( 12, [1..10] )", false),
1187
            ("during( 1, [1..10] )", true),
1188
            ("during( 10, [1..10] )", true),
1189
            ("during( 1, (1..10] )", false),
1190
            ("during( 10, [1..10) )", false),
1191
            ("during( [4..6], [1..10] )", true),
1192
            ("during( [1..5], [1..10] )", true),
1193
            ("during( (1..5], (1..10] )", true),
1194
            ("during( (1..10), [1..10] )", true),
1195
            ("during( [5..10), [1..10) )", true),
1196
            ("during( [1..10), [1..10] )", true),
1197
            ("during( (1..10], [1..10] )", true),
1198
            ("during( [1..10], [1..10] )", true),
1199
            ("starts( 1, [1..10] )", true),
1200
            ("starts( 1, (1..10] )", false),
1201
            ("starts( 2, [1..10] )", false),
1202
            ("starts( [1..5], [1..10] )", true),
1203
            ("starts( (1..5], (1..10] )", true),
1204
            ("starts( (1..5], [1..10] )", false),
1205
            ("starts( [1..5], (1..10] )", false),
1206
            ("starts( [1..10], [1..10] )", true),
1207
            ("starts( [1..10), [1..10] )", true),
1208
            ("starts( (1..10), (1..10) )", true),
1209
            ("started by( [1..10], 1 )", true),
1210
            ("started by( (1..10], 1 )", false),
1211
            ("started by( [1..10], 2 )", false),
1212
            ("started by( [1..10], [1..5] )", true),
1213
            ("started by( (1..10], (1..5] )", true),
1214
            ("started by( [1..10], (1..5] )", false),
1215
            ("started by( (1..10], [1..5] )", false),
1216
            ("started by( [1..10], [1..10] )", true),
1217
            ("started by( [1..10], [1..10) )", true),
1218
            ("started by( (1..10), (1..10) )", true),
1219
            ("coincides( 5, 5 )", true),
1220
            ("coincides( 3, 4 )", false),
1221
            ("coincides( [1..5], [1..5] )", true),
1222
            ("coincides( (1..5), [1..5] )", false),
1223
            ("coincides( [1..5], [2..6] )", false),
1224
            ("overlaps( [1..5], [3..8] )", true),
1225
            ("overlaps( [3..8], [1..5] )", true),
1226
            ("overlaps( [1..8], [3..5] )", true),
1227
            ("overlaps( [3..5], [1..8] )", true),
1228
            ("overlaps( [1..5], [6..8] )", false),
1229
            ("overlaps( [6..8], [1..5] )", false),
1230
            ("overlaps( [1..5], [5..8] )", true),
1231
            ("overlaps( [1..5], (5..8] )", false),
1232
            ("overlaps( [1..5), [5..8] )", false),
1233
            ("overlaps( [1..5), (5..8] )", false),
1234
            ("overlaps( [5..8], [1..5] )", true),
1235
            ("overlaps( (5..8], [1..5] )", false),
1236
            ("overlaps( [5..8], [1..5) )", false),
1237
            ("overlaps( (5..8], [1..5) )", false),
1238
        ];
1239
        for (src, want) in cases {
1240
            assert_eq!(ev(src), b(*want), "`{src}`");
1241
        }
1242
    }
1243
1244
    #[test]
1245
    fn in_unary_test_lists_tck_0072() {
1246
        // Comma-list-of-tests `in`-RHS forms (Form 1): a bracketed/parenthesised list
1247
        // of positive unary tests is an OR of its elements. Endpoints, nested ranges,
1248
        // comparison elements (`< 5`, `>= 10`), and the one-element paren tests
1249
        // `(= e)` / `(!= e)` all flow through the dedicated test-mode `InRhs`
1250
        // productions; the cases are lifted straight from 0072-feel-in.
1251
        let cases: &[(&str, bool)] = &[
1252
            // bracket list of endpoints
1253
            ("1 in [2,3,1]", true),
1254
            ("1 in [2,3,4]", false),
1255
            (r#""a" in ["b","c","a"]"#, true),
1256
            (r#""a" in ["b","c","d"]"#, false),
1257
            ("true in [true, false]", true),
1258
            ("true in [false, false]", false),
1259
            // bracket list of ranges (nested intervals reclassified to interval tests)
1260
            ("1 in [[2..4], [1..3]]", true),
1261
            ("1 in [[2..4], [5..7]]", false),
1262
            (r#""b" in [["f".."h"], ["a".."c"]]"#, true),
1263
            // paren list, incl. comparison elements
1264
            ("10 in (1, < 5, >=10)", true),
1265
            ("3 in (1, < 5, >=10)", true),
1266
            ("7 in (1, < 5, >=10)", false),
1267
            ("5 in (1, 5, 9)", true),
1268
            ("10 in (1, 5, 9)", false),
1269
            ("true in (false, true)", true),
1270
            ("true in (false, false)", false),
1271
            (r#""d" in ("c", < "c", >="d")"#, true),
1272
            (r#""d" in ("c", >="e")"#, false),
1273
            // one-element paren tests `(= e)` / `(!= e)` — Compare elements, no Form-4 desugar
1274
            ("10 in (=10)", true),
1275
            ("10 in (!=10)", false),
1276
            ("5 in (!=10)", true),
1277
            ("true in (=true)", true),
1278
            ("true in (!=true)", false),
1279
            (r#""a" in (="a")"#, true),
1280
            (r#""a" in (!="a")"#, false),
1281
            // list / context values as endpoints (same-type equality; a *cross*-type
1282
            // endpoint like `[1,2,3] in [1,2,3]` is the ADR-14 error-null deviation,
1283
            // tested elsewhere, not here)
1284
            ("[1,2,3] in [[1,2,3,4], [1,2,3]]", true),
1285
            ("[1,2,3] in ([1,2,3])", true),
1286
            ("[1,2,3] in (=[1,2,3])", true),
1287
            ("[1,2,3] in (!=[1,2,3])", false),
1288
            (r#"{a: "foo"} in ({a: "bar"}, {a: "foo"})"#, true),
1289
            (r#"{a: "foo"} in (={a: "foo"})"#, true),
1290
            // single interval / comparison / bare endpoint still parse as before
1291
            ("5 in [1..10]", true),
1292
            ("5 in (5..10]", false),
1293
            ("5 in [5..10]", true),
1294
            ("5 in (1..10)", true),
1295
            ("1 in (1..10)", false),
1296
            ("3 in < 5", true),
1297
            ("1 in 1", true),
1298
            ("1 in 2", false),
1299
        ];
1300
        for (src, want) in cases {
1301
            assert_eq!(ev(src), b(*want), "`{src}`");
1302
        }
1303
    }
1304
1305
    #[test]
1306
    fn arithmetic_and_precedence() {
1307
        assert_eq!(ev("1 + 1"), num(2.0));
1308
        assert_eq!(ev("1 + 2 * 3"), num(7.0)); // * binds tighter than +
1309
        assert_eq!(ev("(1 + 2) * 3"), num(9.0));
1310
        assert_eq!(ev("10 - 4 - 3"), num(3.0)); // - is left-associative
1311
        assert_eq!(ev("12 / 4"), num(3.0));
1312
        assert_eq!(ev("--10"), num(10.0)); // unary minus stacks
1313
    }
1314
1315
    #[test]
1316
    fn exponent_is_left_associative_and_below_unary_minus() {
1317
        // Verified against DMN-TCK 0075-feel-exponent.
1318
        assert_eq!(ev("3 ** 4 ** 5"), num(3486784401.0)); // (3**4)**5
1319
        assert_eq!(ev("-3 ** 2"), num(9.0)); // (-3)**2
1320
        assert_eq!(ev("2 * 3 ** 2"), num(18.0)); // ** tighter than *
1321
    }
1322
1323
    #[test]
1324
    fn type_errors_and_div_zero_are_null() {
1325
        assert_eq!(ev("1 + true"), Value::Null);
1326
        assert_eq!(ev(r#"1 + "x""#), Value::Null);
1327
        assert_eq!(ev("1 / 0"), Value::Null);
1328
        assert_eq!(ev("-true"), Value::Null);
1329
    }
1330
1331
    #[test]
1332
    fn comparison() {
1333
        assert_eq!(ev("1 < 2"), b(true));
1334
        assert_eq!(ev("2 <= 2"), b(true));
1335
        assert_eq!(ev("3 > 5"), b(false));
1336
        assert_eq!(ev(r#""apple" < "banana""#), b(true)); // lexicographic
1337
        assert_eq!(ev("1 < null"), Value::Null); // ordering with null -> null
1338
        assert_eq!(ev("1 < true"), Value::Null); // incomparable types -> null
1339
    }
1340
1341
    #[test]
1342
    fn equality_three_valued() {
1343
        // Values taken from DMN-TCK 0068-feel-equality.
1344
        assert_eq!(ev("null = null"), b(true));
1345
        assert_eq!(ev("null != null"), b(false));
1346
        assert_eq!(ev("true = null"), b(false));
1347
        assert_eq!(ev("true = false"), b(false));
1348
        assert_eq!(ev("123 = 123"), b(true));
1349
        assert_eq!(ev("-1 = 1"), b(false));
1350
        assert_eq!(ev(r#""foo" = "foo""#), b(true));
1351
        assert_eq!(ev(r#""foo" != "Foo""#), b(true));
1352
        // Different non-null types compare to null, not false.
1353
        assert_eq!(ev("false = 0"), Value::Null);
1354
        assert_eq!(ev(r#"100 = "100""#), Value::Null);
1355
        // Lists compare structurally.
1356
        assert_eq!(ev("[1,2,3] = [1,2,3]"), b(true));
1357
        assert_eq!(ev("[1,1,1] = [1,1,1,1]"), b(false));
1358
        assert_eq!(ev("[1,2,3] = [3,2,1]"), b(false));
1359
        assert_eq!(ev("[] = []"), b(true));
1360
        assert_eq!(ev("[] = null"), b(false));
1361
    }
1362
1363
    #[test]
1364
    fn between() {
1365
        assert_eq!(ev("5 between 1 and 10"), b(true));
1366
        assert_eq!(ev("1 between 1 and 10"), b(true)); // inclusive
1367
        assert_eq!(ev("0 between 1 and 10"), b(false));
1368
        assert_eq!(ev(r#""c" between "b" and "d""#), b(true));
1369
    }
1370
1371
    #[test]
1372
    fn logic_three_valued() {
1373
        // Values taken from DMN-TCK 0064/0065/0066.
1374
        assert_eq!(ev("true and true"), b(true));
1375
        assert_eq!(ev("true and false"), b(false));
1376
        assert_eq!(ev("true and null"), Value::Null);
1377
        assert_eq!(ev("false and null"), b(false)); // false dominates
1378
        assert_eq!(ev("false and 123"), b(false));
1379
        assert_eq!(ev("true and 123"), Value::Null); // non-boolean -> null
1380
        assert_eq!(ev("true or false"), b(true));
1381
        assert_eq!(ev("true or null"), b(true)); // true dominates
1382
        assert_eq!(ev("false or null"), Value::Null);
1383
        assert_eq!(ev("123 or true"), b(true));
1384
        assert_eq!(ev("not(true)"), b(false));
1385
        assert_eq!(ev("not(false)"), b(true));
1386
        assert_eq!(ev("not(null)"), Value::Null);
1387
        assert_eq!(ev("not(0)"), Value::Null);
1388
    }
1389
1390
    #[test]
1391
    fn membership_and_interval_inclusivity() {
1392
        assert_eq!(ev("5 in [1..10]"), b(true));
1393
        assert_eq!(ev("1 in [1..10]"), b(true)); // closed lower includes
1394
        assert_eq!(ev("1 in (1..10]"), b(false)); // open lower excludes
1395
        assert_eq!(ev("10 in [1..10)"), b(false)); // open upper excludes
1396
        assert_eq!(ev("11 in [1..10]"), b(false)); // out of range
1397
        // A null bound makes the test null (Kleene), per DMN-TCK 0072.
1398
        assert_eq!(ev("5 in (null..10]"), Value::Null);
1399
    }
1400
1401
    #[test]
1402
    fn membership_unary_comparison_tests() {
1403
        // `in <op> endpoint` — a positive unary test (DMN rule 49).
1404
        assert_eq!(ev("1 in <= 10"), b(true));
1405
        assert_eq!(ev("11 in <= 10"), b(false));
1406
        assert_eq!(ev("11 in >= 10"), b(true));
1407
        assert_eq!(ev("1 in < 10"), b(true));
1408
        assert_eq!(ev("11 in > 10"), b(true));
1409
        assert_eq!(ev("10 in = 10"), b(true));
1410
        assert_eq!(ev("10 in != 10"), b(false));
1411
        // The endpoint is an arbitrary expression (a list value, a string).
1412
        assert_eq!(ev("[1, 2, 3] in = [1, 2, 3]"), b(true));
1413
        assert_eq!(ev("[1, 2, 3] in != [1, 2, 3, 4]"), b(true));
1414
        assert_eq!(ev(r#""b" in > "a""#), b(true));
1415
    }
1416
1417
    #[test]
1418
    fn membership_not_test_negation() {
1419
        // `x in not(...)` is *test* negation (DMN rule 49), not the boolean built-in:
1420
        // `x in not(t)` ≡ `not(x satisfies t)`, three-valued.
1421
        // List negation: `not(1,2,3)` ≡ `not(x = 1 or x = 2 or x = 3)`.
1422
        assert_eq!(ev("5 in not(1, 2, 3)"), b(true));
1423
        assert_eq!(ev("2 in not(1, 2, 3)"), b(false));
1424
        // Single bare endpoint: `not(5)` negates the `= 5` test.
1425
        assert_eq!(ev("4 in not(5)"), b(true));
1426
        assert_eq!(ev("5 in not(5)"), b(false));
1427
        // Comparison test negation: `not(< 5)` ≡ `not(x < 5)`.
1428
        assert_eq!(ev("7 in not(< 5)"), b(true));
1429
        assert_eq!(ev("3 in not(< 5)"), b(false));
1430
        // Interval test negation: `not([1..10])` ≡ `not(1 <= x <= 10)`.
1431
        assert_eq!(ev("11 in not([1..10])"), b(true));
1432
        assert_eq!(ev("5 in not([1..10])"), b(false));
1433
        // Mixed inner tests OR-fold before negation.
1434
        assert_eq!(ev("8 in not(< 5, > 10)"), b(true));
1435
        assert_eq!(ev("3 in not(< 5, > 10)"), b(false));
1436
        // Kleene: negating an unknown (a null bound) stays null, never a definite true.
1437
        assert_eq!(ev("5 in not((null..10])"), Value::Null);
1438
    }
1439
1440
    #[test]
1441
    fn if_then_else() {
1442
        assert_eq!(ev("if true then 1 else 2"), num(1.0));
1443
        assert_eq!(ev("if false then 1 else 2"), num(2.0));
1444
        assert_eq!(ev("if 1 < 2 then 10 else 20"), num(10.0));
1445
        // A null condition takes the else branch (null is a value -> "not true",
1446
        // per DMN-TCK 0032 / ADR-13).
1447
        assert_eq!(ev("if null then 1 else 2"), num(2.0));
1448
        // A wrong-TYPE condition is a type error and stays null (ADR-9/ADR-13).
1449
        assert_eq!(ev("if 5 then 1 else 2"), Value::Null);
1450
        assert_eq!(ev(r#"if "x" then 1 else 2"#), Value::Null);
1451
    }
1452
1453
    #[test]
1454
    fn error_provenance() {
1455
        // Raw view: do NOT collapse error provenance (unlike `ev`).
1456
        let raw = |src: &str| {
1457
            evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
1458
        };
1459
1460
        // Type / domain errors produce an error-null...
1461
        assert_eq!(raw("1 + true"), Value::Error);
1462
        assert_eq!(raw("1 / 0"), Value::Error);
1463
        assert_eq!(raw("-true"), Value::Error);
1464
        assert_eq!(raw("1 < true"), Value::Error); // incomparable types
1465
        assert_eq!(raw(r#"100 = "100""#), Value::Error); // type mismatch in `=`
1466
        assert_eq!(raw("if 5 then 1 else 2"), Value::Error); // wrong-type condition
1467
        assert_eq!(raw("5 .a"), Value::Error); // path on a non-context
1468
        assert_eq!(raw("not(0)"), Value::Error); // `not` of a non-boolean
1469
1470
        // ...while a genuine value-null stays a value-null.
1471
        assert_eq!(raw("null"), Value::Null);
1472
        assert_eq!(raw("missing"), Value::Null); // unbound variable
1473
        assert_eq!(raw("1 < null"), Value::Null); // value-null operand: unknown
1474
        assert_eq!(raw("if null then 1 else 2"), num(2.0)); // value-null -> else
1475
        assert_eq!(raw("not(null)"), Value::Null); // not unknown = unknown
1476
        assert_eq!(raw("true and null"), Value::Null); // value-null: untainted
1477
1478
        // error-null and value-null behave identically under FEEL equality.
1479
        assert_eq!(raw("null = (1 + true)"), b(true));
1480
1481
        // Design 1: a dominator swallows the error (truth value wins, TCK-safe)...
1482
        assert_eq!(raw("false and (1 + true)"), b(false));
1483
        assert_eq!(raw("true or (1 + true)"), b(true));
1484
        // ...but provenance is sticky where the result is the unknown null.
1485
        assert_eq!(raw("true and (1 + true)"), Value::Error);
1486
        assert_eq!(raw("false or (1 + true)"), Value::Error);
1487
    }
1488
1489
    #[test]
1490
    fn for_loops() {
1491
        assert_eq!(
1492
            ev("for i in [1,2,3] return i + 1"),
1493
            list(vec![num(2.0), num(3.0), num(4.0)])
1494
        );
1495
        assert_eq!(ev("for i in [] return i"), list(vec![]));
1496
        assert_eq!(
1497
            ev("for i in 2..4 return i"),
1498
            list(vec![num(2.0), num(3.0), num(4.0)])
1499
        );
1500
        assert_eq!(
1501
            ev("for i in 4..2 return i"), // descending
1502
            list(vec![num(4.0), num(3.0), num(2.0)])
1503
        );
1504
        assert_eq!(
1505
            ev("for i in -1..1 return i"),
1506
            list(vec![num(-1.0), num(0.0), num(1.0)])
1507
        );
1508
        // body may itself be a control-flow expression
1509
        assert_eq!(
1510
            ev("for i in [1,2,3] return if i = 2 then 0 else i"),
1511
            list(vec![num(1.0), num(0.0), num(3.0)])
1512
        );
1513
        // nested for
1514
        assert_eq!(
1515
            ev("for x in [[1,2],[3,4]] return for y in x return y"),
1516
            list(vec![
1517
                list(vec![num(1.0), num(2.0)]),
1518
                list(vec![num(3.0), num(4.0)]),
1519
            ])
1520
        );
1521
    }
1522
1523
    #[test]
1524
    fn for_multiple_iteration_contexts() {
1525
        // Cartesian product, rightmost context varies fastest (FEEL rule 44).
1526
        assert_eq!(
1527
            ev("for x in [1,2,3], y in [10,20] return x + y"),
1528
            list(vec![
1529
                num(11.0),
1530
                num(21.0),
1531
                num(12.0),
1532
                num(22.0),
1533
                num(13.0),
1534
                num(23.0),
1535
            ])
1536
        );
1537
        // Matches DMN-TCK 0033-for-loops: `for h in heights, w in widths`.
1538
        assert_eq!(
1539
            ev("for h in [10,20,30], w in [2,3] return h * w"),
1540
            list(vec![
1541
                num(20.0),
1542
                num(30.0),
1543
                num(40.0),
1544
                num(60.0),
1545
                num(60.0),
1546
                num(90.0),
1547
            ])
1548
        );
1549
        // A later source may reference an earlier variable (left-to-right scope).
1550
        assert_eq!(
1551
            ev("for i in [1,2], j in i..3 return j"),
1552
            list(vec![num(1.0), num(2.0), num(3.0), num(2.0), num(3.0)])
1553
        );
1554
        // An empty source anywhere yields an empty product.
1555
        assert_eq!(ev("for i in [1,2], j in [] return i"), list(vec![]));
1556
        assert_eq!(ev("for i in [], j in [1] return i"), list(vec![]));
1557
        // Three contexts compose.
1558
        assert_eq!(
1559
            ev("for a in [1], b in [2,3], c in [4,5] return a + b + c"),
1560
            list(vec![num(7.0), num(8.0), num(8.0), num(9.0)])
1561
        );
1562
    }
1563
1564
    #[test]
1565
    fn quantifiers() {
1566
        assert_eq!(ev("some i in [1,2,3] satisfies i > 2"), b(true));
1567
        assert_eq!(ev("some i in [1,2,3] satisfies i > 5"), b(false));
1568
        assert_eq!(ev("every i in [2,4,6] satisfies i > 1"), b(true));
1569
        assert_eq!(ev("every i in [1,2,3] satisfies i > 2"), b(false));
1570
        // empty list: some -> false, every -> true
1571
        assert_eq!(ev("some i in [] satisfies i > 0"), b(false));
1572
        assert_eq!(ev("every i in [] satisfies i > 0"), b(true));
1573
        // range source
1574
        assert_eq!(ev("every i in 1..5 satisfies i > 0"), b(true));
1575
    }
1576
1577
    #[test]
1578
    fn quantifiers_multiple_iteration_contexts() {
1579
        // `some` short-circuits to true on the first satisfying tuple (1+4 = 5).
1580
        assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 5"), b(true));
1581
        assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 99"), b(false));
1582
        // `every` is true only when all product tuples satisfy the predicate.
1583
        assert_eq!(ev("every x in [1,2], y in [3,4] satisfies x < y"), b(true));
1584
        assert_eq!(ev("every x in [1,2], y in [1,2] satisfies x <= y"), b(false));
1585
        // An empty source: the product is empty (some -> false, every -> true).
1586
        assert_eq!(ev("some x in [1,2], y in [] satisfies x = y"), b(false));
1587
        assert_eq!(ev("every x in [1,2], y in [] satisfies x = y"), b(true));
1588
    }
1589
1590
    #[test]
1591
    fn variable_resolution() {
1592
        let mut ctx = Context::empty();
1593
        ctx.insert("preis", num(10.0));
1594
        ctx.insert("über", num(3.0)); // Unicode identifier (umlaut)
1595
        let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}"));
1596
1597
        assert_eq!(ev("preis"), num(10.0));
1598
        assert_eq!(ev("preis + über"), num(13.0));
1599
        assert_eq!(ev("über * 2"), num(6.0));
1600
        // Unbound names resolve to null (FEEL-friendly), not an error.
1601
        assert_eq!(ev("unbekannt"), Value::Null);
1602
        // Loop variable still shadows correctly alongside context vars.
1603
        assert_eq!(
1604
            ev("for preis in [1,2] return preis + über"),
1605
            list(vec![num(4.0), num(5.0)])
1606
        );
1607
    }
1608
1609
    #[test]
1610
    fn context_literals_and_path_access() {
1611
        use std::collections::BTreeMap;
1612
        let ctx_val = |pairs: &[(&str, Value)]| {
1613
            Value::Context(
1614
                pairs
1615
                    .iter()
1616
                    .map(|(k, v)| (k.to_string(), v.clone()))
1617
                    .collect::<BTreeMap<_, _>>(),
1618
            )
1619
        };
1620
1621
        // Context literal builds a map; member access reads it back.
1622
        assert_eq!(
1623
            ev("{a: 1, b: 2}"),
1624
            ctx_val(&[("a", num(1.0)), ("b", num(2.0))])
1625
        );
1626
        assert_eq!(ev("{a: 1, b: 2}.a"), num(1.0));
1627
        assert_eq!(ev("{}"), ctx_val(&[]));
1628
        // String keys are allowed.
1629
        assert_eq!(ev(r#"{"x": 10}.x"#), num(10.0));
1630
        // Progressive binding: a later entry sees an earlier one.
1631
        assert_eq!(ev("{a: 1, b: a + 1}.b"), num(2.0));
1632
        // Missing member or path on a non-context -> null.
1633
        assert_eq!(ev("{a: 1}.z"), Value::Null);
1634
        assert_eq!(ev("5 .a"), Value::Null);
1635
        // Nested contexts and chained paths.
1636
        assert_eq!(ev("{a: {b: {c: 7}}}.a.b.c"), num(7.0));
1637
    }
1638
1639
    /// A context-`Value` builder for the filter/projection tests below.
1640
    fn ctx_val(pairs: &[(&str, Value)]) -> Value {
1641
        use std::collections::BTreeMap;
1642
        Value::Context(
1643
            pairs
1644
                .iter()
1645
                .map(|(k, v)| (k.to_string(), v.clone()))
1646
                .collect::<BTreeMap<_, _>>(),
1647
        )
1648
    }
1649
1650
    #[test]
1651
    fn list_index_access() {
1652
        // 1-based positional index; negative counts from the end (DMN §10.3.2.5).
1653
        assert_eq!(ev("[1, 2, 3][1]"), num(1.0));
1654
        assert_eq!(ev("[1, 2, 3][3]"), num(3.0));
1655
        assert_eq!(ev("[1, 2, 3][-1]"), num(3.0));
1656
        assert_eq!(ev("[1, 2, 3][-3]"), num(1.0));
1657
        // Out of range (either direction), zero, and non-integer -> null.
1658
        assert_eq!(ev("[1, 2, 3][4]"), Value::Null);
1659
        assert_eq!(ev("[1, 2, 3][-4]"), Value::Null);
1660
        assert_eq!(ev("[1, 2, 3][0]"), Value::Null);
1661
        assert_eq!(ev("[1, 2, 3][1.5]"), Value::Null);
1662
        // A non-list source is a singleton; a null source stays null.
1663
        assert_eq!(ev("5[1]"), num(5.0));
1664
        assert_eq!(ev("5[2]"), Value::Null);
1665
        assert_eq!(ev("null[1]"), Value::Null);
1666
        // The index is an arbitrary expression evaluated in the outer scope.
1667
        assert_eq!(ev("[10, 20, 30][1 + 1]"), num(20.0));
1668
    }
1669
1670
    #[test]
1671
    fn list_boolean_filter() {
1672
        // The predicate keeps elements where it is true; `item` is the element.
1673
        assert_eq!(ev("[1, 2, 3, 4][item > 2]"), list(vec![num(3.0), num(4.0)]));
1674
        assert_eq!(ev("[1, 2, 3][item > 9]"), list(vec![]));
1675
        // A constant boolean filter selects all / none.
1676
        assert_eq!(
1677
            ev("[1, 2, 3][true]"),
1678
            list(vec![num(1.0), num(2.0), num(3.0)])
1679
        );
1680
        assert_eq!(ev("[1, 2, 3][false]"), list(vec![]));
1681
        // A non-list source filters as a singleton.
1682
        assert_eq!(ev("5[item > 3]"), list(vec![num(5.0)]));
1683
        assert_eq!(ev("5[item < 3]"), list(vec![]));
1684
    }
1685
1686
    #[test]
1687
    fn list_filter_over_contexts() {
1688
        // A context element's entries are referenceable without an `item.` prefix...
1689
        assert_eq!(
1690
            ev("[{x: 1, y: 2}, {x: 2, y: 3}][x = 1]"),
1691
            list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])])
1692
        );
1693
        // ...or via the explicit `item` binding.
1694
        assert_eq!(
1695
            ev("[{x: 1, y: 2}, {x: 2, y: 3}][item.x = 2]"),
1696
            list(vec![ctx_val(&[("x", num(2.0)), ("y", num(3.0))])])
1697
        );
1698
        // A null key compares to null (not true), so that row is dropped.
1699
        assert_eq!(
1700
            ev("[{x: 1, y: 2}, {x: null, y: 3}][x < 2]"),
1701
            list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])])
1702
        );
1703
        // When the element itself carries an `item` key, that key wins as `item`.
1704
        assert_eq!(
1705
            ev("[{item: 7, x: 1}][item = 7]"),
1706
            list(vec![ctx_val(&[("item", num(7.0)), ("x", num(1.0))])])
1707
        );
1708
    }
1709
1710
    #[test]
1711
    fn list_projection_over_contexts() {
1712
        // `.field` over a list of contexts maps the access (DMN §10.3.2.5).
1713
        assert_eq!(
1714
            ev("[{x: 1, y: 2}, {x: 2, y: 3}].y"),
1715
            list(vec![num(2.0), num(3.0)])
1716
        );
1717
        // A missing key yields a null in that slot.
1718
        assert_eq!(
1719
            ev("[{x: 1, y: 2}, {x: 2}].y"),
1720
            list(vec![num(2.0), Value::Null])
1721
        );
1722
        // Projection then index composes left-to-right: `(xs.x)[2]`.
1723
        assert_eq!(ev("[{x: 1}, {x: 2}, {x: 3}].x[2]"), num(2.0));
1724
    }
1725
1726
    #[test]
1727
    fn is_function_value_identity() {
1728
        // Same type & value -> true; different value -> false.
1729
        assert_eq!(ev("is(1, 1)"), b(true));
1730
        assert_eq!(ev("is(1, 2)"), b(false));
1731
        assert_eq!(ev(r#"is("a", "a")"#), b(true));
1732
        // Different type -> false, never null (unlike `=`).
1733
        assert_eq!(ev(r#"is(1, "1")"#), b(false));
1734
        assert_eq!(ev("is(1, null)"), b(false));
1735
        // Durations: same normalised value & type -> true; different type -> false.
1736
        assert_eq!(ev(r#"is(@"P1D", @"PT24H")"#), b(true));
1737
        assert_eq!(ev(r#"is(@"P0Y", @"P0D")"#), b(false));
1738
        // `Z` and `+00:00` are the same; a zoneless time is not the same as a zoned one.
1739
        assert_eq!(ev(r#"is(@"23:00:50Z", @"23:00:50+00:00")"#), b(true));
1740
        assert_eq!(ev(r#"is(@"23:00:50", @"23:00:50Z")"#), b(false));
1741
        // A single named operand makes the other a `null` (ADR-23 under-supply).
1742
        assert_eq!(ev("is(value1: 1)"), b(false));
1743
    }
1744
1745
    #[test]
1746
    fn string_escape_decoding() {
1747
        // `\uXXXX` (incl. UTF-16 surrogate pairs), `\UXXXXXX`, and C-style escapes.
1748
        assert_eq!(ev(r#"string length("\u0009")"#), num(1.0)); // tab via \u escape
1749
        assert_eq!(ev(r#"string length("\U01F40E")"#), num(1.0)); // 🐎 (astral plane)
1750
        assert_eq!(ev(r#"string length("\uD83D\uDCA9")"#), num(1.0)); // UTF-16 surrogate pair
1751
        assert_eq!(ev(r#""a\nb""#), Value::String("a\nb".into()));
1752
        // An escaped backslash is one backslash: `\\u0009` is 6 literal characters.
1753
        assert_eq!(ev(r#"string length("\\u0009")"#), num(6.0));
1754
        // An unrecognised escape (e.g. a regex metacharacter) is preserved verbatim.
1755
        assert_eq!(ev(r#""\d""#), Value::String("\\d".into()));
1756
    }
1757
1758
    #[test]
1759
    fn path_access_on_context_variable() {
1760
        let mut inner = std::collections::BTreeMap::new();
1761
        inner.insert("age".to_string(), num(42.0));
1762
        let mut ctx = Context::empty();
1763
        ctx.insert("person", Value::Context(inner));
1764
        let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}"));
1765
1766
        assert_eq!(ev("person.age"), num(42.0));
1767
        assert_eq!(ev("person.age > 18"), b(true));
1768
        assert_eq!(ev("person.missing"), Value::Null);
1769
    }
1770
1771
    #[test]
1772
    fn context_equality_is_structural() {
1773
        assert_eq!(ev("{a: 1, b: 2} = {a: 1, b: 2}"), b(true));
1774
        assert_eq!(ev("{a: 1, b: 2} = {b: 2, a: 1}"), b(true)); // order-insensitive
1775
        assert_eq!(ev("{a: 1} = {a: 2}"), b(false));
1776
        assert_eq!(ev("{a: 1} = {a: 1, b: 2}"), b(false));
1777
        assert_eq!(ev("{a: 1} = 1"), Value::Null); // different types -> null
1778
    }
1779
1780
    #[test]
1781
    fn multi_word_names_as_identifiers() {
1782
        // Full FEEL names may contain spaces (ADR-17). The lexer joins them.
1783
        let mut ctx = Context::empty();
1784
        ctx.insert("full name", Value::String("Ada".into()));
1785
        ctx.insert("year of birth", num(1815.0));
1786
        let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}"));
1787
1788
        assert_eq!(ev("full name"), Value::String("Ada".into()));
1789
        assert_eq!(ev("year of birth + 1"), num(1816.0));
1790
        // Multi-word loop variable, referenced in the body.
1791
        assert_eq!(
1792
            ev("for my index in [1, 2] return my index + 1"),
1793
            list(vec![num(2.0), num(3.0)])
1794
        );
1795
        // Multi-word context-literal key, read back via a multi-word path segment.
1796
        assert_eq!(ev("{first name: 1}.first name"), num(1.0));
1797
        // An unbound multi-word name is a value-null, not a parse error.
1798
        assert_eq!(ev("unbound display name"), Value::Null);
1799
    }
1800
1801
    #[test]
1802
    fn multi_word_join_is_backward_compatible() {
1803
        // Keywords still break a name run: `and` stays the boolean operator.
1804
        assert_eq!(ev("true and false"), b(false));
1805
        // Chained path access is unaffected.
1806
        assert_eq!(ev("{a: {b: 1}}.a.b"), num(1.0));
1807
        // A single-word builtin call is unaffected by the join machinery; the
1808
        // `(` lookahead keeps `string(1)` one word, not a merge with what follows.
1809
        assert_eq!(ev("string(1)"), Value::String("1".into()));
1810
        assert_eq!(ev("count([1, 2, 3])"), num(3.0));
1811
    }
1812
1813
    #[test]
1814
    fn keyword_phrase_builtin_parses_in_call_position() {
1815
        // A keyword-containing builtin name (`date and time`) is recognised as one
1816
        // call head in call position and evaluates (ADR-18), NOT as
1817
        // `date and (time(...))` (ADR-17). The lexer joins it as a single Name token
1818
        // in every position, so `date and time` out of call position is the Name
1819
        // `"date and time"` — which now evaluates to a first-class function value
1820
        // (ADR-36) rather than null (which was the unbound-variable result before).
1821
        assert_eq!(
1822
            ev(r#"string(date and time("2018-12-08"))"#),
1823
            Value::String("2018-12-08T00:00:00".into())
1824
        );
1825
        // Out of call position: resolves to the built-in function value (ADR-36).
1826
        assert!(matches!(ev("date and time"), Value::Function(_)));
1827
    }
1828
1829
    #[test]
1830
    fn temporal_literals_and_ordering() {
1831
        // `@"…"` literals parse by lexical form (ADR-18). `string(x)` gives the
1832
        // canonical ISO form, so we round-trip through it to assert the value.
1833
        let iso = |src: &str| ev(&format!("string({src})"));
1834
        let s = |v: &str| Value::String(v.to_string());
1835
1836
        assert_eq!(iso(r#"@"2017-08-03""#), s("2017-08-03"));
1837
        assert_eq!(iso(r#"@"-2017-01-01""#), s("-2017-01-01")); // negative year
1838
        assert_eq!(iso(r#"@"10:30:05""#), s("10:30:05"));
1839
        assert_eq!(iso(r#"@"10:30:05+02:00""#), s("10:30:05+02:00"));
1840
        assert_eq!(iso(r#"@"2017-01-01T23:59:01""#), s("2017-01-01T23:59:01"));
1841
        assert_eq!(iso(r#"@"2017-01-01T23:59:01Z""#), s("2017-01-01T23:59:01Z"));
1842
        assert_eq!(
1843
            iso(r#"@"2017-01-01T23:59:01+02:00""#),
1844
            s("2017-01-01T23:59:01+02:00")
1845
        );
1846
        assert_eq!(
1847
            iso(r#"@"2017-08-10T23:59:01.987654321""#),
1848
            s("2017-08-10T23:59:01.987654321")
1849
        );
1850
        // durations: years-months vs days-time, with sign and zero forms.
1851
        assert_eq!(iso(r#"@"P1Y2M""#), s("P1Y2M"));
1852
        assert_eq!(iso(r#"@"P0M""#), s("P0M"));
1853
        assert_eq!(iso(r#"@"-P1Y8M""#), s("-P1Y8M"));
1854
        assert_eq!(iso(r#"@"P2DT1H40M""#), s("P2DT1H40M"));
1855
        assert_eq!(iso(r#"@"P1DT2H3M4.123456789S""#), s("P1DT2H3M4.123456789S"));
1856
        // a named IANA zone resolves (bundled tzdb).
1857
        assert_eq!(
1858
            iso(r#"@"2017-06-23T11:23:00@Europe/Paris""#),
1859
            s("2017-06-23T11:23:00@Europe/Paris")
1860
        );
1861
1862
        // malformed literal -> error-null (lenient view: null).
1863
        assert_eq!(ev(r#"@"not-a-date""#), Value::Null);
1864
        assert_eq!(ev(r#"@"2017-06-23T11:23:00@xyz/abc""#), Value::Null);
1865
1866
        // ordering & equality within a type.
1867
        assert_eq!(ev(r#"@"2017-01-01" < @"2017-12-31""#), b(true));
1868
        assert_eq!(ev(r#"@"2017-01-01" = @"2017-01-01""#), b(true));
1869
        assert_eq!(ev(r#"@"P1Y" < @"P2Y""#), b(true));
1870
        assert_eq!(ev(r#"@"PT1H" < @"PT2H""#), b(true));
1871
        // same instant, different offset -> equal date-times.
1872
        assert_eq!(
1873
            ev(r#"@"2017-01-01T12:00:00+02:00" = @"2017-01-01T11:00:00+01:00""#),
1874
            b(true)
1875
        );
1876
        // cross temporal types are a type mismatch -> null (lenient).
1877
        assert_eq!(ev(r#"@"2017-01-01" = @"P1Y""#), Value::Null);
1878
        assert_eq!(ev(r#"@"P1Y" < @"PT1H""#), Value::Null);
1879
    }
1880
1881
    #[test]
1882
    fn temporal_arithmetic_negation_and_properties() {
1883
        let iso = |src: &str| ev(&format!("string({src})"));
1884
        let s = |v: &str| Value::String(v.to_string());
1885
1886
        // date/datetime + duration
1887
        assert_eq!(iso(r#"@"2017-01-01" + @"P1Y2M""#), s("2018-03-01")); // date + ymd -> date
1888
        assert_eq!(iso(r#"@"2017-01-01" + @"P1D""#), s("2017-01-02")); // date + dtd -> date
1889
        assert_eq!(iso(r#"@"2017-01-01" + @"PT36H""#), s("2017-01-02")); // dtd added, date part kept
1890
        assert_eq!(
1891
            iso(r#"@"2017-01-01T10:00:00" + @"P1M""#),
1892
            s("2017-02-01T10:00:00")
1893
        );
1894
        assert_eq!(iso(r#"@"23:00:00" + @"PT2H""#), s("01:00:00")); // time wraps mod 24h
1895
1896
        // duration ± duration (same family)
1897
        assert_eq!(iso(r#"@"P1Y" + @"P2M""#), s("P1Y2M"));
1898
        assert_eq!(iso(r#"@"PT1H" + @"PT30M""#), s("PT1H30M"));
1899
1900
        // date/datetime − date/datetime -> days-and-time duration
1901
        assert_eq!(iso(r#"@"2017-01-10" - @"2017-01-01""#), s("P9D"));
1902
        assert_eq!(
1903
            iso(r#"@"2017-01-01T12:00:00" - @"2017-01-01T10:00:00""#),
1904
            s("PT2H")
1905
        );
1906
1907
        // duration * / number, and duration / duration -> number
1908
        assert_eq!(iso(r#"@"P1Y" * 2"#), s("P2Y"));
1909
        assert_eq!(iso(r#"@"PT1H" * 3"#), s("PT3H"));
1910
        assert_eq!(iso(r#"@"P2Y" / 2"#), s("P1Y"));
1911
        assert_eq!(ev(r#"@"PT2H" / @"PT1H""#), num(2.0));
1912
1913
        // negation of a duration
1914
        assert_eq!(iso(r#"-@"P1Y""#), s("-P1Y"));
1915
1916
        // invalid combinations -> null (lenient view of error-null)
1917
        assert_eq!(ev(r#"@"2017-01-01" + @"2017-01-02""#), Value::Null); // date + date
1918
        assert_eq!(ev(r#"@"P1Y" + @"PT1H""#), Value::Null); // mixed duration families
1919
1920
        // property / component access
1921
        assert_eq!(ev(r#"@"2017-08-03".year"#), num(2017.0));
1922
        assert_eq!(ev(r#"@"2017-08-03".month"#), num(8.0));
1923
        assert_eq!(ev(r#"@"2017-08-03".day"#), num(3.0));
1924
        assert_eq!(ev(r#"@"2017-08-03".weekday"#), num(4.0)); // Thursday
1925
        assert_eq!(ev(r#"@"10:30:05".hour"#), num(10.0));
1926
        assert_eq!(ev(r#"@"10:30:05".minute"#), num(30.0));
1927
        assert_eq!(ev(r#"@"10:30:05".second"#), num(5.0));
1928
        assert_eq!(ev(r#"string(@"10:30:05+02:00".time offset)"#), s("PT2H"));
1929
        assert_eq!(ev(r#"@"10:30:05".timezone"#), Value::Null);
1930
        assert_eq!(
1931
            ev(r#"@"2017-06-23T11:23:00@Europe/Paris".timezone"#),
1932
            s("Europe/Paris")
1933
        );
1934
        assert_eq!(ev(r#"@"P1Y2M".years"#), num(1.0));
1935
        assert_eq!(ev(r#"@"P1Y2M".months"#), num(2.0));
1936
        assert_eq!(ev(r#"@"P2DT3H".days"#), num(2.0));
1937
        assert_eq!(ev(r#"@"P2DT3H".hours"#), num(3.0));
1938
        // unknown property on a temporal -> value-null (not an error).
1939
        assert_eq!(ev(r#"@"2017-08-03".nonsense"#), Value::Null);
1940
    }
1941
1942
    #[test]
1943
    fn parse_error_is_reported() {
1944
        assert!(matches!(
1945
            evaluate("1 +", &Context::empty()),
1946
            Err(FeelError::Parse(_))
1947
        ));
1948
        assert!(matches!(
1949
            evaluate("if x then", &Context::empty()),
1950
            Err(FeelError::Parse(_))
1951
        ));
1952
    }
1953
1954
    #[test]
1955
    fn builtin_functions() {
1956
        let s = |v: &str| Value::String(v.to_string());
1957
1958
        // --- numeric --- (spec §10.3.4.5)
1959
        assert_eq!(ev("abs(-10)"), num(10.0));
1960
        assert_eq!(ev("abs(10)"), num(10.0));
1961
        assert_eq!(ev("modulo(12, 5)"), num(2.0));
1962
        assert_eq!(ev("modulo(-12, 5)"), num(3.0)); // result follows divisor's sign
1963
        assert_eq!(ev("modulo(12, -5)"), num(-3.0));
1964
        assert_eq!(ev("floor(1.5)"), num(1.0));
1965
        assert_eq!(ev("floor(-1.56, 1)"), num(-1.6));
1966
        assert_eq!(ev("ceiling(1.5)"), num(2.0));
1967
        assert_eq!(ev("ceiling(-1.56, 1)"), num(-1.5));
1968
        assert_eq!(ev("decimal(1.5, 0)"), num(2.0)); // round half to even
1969
        assert_eq!(ev("decimal(2.5, 0)"), num(2.0)); // round half to even
1970
        assert_eq!(ev("modulo(12, 0)"), Value::Null); // divide by zero -> null
1971
        assert_eq!(ev("abs(true)"), Value::Null); // wrong type -> null
1972
        assert_eq!(ev("sqrt(16)"), num(4.0));
1973
        assert_eq!(ev("sqrt(-1)"), Value::Null); // negative -> domain error -> null
1974
        assert_eq!(ev("exp(0)"), num(1.0));
1975
        assert_eq!(ev("log(1)"), num(0.0));
1976
        assert_eq!(ev("log(0)"), Value::Null); // non-positive -> domain error -> null
1977
        assert_eq!(ev("even(2)"), b(true));
1978
        assert_eq!(ev("even(3)"), b(false));
1979
        assert_eq!(ev("even(2.5)"), Value::Null); // non-integer -> domain error -> null
1980
        assert_eq!(ev("odd(3)"), b(true));
1981
        assert_eq!(ev("odd(2)"), b(false));
1982
1983
        // --- list --- (spec §10.3.4.4)
1984
        assert_eq!(ev("count([1, 2, 3])"), num(3.0));
1985
        assert_eq!(ev("count([])"), num(0.0));
1986
        assert_eq!(ev("count([1, [2, 3]])"), num(2.0)); // counts structural elements
1987
        assert_eq!(ev("min([1, 2, 3])"), num(1.0));
1988
        assert_eq!(ev("max(1, 2, 3)"), num(3.0)); // varargs form
1989
        assert_eq!(ev("min(1)"), num(1.0));
1990
        assert_eq!(ev("min([])"), Value::Null); // empty -> null
1991
        assert_eq!(ev("sum([1, 2, 3])"), num(6.0));
1992
        assert_eq!(ev("sum(1, 2, 3)"), num(6.0));
1993
        assert_eq!(ev("sum([])"), Value::Null);
1994
        assert_eq!(ev("mean([1, 2, 3])"), num(2.0));
1995
        assert_eq!(ev("product([2, 3, 4])"), num(24.0));
1996
        assert_eq!(ev("median(8, 2, 5, 3, 4)"), num(4.0));
1997
        assert_eq!(ev("median([6, 1, 2, 3])"), num(2.5)); // even count -> avg of middle two
1998
        assert_eq!(ev("mode([6, 1, 9, 6, 1])"), list(vec![num(1.0), num(6.0)]));
1999
        assert_eq!(ev("mode([])"), list(vec![])); // mode of empty list is []
2000
        assert_eq!(ev("all([false, null, true])"), b(false)); // a false dominates
2001
        assert_eq!(ev("all([true, true])"), b(true));
2002
        assert_eq!(ev("all([])"), b(true));
2003
        assert_eq!(ev("any([false, null, true])"), b(true)); // a true dominates
2004
        assert_eq!(ev("any([])"), b(false));
2005
        assert_eq!(
2006
            ev("append([1], 2, 3)"),
2007
            list(vec![num(1.0), num(2.0), num(3.0)])
2008
        );
2009
        assert_eq!(
2010
            ev("concatenate([1, 2], [3])"),
2011
            list(vec![num(1.0), num(2.0), num(3.0)])
2012
        );
2013
        assert_eq!(
2014
            ev("union([1, 2], [2, 3])"),
2015
            list(vec![num(1.0), num(2.0), num(3.0)])
2016
        );
2017
        assert_eq!(ev("remove([1, 2, 3], 2)"), list(vec![num(1.0), num(3.0)]));
2018
        assert_eq!(
2019
            ev("reverse([1, 2, 3])"),
2020
            list(vec![num(3.0), num(2.0), num(1.0)])
2021
        );
2022
        assert_eq!(
2023
            ev("flatten([[1, 2], [[3]], 4])"),
2024
            list(vec![num(1.0), num(2.0), num(3.0), num(4.0)])
2025
        );
2026
        assert_eq!(
2027
            ev("sublist([4, 5, 6], 1, 2)"),
2028
            list(vec![num(4.0), num(5.0)])
2029
        );
2030
2031
        // --- string --- (spec §10.3.4.1, §10.3.4.3)
2032
        assert_eq!(ev(r#"substring("foobar", 3)"#), s("obar"));
2033
        assert_eq!(ev(r#"substring("foobar", 3, 3)"#), s("oba"));
2034
        assert_eq!(ev(r#"substring("foobar", -2, 1)"#), s("a")); // negative from end
2035
        assert_eq!(ev(r#"contains("foobar", "of")"#), b(false));
2036
        assert_eq!(ev(r#"contains("foobar", "oob")"#), b(true));
2037
        assert_eq!(ev("string(1.1)"), s("1.1"));
2038
        assert_eq!(ev("string(null)"), Value::Null);
2039
        assert_eq!(ev(r#"number("1.1")"#), num(1.1));
2040
        assert_eq!(ev(r#"number("1,000.0", ",", ".")"#), num(1000.0));
2041
2042
        // --- temporal clock builtins return temporal values (ADR-18) ---
2043
        assert!(matches!(ev("now()"), Value::DateTime(_)));
2044
        assert!(matches!(ev("today()"), Value::Date(_)));
2045
        assert_eq!(ev("now(1)"), Value::Null); // wrong arity -> null
2046
    }
2047
2048
    #[test]
2049
    fn temporal_constructors_and_component_functions() {
2050
        let iso = |src: &str| ev(&format!("string({src})"));
2051
        let s = |v: &str| Value::String(v.to_string());
2052
2053
        // date(...)
2054
        assert_eq!(iso("date(2017, 8, 3)"), s("2017-08-03"));
2055
        assert_eq!(iso(r#"date("2017-08-03")"#), s("2017-08-03"));
2056
        assert_eq!(iso(r#"date(@"2017-08-03T10:00:00")"#), s("2017-08-03")); // from datetime
2057
        assert_eq!(ev("date(2017, 13, 1)"), Value::Null); // out of range -> null
2058
        assert_eq!(ev("date(2017, null, 1)"), Value::Null); // null component -> null
2059
        assert_eq!(ev("date(null)"), Value::Null);
2060
2061
        // time(...)
2062
        assert_eq!(iso("time(11, 59, 0)"), s("11:59:00"));
2063
        assert_eq!(iso(r#"time("10:30:05")"#), s("10:30:05"));
2064
        assert_eq!(
2065
            iso(r#"time(11, 59, 0, duration("PT2H"))"#),
2066
            s("11:59:00+02:00")
2067
        );
2068
2069
        // date and time(...)
2070
        assert_eq!(
2071
            iso(r#"date and time("2017-01-01T10:00:00")"#),
2072
            s("2017-01-01T10:00:00")
2073
        );
2074
        assert_eq!(
2075
            iso(r#"date and time(@"2017-01-01", @"10:00:00")"#),
2076
            s("2017-01-01T10:00:00")
2077
        );
2078
2079
        // duration(...) and years and months duration(...)
2080
        assert_eq!(iso(r#"duration("P1Y2M")"#), s("P1Y2M"));
2081
        assert_eq!(iso(r#"duration("P2DT3H")"#), s("P2DT3H"));
2082
        assert_eq!(ev(r#"duration("1D")"#), Value::Null); // missing P -> null
2083
        assert_eq!(
2084
            iso(r#"years and months duration(@"2011-12-22", @"2013-08-24")"#),
2085
            s("P1Y8M")
2086
        );
2087
        assert_eq!(
2088
            iso(r#"years and months duration(@"2013-08-24", @"2011-12-22")"#),
2089
            s("-P1Y8M")
2090
        );
2091
2092
        // component functions
2093
        assert_eq!(ev(r#"day of week(@"2021-01-11")"#), s("Monday"));
2094
        assert_eq!(ev(r#"month of year(@"2021-04-01")"#), s("April"));
2095
        assert_eq!(ev(r#"day of year(@"1970-01-01")"#), num(1.0));
2096
        assert_eq!(ev(r#"week of year(@"1970-01-01")"#), num(1.0));
2097
        assert_eq!(ev(r#"day of week(null)"#), Value::Null);
2098
2099
        // abs of a duration (ADR-18; ADR-15 deferred it)
2100
        assert_eq!(iso(r#"abs(@"-P1Y")"#), s("P1Y"));
2101
        assert_eq!(iso(r#"abs(duration("-PT2H"))"#), s("PT2H"));
2102
    }
2103
2104
    #[test]
2105
    fn now_today_use_injected_clock() {
2106
        // `now()`/`today()` read the injected instant, so they are deterministic
2107
        // and (in feel-pg) can be pinned to the transaction start (ADR-18).
2108
        let z = jiff::civil::date(2024, 3, 10)
2109
            .at(12, 0, 0, 0)
2110
            .to_zoned(jiff::tz::TimeZone::get("America/New_York").unwrap())
2111
            .unwrap();
2112
        let env = EvalEnv::new(&regex_provider::DEFAULT, z);
2113
        let eval = |src: &str| {
2114
            compile(src)
2115
                .unwrap()
2116
                .evaluate_with_env(&Context::empty(), &env)
2117
                .unwrap()
2118
                .into_lenient()
2119
        };
2120
        assert_eq!(
2121
            eval("string(now())"),
2122
            Value::String("2024-03-10T12:00:00@America/New_York".into())
2123
        );
2124
        assert_eq!(eval("string(today())"), Value::String("2024-03-10".into()));
2125
    }
2126
2127
    #[test]
2128
    fn multi_word_builtin_functions() {
2129
        use std::collections::BTreeMap;
2130
        let s = |v: &str| Value::String(v.to_string());
2131
        let ctx_val = |pairs: &[(&str, Value)]| {
2132
            Value::Context(
2133
                pairs
2134
                    .iter()
2135
                    .map(|(k, v)| (k.to_string(), v.clone()))
2136
                    .collect::<BTreeMap<_, _>>(),
2137
            )
2138
        };
2139
2140
        // --- string (multi-word) --- (spec §10.3.4.1)
2141
        assert_eq!(ev(r#"string length("abc")"#), num(3.0));
2142
        assert_eq!(ev(r#"string length("aaaaa dddd ")"#), num(11.0)); // trailing space counts
2143
        assert_eq!(ev(r#"upper case("aBc")"#), s("ABC"));
2144
        assert_eq!(ev(r#"lower case("aBc4")"#), s("abc4"));
2145
        assert_eq!(ev(r#"substring before("foobar", "bar")"#), s("foo"));
2146
        assert_eq!(ev(r#"substring before("abc", "a")"#), s("")); // match at start
2147
        assert_eq!(ev(r#"substring before("foobar", "x")"#), s("")); // not found
2148
        assert_eq!(ev(r#"substring after("foobar", "ob")"#), s("ar"));
2149
        assert_eq!(ev(r#"substring after("abc", "")"#), s("abc")); // empty match
2150
        assert_eq!(ev(r#"starts with("foobar", "foo")"#), b(true));
2151
        assert_eq!(ev(r#"starts with("foobar", "x")"#), b(false));
2152
        assert_eq!(ev(r#"ends with("foobar", "bar")"#), b(true));
2153
        assert_eq!(ev(r#"string join(["a","b","c"])"#), s("abc"));
2154
        assert_eq!(
2155
            ev(r#"string join(["a","b","c"], " and ")"#),
2156
            s("a and b and c")
2157
        );
2158
        assert_eq!(ev(r#"string join(["a","b","c"], null)"#), s("abc")); // null delim = ""
2159
        assert_eq!(ev(r#"string join(["a",null,"c"], "X")"#), s("aXc")); // null items skipped
2160
        assert_eq!(ev("string join([])"), s("")); // empty list -> empty string
2161
        assert_eq!(ev(r#"string join("a", "X")"#), s("a")); // scalar -> one-element list
2162
        assert_eq!(ev("string join()"), Value::Null); // wrong arity -> null
2163
        assert_eq!(ev(r#"string join([1,2,3], "X")"#), Value::Null); // non-string items -> null
2164
2165
        // --- list (multi-word) --- (spec §10.3.4.4)
2166
        assert_eq!(ev("list contains([1,2,3], 2)"), b(true));
2167
        assert_eq!(ev("list contains([1,2,3], 9)"), b(false));
2168
        assert_eq!(ev("list contains([[1,2],[3]], [3])"), b(true)); // structural element
2169
        assert_eq!(ev("index of([1,2,3,2], 2)"), list(vec![num(2.0), num(4.0)]));
2170
        assert_eq!(ev("index of([1,2,3], 9)"), list(vec![]));
2171
        assert_eq!(
2172
            ev("distinct values([1,2,3,2,1])"),
2173
            list(vec![num(1.0), num(2.0), num(3.0)])
2174
        );
2175
        assert_eq!(
2176
            ev("insert before([1,2,3], 1, 4)"),
2177
            list(vec![num(4.0), num(1.0), num(2.0), num(3.0)])
2178
        );
2179
        assert_eq!(
2180
            ev("insert before([1,2,3], 3, 4)"),
2181
            list(vec![num(1.0), num(2.0), num(4.0), num(3.0)])
2182
        );
2183
        assert_eq!(
2184
            ev("list replace([1,2,3], 2, 4)"),
2185
            list(vec![num(1.0), num(4.0), num(3.0)])
2186
        );
2187
        assert_eq!(
2188
            ev("list replace([1,2,3], -1, 4)"),
2189
            list(vec![num(1.0), num(2.0), num(4.0)])
2190
        );
2191
        assert_eq!(ev("list replace([1,2,3], 0, 4)"), Value::Null); // position 0 invalid
2192
        assert_eq!(
2193
            ev("list replace([1,2,3], 2.5, 4)"), // position truncates toward zero
2194
            list(vec![num(1.0), num(4.0), num(3.0)])
2195
        );
2196
2197
        // --- context (multi-word) --- (spec §10.3.4.6)
2198
        assert_eq!(ev(r#"get value({a: "foo"}, "a")"#), s("foo"));
2199
        assert_eq!(ev(r#"get value({a: "foo"}, "z")"#), Value::Null); // absent key
2200
        assert_eq!(ev(r#"get value({a: null}, "a")"#), Value::Null); // present null value
2201
        assert_eq!(ev(r#"get value("foo", "a")"#), Value::Null); // not a context -> null
2202
        assert_eq!(
2203
            ev(r#"get entries({a: "foo", b: "bar"})"#),
2204
            list(vec![
2205
                ctx_val(&[("key", s("a")), ("value", s("foo"))]),
2206
                ctx_val(&[("key", s("b")), ("value", s("bar"))]),
2207
            ])
2208
        );
2209
        assert_eq!(ev("get entries({})"), list(vec![]));
2210
2211
        // --- keyword-phrase temporal builtin now evaluates (ADR-18) ---
2212
        assert_eq!(
2213
            ev(r#"string(date and time("2018-12-08"))"#),
2214
            s("2018-12-08T00:00:00")
2215
        );
2216
    }
2217
2218
    #[test]
2219
    fn round_builtin_functions() {
2220
        // round up/down/half up/half down(n, scale) (DMN-TCK 1141–1144). Numbers
2221
        // are f64 (ADR-2), so the modes use native f64 rounding.
2222
        assert_eq!(ev("round up(5.5, 0)"), num(6.0)); // away from zero
2223
        assert_eq!(ev("round up(-5.5, 0)"), num(-6.0));
2224
        assert_eq!(ev("round up(1.121, 2)"), num(1.13));
2225
        assert_eq!(ev("round down(5.5, 0)"), num(5.0)); // toward zero
2226
        assert_eq!(ev("round down(-5.5, 0)"), num(-5.0));
2227
        assert_eq!(ev("round half up(2.5, 0)"), num(3.0)); // ties away from zero
2228
        assert_eq!(ev("round half up(-2.5, 0)"), num(-3.0));
2229
        assert_eq!(ev("round half down(2.5, 0)"), num(2.0)); // ties toward zero
2230
        assert_eq!(ev("round half down(-2.5, 0)"), num(-2.0));
2231
        assert_eq!(ev("round up(null, 0)"), Value::Null); // null arg -> null
2232
        assert_eq!(ev("round up(5.5)"), Value::Null); // scale required -> arity null
2233
        assert_eq!(ev("round up(5.5, 6176)"), num(5.5)); // scale beyond f64 range: no effect
2234
        assert_eq!(ev("round up(5.5, (6176 + 1))"), Value::Null); // out of decimal128 range -> null
2235
    }
2236
2237
    #[test]
2238
    fn context_builtin_functions() {
2239
        use std::collections::BTreeMap;
2240
        let ctx_val = |pairs: &[(&str, Value)]| {
2241
            Value::Context(
2242
                pairs
2243
                    .iter()
2244
                    .map(|(k, v)| (k.to_string(), v.clone()))
2245
                    .collect::<BTreeMap<_, _>>(),
2246
            )
2247
        };
2248
2249
        // context(entries) (DMN-TCK 1145)
2250
        assert_eq!(
2251
            ev(r#"context([{key:"a", value:1}, {key:"b", value:2}])"#),
2252
            ctx_val(&[("a", num(1.0)), ("b", num(2.0))])
2253
        );
2254
        assert_eq!(
2255
            ev(r#"context({key:"a", value:1})"#),
2256
            ctx_val(&[("a", num(1.0))])
2257
        ); // single coerced
2258
        assert_eq!(
2259
            ev(r#"context([{key:"a", value:1}, {key:"a", value:2}])"#),
2260
            Value::Null
2261
        ); // duplicate key
2262
        assert_eq!(ev(r#"context({key:"a"})"#), Value::Null); // missing value
2263
2264
        // context put(context, key, value) (DMN-TCK 1146)
2265
        assert_eq!(
2266
            ev(r#"context put({}, "a", 1)"#),
2267
            ctx_val(&[("a", num(1.0))])
2268
        );
2269
        assert_eq!(
2270
            ev(r#"context put({"a": 1}, "a", 2)"#),
2271
            ctx_val(&[("a", num(2.0))])
2272
        ); // overwrite
2273
        assert_eq!(
2274
            ev(r#"context put({x:1, y: {a: 0}}, ["y", "a"], 2)"#), // nested path
2275
            ctx_val(&[("x", num(1.0)), ("y", ctx_val(&[("a", num(2.0))]))])
2276
        );
2277
        assert_eq!(
2278
            ev(r#"context put({x:1, y: {a: 0}}, ["y", "a", "b"], 2)"#),
2279
            Value::Null
2280
        ); // descend into non-context
2281
        assert_eq!(ev(r#"context put(null, "a", 1)"#), Value::Null);
2282
2283
        // context merge(contexts) (DMN-TCK 1147)
2284
        assert_eq!(
2285
            ev(r#"context merge([{a: 1}, {b: 2}])"#),
2286
            ctx_val(&[("a", num(1.0)), ("b", num(2.0))])
2287
        );
2288
        assert_eq!(
2289
            ev(r#"context merge([{a: 1}, {a: 2}])"#),
2290
            ctx_val(&[("a", num(2.0))])
2291
        ); // later wins
2292
        assert_eq!(ev(r#"context merge({a: 1})"#), ctx_val(&[("a", num(1.0))])); // single coerced
2293
        assert_eq!(ev(r#"context merge([{a: 1}, 2])"#), Value::Null); // non-context element
2294
    }
2295
2296
    // The regex builtins are dialect-dependent (ADR-16): under the default
2297
    // `rust-regex` provider they keep the Rust-dialect results recorded in
2298
    // ADR-15; under `--no-default-features` (no provider) they evaluate to null.
2299
    #[cfg(feature = "rust-regex")]
2300
    #[test]
2301
    fn builtin_regex_functions() {
2302
        let s = |v: &str| Value::String(v.to_string());
2303
        assert_eq!(ev(r#"replace("banana", "a", "o")"#), s("bonono"));
2304
        assert_eq!(ev(r#"matches("foobar", "^fo*b")"#), b(true));
2305
        assert_eq!(
2306
            ev(r#"split("a;b;c;;", ";")"#),
2307
            list(vec![s("a"), s("b"), s("c"), s(""), s("")])
2308
        );
2309
    }
2310
2311
    #[cfg(not(feature = "rust-regex"))]
2312
    #[test]
2313
    fn regex_builtins_are_error_null_without_a_provider() {
2314
        // No host engine is injected on the default `evaluate` path, so the three
2315
        // regex builtins are an error-null ("unsupported in this build") — raw,
2316
        // not collapsed — so the strict boundary surfaces it (ADR-14/ADR-16).
2317
        let raw =
2318
            |src: &str| evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}`: {e}"));
2319
        assert_eq!(raw(r#"matches("foobar", "^fo*b")"#), Value::Error);
2320
        assert_eq!(raw(r#"replace("banana", "a", "o")"#), Value::Error);
2321
        assert_eq!(raw(r#"split("a;b;c", ";")"#), Value::Error);
2322
        // Non-regex builtins are unaffected.
2323
        assert_eq!(raw("sum([1, 2, 3])"), num(6.0));
2324
    }
2325
2326
    /// Named-argument built-in calls (FEEL spec §10.3.2.13.5).
2327
    ///
2328
    /// Each test cites the TCK fixture or spec table section that motivates it.
2329
    #[test]
2330
    fn named_args_builtin_functions() {
2331
        let s = |v: &str| Value::String(v.to_string());
2332
2333
        // spec §10.3.4.3 Table 75: `substring(string, start position, length?)`
2334
        // Named call must equal the positional call (TCK 0008-feel-builtins / substring).
2335
        assert_eq!(
2336
            ev(r#"substring(string: "foobar", start position: 3)"#),
2337
            s("obar")
2338
        );
2339
        assert_eq!(
2340
            ev(r#"substring("foobar", 3)"#),
2341
            s("obar")
2342
        );
2343
2344
        // spec §10.3.4.3: named arguments are order-independent.
2345
        assert_eq!(
2346
            ev(r#"substring(start position: 3, string: "foobar")"#),
2347
            s("obar")
2348
        );
2349
2350
        // spec §10.3.4.3: omitting the optional `length` named arg still works.
2351
        assert_eq!(
2352
            ev(r#"substring(string: "foobar", start position: 3)"#),
2353
            ev(r#"substring("foobar", 3)"#)
2354
        );
2355
2356
        // spec §10.3.4.3: supplying the optional `length` by name.
2357
        assert_eq!(
2358
            ev(r#"substring(string: "foobar", start position: 3, length: 3)"#),
2359
            s("oba")
2360
        );
2361
2362
        // spec §10.3.4.3: `contains(string, match)`.
2363
        assert_eq!(
2364
            ev(r#"contains(string: "foobar", match: "oob")"#),
2365
            b(true)
2366
        );
2367
2368
        // spec §10.3.4.3: `string length(string)`.
2369
        assert_eq!(ev(r#"string length(string: "abc")"#), num(3.0));
2370
2371
        // spec §10.3.4.3: `upper case(string)` / `lower case(string)`.
2372
        assert_eq!(ev(r#"upper case(string: "aBc")"#), s("ABC"));
2373
        assert_eq!(ev(r#"lower case(string: "aBc4")"#), s("abc4"));
2374
2375
        // spec §10.3.4.3: `starts with(string, match)`.
2376
        assert_eq!(ev(r#"starts with(string: "foobar", match: "foo")"#), b(true));
2377
2378
        // spec §10.3.4.3: `ends with(string, match)`.
2379
        assert_eq!(ev(r#"ends with(string: "foobar", match: "bar")"#), b(true));
2380
2381
        // spec §10.3.4.3: `substring before(string, match)` / `substring after(string, match)`.
2382
        assert_eq!(
2383
            ev(r#"substring before(string: "foobar", match: "bar")"#),
2384
            s("foo")
2385
        );
2386
        assert_eq!(
2387
            ev(r#"substring after(string: "foobar", match: "ob")"#),
2388
            s("ar")
2389
        );
2390
2391
        // spec §10.3.4.4: `list contains(list, element)`.
2392
        assert_eq!(ev("list contains(list: [1,2,3], element: 2)"), b(true));
2393
2394
        // spec §10.3.4.4: `count(list)`.
2395
        assert_eq!(ev("count(list: [1,2,3])"), num(3.0));
2396
2397
        // spec §10.3.4.4: `sublist(list, start position, length?)`.
2398
        assert_eq!(
2399
            ev("sublist(list: [4,5,6], start position: 1, length: 2)"),
2400
            list(vec![num(4.0), num(5.0)])
2401
        );
2402
2403
        // spec §10.3.4.5: `decimal(n, scale)`.
2404
        assert_eq!(ev("decimal(n: 1.5, scale: 0)"), num(2.0));
2405
2406
        // spec §10.3.4.5: `abs(n)`.
2407
        assert_eq!(ev("abs(n: -10)"), num(10.0));
2408
2409
        // spec §10.3.4.5: `modulo(dividend, divisor)`.
2410
        assert_eq!(ev("modulo(dividend: 12, divisor: 5)"), num(2.0));
2411
2412
        // spec §10.3.4.10: `get value(m, key)`.
2413
        assert_eq!(ev(r#"get value(m: {a: 1}, key: "a")"#), num(1.0));
2414
2415
        // spec §10.3.4.1: `string(from)`.
2416
        assert_eq!(ev("string(from: 1.1)"), s("1.1"));
2417
2418
        // Unknown parameter name -> error-null (spec §10.3.2.13.5: no match -> null).
2419
        // ev() uses into_lenient(), so error-null collapses to Value::Null.
2420
        assert_eq!(
2421
            ev(r#"substring(string: "foobar", start: 3)"#),
2422
            Value::Null
2423
        );
2424
2425
        // A variadic-only built-in called with named args -> null (no table entry).
2426
        // `sum` accepts either a list or N scalars; it has no named-parameter form.
2427
        assert_eq!(ev("sum(n: 1)"), Value::Null);
2428
    }
2429
2430
    // --- `instance of` type predicate (DMN §10.3.2.9, ADR-26) ---------------- //
2431
2432
    #[test]
2433
    fn instance_of_primitives_and_null() {
2434
        // spec Table 62.
2435
        assert_eq!(ev(r#""abc" instance of string"#), b(true));
2436
        assert_eq!(ev("123 instance of string"), b(false));
2437
        // A bare `list` requires parameters, so it is unmappable -> null (spec example).
2438
        assert_eq!(ev("123 instance of list"), Value::Null);
2439
2440
        // Primitive cross-checks.
2441
        assert_eq!(ev("123.01 instance of number"), b(true));
2442
        assert_eq!(ev("true instance of boolean"), b(true));
2443
        assert_eq!(ev("true instance of number"), b(false));
2444
        assert_eq!(ev("123 instance of Any"), b(true));
2445
2446
        // Top-level null rule: null is an instance only of `Null`.
2447
        assert_eq!(ev("null instance of Null"), b(true));
2448
        assert_eq!(ev("null instance of string"), b(false));
2449
        assert_eq!(ev("null instance of Any"), b(false));
2450
2451
        // An unknown / item-definition type name is unmappable -> null.
2452
        assert_eq!(ev("256 instance of t255"), Value::Null);
2453
2454
        // `and` after a type is logical-and, not part of the type name.
2455
        assert_eq!(ev("1 instance of number and 2 instance of number"), b(true));
2456
        assert_eq!(ev("1 instance of string and 2 instance of number"), b(false));
2457
    }
2458
2459
    #[test]
2460
    fn instance_of_temporal() {
2461
        assert_eq!(ev(r#"date("2018-12-08") instance of date"#), b(true));
2462
        assert_eq!(ev(r#"date("2018-12-08") instance of date and time"#), b(false));
2463
        assert_eq!(ev(r#"time("10:30:00") instance of time"#), b(true));
2464
        // `date and time` works as both a constructor head and a type name.
2465
        assert_eq!(
2466
            ev(r#"date and time("2018-12-08T10:30:00") instance of date and time"#),
2467
            b(true)
2468
        );
2469
        // The two duration kinds are distinguished.
2470
        assert_eq!(ev(r#"duration("P1Y") instance of years and months duration"#), b(true));
2471
        assert_eq!(ev(r#"duration("P1Y") instance of days and time duration"#), b(false));
2472
        assert_eq!(ev(r#"duration("P1D") instance of days and time duration"#), b(true));
2473
    }
2474
2475
    #[test]
2476
    fn instance_of_generic_list_and_context() {
2477
        // list<T>: a list whose every element conforms to T.
2478
        assert_eq!(ev("[1, 2, 3] instance of list<Any>"), b(true));
2479
        assert_eq!(ev("[1, 2, 3] instance of list<number>"), b(true));
2480
        assert_eq!(ev(r#"[1, "a"] instance of list<number>"#), b(false));
2481
        assert_eq!(ev("[1] instance of number"), b(false)); // a list is not a number
2482
2483
        // context<…>: the value must carry (at least) every target key, each conforming.
2484
        assert_eq!(ev(r#"{a: "foo"} instance of context<a: string>"#), b(true));
2485
        assert_eq!(ev(r#"{a: "123", b: 123} instance of context<a: string>"#), b(true)); // extra key ok
2486
        assert_eq!(ev(r#"{a: "123"} instance of context<a: number>"#), b(false));
2487
        // A nested null field conforms (Null <: T), unlike a top-level null.
2488
        assert_eq!(ev("{a: null} instance of context<a: string>"), b(true));
2489
        // Nested context types.
2490
        assert_eq!(ev("{a: {b: 123}} instance of context<a: context<b: number>>"), b(true));
2491
        assert_eq!(ev("{a: {b: 123}} instance of context<a: context<b: string>>"), b(false));
2492
        // A list of contexts.
2493
        assert_eq!(
2494
            ev(r#"[{a: "a", b: "b"}] instance of list<context<a: string, b: string>>"#),
2495
            b(true)
2496
        );
2497
        assert_eq!(
2498
            ev(r#"[{a: "a"}] instance of list<context<a: string, b: string>>"#),
2499
            b(false)
2500
        );
2501
    }
2502
2503
    #[test]
2504
    fn instance_of_functions() {
2505
        assert_eq!(ev(r#"(function() "foo") instance of function<> -> Any"#), b(true));
2506
        assert_eq!(ev(r#"(function() "foo") instance of Any"#), b(true));
2507
        assert_eq!(ev(r#"(function() "foo") instance of number"#), b(false));
2508
        // Untyped closures map to (Any, …) -> Any, so only the arity is checked.
2509
        assert_eq!(ev("(function(x) x) instance of function<Any> -> Any"), b(true));
2510
        assert_eq!(ev("(function(x) x) instance of function<> -> Any"), b(false));
2511
    }
2512
}
2513
2514
/// Tests for the lazy [`Value::Foreign`] seam (ADR-21). feel-core never constructs
2515
/// a `Foreign`, so these drive a *test-only* [`ForeignObject`] to prove the
2516
/// force-on-consume / lazy-on-path contract from inside the core.
2517
#[cfg(test)]
2518
mod foreign_tests {
2519
    use super::*;
2520
    use crate::foreign::{Foreign, ForeignObject};
2521
    use std::collections::BTreeMap;
2522
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
2523
    use std::sync::Arc;
2524
2525
    /// A foreign object backed by a fixed map, counting `get`/`force` calls so the
2526
    /// tests can assert *when* the host is consulted (path = `get`, consume =
2527
    /// `force`).
2528
    #[derive(Debug)]
2529
    struct TestObj {
2530
        data: BTreeMap<String, Value>,
2531
        gets: Arc<AtomicUsize>,
2532
        forces: Arc<AtomicUsize>,
2533
    }
2534
2535
    impl ForeignObject for TestObj {
2536
        fn get(&self, key: &str) -> Value {
2537
            self.gets.fetch_add(1, AtomicOrdering::SeqCst);
2538
            self.data.get(key).cloned().unwrap_or(Value::Null)
2539
        }
2540
        fn force(&self) -> Value {
2541
            self.forces.fetch_add(1, AtomicOrdering::SeqCst);
2542
            Value::Context(self.data.clone())
2543
        }
2544
        fn as_any(&self) -> &dyn std::any::Any {
2545
            self
2546
        }
2547
    }
2548
2549
    fn obj(pairs: &[(&str, Value)], gets: &Arc<AtomicUsize>, forces: &Arc<AtomicUsize>) -> Value {
2550
        let data = pairs
2551
            .iter()
2552
            .map(|(k, v)| (k.to_string(), v.clone()))
2553
            .collect();
2554
        Value::Foreign(Foreign(Arc::new(TestObj {
2555
            data,
2556
            gets: gets.clone(),
2557
            forces: forces.clone(),
2558
        })))
2559
    }
2560
2561
    fn run(src: &str, ctx: &Context) -> Value {
2562
        evaluate(src, ctx).unwrap().into_lenient()
2563
    }
2564
2565
    #[test]
2566
    fn path_access_is_lazy_and_calls_get_not_force() {
2567
        let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
2568
        // order -> { customer -> { name: "Ada" } }, all lazy.
2569
        let customer = obj(&[("name", Value::String("Ada".into()))], &gets, &forces);
2570
        let order = obj(&[("customer", customer)], &gets, &forces);
2571
        let mut ctx = Context::empty();
2572
        ctx.insert("order", order);
2573
2574
        assert_eq!(
2575
            run("order.customer.name", &ctx),
2576
            Value::String("Ada".into())
2577
        );
2578
        // Two dots -> two `get`s; the dot never forces.
2579
        assert_eq!(gets.load(AtomicOrdering::SeqCst), 2);
2580
        assert_eq!(forces.load(AtomicOrdering::SeqCst), 0);
2581
        // A missing member is a value-null, like a missing context key.
2582
        assert_eq!(run("order.customer.missing", &ctx), Value::Null);
2583
    }
2584
2585
    #[test]
2586
    fn non_path_use_forces() {
2587
        let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
2588
        let o = obj(&[("a", Value::Number(1.0))], &gets, &forces);
2589
        let mut ctx = Context::empty();
2590
        ctx.insert("o", o);
2591
2592
        // Equality consumes the value -> the operand is forced to a context.
2593
        assert_eq!(run("o = {a: 1}", &ctx), Value::Boolean(true));
2594
        assert!(forces.load(AtomicOrdering::SeqCst) >= 1);
2595
    }
2596
2597
    #[test]
2598
    fn forced_is_identity_on_non_foreign() {
2599
        assert_eq!(Value::Number(2.0).forced(), Value::Number(2.0));
2600
        assert_eq!(Value::Null.forced(), Value::Null);
2601
        assert_eq!(
2602
            Value::String("x".into()).forced(),
2603
            Value::String("x".into())
2604
        );
2605
    }
2606
2607
    /// An unbounded (cycle-equivalent) lazy graph: every key but `value` yields
2608
    /// another node. A *finite* expression terminates because it can only navigate
2609
    /// a finite path — no engine cycle guard is needed (ADR-21).
2610
    #[derive(Debug)]
2611
    struct Infinite;
2612
    impl ForeignObject for Infinite {
2613
        fn get(&self, key: &str) -> Value {
2614
            if key == "value" {
2615
                Value::Number(42.0)
2616
            } else {
2617
                Value::Foreign(Foreign(Arc::new(Infinite)))
2618
            }
2619
        }
2620
        fn force(&self) -> Value {
2621
            Value::Context(BTreeMap::new())
2622
        }
2623
        fn as_any(&self) -> &dyn std::any::Any {
2624
            self
2625
        }
2626
    }
2627
2628
    #[test]
2629
    fn unbounded_graph_terminates_along_a_finite_path() {
2630
        let mut ctx = Context::empty();
2631
        ctx.insert("o", Value::Foreign(Foreign(Arc::new(Infinite))));
2632
        assert_eq!(run("o.self.self.self.value", &ctx), Value::Number(42.0));
2633
        assert_eq!(run("o.a.b.c.d.e.f.value", &ctx), Value::Number(42.0));
2634
    }
2635
2636
    #[test]
2637
    fn value_size_did_not_grow() {
2638
        // `Value`'s size is set by its largest variant — the temporal `DateTime`
2639
        // payload (32 bytes), giving 40 with the discriminant. The new `Foreign`
2640
        // variant is a 16-byte fat pointer, well under that, so `Value` does not
2641
        // grow: the zero-cost-for-Rust guarantee (ADR-21). Pin both so a regression
2642
        // (an accidental inline payload, or `Foreign` becoming the determining
2643
        // variant) is caught.
2644
        assert_eq!(std::mem::size_of::<Foreign>(), 16);
2645
        assert_eq!(std::mem::size_of::<Value>(), 40);
2646
    }
2647
2648
    // ---- descendant expression `e ... name` (DMN §10.3.2.7, grammar rule 68) ----
2649
2650
    #[test]
2651
    fn descendant_spec_example() {
2652
        // The spec's canonical example (§10.3.2.7): collect every `b` nested anywhere,
2653
        // pre-order. `{a:{b:{b:1}}} ... b` -> [{b:1}, 1].
2654
        let ctx = Context::empty();
2655
        assert_eq!(
2656
            run("{a: {b: {b: 1}}} ... b", &ctx),
2657
            Value::List(vec![
2658
                Value::Context(BTreeMap::from([("b".to_string(), Value::Number(1.0))])),
2659
                Value::Number(1.0),
2660
            ])
2661
        );
2662
    }
2663
2664
    #[test]
2665
    fn descendant_collects_across_a_list_of_contexts() {
2666
        let ctx = Context::empty();
2667
        assert_eq!(
2668
            run("[{x:1},{x:2}] ... x", &ctx),
2669
            Value::List(vec![Value::Number(1.0), Value::Number(2.0)])
2670
        );
2671
    }
2672
2673
    #[test]
2674
    fn descendant_no_match_is_empty_list() {
2675
        // A search that finds nothing still yields a (flat) list, not null.
2676
        let ctx = Context::empty();
2677
        assert_eq!(run("{a:1} ... z", &ctx), Value::List(vec![]));
2678
    }
2679
2680
    #[test]
2681
    fn descendant_on_null_and_scalar() {
2682
        let ctx = Context::empty();
2683
        // null propagates.
2684
        assert_eq!(run("null ... x", &ctx), Value::Null);
2685
        // A non-navigable scalar: applicability "type e is a context" fails -> null
2686
        // (mirrors `.` on a non-context).
2687
        assert_eq!(run("5 ... x", &ctx), Value::Null);
2688
    }
2689
2690
    #[test]
2691
    fn descendant_descends_into_foreign() {
2692
        // order -> { customer -> { name: "Ada" } }, all lazy Foreigns.
2693
        let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
2694
        let customer = obj(&[("name", Value::String("Ada".into()))], &gets, &forces);
2695
        let order = obj(&[("customer", customer)], &gets, &forces);
2696
        let mut ctx = Context::empty();
2697
        ctx.insert("order", order);
2698
        // Descendant forces its way down the lazy graph and collects `name`.
2699
        assert_eq!(
2700
            run("order ... name", &ctx),
2701
            Value::List(vec![Value::String("Ada".into())])
2702
        );
2703
    }
2704
2705
    /// A cyclic foreign graph that mimics a host (feel-py) wrapping the *same*
2706
    /// object with a *fresh* `Arc` on every access: `force`/`get("next")` mint a new
2707
    /// `Arc<Cycle>` carrying the same `id`, so the Rust allocation address differs
2708
    /// every time. Only the `identity()` override (the stable `id`) lets the
2709
    /// descendant guard break the cycle — exactly the feel-py/lua/wasm scenario.
2710
    #[derive(Debug)]
2711
    struct Cycle {
2712
        id: usize,
2713
        value: f64,
2714
    }
2715
    impl ForeignObject for Cycle {
2716
        fn get(&self, key: &str) -> Value {
2717
            match key {
2718
                "value" => Value::Number(self.value),
2719
                "next" => Value::Foreign(Foreign(Arc::new(Cycle {
2720
                    id: self.id,
2721
                    value: self.value,
2722
                }))),
2723
                _ => Value::Null,
2724
            }
2725
        }
2726
        fn force(&self) -> Value {
2727
            let mut map = BTreeMap::new();
2728
            map.insert("value".to_string(), Value::Number(self.value));
2729
            map.insert(
2730
                "next".to_string(),
2731
                Value::Foreign(Foreign(Arc::new(Cycle {
2732
                    id: self.id,
2733
                    value: self.value,
2734
                }))),
2735
            );
2736
            Value::Context(map)
2737
        }
2738
        fn as_any(&self) -> &dyn std::any::Any {
2739
            self
2740
        }
2741
        fn identity(&self) -> usize {
2742
            self.id
2743
        }
2744
    }
2745
2746
    #[test]
2747
    fn descendant_terminates_on_a_cyclic_foreign_with_fresh_arcs() {
2748
        // Without the identity() override this would loop forever; with it, the
2749
        // back-edge into the same `id` is skipped after the first descent.
2750
        let mut ctx = Context::empty();
2751
        ctx.insert(
2752
            "c",
2753
            Value::Foreign(Foreign(Arc::new(Cycle { id: 7, value: 42.0 }))),
2754
        );
2755
        // value=42 at the top, then once more at the (single) re-entered node before
2756
        // the back-edge is cut -> [42, 42].
2757
        assert_eq!(
2758
            run("c ... value", &ctx),
2759
            Value::List(vec![Value::Number(42.0), Value::Number(42.0)])
2760
        );
2761
    }
2762
2763
    /// A self-referential cycle via a *single shared* `Arc` (the allocation address
2764
    /// is reused), so the DEFAULT `identity()` (allocation address) suffices — this
2765
    /// exercises the default code path rather than an override.
2766
    #[derive(Debug)]
2767
    struct SharedCycle {
2768
        next: std::sync::OnceLock<Value>,
2769
        value: f64,
2770
    }
2771
    impl ForeignObject for SharedCycle {
2772
        fn get(&self, key: &str) -> Value {
2773
            match key {
2774
                "value" => Value::Number(self.value),
2775
                "next" => self.next.get().cloned().unwrap_or(Value::Null),
2776
                _ => Value::Null,
2777
            }
2778
        }
2779
        fn force(&self) -> Value {
2780
            let mut map = BTreeMap::new();
2781
            map.insert("value".to_string(), Value::Number(self.value));
2782
            map.insert(
2783
                "next".to_string(),
2784
                self.next.get().cloned().unwrap_or(Value::Null),
2785
            );
2786
            Value::Context(map)
2787
        }
2788
        fn as_any(&self) -> &dyn std::any::Any {
2789
            self
2790
        }
2791
    }
2792
2793
    #[test]
2794
    fn descendant_terminates_on_a_cyclic_foreign_with_a_shared_arc() {
2795
        let arc = Arc::new(SharedCycle {
2796
            next: std::sync::OnceLock::new(),
2797
            value: 9.0,
2798
        });
2799
        // Wire the self-reference after the Arc exists (same allocation reused).
2800
        arc.next
2801
            .set(Value::Foreign(Foreign(arc.clone())))
2802
            .unwrap();
2803
        let mut ctx = Context::empty();
2804
        ctx.insert("c", Value::Foreign(Foreign(arc)));
2805
        assert_eq!(
2806
            run("c ... value", &ctx),
2807
            Value::List(vec![Value::Number(9.0), Value::Number(9.0)])
2808
        );
2809
    }
2810
2811
    #[test]
2812
    fn descendant_dedups_a_shared_acyclic_foreign_dag() {
2813
        // Pure-FEEL contrast first: two DISTINCT value contexts (owned, never
2814
        // Foreign) -> both traversed -> multiset [1, 1]. The spec domain is exact.
2815
        let ctx = Context::empty();
2816
        assert_eq!(
2817
            run("{x:{v:1}, y:{v:1}} ... v", &ctx),
2818
            Value::List(vec![Value::Number(1.0), Value::Number(1.0)])
2819
        );
2820
2821
        // Same shape but the inner object is ONE shared host object (a diamond/DAG,
2822
        // not a cycle): both `x` and `y` reference the same `a` (same Foreign
2823
        // identity). The GLOBAL visited-set collects `v` once, not once per path —
2824
        // the intentional DAG de-dup (ADR-46). Host object graphs are out of DMN
2825
        // spec; the global set is chosen over a path-scoped set to avoid exponential
2826
        // blowup on diamond-heavy DAGs, accepting per-path multiset semantics for
2827
        // shared host data.
2828
        let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
2829
        let a = obj(&[("v", Value::Number(1.0))], &gets, &forces);
2830
        let g = obj(&[("x", a.clone()), ("y", a.clone())], &gets, &forces);
2831
        let mut ctx = Context::empty();
2832
        ctx.insert("g", g);
2833
        assert_eq!(
2834
            run("g ... v", &ctx),
2835
            Value::List(vec![Value::Number(1.0)])
2836
        );
2837
    }
2838
}
2839
2840
/// User-defined functions: native FEEL closures and host callables (ADR-23).
2841
///
2842
/// The DMN-TCK has dedicated cases (compliance-level-3 `0030`/`0031`), but those
2843
/// decisions are *boxed* (a `<context>`/`<functionDefinition>`), not single literal
2844
/// expressions, and use named-argument and library-import forms outside this slice,
2845
/// so `tools/ingest_tck.py` cannot ingest them. The closure tests below therefore
2846
/// reconstruct the TCK 0030 semantics as self-contained FEEL expressions; each
2847
/// carries a `mirrors DMN-TCK …` note so this stays easy to refresh against the
2848
/// source. Source: https://github.com/dmn-tck/tck — TestCases/compliance-level-3/0030-user-defined-functions
2849
#[cfg(test)]
2850
mod function_tests {
2851
    use super::*;
2852
    use crate::function::{Args, ForeignFunction, Func};
2853
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
2854
    use std::sync::Arc;
2855
2856
    /// Evaluate against an empty context, collapsing error provenance (lenient view).
2857
    fn ev(src: &str) -> Value {
2858
        evaluate(src, &Context::empty())
2859
            .unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
2860
            .into_lenient()
2861
    }
2862
2863
    // --- native FEEL closures (`function(…)` literals) ------------------------ //
2864
2865
    #[test]
2866
    fn closure_literal_and_positional_invocation() {
2867
        // A function bound in a context entry, then invoked by name — the self-
2868
        // contained shape of a TCK boxed-context function invocation.
2869
        assert_eq!(
2870
            ev("{f: function(a, b) a + b, r: f(1, 2)}.r"),
2871
            Value::Number(3.0)
2872
        );
2873
        // mirrors DMN-TCK 0030 testCase 001 "simple function invocation":
2874
        // f("feel","#") + f("feel","#") == "feel#" + "feel#" == "feel#feel#".
2875
        assert_eq!(
2876
            ev(r##"{f: function(a, b) a + b, r: f("feel", "#") + f("feel", "#")}.r"##),
2877
            Value::String("feel#feel#".into())
2878
        );
2879
        // a zero-parameter function.
2880
        assert_eq!(ev("{f: function() 42, r: f()}.r"), Value::Number(42.0));
2881
    }
2882
2883
    #[test]
2884
    fn named_and_mixed_invocation() {
2885
        // mirrors DMN-TCK 0030 testCase 001 "named function invocation": the names
2886
        // are bound by position-independent name, here swapped, giving "#feel#feel".
2887
        assert_eq!(
2888
            ev(r##"{f: function(a, b) a + b, r: f(b: "feel", a: "#") + f(b: "feel", a: "#")}.r"##),
2889
            Value::String("#feel#feel".into())
2890
        );
2891
        // named arguments, order reversed: a - b with a=7, b=2 -> 5.
2892
        assert_eq!(
2893
            ev("{f: function(a, b) a - b, r: f(b: 2, a: 7)}.r"),
2894
            Value::Number(5.0)
2895
        );
2896
        // mixed positional + named (ADR-23 superset of FEEL spec rule 39): 7 - 2 = 5.
2897
        assert_eq!(
2898
            ev("{f: function(a, b) a - b, r: f(7, b: 2)}.r"),
2899
            Value::Number(5.0)
2900
        );
2901
    }
2902
2903
    #[test]
2904
    fn lexical_capture() {
2905
        // The body sees `x` from the scope the function was defined in (a closure).
2906
        assert_eq!(
2907
            ev("{x: 10, f: function(a) a + x, r: f(5)}.r"),
2908
            Value::Number(15.0)
2909
        );
2910
    }
2911
2912
    #[test]
2913
    fn arity_is_lenient() {
2914
        // Under-supplied positional: the unused param is value-null, so f(7)=7.
2915
        assert_eq!(ev("{f: function(a, b) a, r: f(7)}.r"), Value::Number(7.0));
2916
        // An unsupplied param read in the body is null -> a + null -> null.
2917
        assert_eq!(ev("{f: function(a, b) a + b, r: f(7)}.r"), Value::Null);
2918
        // Non-conformance is an error-null (-> null lenient): too many positional,
2919
        assert_eq!(ev("{f: function(a) a, r: f(1, 2)}.r"), Value::Null);
2920
        // an unknown named parameter,
2921
        assert_eq!(ev("{f: function(a) a, r: f(z: 1)}.r"), Value::Null);
2922
        // and a parameter supplied both positionally and by name.
2923
        assert_eq!(ev("{f: function(a, b) a, r: f(1, a: 2)}.r"), Value::Null);
2924
    }
2925
2926
    #[test]
2927
    fn function_equality_is_identity() {
2928
        // The same binding referenced twice is the same value -> equal.
2929
        assert_eq!(ev("{f: function(a) a, r: f = f}.r"), Value::Boolean(true));
2930
        // Two distinct function literals are incomparable -> error-null (-> null).
2931
        assert_eq!(
2932
            ev("{f: function(a) a, g: function(a) a, r: f = g}.r"),
2933
            Value::Null
2934
        );
2935
    }
2936
2937
    #[test]
2938
    fn recursion_guard_returns_null_not_overflow() {
2939
        // A self-applying function recurses unboundedly; the call-depth cap turns
2940
        // that into an error-null (-> null) instead of a stack overflow (ADR-23).
2941
        assert_eq!(
2942
            ev("{apply: function(g, n) g(g, n), r: apply(apply, 1)}.r"),
2943
            Value::Null
2944
        );
2945
    }
2946
2947
    // --- typed formal parameters (FEEL rule 56, ADR-35) ---------------------- //
2948
2949
    #[test]
2950
    fn typed_formal_params_parse_and_eval() {
2951
        // A typed param `a: number` is semantically identical to bare `a` — the type
2952
        // annotation is parsed and discarded in this slice (ADR-35).
2953
        assert_eq!(
2954
            ev("{f: function (a: number) 1 + a, r: f(2)}.r"),
2955
            Value::Number(3.0)
2956
        );
2957
        // Multiple typed params.
2958
        assert_eq!(
2959
            ev("{f: function (a: number, b: number) a * b, r: f(3, 4)}.r"),
2960
            Value::Number(12.0)
2961
        );
2962
        // Mixed typed and bare params — the parser accepts both in the same list.
2963
        assert_eq!(
2964
            ev("{f: function (a: number, b) a + b, r: f(10, 5)}.r"),
2965
            Value::Number(15.0)
2966
        );
2967
        // A typed param with a generic type `function<number> -> number` (rule 56).
2968
        assert_eq!(
2969
            ev("{bkm: function (fn1: function<number> -> number) fn1(3), r: bkm(function (x: number) x + 1)}.r"),
2970
            Value::Number(4.0)
2971
        );
2972
    }
2973
2974
    #[test]
2975
    fn typed_params_closure_and_currying() {
2976
        // Typed params work with closures (closed-over var `base`).
2977
        assert_eq!(
2978
            ev("{base: 10, f: function (a: number) a * base, r: f(5)}.r"),
2979
            Value::Number(50.0)
2980
        );
2981
        // Curried closures: outer typed param `a` captured in inner lambda.
2982
        assert_eq!(
2983
            ev("{outer: function (a: number) function (b: number) a * b, step1: outer(3), r: step1(4)}.r"),
2984
            Value::Number(12.0)
2985
        );
2986
        // Three-level currying.
2987
        assert_eq!(
2988
            ev("{f: function (a: number) function (b: number) function (c: number) a + b + c, s1: f(1), s2: s1(2), r: s2(3)}.r"),
2989
            Value::Number(6.0)
2990
        );
2991
    }
2992
2993
    // --- first-class built-in function values (ADR-36) ----------------------- //
2994
2995
    #[test]
2996
    fn builtin_as_first_class_value() {
2997
        // A bare built-in name evaluates to a Function value when used as a value.
2998
        assert!(matches!(ev("abs"), Value::Function(_)));
2999
        assert!(matches!(ev("sqrt"), Value::Function(_)));
3000
        // A context binding shadows the built-in (binding takes precedence).
3001
        assert_eq!(ev("{abs: 42, r: abs}.r"), Value::Number(42.0));
3002
    }
3003
3004
    #[test]
3005
    fn builtin_passed_as_argument_and_invoked() {
3006
        // A built-in can be passed as a lambda argument and invoked via the param.
3007
        assert_eq!(
3008
            ev("{bkm: function (fn1, fn2) fn1(-5) * fn2(25), r: bkm(abs, sqrt)}.r"),
3009
            Value::Number(25.0)
3010
        );
3011
        // A built-in with wrong arity -> error-null -> null (lenient).
3012
        assert_eq!(
3013
            ev("{bkm: function (fn1) fn1(10, 2), r: bkm(sqrt)}.r"),
3014
            Value::Null
3015
        );
3016
    }
3017
3018
    // --- higher-order built-ins: sort + matching list replace (ADR-37) -------- //
3019
3020
    fn num(v: f64) -> Value {
3021
        Value::Number(v)
3022
    }
3023
    fn str_val(v: &str) -> Value {
3024
        Value::String(v.into())
3025
    }
3026
3027
    #[test]
3028
    fn sort_ascending_descending() {
3029
        // Numeric ascending.
3030
        assert_eq!(
3031
            ev("sort([3,1,4,5,2], function(x,y) x<y)"),
3032
            Value::List(vec![num(1.0), num(2.0), num(3.0), num(4.0), num(5.0)])
3033
        );
3034
        // Numeric descending (0013-sort sort1: sort(listA, function(x,y) x>y)).
3035
        assert_eq!(
3036
            ev("sort([3,1,5,4], function(x,y) x>y)"),
3037
            Value::List(vec![num(5.0), num(4.0), num(3.0), num(1.0)])
3038
        );
3039
        // String ascending (basic latin).
3040
        assert_eq!(
3041
            ev(r#"sort(["c","a","b"], function(x,y) x<y)"#),
3042
            Value::List(vec![str_val("a"), str_val("b"), str_val("c")])
3043
        );
3044
        // Empty list.
3045
        assert_eq!(ev("sort([], function(x,y) x<y)"), Value::List(vec![]));
3046
        // Single-element list.
3047
        assert_eq!(
3048
            ev("sort([42], function(x,y) x<y)"),
3049
            Value::List(vec![num(42.0)])
3050
        );
3051
    }
3052
3053
    #[test]
3054
    fn sort_by_context_field() {
3055
        // Sort contexts by a numeric field — mirrors 0013-sort sort2.
3056
        assert_eq!(
3057
            ev("{t: sort([{v:3},{v:1},{v:2}], function(x,y) x.v < y.v), r: t[1].v}.r"),
3058
            num(1.0)
3059
        );
3060
    }
3061
3062
    #[test]
3063
    fn sort_stable() {
3064
        // Elements comparing equal (precedes returns false both ways) must stay in
3065
        // their original relative order (stable sort).
3066
        assert_eq!(
3067
            ev("sort([1,1,2], function(x,y) x<y)"),
3068
            Value::List(vec![num(1.0), num(1.0), num(2.0)])
3069
        );
3070
    }
3071
3072
    #[test]
3073
    fn sort_named_args() {
3074
        // Named-argument form: sort(list: …, precedes: …).
3075
        assert_eq!(
3076
            ev("sort(list: [3,1,2], precedes: function(x,y) x<y)"),
3077
            Value::List(vec![num(1.0), num(2.0), num(3.0)])
3078
        );
3079
    }
3080
3081
    #[test]
3082
    fn sort_as_first_class_builtin() {
3083
        // `sort` can be referenced as a first-class value and passed around.
3084
        assert!(matches!(ev("sort"), Value::Function(_)));
3085
    }
3086
3087
    #[test]
3088
    fn sort_error_cases() {
3089
        // Null list -> null (value-null from sort_fn).
3090
        assert_eq!(ev("sort(null, function(x,y) x<y)"), Value::Null);
3091
        // Non-list first arg -> error-null -> null (lenient).
3092
        assert_eq!(ev("sort(1, function(x,y) x<y)"), Value::Null);
3093
        // Non-function second arg -> error-null -> null.
3094
        assert_eq!(ev("sort([1,2], 3)"), Value::Null);
3095
        // Closure with wrong arity (1 param instead of 2) -> error-null -> null.
3096
        assert_eq!(ev("sort([1,2], function(x) x)"), Value::Null);
3097
        // Comparator returning non-boolean -> error-null -> null.
3098
        assert_eq!(ev("sort([1,2], function(x,y) null)"), Value::Null);
3099
    }
3100
3101
    #[test]
3102
    fn sort_higher_order_closure_over_input() {
3103
        // 0092-017: comparator closes over an input value.
3104
        assert_eq!(
3105
            ev(r#"{input_017_1: "a", bkm: function (fn1) sort(["a","z","a","z"], fn1), r: bkm(function (a: string, b: string) if a = input_017_1 then true else false)}.r"#),
3106
            Value::List(vec![str_val("a"), str_val("a"), str_val("z"), str_val("z")])
3107
        );
3108
        // 0092-018: BKM passed as the comparator.
3109
        assert_eq!(
3110
            ev(r#"{bkm_018: function (p1, p2) if p1 = "a" then true else false, r: sort(["a","z","a","z"], bkm_018)}.r"#),
3111
            Value::List(vec![str_val("a"), str_val("a"), str_val("z"), str_val("z")])
3112
        );
3113
    }
3114
3115
    #[test]
3116
    fn list_replace_matching_form() {
3117
        // Replace items where match(item, newItem) returns true.
3118
        assert_eq!(
3119
            ev("list replace([2,4,7,8], function(item,newItem) item<newItem, 5)"),
3120
            Value::List(vec![num(5.0), num(5.0), num(7.0), num(8.0)])
3121
        );
3122
        // All items match.
3123
        assert_eq!(
3124
            ev("list replace([1,2,3], function(item,newItem) true, 5)"),
3125
            Value::List(vec![num(5.0), num(5.0), num(5.0)])
3126
        );
3127
        // No items match.
3128
        assert_eq!(
3129
            ev("list replace([1,2,3], function(item,newItem) false, 5)"),
3130
            Value::List(vec![num(1.0), num(2.0), num(3.0)])
3131
        );
3132
    }
3133
3134
    #[test]
3135
    fn list_replace_matching_named_args() {
3136
        // Named `match:` overload (1155 test 117).
3137
        assert_eq!(
3138
            ev("list replace(match: function(item, newItem) item = 2, newItem: 4, list: [1,2,3])"),
3139
            Value::List(vec![num(1.0), num(4.0), num(3.0)])
3140
        );
3141
    }
3142
3143
    #[test]
3144
    fn list_replace_matching_error_cases() {
3145
        // Comparator returning a non-boolean value -> error-null -> null (1155 test 165).
3146
        assert_eq!(
3147
            ev("list replace([2,4], function(item,newItem) item, 5)"),
3148
            Value::Null
3149
        );
3150
        // Closure with 3 params instead of 2 -> error-null -> null (1155 test 149).
3151
        assert_eq!(
3152
            ev("list replace([2,4], function(item,newItem,extra) item=2, 5)"),
3153
            Value::Null
3154
        );
3155
        // Closure with 1 param instead of 2 -> error-null -> null (1155 test 157).
3156
        assert_eq!(
3157
            ev("list replace([2,4], function(item) item=2, 5)"),
3158
            Value::Null
3159
        );
3160
    }
3161
3162
    // --- value-invocation of a non-function → null (ADR-38, 1131) ----------- //
3163
3164
    #[test]
3165
    fn invoke_non_function_yields_null() {
3166
        // unknown name → error-null (FnCall path, unchanged)
3167
        assert_eq!(ev("non_existing_function()"), Value::Null);
3168
        // null, string, number, boolean, date — all non-functions → null
3169
        assert_eq!(ev("null()"), Value::Null);
3170
        assert_eq!(ev("\"some_func\"()"), Value::Null);
3171
        assert_eq!(ev("\"abs\"(-1)"), Value::Null);
3172
        assert_eq!(ev("123()"), Value::Null);
3173
        assert_eq!(ev("true()"), Value::Null);
3174
        assert_eq!(ev("false()"), Value::Null);
3175
        assert_eq!(ev("@\"2023-11-11\"()"), Value::Null);
3176
        // Named calls to built-ins must be unaffected (FnCall path still works).
3177
        assert_eq!(ev("abs(-1)"), Value::Number(1.0));
3178
        assert_eq!(ev("abs(n: -2)"), Value::Number(2.0));
3179
    }
3180
3181
    // --- host callables (ForeignFunction) ------------------------------------ //
3182
3183
    /// A host function that sums all of its numeric arguments (positional + named),
3184
    /// so the tests can exercise both argument forms crossing the seam.
3185
    #[derive(Debug)]
3186
    struct SumFn;
3187
    impl ForeignFunction for SumFn {
3188
        fn call(&self, args: Args) -> Value {
3189
            let mut total = 0.0;
3190
            for v in args.positional {
3191
                if let Value::Number(n) = v.forced() {
3192
                    total += n;
3193
                }
3194
            }
3195
            for (_, v) in args.named {
3196
                if let Value::Number(n) = v.forced() {
3197
                    total += n;
3198
                }
3199
            }
3200
            Value::Number(total)
3201
        }
3202
        fn as_any(&self) -> &dyn std::any::Any {
3203
            self
3204
        }
3205
    }
3206
3207
    fn host_fn(f: impl ForeignFunction + 'static) -> Value {
3208
        Value::Function(Arc::new(Func::Foreign(Arc::new(f))))
3209
    }
3210
3211
    #[test]
3212
    fn host_function_as_context_value() {
3213
        let mut ctx = Context::empty();
3214
        ctx.insert("add", host_fn(SumFn));
3215
        let run = |src: &str| evaluate(src, &ctx).unwrap().into_lenient();
3216
        assert_eq!(run("add(2, 3)"), Value::Number(5.0));
3217
        // Named args reach the host too (here name-agnostic, summed).
3218
        assert_eq!(run("add(x: 2, y: 3)"), Value::Number(5.0));
3219
        // Mixed positional + named.
3220
        assert_eq!(run("add(2, y: 3)"), Value::Number(5.0));
3221
    }
3222
3223
    /// A host registry exposing `add` as an ambient function (the second injection
3224
    /// path beside a context binding; ADR-23).
3225
    struct Registry;
3226
    impl FunctionRegistry for Registry {
3227
        fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
3228
            (name == "add").then(|| Arc::new(SumFn) as Arc<dyn ForeignFunction>)
3229
        }
3230
    }
3231
3232
    #[test]
3233
    fn host_function_via_registry() {
3234
        let compiled = compile("add(2, 3, 4)").unwrap();
3235
        let env =
3236
            EvalEnv::with_functions(&crate::regex_provider::DEFAULT, default_now(), &Registry);
3237
        let r = compiled
3238
            .evaluate_with_env(&Context::empty(), &env)
3239
            .unwrap()
3240
            .into_lenient();
3241
        assert_eq!(r, Value::Number(9.0));
3242
    }
3243
3244
    /// A counting foreign *object*, to prove a closure's arguments stay unforced so
3245
    /// path access inside the body remains lazy (ADR-21).
3246
    #[derive(Debug)]
3247
    struct CountObj {
3248
        gets: Arc<AtomicUsize>,
3249
        forces: Arc<AtomicUsize>,
3250
    }
3251
    impl crate::foreign::ForeignObject for CountObj {
3252
        fn get(&self, key: &str) -> Value {
3253
            self.gets.fetch_add(1, AtomicOrdering::SeqCst);
3254
            if key == "x" {
3255
                Value::Number(99.0)
3256
            } else {
3257
                Value::Null
3258
            }
3259
        }
3260
        fn force(&self) -> Value {
3261
            self.forces.fetch_add(1, AtomicOrdering::SeqCst);
3262
            Value::Null
3263
        }
3264
        fn as_any(&self) -> &dyn std::any::Any {
3265
            self
3266
        }
3267
    }
3268
3269
    #[test]
3270
    fn closure_arguments_stay_unforced() {
3271
        let gets = Arc::new(AtomicUsize::new(0));
3272
        let forces = Arc::new(AtomicUsize::new(0));
3273
        let o = Value::Foreign(crate::foreign::Foreign(Arc::new(CountObj {
3274
            gets: gets.clone(),
3275
            forces: forces.clone(),
3276
        })));
3277
        let mut ctx = Context::empty();
3278
        ctx.insert("o", o);
3279
        // `f(o)` binds the foreign object to `p` unforced; the body navigates `p.x`
3280
        // via a single `get`, never forcing the whole object.
3281
        let r = evaluate("{f: function(p) p.x, r: f(o)}.r", &ctx)
3282
            .unwrap()
3283
            .into_lenient();
3284
        assert_eq!(r, Value::Number(99.0));
3285
        assert_eq!(gets.load(AtomicOrdering::SeqCst), 1);
3286
        assert_eq!(forces.load(AtomicOrdering::SeqCst), 0);
3287
    }
3288
}