Public repository: timo / feel

Reader

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

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