Public repository: timo / feel

Reader

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

Outline: 101 definitions
1
//! Built-in functions — the non-temporal slice (DECISIONS.md ADR-15/ADR-17).
2
//!
3
//! Single-word (`abs`, `count`) and multi-word (`string length`, `list
4
//! contains`, `get value`) names alike; the lexer hands a space-normalised name
5
//! string here, so dispatch is a plain match either way (ADR-17).
6
//!
7
//! Dispatch is by name + arity. Error policy follows ADR-14: a type/arity/domain
8
//! error (or an unknown function) is an *error-null* (`Value::Error`), while a
9
//! spec-legitimate empty/absent result (e.g. `sum([]) = null`) is a *value-null*
10
//! (`Value::Null`). The two coincide once collapsed at the lenient boundary, but
11
//! we keep the provenance so the strict boundary and unit tests can tell them
12
//! apart.
13
//!
14
//! Many aggregates accept *either* a single list argument *or* a list of scalar
15
//! arguments (`sum([1,2,3])` == `sum(1,2,3)`); [`coerce_list`] encodes that rule.
16
//!
17
//! `replace`/`split`/`matches` are dialect-dependent: they route through the
18
//! injected [`FeelRegex`] provider so each target uses its **host's** regex
19
//! engine (ADR-16). The argument-shape handling (arity, string vs null typing,
20
//! the optional `flags` argument) stays here; only pattern compilation and the
21
//! match/replace/split itself live in the provider.
22
23
use std::cmp::Ordering;
24
use std::collections::BTreeMap;
25
26
use crate::eval::{as_number, feel_order};
27
use crate::function::{Applier, Args, Func};
28
use crate::regex_provider::{match_value, FeelRegex};
29
use crate::{EvalEnv, Value};
30
31
/// FEEL multi-word names that contain a *keyword* word-part, which Tier-1
32
/// whitespace joining in the lexer cannot form (a keyword is a separate token that
33
/// stops the merge). The lexer recognises these against this fixed, closed
34
/// dictionary and joins them into a single `Name` token **wherever they occur**
35
/// (DECISIONS.md ADR-17/ADR-26). They are FEEL's atomic temporal type names
36
/// (`x instance of date and time`) and constructor names (`date and time(…)`),
37
/// reserved words rather than user variables, so the unconditional join needs no
38
/// name oracle. The phrases share no prefix.
39
pub(crate) const KEYWORD_PHRASE_BUILTINS: &[&str] = &[
40
    "date and time",
41
    "years and months duration",
42
    "days and time duration",
43
];
44
45
/// Return `true` if `name` is a recognised built-in (i.e. `call` returns `Some` for it).
46
///
47
/// Used by the evaluator to promote a bare built-in name used as a value expression
48
/// to a [`Func::Builtin`](crate::function::Func::Builtin) — e.g. `bkm(abs, sqrt)`
49
/// where `abs`/`sqrt` are first-class function values (ADR-36). The names match
50
/// the spec's joined multi-word form (e.g. `"string length"`, `"date and time"`) as
51
/// produced by the lexer.
52
pub(crate) fn is_builtin(name: &str) -> bool {
53
    matches!(
54
        name,
55
        // conversion
56
        "string" | "number" |
57
        // string functions
58
        "substring" | "contains" | "replace" | "split" | "matches" |
59
        "string length" | "upper case" | "lower case" |
60
        "substring before" | "substring after" |
61
        "starts with" | "ends with" | "string join" |
62
        // list functions
63
        "count" | "min" | "max" | "sum" | "mean" | "product" |
64
        "median" | "stddev" | "mode" | "all" | "any" |
65
        "append" | "concatenate" | "union" | "remove" | "reverse" |
66
        "flatten" | "sublist" | "list contains" | "index of" |
67
        "distinct values" | "insert before" | "list replace" | "sort" |
68
        // context functions
69
        "get value" | "get entries" | "context" | "context put" | "context merge" |
70
        // numeric functions
71
        "decimal" | "floor" | "ceiling" |
72
        "round up" | "round down" | "round half up" | "round half down" |
73
        "abs" | "modulo" | "sqrt" | "exp" | "log" | "even" | "odd" |
74
        // temporal clock
75
        "now" | "today" |
76
        // temporal constructors / component functions
77
        "date" | "time" | "date and time" | "duration" | "years and months duration" |
78
        "day of week" | "month of year" | "day of year" | "week of year" |
79
        // boolean / range
80
        "is" | "range" |
81
        // Allen's interval relations
82
        "before" | "after" | "meets" | "met by" |
83
        "overlaps" | "overlaps before" | "overlaps after" |
84
        "finishes" | "finished by" | "includes" | "during" |
85
        "starts" | "started by" | "coincides"
86
    )
87
}
88
89
/// Dispatch a single- or multi-word built-in call. Arguments are already
90
/// evaluated (but unforced). The `env` carries the regex provider (consulted only
91
/// by `matches`/`replace`/`split`) and the instant `now()`/`today()` read (ADR-18).
92
/// `applier` is the evaluator's function-apply capability, threaded in so that
93
/// higher-order built-ins (`sort`, matching `list replace`) can invoke a
94
/// function-valued argument through the same call path as a direct FEEL call
95
/// — including the recursion-depth guard (ADR-37).
96
///
97
/// Returns `None` for a name this module does not implement, so the caller can fall
98
/// through to a host function (ADR-23); every recognised built-in returns `Some`.
99
pub(crate) fn call(
100
    name: &str,
101
    args: crate::function::Args,
102
    env: &EvalEnv,
103
    applier: &dyn Applier,
104
) -> Option<Value> {
105
    // Named arguments must be placed into this built-in's positional parameter
106
    // order before dispatch (FEEL spec §10.3.2.13.5). That reordering needs a
107
    // per-built-in parameter-name table (the Sonnet-Teilaufgabe in the plan); see
108
    // [`reorder_named`]. A purely positional call needs no table.
109
    let args: Vec<Value> = if args.named.is_empty() {
110
        args.positional
111
    } else {
112
        reorder_named(name, args)?
113
    };
114
    // Builtins consume concrete values, so force any lazy host argument one level
115
    // first (ADR-21). This is scoped to *builtins*: a user-defined-function call
116
    // binds its arguments unforced, exactly like a `for`/quantifier variable, so
117
    // path laziness flows through that call. `forced` is a no-op tag test for every
118
    // non-`Foreign`, and the same-type map reuses the buffer.
119
    let args: Vec<Value> = args.into_iter().map(Value::forced).collect();
120
    // A type error in any (top-level) argument propagates as an error-null. (For an
121
    // unknown name this still returns `Some(Error)` if an argument is itself an
122
    // error-null, shadowing the host registry in that marginal case; acceptable.)
123
    if args.iter().any(|a| matches!(a, Value::Error)) {
124
        return Some(Value::Error);
125
    }
126
    let regex = env.regex;
127
    Some(match name {
128
        // --- conversion ---
129
        "string" => string_fn(args),
130
        "number" => number_fn(args),
131
132
        // --- string ---
133
        "substring" => substring_fn(args),
134
        "contains" => contains_fn(args),
135
        "replace" => replace_fn(args, regex),
136
        "split" => split_fn(args, regex),
137
        "matches" => matches_fn(args, regex),
138
        "string length" => string_length_fn(args),
139
        "upper case" => case_fn(args, true),
140
        "lower case" => case_fn(args, false),
141
        "substring before" => substring_before_after_fn(args, true),
142
        "substring after" => substring_before_after_fn(args, false),
143
        "starts with" => starts_ends_with_fn(args, true),
144
        "ends with" => starts_ends_with_fn(args, false),
145
        "string join" => string_join_fn(args),
146
147
        // --- list ---
148
        "count" => count_fn(args),
149
        "min" => min_max_fn(args, true),
150
        "max" => min_max_fn(args, false),
151
        "sum" => sum_fn(args),
152
        "mean" => mean_fn(args),
153
        "product" => product_fn(args),
154
        "median" => median_fn(args),
155
        "stddev" => stddev_fn(args),
156
        "mode" => mode_fn(args),
157
        "all" => all_any_fn(args, true),
158
        "any" => all_any_fn(args, false),
159
        "append" => append_fn(args),
160
        "concatenate" => concatenate_fn(args),
161
        "union" => union_fn(args),
162
        "remove" => remove_fn(args),
163
        "reverse" => reverse_fn(args),
164
        "flatten" => flatten_fn(args),
165
        "sublist" => sublist_fn(args),
166
        "list contains" => list_contains_fn(args),
167
        "index of" => index_of_fn(args),
168
        "distinct values" => distinct_values_fn(args),
169
        "insert before" => insert_before_fn(args),
170
        "list replace" => list_replace_fn(args, applier),
171
        "sort" => sort_fn(args, applier),
172
173
        // --- context ---
174
        "get value" => get_value_fn(args),
175
        "get entries" => get_entries_fn(args),
176
        "context" => context_fn(args),
177
        "context put" => context_put_fn(args),
178
        "context merge" => context_merge_fn(args),
179
180
        // --- numeric ---
181
        "decimal" => decimal_fn(args),
182
        "floor" => floor_ceiling_fn(args, true),
183
        "ceiling" => floor_ceiling_fn(args, false),
184
        "round up" => round_fn(args, RoundMode::Up),
185
        "round down" => round_fn(args, RoundMode::Down),
186
        "round half up" => round_fn(args, RoundMode::HalfUp),
187
        "round half down" => round_fn(args, RoundMode::HalfDown),
188
        "abs" => abs_fn(args),
189
        "modulo" => modulo_fn(args),
190
        "sqrt" => sqrt_fn(args),
191
        "exp" => exp_fn(args),
192
        "log" => log_fn(args),
193
        "even" => even_odd_fn(args, true),
194
        "odd" => even_odd_fn(args, false),
195
196
        // --- temporal clock (ADR-18) — read the injected instant, not the wall
197
        //     clock, so feel-pg can pin it to the transaction start and tests are
198
        //     deterministic. ---
199
        "now" => nullary(args, || crate::temporal::now_value(&env.now)),
200
        "today" => nullary(args, || crate::temporal::today_value(&env.now)),
201
202
        // --- temporal constructors & component functions (ADR-18) ---
203
        // `time`/`date and time` are the only constructors that can attach a named
204
        // zone (via string parsing); vet it away under the IMMUTABLE policy (RD-10).
205
        // `date` carries no zone, so it needs no vetting.
206
        "date" => date_fn(args),
207
        "time" => env.vet_named_zone(time_fn(args)),
208
        "date and time" => env.vet_named_zone(date_and_time_fn(args)),
209
        "duration" => duration_fn(args),
210
        "years and months duration" => years_and_months_duration_fn(args),
211
        "day of week" => component_str_fn(args, crate::temporal::day_of_week_name),
212
        "month of year" => component_str_fn(args, crate::temporal::month_of_year_name),
213
        "day of year" => component_num_fn(args, crate::temporal::day_of_year_num),
214
        "week of year" => component_num_fn(args, crate::temporal::week_of_year_num),
215
216
        // --- boolean (spec §10.3.4.5) ---
217
        "is" => is_fn(args),
218
219
        // --- range (spec §10.3.4.6) ---
220
        "range" => range_fn(args, env),
221
        // Range/point relations (spec §10.3.4.6, Allen's interval algebra). Each takes
222
        // two arguments, any mix of a point (orderable scalar) and a range value.
223
        "before" | "after" | "meets" | "met by" | "overlaps" | "overlaps before"
224
        | "overlaps after" | "finishes" | "finished by" | "includes" | "during"
225
        | "starts" | "started by" | "coincides" => range_relation(name, args),
226
227
        // Not a built-in: let the caller try a host function (ADR-23).
228
        _ => return None,
229
    })
230
}
231
232
/// Formal parameter names, in positional order, for each named-callable built-in
233
/// (FEEL spec §10.3.4 tables). The names are taken verbatim from the spec so that
234
/// `substring(string: "foobar", start position: 3)` matches exactly.
235
///
236
/// Purely variadic / dual-form aggregates (`min`, `max`, `sum`, `mean`, `product`,
237
/// `median`, `stddev`, `mode`, `all`, `any`) and varargs list builders (`append`,
238
/// `concatenate`, `union`) are **not** in this table: the spec gives them no single
239
/// named-parameter form, and a named call to them should be an error-null.
240
///
241
/// `context put` has two overloads (`key: string` vs `keys: list`); both share the
242
/// same three-element positional signature, so a single row covers both.
243
fn builtin_param_names(name: &str) -> Option<&'static [&'static str]> {
244
    // Spec §10.3.4.1 — conversion functions
245
    // `number(from)` and `number(from, grouping separator, decimal separator)`
246
    // share the same positional order; named callers must supply matching names.
247
    // `date and time(from)` and `date and time(date, time)` are overloaded; the
248
    // 3-slot table covers both (the 1-arg `from` form uses slot 0 only).
249
    Some(match name {
250
        // --- conversion (spec §10.3.4.1) ---
251
        "string" => &["from"],
252
        "number" => &["from", "grouping separator", "decimal separator"],
253
        "duration" => &["from"],
254
        "years and months duration" => &["from", "to"],
255
256
        // --- temporal constructors (spec §10.3.4.1) ---
257
        // `date` has three overloads; the 3-slot table handles all of them
258
        // (single-arg `from` uses slot 0, three-arg form fills all three).
259
        "date" => &["year", "month", "day"],
260
        // `time` has a 4-arg component form; the `from` single-arg form uses slot 0.
261
        "time" => &["hour", "minute", "second", "offset"],
262
        // `date and time` has a 2-arg `(date, time)` form and a 1-arg `from` form.
263
        "date and time" => &["date", "time"],
264
265
        // --- temporal component functions (spec §10.3.4.8) ---
266
        "day of week" => &["date"],
267
        "month of year" => &["date"],
268
        "day of year" => &["date"],
269
        "week of year" => &["date"],
270
271
        // --- boolean (spec §10.3.4.5) ---
272
        "is" => &["value1", "value2"],
273
274
        // --- range (spec §10.3.4.6) ---
275
        "range" => &["from"],
276
277
        // --- string functions (spec §10.3.4.3) ---
278
        "substring" => &["string", "start position", "length"],
279
        "string length" => &["string"],
280
        "upper case" => &["string"],
281
        "lower case" => &["string"],
282
        "substring before" => &["string", "match"],
283
        "substring after" => &["string", "match"],
284
        "contains" => &["string", "match"],
285
        "starts with" => &["string", "match"],
286
        "ends with" => &["string", "match"],
287
        "replace" => &["input", "pattern", "replacement", "flags"],
288
        "matches" => &["input", "pattern", "flags"],
289
        // `split` is named `string, delimiter` in spec Table 75.
290
        "split" => &["string", "delimiter"],
291
        "string join" => &["list", "delimiter"],
292
293
        // --- list functions (spec §10.3.4.4) ---
294
        "list contains" => &["list", "element"],
295
        "count" => &["list"],
296
        "sublist" => &["list", "start position", "length"],
297
        "remove" => &["list", "position"],
298
        "reverse" => &["list"],
299
        "flatten" => &["list"],
300
        "index of" => &["list", "match"],
301
        "distinct values" => &["list"],
302
        "insert before" => &["list", "position", "newItem"],
303
        // `list replace` has two 3-parameter overloads: positional (`position`) and
304
        // matching-function (`match`). `reorder_named` selects the right table based
305
        // on which slot-1 key appears in the named arguments (see its implementation).
306
        // This entry covers the positional overload; the matching overload is handled
307
        // directly in `reorder_named`.
308
        "list replace" => &["list", "position", "newItem"],
309
        "sort" => &["list", "precedes"],
310
311
        // --- context functions (spec §10.3.4.10) ---
312
        "get value" => &["m", "key"],
313
        "get entries" => &["m"],
314
        "context" => &["entries"],
315
        // Both `context put(context, key, value)` and `context put(context, keys, value)`
316
        // share the same positional slots; the `key`/`keys` distinction is resolved by
317
        // the underlying impl, not here.
318
        "context put" => &["context", "key", "value"],
319
        "context merge" => &["contexts"],
320
321
        // --- numeric functions (spec §10.3.4.5) ---
322
        "decimal" => &["n", "scale"],
323
        "floor" => &["n", "scale"],
324
        "ceiling" => &["n", "scale"],
325
        "round up" => &["n", "scale"],
326
        "round down" => &["n", "scale"],
327
        "round half up" => &["n", "scale"],
328
        "round half down" => &["n", "scale"],
329
        "abs" => &["n"],
330
        "modulo" => &["dividend", "divisor"],
331
        "sqrt" => &["number"],
332
        "exp" => &["number"],
333
        "log" => &["number"],
334
        "even" => &["number"],
335
        "odd" => &["number"],
336
337
        // Any other name has no named-parameter table entry.
338
        _ => return None,
339
    })
340
}
341
342
/// Reorder a built-in call's positional + named arguments into the built-in's
343
/// positional parameter order (FEEL spec §10.3.2.13.5 allows named arguments for
344
/// built-ins too). Uses [`builtin_param_names`] to look up the formal parameter
345
/// table, then slots each named argument at its declared index, filling any
346
/// unsupplied trailing optional parameters with [`Value::Null`].
347
///
348
/// Returns `None` when:
349
/// - `name` has no parameter-name table (variadic or unknown built-in), or
350
/// - a named argument refers to an unknown parameter name, or
351
/// - a parameter is supplied both positionally and by name.
352
///
353
/// `None` propagates as an error-null at the call site (the caller tries the host
354
/// function registry next; an unrecognised name still falls through correctly).
355
fn reorder_named(name: &str, args: crate::function::Args) -> Option<Vec<Value>> {
356
    // `list replace` has two 3-parameter overloads with different slot-1 names:
357
    //   position form: (list, position, newItem)  — spec Table 72 §10.3.4.4
358
    //   match form:    (list, match, newItem)      — spec Table 72, function predicate
359
    // Route to the right table based on which slot-1 key appears in the named args.
360
    let params: &[&str] = if name == "list replace" {
361
        if args.named.iter().any(|(k, _)| k == "match") {
362
            &["list", "match", "newItem"]
363
        } else {
364
            &["list", "position", "newItem"]
365
        }
366
    } else {
367
        builtin_param_names(name)?
368
    };
369
370
    let crate::function::Args { positional, named } = args;
371
372
    // More positional arguments than the table has slots -> error-null.
373
    if positional.len() > params.len() {
374
        return None;
375
    }
376
377
    // Start with a slot vector: fill positional slots left to right, leave the
378
    // rest as `None` (not yet supplied).
379
    let mut slots: Vec<Option<Value>> = positional.into_iter().map(Some).collect();
380
    slots.resize(params.len(), None);
381
382
    // Place each named argument at its declared index.
383
    for (arg_name, value) in named {
384
        let idx = params.iter().position(|&p| p == arg_name)?; // unknown name -> None
385
        if slots[idx].is_some() {
386
            return None; // double-supplied (positional + named) -> error-null
387
        }
388
        slots[idx] = Some(value);
389
    }
390
391
    // Determine the effective length: trim trailing None slots that were never
392
    // supplied (the built-in's own arity logic handles optional trailing params).
393
    let last_supplied = slots.iter().rposition(|s| s.is_some());
394
    let take = match last_supplied {
395
        Some(i) => i + 1,
396
        None => 0,
397
    };
398
399
    // Convert to Vec<Value>, substituting Value::Null for any gap that is still
400
    // unsupplied but lies before the last-supplied slot.
401
    let out = slots
402
        .into_iter()
403
        .take(take)
404
        .map(|s| s.unwrap_or(Value::Null))
405
        .collect();
406
407
    Some(out)
408
}
409
410
/// A nullary builtin: produce the value when called with no arguments, else an
411
/// arity error-null.
412
fn nullary(args: Vec<Value>, f: impl FnOnce() -> Value) -> Value {
413
    if args.is_empty() {
414
        f()
415
    } else {
416
        Value::Error
417
    }
418
}
419
420
// --------------------------------------------------------------------------- //
421
// Temporal constructors & component functions (ADR-18)
422
// --------------------------------------------------------------------------- //
423
//
424
// Null-propagation rule: a `null` argument yields a value-null (the TCK expects a
425
// nil result, e.g. `date(2017, null, 1) = null`); a wrong type or out-of-range
426
// component is an error-null. Both collapse to `null` at the lenient boundary.
427
428
/// An integer component argument: a number with no fractional part, a (value-)null,
429
/// or a wrong type.
430
enum IntArg {
431
    Int(i64),
432
    Null,
433
    Err,
434
}
435
436
fn int_arg(v: &Value) -> IntArg {
437
    match v {
438
        Value::Number(n) if n.fract() == 0.0 => IntArg::Int(*n as i64),
439
        Value::Null => IntArg::Null,
440
        _ => IntArg::Err,
441
    }
442
}
443
444
/// A seconds component: an integer-or-fractional number (split into whole seconds
445
/// and nanoseconds), a null, or a wrong type.
446
enum SecArg {
447
    Sec(i64, i64),
448
    Null,
449
    Err,
450
}
451
452
fn sec_arg(v: &Value) -> SecArg {
453
    match v {
454
        Value::Number(n) => {
455
            let whole = n.trunc() as i64;
456
            let nanos = ((n - n.trunc()) * 1e9).round() as i64;
457
            SecArg::Sec(whole, nanos)
458
        }
459
        Value::Null => SecArg::Null,
460
        _ => SecArg::Err,
461
    }
462
}
463
464
fn date_fn(args: Vec<Value>) -> Value {
465
    match args.as_slice() {
466
        [Value::Null] => Value::Null,
467
        [Value::String(s)] => crate::temporal::parse_date(s)
468
            .map(Value::Date)
469
            .unwrap_or(Value::Error),
470
        [Value::Date(d)] => Value::Date(*d),
471
        [Value::DateTime(dt)] => Value::Date(dt.dt.date()),
472
        [y, m, d] => match (int_arg(y), int_arg(m), int_arg(d)) {
473
            (IntArg::Null, _, _) | (_, IntArg::Null, _) | (_, _, IntArg::Null) => Value::Null,
474
            (IntArg::Int(y), IntArg::Int(m), IntArg::Int(d)) => crate::temporal::make_date(y, m, d)
475
                .map(Value::Date)
476
                .unwrap_or(Value::Error),
477
            _ => Value::Error,
478
        },
479
        _ => Value::Error,
480
    }
481
}
482
483
fn time_fn(args: Vec<Value>) -> Value {
484
    match args.as_slice() {
485
        [Value::Null] => Value::Null,
486
        [Value::String(s)] => crate::temporal::parse_time(s)
487
            .map(Value::Time)
488
            .unwrap_or(Value::Error),
489
        [Value::Time(t)] => Value::Time(t.clone()),
490
        [v @ Value::DateTime(_)] => crate::temporal::time_of(v)
491
            .map(Value::Time)
492
            .unwrap_or(Value::Error),
493
        // `time(date)` yields midnight UTC (`00:00:00Z`) per the TCK.
494
        [Value::Date(_)] => Value::Time(crate::temporal::midnight_utc_time()),
495
        [h, m, s] => time_components(h, m, s, None),
496
        [h, m, s, off] => match off {
497
            // A null offset means a local time (no zone), not a null result.
498
            Value::Null => time_components(h, m, s, None),
499
            Value::DaysTimeDuration(d) => match crate::temporal::offset_zone_from_dtd(*d) {
500
                Some(zone) => time_components(h, m, s, Some(zone)),
501
                None => Value::Error,
502
            },
503
            _ => Value::Error,
504
        },
505
        _ => Value::Error,
506
    }
507
}
508
509
fn time_components(h: &Value, m: &Value, s: &Value, zone: Option<crate::temporal::Zone>) -> Value {
510
    match (int_arg(h), int_arg(m), sec_arg(s)) {
511
        (IntArg::Null, _, _) | (_, IntArg::Null, _) | (_, _, SecArg::Null) => Value::Null,
512
        (IntArg::Int(h), IntArg::Int(m), SecArg::Sec(s, nanos)) => {
513
            crate::temporal::make_time(h, m, s, nanos, zone)
514
                .map(Value::Time)
515
                .unwrap_or(Value::Error)
516
        }
517
        _ => Value::Error,
518
    }
519
}
520
521
fn date_and_time_fn(args: Vec<Value>) -> Value {
522
    match args.as_slice() {
523
        [Value::Null] => Value::Null,
524
        [Value::String(s)] => crate::temporal::parse_date_time(s)
525
            .map(Value::DateTime)
526
            .unwrap_or(Value::Error),
527
        [v @ Value::DateTime(_)] => v.clone(),
528
        // `date and time(date-or-datetime, time)`: take the date part of the first
529
        // argument and the second's time (with its zone). The first argument's own
530
        // zone, if any, is dropped.
531
        [a, b] => match (a, b) {
532
            (Value::Null, _) | (_, Value::Null) => Value::Null,
533
            (_, Value::Time(t)) => match crate::temporal::date_of(a) {
534
                Some(d) => Value::DateTime(crate::temporal::combine_date_time(d, t)),
535
                None => Value::Error,
536
            },
537
            _ => Value::Error,
538
        },
539
        _ => Value::Error,
540
    }
541
}
542
543
fn duration_fn(args: Vec<Value>) -> Value {
544
    match args.as_slice() {
545
        [Value::Null] => Value::Null,
546
        [Value::String(s)] => crate::temporal::parse_duration(s).unwrap_or(Value::Error),
547
        _ => Value::Error,
548
    }
549
}
550
551
fn years_and_months_duration_fn(args: Vec<Value>) -> Value {
552
    match args.as_slice() {
553
        [a, b] => match (a, b) {
554
            (Value::Null, _) | (_, Value::Null) => Value::Null,
555
            _ => match (crate::temporal::date_of(a), crate::temporal::date_of(b)) {
556
                (Some(x), Some(y)) => crate::temporal::ym_between(x, y)
557
                    .map(Value::YearsMonthsDuration)
558
                    .unwrap_or(Value::Error),
559
                _ => Value::Error,
560
            },
561
        },
562
        _ => Value::Error,
563
    }
564
}
565
566
/// `day of week` / `month of year`: a string name from a date/date-and-time.
567
fn component_str_fn(args: Vec<Value>, f: fn(jiff::civil::Date) -> &'static str) -> Value {
568
    match args.as_slice() {
569
        [Value::Null] => Value::Null,
570
        [v] => crate::temporal::date_of(v)
571
            .map(|d| Value::String(f(d).to_string()))
572
            .unwrap_or(Value::Error),
573
        _ => Value::Error,
574
    }
575
}
576
577
/// `day of year` / `week of year`: a number from a date/date-and-time.
578
fn component_num_fn(args: Vec<Value>, f: fn(jiff::civil::Date) -> i64) -> Value {
579
    match args.as_slice() {
580
        [Value::Null] => Value::Null,
581
        [v] => crate::temporal::date_of(v)
582
            .map(|d| Value::Number(f(d) as f64))
583
            .unwrap_or(Value::Error),
584
        _ => Value::Error,
585
    }
586
}
587
588
// --------------------------------------------------------------------------- //
589
// Shared helpers
590
// --------------------------------------------------------------------------- //
591
592
/// A numeric argument, distinguishing the three FEEL outcomes: a number, a
593
/// value-null (which most numeric functions propagate as `null`), or a wrong
594
/// type (an error-null).
595
enum NumArg {
596
    Num(f64),
597
    Null,
598
    Err,
599
}
600
601
fn num_arg(v: &Value) -> NumArg {
602
    match v {
603
        Value::Number(n) => NumArg::Num(*n),
604
        Value::Null => NumArg::Null,
605
        _ => NumArg::Err,
606
    }
607
}
608
609
/// The varargs rule for aggregates: a single list argument is the list itself;
610
/// otherwise the arguments *are* the list (so `min(1,2,3)` == `min([1,2,3])`).
611
fn coerce_list(args: Vec<Value>) -> Vec<Value> {
612
    if args.len() == 1 {
613
        if let Value::List(items) = &args[0] {
614
            return items.clone();
615
        }
616
    }
617
    args
618
}
619
620
/// Extract every item as a number, or `None` if any item is not a number.
621
fn numbers(items: &[Value]) -> Option<Vec<f64>> {
622
    items.iter().map(as_number).collect()
623
}
624
625
/// Resolve a 1-based FEEL position (negative counts from the end) to a 0-based
626
/// index in `[0, len]`. Position 0 is invalid. Returns `None` when out of range.
627
pub(crate) fn resolve_index(pos: i64, len: i64) -> Option<i64> {
628
    if pos == 0 {
629
        return None;
630
    }
631
    let idx = if pos > 0 { pos - 1 } else { len + pos };
632
    if idx < 0 || idx > len {
633
        None
634
    } else {
635
        Some(idx)
636
    }
637
}
638
639
// --------------------------------------------------------------------------- //
640
// Boolean
641
// --------------------------------------------------------------------------- //
642
643
/// `is(value1, value2)` (spec §10.3.4.5): value identity — `true` iff both are the
644
/// same FEEL type *and* equal in the value space, `false` otherwise. It never
645
/// returns null (an absent operand counts as `null`, so e.g. `is(value1: x)` is
646
/// `x = null`). This is exactly feel-core's structural `Value` equality:
647
///   * different `Value` variant ⇒ different type ⇒ `false` (`is(@"P0Y", @"P0D")`,
648
///     `is(@"2012-12-25", @"2012-12-25T00:00:00Z")`);
649
///   * durations compare on their normalised magnitude (`is(@"P1D", @"PT24H")`,
650
///     `is(@"P1Y", @"P12M")` are `true`);
651
///   * times/date-times compare on civil value *and* zone representation, where the
652
///     parser already folds `+00:00` into `Z` (so `is(@"…Z", @"…+00:00")` is `true`)
653
///     but keeps a named zone distinct from an offset and from `Z`. It is therefore
654
///     stricter than `=` (which is instant-based for zoned date-times).
655
fn is_fn(args: Vec<Value>) -> Value {
656
    match args.as_slice() {
657
        // One supplied operand: the other is an unsupplied `null` (ADR-23 lenient
658
        // binding), so `is(value1: x) = (x = null)`.
659
        [a] => Value::Boolean(*a == Value::Null),
660
        [a, b] => Value::Boolean(a == b),
661
        _ => Value::Error, // wrong arity (0 or >2)
662
    }
663
}
664
665
// --------------------------------------------------------------------------- //
666
// Range (spec §10.3.4.6)
667
// --------------------------------------------------------------------------- //
668
669
/// `range(from)` (spec §10.3.4.6): parse a string such as `"[1..10)"` into a
670
/// [`Value::Range`]. The argument must be a single string whose content is a range
671
/// *literal* with self-contained literal endpoints (see [`range_endpoint_is_literal`]);
672
/// the resulting range must have two non-null, same-typed, ascending endpoints. Every
673
/// other case — wrong arity, a non-string argument, an unparseable or non-range
674
/// string, a non-literal endpoint, mismatched endpoint types, or a reversed range —
675
/// is an error-null (the TCK's `1156-range-function` expects `null` for all of them).
676
fn range_fn(args: Vec<Value>, env: &EvalEnv) -> Value {
677
    let s = match args.as_slice() {
678
        [Value::String(s)] => s,
679
        _ => return Value::Error, // wrong arity or non-string argument
680
    };
681
    let compiled = match crate::compile(s) {
682
        Ok(c) => c,
683
        Err(_) => return Value::Error, // not a parseable FEEL expression
684
    };
685
    // Shape gate: the string must be a range literal whose endpoints are literals.
686
    // This is why we inspect the AST rather than only evaluating — `date(string("…"))`
687
    // *evaluates* to a date but is not a literal, so the spec wants it to be null.
688
    match compiled.ast() {
689
        crate::ast::Expr::RangeLit(iv) => {
690
            // The `range()` string follows FEEL grammar rule 66 ("range literal"), the
691
            // same rule the value-position literal grammar enforces (ADR-31): a *present*
692
            // endpoint must be a self-contained literal, an *omitted* endpoint is allowed
693
            // only with an OPEN bracket on that side — alternatives (b) `open start ".."
694
            // endpoint end` and (c) `start ".." endpoint open end` — and AT MOST one may
695
            // be omitted. So `range("[2..)")` (≡ `>=2`) and `range("(..2)")` (≡ `<2`) are
696
            // valid, but a CLOSED bracket with no value, or BOTH endpoints omitted (no
697
            // rule-66 alternative), is null: `range("[..2]")` / `range("[1..]")` (DMN-TCK
698
            // 1156 004_e/004_f), `range("[..]")` / `range("(..)")`. (For range() the
699
            // value-position grammar already rejects the closed/both-omitted strings at
700
            // `compile` above; these checks are the defensive belt-and-suspenders.)
701
            let side_ok = |e: &Option<Box<crate::ast::Expr>>, open: bool| match e {
702
                Some(e) => range_endpoint_is_literal(e),
703
                None => open, // omitted ⇒ the bracket on that side must be open
704
            };
705
            if matches!((&iv.start, &iv.end), (None, None))
706
                || !side_ok(&iv.start, iv.start_open)
707
                || !side_ok(&iv.end, iv.end_open)
708
            {
709
                return Value::Error;
710
            }
711
        }
712
        _ => return Value::Error, // a non-range expression (`">=10"`, `"[1,2,3]"`, …)
713
    }
714
    // Endpoints are literals, so an empty context suffices; the env still carries the
715
    // (unused) clock/zone policy the temporal constructors expect.
716
    let r = match compiled.evaluate_with_env(&crate::Context::empty(), env) {
717
        Ok(Value::Range(r)) => r,
718
        _ => return Value::Error,
719
    };
720
    // A well-formed range has, for every *present* endpoint, an orderable non-null
721
    // value, and — when both are present — the two in non-descending order. An
722
    // unbounded side imposes no ordering. `feel_order` returns `None` for
723
    // null/mismatched types, so `range("[null..)")` and `range("[1..\"b\"]")` stay null.
724
    let ok = match (&r.start, &r.end) {
725
        (Some(s), Some(e)) => matches!(feel_order(s, e), Some(ord) if ord != Ordering::Greater),
726
        (Some(v), None) | (None, Some(v)) => feel_order(v, v).is_some(),
727
        (None, None) => false, // gated above; unreachable
728
    };
729
    if ok {
730
        Value::Range(r)
731
    } else {
732
        Value::Error
733
    }
734
}
735
736
/// Is `e` an admissible *literal* endpoint for [`range_fn`] (DMN §10.3.4.6)? Allowed:
737
/// a number / string / `@"…"` temporal literal / `null`, or a temporal *constructor*
738
/// applied directly to a single string literal (`date("…")`, `time("…")`,
739
/// `duration("…")`, `date and time("…")`). Anything richer — a variable, an
740
/// arithmetic expression, or a nested call like `date(string("…"))` — is rejected, so
741
/// `range("[date(input)..…]")` and `range("[date(string(\"…\"))..…]")` are null.
742
fn range_endpoint_is_literal(e: &crate::ast::Expr) -> bool {
743
    use crate::ast::Expr;
744
    match e {
745
        Expr::Number(_) | Expr::Str(_) | Expr::TemporalLit(_) | Expr::Null => true,
746
        Expr::FnCall(name, args) => {
747
            matches!(name.as_str(), "date" | "time" | "duration" | "date and time")
748
                && args.named.is_empty()
749
                && matches!(args.positional.as_slice(), [Expr::Str(_)])
750
        }
751
        _ => false,
752
    }
753
}
754
755
/// One endpoint of an interval for the §10.3.4.6 relations: a concrete value, or an
756
/// *unbounded* bound (`±∞`; ADR-31). A range's lower bound is `NegInf` when omitted,
757
/// its upper bound `PosInf`; `±∞` compares below/above every concrete value, so the
758
/// Allen formulas below need no further special-casing.
759
#[derive(Clone, Copy)]
760
enum Bound<'a> {
761
    NegInf,
762
    Val(&'a Value),
763
    PosInf,
764
}
765
766
/// A point or range viewed uniformly as an interval with two endpoints and their
767
/// inclusion. A *point* `p` is the degenerate closed interval `[p..p]`, which makes
768
/// the range/range relation formulas below cover every point/range overload of the
769
/// §10.3.4.6 relations with a single definition each (verified against `1130`).
770
struct Iv<'a> {
771
    start: Bound<'a>,
772
    /// Lower bound *excluded* (the `(`/`]` openness flag). Canonically `false` when
773
    /// the bound is unbounded, where openness is meaningless (ADR-31).
774
    start_open: bool,
775
    end: Bound<'a>,
776
    /// Upper bound *excluded* (the `)`/`[` openness flag). Canonically `false` when
777
    /// unbounded.
778
    end_open: bool,
779
}
780
781
/// View a value as an interval: a range as itself (an omitted endpoint becoming
782
/// `±∞`), an orderable scalar (number, string, or any temporal) as the closed point
783
/// interval `[v..v]`. Anything else (boolean, list, context, null, …) has no order,
784
/// so it is not a valid relation operand -> `None` (an error-null at the call site).
785
/// The openness flag of an unbounded side is forced to `false` so the formulas treat
786
/// two `±∞` of the same sign as coinciding regardless of the brackets written.
787
fn as_interval(v: &Value) -> Option<Iv<'_>> {
788
    match v {
789
        Value::Range(r) => Some(Iv {
790
            start: r.start.as_ref().map_or(Bound::NegInf, Bound::Val),
791
            start_open: r.start.is_some() && r.start_open,
792
            end: r.end.as_ref().map_or(Bound::PosInf, Bound::Val),
793
            end_open: r.end.is_some() && r.end_open,
794
        }),
795
        Value::Number(_) | Value::String(_) => Some(Iv {
796
            start: Bound::Val(v),
797
            start_open: false,
798
            end: Bound::Val(v),
799
            end_open: false,
800
        }),
801
        _ if crate::temporal::is_temporal(v) => Some(Iv {
802
            start: Bound::Val(v),
803
            start_open: false,
804
            end: Bound::Val(v),
805
            end_open: false,
806
        }),
807
        _ => None,
808
    }
809
}
810
811
/// Evaluate a §10.3.4.6 range/point relation named `name` over two operands. Each
812
/// operand is viewed as an interval ([`as_interval`]); incomparable or non-orderable
813
/// operands (a type mismatch, a `null` endpoint, a boolean/list operand) yield an
814
/// error-null. Arity must be exactly two.
815
fn range_relation(name: &str, args: Vec<Value>) -> Value {
816
    let [a, b] = match <[Value; 2]>::try_from(args) {
817
        Ok(pair) => pair,
818
        Err(_) => return Value::Error, // wrong arity
819
    };
820
    let (a, b) = match (as_interval(&a), as_interval(&b)) {
821
        (Some(a), Some(b)) => (a, b),
822
        _ => return Value::Error,
823
    };
824
    // The 13 relations reduce to 8 base shapes; the rest are the same shape with the
825
    // operands swapped (e.g. `after = before(b, a)`, `during = includes(b, a)`).
826
    let held = match name {
827
        "before" => rel_before(&a, &b),
828
        "after" => rel_before(&b, &a),
829
        "meets" => rel_meets(&a, &b),
830
        "met by" => rel_meets(&b, &a),
831
        "overlaps" => rel_overlaps(&a, &b),
832
        "overlaps before" => rel_overlaps_before(&a, &b),
833
        "overlaps after" => rel_overlaps_before(&b, &a),
834
        "finishes" => rel_finishes(&a, &b),
835
        "finished by" => rel_finishes(&b, &a),
836
        "includes" => rel_includes(&a, &b),
837
        "during" => rel_includes(&b, &a),
838
        "starts" => rel_starts(&a, &b),
839
        "started by" => rel_starts(&b, &a),
840
        "coincides" => rel_coincides(&a, &b),
841
        _ => return Value::Error,
842
    };
843
    match held {
844
        Some(t) => Value::Boolean(t),
845
        None => Value::Error, // an endpoint comparison was incomparable (type/null)
846
    }
847
}
848
849
/// Order two endpoints, `None` if incomparable (different types or a `null`). An
850
/// unbounded bound (`±∞`; ADR-31) compares below/above every concrete value; two
851
/// `±∞` of the same sign are equal (so e.g. `coincides([..5], [..5])` holds).
852
fn ep_cmp(x: Bound, y: Bound) -> Option<Ordering> {
853
    match (x, y) {
854
        (Bound::NegInf, Bound::NegInf) | (Bound::PosInf, Bound::PosInf) => Some(Ordering::Equal),
855
        (Bound::NegInf, _) | (_, Bound::PosInf) => Some(Ordering::Less),
856
        (Bound::PosInf, _) | (_, Bound::NegInf) => Some(Ordering::Greater),
857
        (Bound::Val(a), Bound::Val(b)) => feel_order(a, b),
858
    }
859
}
860
861
// The base relations (DMN §10.3.4.6), each over inclusion-aware endpoints. `?` on the
862
// endpoint comparisons makes any incomparable pair short-circuit to an error-null.
863
// `start_open`/`end_open` are the *excluded* flags, so "included" is their negation.
864
865
fn rel_before(a: &Iv, b: &Iv) -> Option<bool> {
866
    // a.end < b.start, or they touch at an excluded boundary.
867
    let es = ep_cmp(a.end, b.start)?;
868
    Some(es == Ordering::Less || (es == Ordering::Equal && (a.end_open || b.start_open)))
869
}
870
871
fn rel_meets(a: &Iv, b: &Iv) -> Option<bool> {
872
    // a.end included, b.start included, and a.end = b.start.
873
    let es = ep_cmp(a.end, b.start)?;
874
    Some(!a.end_open && !b.start_open && es == Ordering::Equal)
875
}
876
877
fn rel_overlaps(a: &Iv, b: &Iv) -> Option<bool> {
878
    let es = ep_cmp(a.end, b.start)?;
879
    let se = ep_cmp(a.start, b.end)?;
880
    let upper = es == Ordering::Greater || (es == Ordering::Equal && !a.end_open && !b.start_open);
881
    let lower = se == Ordering::Less || (se == Ordering::Equal && !a.start_open && !b.end_open);
882
    Some(upper && lower)
883
}
884
885
fn rel_overlaps_before(a: &Iv, b: &Iv) -> Option<bool> {
886
    let ss = ep_cmp(a.start, b.start)?;
887
    let es = ep_cmp(a.end, b.start)?;
888
    let ee = ep_cmp(a.end, b.end)?;
889
    let starts_before =
890
        ss == Ordering::Less || (ss == Ordering::Equal && !a.start_open && b.start_open);
891
    let reaches_into =
892
        es == Ordering::Greater || (es == Ordering::Equal && !a.end_open && !b.start_open);
893
    let ends_before =
894
        ee == Ordering::Less || (ee == Ordering::Equal && (a.end_open || !b.end_open));
895
    Some(starts_before && reaches_into && ends_before)
896
}
897
898
fn rel_finishes(a: &Iv, b: &Iv) -> Option<bool> {
899
    // Same end (value + inclusion), and a starts strictly inside-or-at b's start.
900
    let ss = ep_cmp(a.start, b.start)?;
901
    let ee = ep_cmp(a.end, b.end)?;
902
    let starts_after =
903
        ss == Ordering::Greater || (ss == Ordering::Equal && (a.start_open || !b.start_open));
904
    Some(a.end_open == b.end_open && ee == Ordering::Equal && starts_after)
905
}
906
907
fn rel_includes(a: &Iv, b: &Iv) -> Option<bool> {
908
    // a's start is at/below b's and a's end is at/above b's (inclusion-aware).
909
    let ss = ep_cmp(a.start, b.start)?;
910
    let ee = ep_cmp(a.end, b.end)?;
911
    let lower = ss == Ordering::Less || (ss == Ordering::Equal && (!a.start_open || b.start_open));
912
    let upper = ee == Ordering::Greater || (ee == Ordering::Equal && (!a.end_open || b.end_open));
913
    Some(lower && upper)
914
}
915
916
fn rel_starts(a: &Iv, b: &Iv) -> Option<bool> {
917
    // Same start (value + inclusion), and a ends strictly inside-or-at b's end.
918
    let ss = ep_cmp(a.start, b.start)?;
919
    let ee = ep_cmp(a.end, b.end)?;
920
    let ends_before = ee == Ordering::Less || (ee == Ordering::Equal && (a.end_open || !b.end_open));
921
    Some(ss == Ordering::Equal && a.start_open == b.start_open && ends_before)
922
}
923
924
fn rel_coincides(a: &Iv, b: &Iv) -> Option<bool> {
925
    let ss = ep_cmp(a.start, b.start)?;
926
    let ee = ep_cmp(a.end, b.end)?;
927
    Some(
928
        ss == Ordering::Equal
929
            && a.start_open == b.start_open
930
            && ee == Ordering::Equal
931
            && a.end_open == b.end_open,
932
    )
933
}
934
935
// --------------------------------------------------------------------------- //
936
// Conversion
937
// --------------------------------------------------------------------------- //
938
939
fn string_fn(args: Vec<Value>) -> Value {
940
    match args.as_slice() {
941
        [Value::Null] => Value::Null, // string(null) = null
942
        [v] => Value::String(value_to_string(v)),
943
        _ => Value::Error,
944
    }
945
}
946
947
fn value_to_string(v: &Value) -> String {
948
    match v {
949
        Value::Number(n) => format_number(*n),
950
        Value::Boolean(b) => b.to_string(),
951
        Value::String(s) => s.clone(),
952
        Value::List(items) => {
953
            let inner: Vec<String> = items.iter().map(render_member).collect();
954
            format!("[{}]", inner.join(", "))
955
        }
956
        Value::Context(map) => {
957
            let inner: Vec<String> = map
958
                .iter()
959
                .map(|(k, v)| format!("{k}: {}", render_member(v)))
960
                .collect();
961
            format!("{{{}}}", inner.join(", "))
962
        }
963
        // Temporal values stringify to their canonical ISO-8601 form (ADR-18).
964
        Value::Date(_)
965
        | Value::Time(_)
966
        | Value::DateTime(_)
967
        | Value::YearsMonthsDuration(_)
968
        | Value::DaysTimeDuration(_) => {
969
            crate::temporal::to_iso(v).unwrap_or_else(|| "null".to_string())
970
        }
971
        // A lazy host value (e.g. a list element that is a `Foreign`) is forced
972
        // one level and rendered as the materialised value (ADR-21).
973
        Value::Foreign(f) => value_to_string(&f.0.force()),
974
        // A function value has no FEEL string form; render an opaque marker (ADR-23).
975
        Value::Function(_) => "function".to_string(),
976
        // A range renders in interval notation, e.g. `[1..10)` / `["a".."c"]`; the
977
        // endpoints are quoted as list members are (so strings keep their quotes). An
978
        // unbounded endpoint (`None`; ADR-31) renders as nothing, echoing the bracket
979
        // the user wrote: `[1..)`, `(..10)`.
980
        Value::Range(r) => format!(
981
            "{}{}..{}{}",
982
            if r.start_open { '(' } else { '[' },
983
            r.start.as_ref().map(render_member).unwrap_or_default(),
984
            r.end.as_ref().map(render_member).unwrap_or_default(),
985
            if r.end_open { ')' } else { ']' },
986
        ),
987
        // An opaque comparison-test value `(< 10)` (ADR-32) renders in its written
988
        // parenthesised form, `(< 10)` / `(= 10)` / `(!= 10)`, with the endpoint quoted
989
        // as a list member is (so a string endpoint keeps its quotes).
990
        Value::UnaryTestVal(t) => {
991
            format!("({} {})", cmp_op_str(t.op), render_member(&t.endpoint))
992
        }
993
        Value::Null | Value::Error => "null".to_string(),
994
    }
995
}
996
997
/// The FEEL source spelling of a comparison operator (for stringifying a
998
/// [`Value::UnaryTestVal`]).
999
fn cmp_op_str(op: crate::ast::CmpOp) -> &'static str {
1000
    use crate::ast::CmpOp::*;
1001
    match op {
1002
        Lt => "<",
1003
        Le => "<=",
1004
        Gt => ">",
1005
        Ge => ">=",
1006
        Eq => "=",
1007
        Ne => "!=",
1008
    }
1009
}
1010
1011
/// Render a value as it appears *inside* a list/context string (strings quoted).
1012
fn render_member(v: &Value) -> String {
1013
    match v {
1014
        Value::String(s) => format!("\"{s}\""),
1015
        other => value_to_string(other),
1016
    }
1017
}
1018
1019
/// FEEL number formatting: no trailing `.0` for integers, `-0` normalised to `0`.
1020
fn format_number(n: f64) -> String {
1021
    if n == 0.0 {
1022
        return "0".to_string();
1023
    }
1024
    format!("{n}")
1025
}
1026
1027
fn number_fn(args: Vec<Value>) -> Value {
1028
    let parse = |s: &str, grouping: Option<&str>, decimal: Option<&str>| -> Value {
1029
        let mut t = s.to_string();
1030
        if let Some(g) = grouping {
1031
            if !g.is_empty() {
1032
                t = t.replace(g, "");
1033
            }
1034
        }
1035
        if let Some(d) = decimal {
1036
            if !d.is_empty() && d != "." {
1037
                t = t.replace(d, ".");
1038
            }
1039
        }
1040
        match t.trim().parse::<f64>() {
1041
            Ok(n) if n.is_finite() => Value::Number(n),
1042
            _ => Value::Error, // malformed -> domain error
1043
        }
1044
    };
1045
    match args.as_slice() {
1046
        [Value::Number(n)] => Value::Number(*n), // number(5) = 5
1047
        [Value::String(s)] => parse(s, None, None),
1048
        [Value::Null] => Value::Null,
1049
        [from, grouping, decimal] => {
1050
            let s = match from {
1051
                Value::String(s) => s,
1052
                Value::Null => return Value::Null,
1053
                _ => return Value::Error,
1054
            };
1055
            let (g, d) = match (separator(grouping), separator(decimal)) {
1056
                (Ok(g), Ok(d)) => (g, d),
1057
                _ => return Value::Error,
1058
            };
1059
            // Spec footnote 1: grouping SHALL be space/comma/period/null; decimal
1060
            // SHALL be period/comma/null; and they SHALL differ unless both null.
1061
            let g_ok = matches!(g.as_deref(), None | Some(" " | "," | "."));
1062
            let d_ok = matches!(d.as_deref(), None | Some("." | ","));
1063
            if !g_ok || !d_ok || (g.is_some() && g == d) {
1064
                return Value::Error;
1065
            }
1066
            parse(s, g.as_deref(), d.as_deref())
1067
        }
1068
        _ => Value::Error,
1069
    }
1070
}
1071
1072
/// A grouping/decimal separator argument: a string, or null (meaning "none").
1073
fn separator(v: &Value) -> Result<Option<String>, ()> {
1074
    match v {
1075
        Value::Null => Ok(None),
1076
        Value::String(s) => Ok(Some(s.clone())),
1077
        _ => Err(()),
1078
    }
1079
}
1080
1081
// --------------------------------------------------------------------------- //
1082
// String
1083
// --------------------------------------------------------------------------- //
1084
1085
fn substring_fn(args: Vec<Value>) -> Value {
1086
    let (string_v, start_v, len_v) = match args.len() {
1087
        2 => (&args[0], &args[1], None),
1088
        3 => (&args[0], &args[1], Some(&args[2])),
1089
        _ => return Value::Error,
1090
    };
1091
    let s = match string_v {
1092
        Value::String(s) => s,
1093
        Value::Null => return Value::Null,
1094
        _ => return Value::Error,
1095
    };
1096
    let start = match num_arg(start_v) {
1097
        NumArg::Num(n) => n.trunc() as i64,
1098
        NumArg::Null => return Value::Null,
1099
        NumArg::Err => return Value::Error,
1100
    };
1101
    let chars: Vec<char> = s.chars().collect();
1102
    let n = chars.len() as i64;
1103
    let Some(from0) = resolve_index(start, n) else {
1104
        return Value::Error;
1105
    };
1106
    let avail = n - from0;
1107
    let take = match len_v {
1108
        None => avail,
1109
        Some(lv) => match num_arg(lv) {
1110
            NumArg::Num(l) => {
1111
                let l = l.trunc() as i64;
1112
                if l < 0 {
1113
                    return Value::Error;
1114
                }
1115
                l.min(avail)
1116
            }
1117
            NumArg::Null => return Value::Null,
1118
            NumArg::Err => return Value::Error,
1119
        },
1120
    };
1121
    let result: String = chars[from0 as usize..(from0 + take) as usize]
1122
        .iter()
1123
        .collect();
1124
    Value::String(result)
1125
}
1126
1127
fn contains_fn(args: Vec<Value>) -> Value {
1128
    match args.as_slice() {
1129
        [Value::String(s), Value::String(m)] => Value::Boolean(s.contains(m.as_str())),
1130
        [Value::Null, _] | [_, Value::Null] => Value::Null,
1131
        _ => Value::Error,
1132
    }
1133
}
1134
1135
fn string_length_fn(args: Vec<Value>) -> Value {
1136
    match args.as_slice() {
1137
        // FEEL string length counts code points, not UTF-8 bytes.
1138
        [Value::String(s)] => Value::Number(s.chars().count() as f64),
1139
        [Value::Null] => Value::Null,
1140
        _ => Value::Error,
1141
    }
1142
}
1143
1144
fn case_fn(args: Vec<Value>, upper: bool) -> Value {
1145
    match args.as_slice() {
1146
        [Value::String(s)] => Value::String(if upper {
1147
            s.to_uppercase()
1148
        } else {
1149
            s.to_lowercase()
1150
        }),
1151
        [Value::Null] => Value::Null,
1152
        _ => Value::Error,
1153
    }
1154
}
1155
1156
fn starts_ends_with_fn(args: Vec<Value>, starts: bool) -> Value {
1157
    match args.as_slice() {
1158
        [Value::String(s), Value::String(m)] => Value::Boolean(if starts {
1159
            s.starts_with(m.as_str())
1160
        } else {
1161
            s.ends_with(m.as_str())
1162
        }),
1163
        [Value::Null, _] | [_, Value::Null] => Value::Null,
1164
        _ => Value::Error,
1165
    }
1166
}
1167
1168
/// `substring before`/`substring after`: split `string` at the **first**
1169
/// occurrence of `match`. Not found (for a non-empty match) is `""`. An empty
1170
/// match sits at position 0, so `before` is `""` and `after` is the whole string.
1171
fn substring_before_after_fn(args: Vec<Value>, before: bool) -> Value {
1172
    match args.as_slice() {
1173
        [Value::String(s), Value::String(m)] => {
1174
            // A byte offset from `find` is always a valid char boundary because it
1175
            // is the start of an actual substring match.
1176
            let part = match s.find(m.as_str()) {
1177
                Some(p) if before => &s[..p],
1178
                Some(p) => &s[p + m.len()..],
1179
                None => "",
1180
            };
1181
            Value::String(part.to_string())
1182
        }
1183
        [Value::Null, _] | [_, Value::Null] => Value::Null,
1184
        _ => Value::Error,
1185
    }
1186
}
1187
1188
/// `string join(list[, delimiter])`: concatenate the string items of `list`,
1189
/// joined by `delimiter` (absent/null → no separator). Null items are skipped; a
1190
/// non-string, non-null item is a type error. A scalar string argument is treated
1191
/// as a one-element list. Other arities (0, 3, …) and non-list/-string arguments
1192
/// are errors (per DMN-TCK 1140).
1193
fn string_join_fn(args: Vec<Value>) -> Value {
1194
    let (list_v, delim) = match args.as_slice() {
1195
        [l] => (l, String::new()),
1196
        [l, d] => {
1197
            let d = match d {
1198
                Value::String(s) => s.clone(),
1199
                Value::Null => String::new(),
1200
                _ => return Value::Error,
1201
            };
1202
            (l, d)
1203
        }
1204
        _ => return Value::Error,
1205
    };
1206
    let items = match list_v {
1207
        Value::List(items) => items.clone(),
1208
        Value::String(s) => vec![Value::String(s.clone())],
1209
        Value::Null => return Value::Null,
1210
        _ => return Value::Error,
1211
    };
1212
    let mut parts: Vec<String> = Vec::new();
1213
    for it in &items {
1214
        match it {
1215
            Value::String(s) => parts.push(s.clone()),
1216
            Value::Null => {} // null entries are skipped
1217
            _ => return Value::Error,
1218
        }
1219
    }
1220
    Value::String(parts.join(&delim))
1221
}
1222
1223
// --------------------------------------------------------------------------- //
1224
// String (regex) — dialect-dependent; the actual engine is the host's (ADR-16).
1225
// These functions only sort out the FEEL argument shapes and hand pattern +
1226
// flags to the provider; `None` from the provider means "invalid in this
1227
// dialect" -> FEEL null.
1228
// --------------------------------------------------------------------------- //
1229
1230
fn matches_fn(args: Vec<Value>, regex: &dyn FeelRegex) -> Value {
1231
    if !regex.available() {
1232
        return Value::Error; // no regex engine in this build -> error-null
1233
    }
1234
    let (input_v, pattern_v, flags_v) = match args.len() {
1235
        2 => (&args[0], &args[1], None),
1236
        3 => (&args[0], &args[1], Some(&args[2])),
1237
        _ => return Value::Error,
1238
    };
1239
    let (Some(input), Some(pattern)) = (as_str_arg(input_v), as_str_arg(pattern_v)) else {
1240
        return str_arg_null_or_error(&[input_v, pattern_v]);
1241
    };
1242
    let flags = match flags_str(flags_v) {
1243
        Ok(f) => f,
1244
        Err(()) => return Value::Error,
1245
    };
1246
    match_value(regex.is_match(&input, &pattern, &flags))
1247
}
1248
1249
fn replace_fn(args: Vec<Value>, regex: &dyn FeelRegex) -> Value {
1250
    if !regex.available() {
1251
        return Value::Error; // no regex engine in this build -> error-null
1252
    }
1253
    let (input_v, pattern_v, repl_v, flags_v) = match args.len() {
1254
        3 => (&args[0], &args[1], &args[2], None),
1255
        4 => (&args[0], &args[1], &args[2], Some(&args[3])),
1256
        _ => return Value::Error,
1257
    };
1258
    let (Some(input), Some(pattern), Some(repl)) = (
1259
        as_str_arg(input_v),
1260
        as_str_arg(pattern_v),
1261
        as_str_arg(repl_v),
1262
    ) else {
1263
        return str_arg_null_or_error(&[input_v, pattern_v, repl_v]);
1264
    };
1265
    let flags = match flags_str(flags_v) {
1266
        Ok(f) => f,
1267
        Err(()) => return Value::Error,
1268
    };
1269
    match regex.replace(&input, &pattern, &repl, &flags) {
1270
        Some(s) => Value::String(s),
1271
        None => Value::Null,
1272
    }
1273
}
1274
1275
fn split_fn(args: Vec<Value>, regex: &dyn FeelRegex) -> Value {
1276
    if !regex.available() {
1277
        return Value::Error; // no regex engine in this build -> error-null
1278
    }
1279
    match args.as_slice() {
1280
        [Value::String(s), Value::String(delim)] => match regex.split(s, delim) {
1281
            Some(parts) => Value::List(parts.into_iter().map(Value::String).collect()),
1282
            None => Value::Null,
1283
        },
1284
        [Value::Null, _] | [_, Value::Null] => Value::Null,
1285
        _ => Value::Error,
1286
    }
1287
}
1288
1289
fn as_str_arg(v: &Value) -> Option<String> {
1290
    match v {
1291
        Value::String(s) => Some(s.clone()),
1292
        _ => None,
1293
    }
1294
}
1295
1296
/// When a string-typed argument wasn't a string: `null` if any was a value-null
1297
/// (propagate), otherwise an error-null (wrong type).
1298
fn str_arg_null_or_error(args: &[&Value]) -> Value {
1299
    if args.iter().any(|a| matches!(a, Value::Null)) {
1300
        Value::Null
1301
    } else {
1302
        Value::Error
1303
    }
1304
}
1305
1306
/// An optional `flags` argument -> its string (absent/null -> `""`).
1307
fn flags_str(v: Option<&Value>) -> Result<String, ()> {
1308
    match v {
1309
        None | Some(Value::Null) => Ok(String::new()),
1310
        Some(Value::String(s)) => Ok(s.clone()),
1311
        Some(_) => Err(()),
1312
    }
1313
}
1314
1315
// --------------------------------------------------------------------------- //
1316
// List
1317
// --------------------------------------------------------------------------- //
1318
1319
fn count_fn(args: Vec<Value>) -> Value {
1320
    match args.as_slice() {
1321
        [Value::List(items)] => Value::Number(items.len() as f64),
1322
        [Value::Null] => Value::Null,
1323
        _ => Value::Error,
1324
    }
1325
}
1326
1327
fn min_max_fn(args: Vec<Value>, is_min: bool) -> Value {
1328
    let items = coerce_list(args);
1329
    if items.is_empty() {
1330
        return Value::Null; // min([]) / max([]) = null
1331
    }
1332
    let mut best = &items[0];
1333
    for it in &items[1..] {
1334
        match feel_order(it, best) {
1335
            Some(ord) => {
1336
                let take = if is_min {
1337
                    ord == Ordering::Less
1338
                } else {
1339
                    ord == Ordering::Greater
1340
                };
1341
                if take {
1342
                    best = it;
1343
                }
1344
            }
1345
            None => return Value::Error, // incomparable / non-orderable item
1346
        }
1347
    }
1348
    // A single, non-orderable item (e.g. a boolean) is still a type error.
1349
    if feel_order(best, best).is_none() {
1350
        return Value::Error;
1351
    }
1352
    best.clone()
1353
}
1354
1355
fn sum_fn(args: Vec<Value>) -> Value {
1356
    let items = coerce_list(args);
1357
    if items.is_empty() {
1358
        return Value::Null;
1359
    }
1360
    match numbers(&items) {
1361
        Some(ns) => Value::Number(ns.iter().sum()),
1362
        None => Value::Error,
1363
    }
1364
}
1365
1366
fn mean_fn(args: Vec<Value>) -> Value {
1367
    let items = coerce_list(args);
1368
    if items.is_empty() {
1369
        return Value::Null;
1370
    }
1371
    match numbers(&items) {
1372
        Some(ns) => Value::Number(ns.iter().sum::<f64>() / ns.len() as f64),
1373
        None => Value::Error,
1374
    }
1375
}
1376
1377
fn product_fn(args: Vec<Value>) -> Value {
1378
    let items = coerce_list(args);
1379
    if items.is_empty() {
1380
        return Value::Null;
1381
    }
1382
    match numbers(&items) {
1383
        Some(ns) => Value::Number(ns.iter().product()),
1384
        None => Value::Error,
1385
    }
1386
}
1387
1388
fn median_fn(args: Vec<Value>) -> Value {
1389
    let items = coerce_list(args);
1390
    if items.is_empty() {
1391
        return Value::Null;
1392
    }
1393
    let Some(mut ns) = numbers(&items) else {
1394
        return Value::Error;
1395
    };
1396
    ns.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
1397
    let n = ns.len();
1398
    let med = if n % 2 == 1 {
1399
        ns[n / 2]
1400
    } else {
1401
        (ns[n / 2 - 1] + ns[n / 2]) / 2.0
1402
    };
1403
    Value::Number(med)
1404
}
1405
1406
fn stddev_fn(args: Vec<Value>) -> Value {
1407
    let items = coerce_list(args);
1408
    let Some(ns) = numbers(&items) else {
1409
        return Value::Error;
1410
    };
1411
    if ns.len() < 2 {
1412
        return Value::Null; // sample stddev undefined for < 2 elements
1413
    }
1414
    let mean = ns.iter().sum::<f64>() / ns.len() as f64;
1415
    let var = ns.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (ns.len() - 1) as f64;
1416
    Value::Number(var.sqrt())
1417
}
1418
1419
fn mode_fn(args: Vec<Value>) -> Value {
1420
    if args.is_empty() {
1421
        return Value::Null; // mode() (N=0 vararg form) -> null; mode([]) -> []
1422
    }
1423
    let items = coerce_list(args);
1424
    let Some(ns) = numbers(&items) else {
1425
        return Value::Error;
1426
    };
1427
    if ns.is_empty() {
1428
        return Value::List(vec![]); // mode([]) = []
1429
    }
1430
    // f64 is not hashable; tally with a small association list.
1431
    let mut counts: Vec<(f64, usize)> = Vec::new();
1432
    for &x in &ns {
1433
        if let Some(entry) = counts.iter_mut().find(|(v, _)| *v == x) {
1434
            entry.1 += 1;
1435
        } else {
1436
            counts.push((x, 1));
1437
        }
1438
    }
1439
    let max = counts.iter().map(|(_, c)| *c).max().unwrap();
1440
    let mut modes: Vec<f64> = counts
1441
        .iter()
1442
        .filter(|(_, c)| *c == max)
1443
        .map(|(v, _)| *v)
1444
        .collect();
1445
    modes.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
1446
    Value::List(modes.into_iter().map(Value::Number).collect())
1447
}
1448
1449
fn all_any_fn(args: Vec<Value>, is_all: bool) -> Value {
1450
    if args.is_empty() {
1451
        // `all()`/`any()` with no arguments is the degenerate N=0 vararg form
1452
        // (undefined) -> null. Distinct from `all([])`/`any([])` (the empty
1453
        // list), which are true/false respectively.
1454
        return Value::Null;
1455
    }
1456
    let items = coerce_list(args);
1457
    let mut saw_unknown = false;
1458
    let mut tainted = false;
1459
    for it in &items {
1460
        match it {
1461
            Value::Boolean(b) => {
1462
                if is_all && !b {
1463
                    return Value::Boolean(false);
1464
                }
1465
                if !is_all && *b {
1466
                    return Value::Boolean(true);
1467
                }
1468
            }
1469
            Value::Null => saw_unknown = true,
1470
            _ => {
1471
                saw_unknown = true;
1472
                tainted = true; // a non-boolean item is a type error
1473
            }
1474
        }
1475
    }
1476
    if saw_unknown {
1477
        return if tainted { Value::Error } else { Value::Null };
1478
    }
1479
    // No dominating value and no unknowns -> all(...) = true, any(...) = false
1480
    // (also the empty-list case: all([]) = true, any([]) = false).
1481
    Value::Boolean(is_all)
1482
}
1483
1484
fn append_fn(args: Vec<Value>) -> Value {
1485
    match args.split_first() {
1486
        Some((Value::List(items), rest)) => {
1487
            let mut out = items.clone();
1488
            out.extend(rest.iter().cloned());
1489
            Value::List(out)
1490
        }
1491
        Some((Value::Null, _)) => Value::Null,
1492
        _ => Value::Error,
1493
    }
1494
}
1495
1496
fn concatenate_fn(args: Vec<Value>) -> Value {
1497
    let mut out = Vec::new();
1498
    for a in &args {
1499
        match a {
1500
            Value::List(items) => out.extend(items.iter().cloned()),
1501
            Value::Null => return Value::Null,
1502
            _ => return Value::Error,
1503
        }
1504
    }
1505
    Value::List(out)
1506
}
1507
1508
fn union_fn(args: Vec<Value>) -> Value {
1509
    let mut out: Vec<Value> = Vec::new();
1510
    for a in &args {
1511
        match a {
1512
            Value::List(items) => {
1513
                for it in items {
1514
                    if !out.iter().any(|x| x == it) {
1515
                        out.push(it.clone());
1516
                    }
1517
                }
1518
            }
1519
            Value::Null => return Value::Null,
1520
            _ => return Value::Error,
1521
        }
1522
    }
1523
    Value::List(out)
1524
}
1525
1526
fn remove_fn(args: Vec<Value>) -> Value {
1527
    match args.as_slice() {
1528
        [Value::List(items), pos_v] => {
1529
            let pos = match num_arg(pos_v) {
1530
                NumArg::Num(p) => p.trunc() as i64,
1531
                NumArg::Null => return Value::Null,
1532
                NumArg::Err => return Value::Error,
1533
            };
1534
            let n = items.len() as i64;
1535
            // `position` indexes an existing element, so it must be < len.
1536
            match resolve_index(pos, n) {
1537
                Some(idx) if idx < n => {
1538
                    let mut out = items.clone();
1539
                    out.remove(idx as usize);
1540
                    Value::List(out)
1541
                }
1542
                _ => Value::Error,
1543
            }
1544
        }
1545
        [Value::Null, _] => Value::Null,
1546
        _ => Value::Error,
1547
    }
1548
}
1549
1550
fn reverse_fn(args: Vec<Value>) -> Value {
1551
    match args.as_slice() {
1552
        [Value::List(items)] => {
1553
            let mut out = items.clone();
1554
            out.reverse();
1555
            Value::List(out)
1556
        }
1557
        [Value::Null] => Value::Null,
1558
        _ => Value::Error,
1559
    }
1560
}
1561
1562
fn flatten_fn(args: Vec<Value>) -> Value {
1563
    fn go(items: &[Value], out: &mut Vec<Value>) {
1564
        for it in items {
1565
            match it {
1566
                Value::List(inner) => go(inner, out),
1567
                other => out.push(other.clone()),
1568
            }
1569
        }
1570
    }
1571
    match args.as_slice() {
1572
        [Value::List(items)] => {
1573
            let mut out = Vec::new();
1574
            go(items, &mut out);
1575
            Value::List(out)
1576
        }
1577
        [Value::Null] => Value::Null,
1578
        _ => Value::Error,
1579
    }
1580
}
1581
1582
fn sublist_fn(args: Vec<Value>) -> Value {
1583
    let (list_v, start_v, len_v) = match args.len() {
1584
        2 => (&args[0], &args[1], None),
1585
        3 => (&args[0], &args[1], Some(&args[2])),
1586
        _ => return Value::Error,
1587
    };
1588
    let items = match list_v {
1589
        Value::List(items) => items,
1590
        Value::Null => return Value::Null,
1591
        _ => return Value::Error,
1592
    };
1593
    let start = match num_arg(start_v) {
1594
        NumArg::Num(s) => s.trunc() as i64,
1595
        NumArg::Null => return Value::Null,
1596
        NumArg::Err => return Value::Error,
1597
    };
1598
    let n = items.len() as i64;
1599
    let Some(from0) = resolve_index(start, n) else {
1600
        return Value::Error;
1601
    };
1602
    let avail = n - from0;
1603
    let take = match len_v {
1604
        None => avail,
1605
        Some(lv) => match num_arg(lv) {
1606
            NumArg::Num(l) => {
1607
                let l = l.trunc() as i64;
1608
                if l < 0 {
1609
                    return Value::Error;
1610
                }
1611
                l.min(avail)
1612
            }
1613
            NumArg::Null => return Value::Null,
1614
            NumArg::Err => return Value::Error,
1615
        },
1616
    };
1617
    Value::List(items[from0 as usize..(from0 + take) as usize].to_vec())
1618
}
1619
1620
fn list_contains_fn(args: Vec<Value>) -> Value {
1621
    match args.as_slice() {
1622
        [Value::List(items), e] => Value::Boolean(items.iter().any(|x| x == e)),
1623
        [Value::Null, _] => Value::Null,
1624
        _ => Value::Error,
1625
    }
1626
}
1627
1628
/// `index of(list, match)`: the 1-based positions where an element equals `match`
1629
/// (FEEL equality), as a list (empty if none).
1630
fn index_of_fn(args: Vec<Value>) -> Value {
1631
    match args.as_slice() {
1632
        [Value::List(items), m] => Value::List(
1633
            items
1634
                .iter()
1635
                .enumerate()
1636
                .filter(|(_, x)| *x == m)
1637
                .map(|(i, _)| Value::Number((i + 1) as f64))
1638
                .collect(),
1639
        ),
1640
        [Value::Null, _] => Value::Null,
1641
        _ => Value::Error,
1642
    }
1643
}
1644
1645
/// `distinct values(list)`: drop duplicates (FEEL equality), keeping first order.
1646
fn distinct_values_fn(args: Vec<Value>) -> Value {
1647
    match args.as_slice() {
1648
        [Value::List(items)] => {
1649
            let mut out: Vec<Value> = Vec::new();
1650
            for it in items {
1651
                if !out.iter().any(|x| x == it) {
1652
                    out.push(it.clone());
1653
                }
1654
            }
1655
            Value::List(out)
1656
        }
1657
        [Value::Null] => Value::Null,
1658
        _ => Value::Error,
1659
    }
1660
}
1661
1662
/// `insert before(list, position, newItem)`: insert `newItem` so it ends up at
1663
/// `position` (1-based, negative from the end). The position must address an
1664
/// existing element; out of range is an error.
1665
fn insert_before_fn(args: Vec<Value>) -> Value {
1666
    match args.as_slice() {
1667
        [Value::List(items), pos_v, new_item] => {
1668
            let pos = match num_arg(pos_v) {
1669
                NumArg::Num(p) => p.trunc() as i64,
1670
                NumArg::Null => return Value::Null,
1671
                NumArg::Err => return Value::Error,
1672
            };
1673
            let n = items.len() as i64;
1674
            match resolve_index(pos, n) {
1675
                Some(idx) if idx < n => {
1676
                    let mut out = items.clone();
1677
                    out.insert(idx as usize, new_item.clone());
1678
                    Value::List(out)
1679
                }
1680
                _ => Value::Error,
1681
            }
1682
        }
1683
        [Value::Null, _, _] => Value::Null,
1684
        _ => Value::Error,
1685
    }
1686
}
1687
1688
/// `list replace(list, match, newItem)` — matching form: replace each element for
1689
/// which `match(item, newItem)` returns `true` (spec §10.3.4.4 Table 72).
1690
/// `list replace(list, position, newItem)` — positional form: replace the element
1691
/// at the 1-based `position` (supports negative indexing). Dispatches on whether
1692
/// `match`/`position` is a `Value::Function` (matching form) or not (positional).
1693
/// A scalar `list` is treated as a one-element list (per DMN-TCK 1155, ADR-37).
1694
fn list_replace_fn(args: Vec<Value>, applier: &dyn Applier) -> Value {
1695
    if args.len() != 3 {
1696
        return Value::Error;
1697
    }
1698
    if let Value::Function(f) = &args[1] {
1699
        // Matching form: replace items where match(item, newItem) is Boolean(true).
1700
        let f = f.clone();
1701
        // Arity guard: a closure with a parameter count other than 2 is not a valid
1702
        // (item, newItem) predicate (spec §10.3.4.4); reject before invoking (ADR-37).
1703
        if let Func::Closure(c) = f.as_ref() {
1704
            if c.params.len() != 2 {
1705
                return Value::Error;
1706
            }
1707
        }
1708
        let new_item = args[2].clone();
1709
        let mut items = match &args[0] {
1710
            Value::List(items) => items.clone(),
1711
            Value::Null => return Value::Null,
1712
            other => vec![other.clone()],
1713
        };
1714
        for item in &mut items {
1715
            match applier.apply(
1716
                &f,
1717
                Args { positional: vec![item.clone(), new_item.clone()], named: vec![] },
1718
            ) {
1719
                Value::Boolean(true) => *item = new_item.clone(),
1720
                Value::Boolean(false) => {} // keep item unchanged
1721
                _ => return Value::Error,   // null, non-boolean, or error-null
1722
            }
1723
        }
1724
        Value::List(items)
1725
    } else {
1726
        // Positional form: replace the element at the 1-based position.
1727
        let [list_v, pos_v, new_item] = args.as_slice() else {
1728
            return Value::Error;
1729
        };
1730
        let mut items = match list_v {
1731
            Value::List(items) => items.clone(),
1732
            Value::Null => return Value::Null,
1733
            other => vec![other.clone()],
1734
        };
1735
        let pos = match num_arg(pos_v) {
1736
            NumArg::Num(p) => p.trunc() as i64,
1737
            NumArg::Null => return Value::Null,
1738
            NumArg::Err => return Value::Error,
1739
        };
1740
        let n = items.len() as i64;
1741
        match resolve_index(pos, n) {
1742
            Some(idx) if idx < n => {
1743
                items[idx as usize] = new_item.clone();
1744
                Value::List(items)
1745
            }
1746
            _ => Value::Error,
1747
        }
1748
    }
1749
}
1750
1751
/// `sort(list, precedes)` — stable sort using a FEEL function as the strict
1752
/// ordering predicate (spec §10.3.4.9). `precedes(x, y)` must return
1753
/// `Boolean(true)` when `x` should come before `y` and `Boolean(false)` when it
1754
/// should not; any other result (null, non-boolean, error-null) makes the whole
1755
/// call an error-null. Implemented as a stable insertion sort — O(n²) but
1756
/// correct and naturally stable for the small lists typical in DMN rules. The
1757
/// comparator is invoked through `applier` so closures and built-in refs both
1758
/// work and the recursion-depth guard is respected (ADR-37).
1759
fn sort_fn(args: Vec<Value>, applier: &dyn Applier) -> Value {
1760
    let [list_v, precedes_v] = args.as_slice() else {
1761
        return Value::Error;
1762
    };
1763
    let mut items = match list_v {
1764
        Value::List(items) => items.clone(),
1765
        Value::Null => return Value::Null,
1766
        _ => return Value::Error,
1767
    };
1768
    let precedes_fn = match precedes_v {
1769
        Value::Function(f) => {
1770
            // Arity guard: a closure with a parameter count other than 2 cannot be a
1771
            // valid (x, y) strict-ordering predicate (spec §10.3.4.9); ADR-37.
1772
            if let Func::Closure(c) = f.as_ref() {
1773
                if c.params.len() != 2 {
1774
                    return Value::Error;
1775
                }
1776
            }
1777
            f.clone()
1778
        }
1779
        _ => return Value::Error, // second argument is not a function value
1780
    };
1781
    // Stable insertion sort: move items[i] left while precedes(items[i], items[i-1]).
1782
    // Cloning before each comparison is safe because the `swap` does not invalidate
1783
    // the borrow (we clone first, then swap).
1784
    for i in 1..items.len() {
1785
        let mut j = i;
1786
        while j > 0 {
1787
            let key = items[j].clone();
1788
            let neighbor = items[j - 1].clone();
1789
            match applier.apply(
1790
                &*precedes_fn,
1791
                Args { positional: vec![key, neighbor], named: vec![] },
1792
            ) {
1793
                Value::Boolean(true) => {
1794
                    items.swap(j, j - 1);
1795
                    j -= 1;
1796
                }
1797
                Value::Boolean(false) => break, // key is in place, move to next element
1798
                _ => return Value::Error,        // null / non-boolean / error-null
1799
            }
1800
        }
1801
    }
1802
    Value::List(items)
1803
}
1804
1805
// --------------------------------------------------------------------------- //
1806
// Context
1807
// --------------------------------------------------------------------------- //
1808
1809
/// `get value(context, key)`: the value bound to `key`, or `null` if absent
1810
/// (including a present `null` value). A non-context or non-string key is an
1811
/// error (per DMN-TCK 0080).
1812
fn get_value_fn(args: Vec<Value>) -> Value {
1813
    match args.as_slice() {
1814
        [Value::Context(map), Value::String(key)] => map.get(key).cloned().unwrap_or(Value::Null),
1815
        [Value::Null, _] | [Value::Context(_), Value::Null] => Value::Null,
1816
        _ => Value::Error,
1817
    }
1818
}
1819
1820
/// `get entries(context)`: a list of `{key, value}` contexts, one per entry, in
1821
/// key order (per DMN-TCK 0081).
1822
fn get_entries_fn(args: Vec<Value>) -> Value {
1823
    match args.as_slice() {
1824
        [Value::Context(map)] => Value::List(
1825
            map.iter()
1826
                .map(|(k, v)| {
1827
                    let mut entry = BTreeMap::new();
1828
                    entry.insert("key".to_string(), Value::String(k.clone()));
1829
                    entry.insert("value".to_string(), v.clone());
1830
                    Value::Context(entry)
1831
                })
1832
                .collect(),
1833
        ),
1834
        [Value::Null] => Value::Null,
1835
        _ => Value::Error,
1836
    }
1837
}
1838
1839
/// `context(entries)`: build a context from a list of `{key, value}` entries (a
1840
/// single entry is coerced to a one-element list). Each entry needs a string
1841
/// `key` and a present `value` (a `null` value is allowed); a missing/non-string
1842
/// key, a missing value, or a duplicate key is an error-null (DMN-TCK 1145).
1843
fn context_fn(args: Vec<Value>) -> Value {
1844
    let entries = match args.as_slice() {
1845
        [Value::List(items)] => items.as_slice(),
1846
        [entry @ Value::Context(_)] => std::slice::from_ref(entry),
1847
        [Value::Null] => return Value::Null,
1848
        _ => return Value::Error,
1849
    };
1850
    let mut out = BTreeMap::new();
1851
    for item in entries {
1852
        let Value::Context(m) = item else {
1853
            return Value::Error;
1854
        };
1855
        let key = match m.get("key") {
1856
            Some(Value::String(k)) => k.clone(),
1857
            _ => return Value::Error,
1858
        };
1859
        let Some(value) = m.get("value") else {
1860
            return Value::Error;
1861
        };
1862
        if out.insert(key, value.clone()).is_some() {
1863
            return Value::Error; // duplicate key -> null
1864
        }
1865
    }
1866
    Value::Context(out)
1867
}
1868
1869
/// `context put(context, key, value)`: a copy of `context` with `key` set to
1870
/// `value`. When `key` is a list of strings it is a path into nested contexts
1871
/// (DMN-TCK 1146). A non-context `context`, a null/non-string key (or any
1872
/// non-string path segment, or an empty path) is an error-null.
1873
fn context_put_fn(args: Vec<Value>) -> Value {
1874
    let [ctx_v, key_v, value] = args.as_slice() else {
1875
        return Value::Error;
1876
    };
1877
    let map = match ctx_v {
1878
        Value::Context(m) => m,
1879
        Value::Null => return Value::Null,
1880
        _ => return Value::Error,
1881
    };
1882
    match key_v {
1883
        Value::String(k) => {
1884
            let mut out = map.clone();
1885
            out.insert(k.clone(), value.clone());
1886
            Value::Context(out)
1887
        }
1888
        Value::List(keys) => deep_put(map, keys, value),
1889
        Value::Null => Value::Null,
1890
        _ => Value::Error,
1891
    }
1892
}
1893
1894
/// Recursive helper for `context put` with a key *path* (`["y", "a"]`). Returns
1895
/// a new context. Mirrors the spec recursion `context put(m[k], rest, v)`: an
1896
/// empty path or non-string segment is an error, and a non-terminal segment must
1897
/// already map to a nested context — descending into a missing or non-context
1898
/// value yields null (DMN-TCK 1146 `nested009`).
1899
fn deep_put(map: &BTreeMap<String, Value>, keys: &[Value], value: &Value) -> Value {
1900
    let Some(Value::String(head)) = keys.first() else {
1901
        return Value::Error; // empty path or non-string segment -> null
1902
    };
1903
    let mut out = map.clone();
1904
    if keys.len() == 1 {
1905
        out.insert(head.clone(), value.clone());
1906
        return Value::Context(out);
1907
    }
1908
    let inner = match out.get(head) {
1909
        Some(Value::Context(m)) => m.clone(),
1910
        None | Some(Value::Null) => return Value::Null, // missing intermediate -> null
1911
        _ => return Value::Error,                       // non-context intermediate -> null
1912
    };
1913
    match deep_put(&inner, &keys[1..], value) {
1914
        v @ Value::Context(_) => {
1915
            out.insert(head.clone(), v);
1916
            Value::Context(out)
1917
        }
1918
        other => other, // propagate null/error from a deeper segment
1919
    }
1920
}
1921
1922
/// `context merge(contexts)`: a single context combining all entries of the
1923
/// given list of contexts (a single context is coerced to a one-element list),
1924
/// later entries overwriting earlier ones at the top level — no deep merge
1925
/// (DMN-TCK 1147). A non-context element is an error-null.
1926
fn context_merge_fn(args: Vec<Value>) -> Value {
1927
    let items = match args.as_slice() {
1928
        [Value::List(items)] => items.as_slice(),
1929
        [ctx @ Value::Context(_)] => std::slice::from_ref(ctx),
1930
        [Value::Null] => return Value::Null,
1931
        _ => return Value::Error,
1932
    };
1933
    let mut out = BTreeMap::new();
1934
    for item in items {
1935
        let Value::Context(m) = item else {
1936
            return Value::Error;
1937
        };
1938
        for (k, v) in m {
1939
            out.insert(k.clone(), v.clone());
1940
        }
1941
    }
1942
    Value::Context(out)
1943
}
1944
1945
// --------------------------------------------------------------------------- //
1946
// Numeric
1947
// --------------------------------------------------------------------------- //
1948
1949
fn decimal_fn(args: Vec<Value>) -> Value {
1950
    match args.as_slice() {
1951
        [n_v, scale_v] => {
1952
            let n = match num_arg(n_v) {
1953
                NumArg::Num(x) => x,
1954
                NumArg::Null => return Value::Null,
1955
                NumArg::Err => return Value::Error,
1956
            };
1957
            let scale = match num_arg(scale_v) {
1958
                NumArg::Num(x) => x.trunc() as i32,
1959
                NumArg::Null => return Value::Null,
1960
                NumArg::Err => return Value::Error,
1961
            };
1962
            let factor = 10f64.powi(scale);
1963
            // FEEL `decimal` rounds half to even (banker's rounding).
1964
            Value::Number((n * factor).round_ties_even() / factor)
1965
        }
1966
        _ => Value::Error,
1967
    }
1968
}
1969
1970
fn floor_ceiling_fn(args: Vec<Value>, is_floor: bool) -> Value {
1971
    let (n_v, scale) = match args.len() {
1972
        1 => (&args[0], 0i32),
1973
        2 => {
1974
            let s = match num_arg(&args[1]) {
1975
                NumArg::Num(x) => x.trunc() as i32,
1976
                NumArg::Null => return Value::Null,
1977
                NumArg::Err => return Value::Error,
1978
            };
1979
            (&args[0], s)
1980
        }
1981
        _ => return Value::Error,
1982
    };
1983
    let n = match num_arg(n_v) {
1984
        NumArg::Num(x) => x,
1985
        NumArg::Null => return Value::Null,
1986
        NumArg::Err => return Value::Error,
1987
    };
1988
    let factor = 10f64.powi(scale);
1989
    let scaled = n * factor;
1990
    let rounded = if is_floor {
1991
        scaled.floor()
1992
    } else {
1993
        scaled.ceil()
1994
    };
1995
    Value::Number(rounded / factor)
1996
}
1997
1998
/// Rounding mode for the four `round …` built-ins (DMN-TCK 1141–1144), matching
1999
/// the spec's `RoundingMode` names.
2000
enum RoundMode {
2001
    /// Away from zero.
2002
    Up,
2003
    /// Toward zero.
2004
    Down,
2005
    /// Nearest, ties away from zero.
2006
    HalfUp,
2007
    /// Nearest, ties toward zero.
2008
    HalfDown,
2009
}
2010
2011
/// `round up/down/half up/half down(n, scale)`: round `n` to `scale` decimal
2012
/// places using `mode`. `scale` is required (two args; the one-arg form is left
2013
/// out of the TCK pending clarification). Numbers are `f64` (ADR-2), so the modes
2014
/// use native f64 rounding.
2015
fn round_fn(args: Vec<Value>, mode: RoundMode) -> Value {
2016
    // decimal128 scale range; outside it the spec yields null. The TCK exercises
2017
    // the boundaries (`round up(5.5, 6176)` and `round up(5.5, -6112)`).
2018
    const MIN_SCALE: i32 = -6111;
2019
    const MAX_SCALE: i32 = 6176;
2020
2021
    let [n_v, scale_v] = args.as_slice() else {
2022
        return Value::Error; // arity error-null (the 1-arg form is not in scope)
2023
    };
2024
    let n = match num_arg(n_v) {
2025
        NumArg::Num(x) => x,
2026
        NumArg::Null => return Value::Null,
2027
        NumArg::Err => return Value::Error,
2028
    };
2029
    let scale = match num_arg(scale_v) {
2030
        NumArg::Num(x) => x.trunc() as i32,
2031
        NumArg::Null => return Value::Null,
2032
        NumArg::Err => return Value::Error,
2033
    };
2034
    if !(MIN_SCALE..=MAX_SCALE).contains(&scale) {
2035
        return Value::Error; // out of decimal128 range -> null
2036
    }
2037
    let factor = 10f64.powi(scale);
2038
    if !factor.is_finite() || factor == 0.0 {
2039
        // The scale is within decimal128's range but beyond f64's exponent range,
2040
        // so at f64 precision the rounding has no effect: return `n` unchanged.
2041
        return Value::Number(n);
2042
    }
2043
    let scaled = n * factor;
2044
    let rounded = match mode {
2045
        RoundMode::Up => {
2046
            if scaled >= 0.0 {
2047
                scaled.ceil()
2048
            } else {
2049
                scaled.floor()
2050
            }
2051
        }
2052
        RoundMode::Down => scaled.trunc(),
2053
        RoundMode::HalfUp => scaled.round(), // f64::round ties away from zero
2054
        RoundMode::HalfDown => (scaled.abs() - 0.5).ceil().copysign(scaled),
2055
    };
2056
    Value::Number(rounded / factor)
2057
}
2058
2059
fn abs_fn(args: Vec<Value>) -> Value {
2060
    match args.as_slice() {
2061
        [Value::Number(n)] => Value::Number(n.abs()),
2062
        // `abs` of a duration (ADR-18; ADR-15 had deferred this).
2063
        [v @ (Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_))] => {
2064
            crate::temporal::abs(v).unwrap_or(Value::Error)
2065
        }
2066
        [Value::Null] => Value::Null,
2067
        _ => Value::Error,
2068
    }
2069
}
2070
2071
fn modulo_fn(args: Vec<Value>) -> Value {
2072
    match args.as_slice() {
2073
        [a_v, b_v] => {
2074
            let a = match num_arg(a_v) {
2075
                NumArg::Num(x) => x,
2076
                NumArg::Null => return Value::Null,
2077
                NumArg::Err => return Value::Error,
2078
            };
2079
            let b = match num_arg(b_v) {
2080
                NumArg::Num(x) => x,
2081
                NumArg::Null => return Value::Null,
2082
                NumArg::Err => return Value::Error,
2083
            };
2084
            if b == 0.0 {
2085
                return Value::Error; // divisor must not be 0
2086
            }
2087
            // modulo(a, b) = a - b * floor(a / b); the result follows b's sign.
2088
            Value::Number(a - b * (a / b).floor())
2089
        }
2090
        _ => Value::Error,
2091
    }
2092
}
2093
2094
/// Apply a unary numeric function: a value-null argument propagates as `null`,
2095
/// a non-number or wrong arity is an error-null, and `f` maps a valid number to
2096
/// the result. `f` may itself return an error-null for a domain error (e.g.
2097
/// `sqrt` of a negative, `log` of a non-positive).
2098
fn unary_num(args: Vec<Value>, f: impl Fn(f64) -> Value) -> Value {
2099
    match args.as_slice() {
2100
        [v] => match num_arg(v) {
2101
            NumArg::Num(n) => f(n),
2102
            NumArg::Null => Value::Null,
2103
            NumArg::Err => Value::Error,
2104
        },
2105
        _ => Value::Error,
2106
    }
2107
}
2108
2109
fn sqrt_fn(args: Vec<Value>) -> Value {
2110
    // sqrt of a negative has no real value -> domain error.
2111
    unary_num(args, |n| {
2112
        if n < 0.0 {
2113
            Value::Error
2114
        } else {
2115
            Value::Number(n.sqrt())
2116
        }
2117
    })
2118
}
2119
2120
fn exp_fn(args: Vec<Value>) -> Value {
2121
    unary_num(args, |n| Value::Number(n.exp()))
2122
}
2123
2124
fn log_fn(args: Vec<Value>) -> Value {
2125
    // log is the natural logarithm; its domain is the positive reals.
2126
    unary_num(args, |n| {
2127
        if n <= 0.0 {
2128
            Value::Error
2129
        } else {
2130
            Value::Number(n.ln())
2131
        }
2132
    })
2133
}
2134
2135
fn even_odd_fn(args: Vec<Value>, want_even: bool) -> Value {
2136
    // even/odd are defined on integers; a non-integral number is a domain error.
2137
    unary_num(args, |n| {
2138
        if n.fract() != 0.0 {
2139
            return Value::Error;
2140
        }
2141
        let is_even = (n % 2.0) == 0.0;
2142
        Value::Boolean(is_even == want_even)
2143
    })
2144
}