feat(core): range() builtin and `in` range-membership
public
feat(core): range() builtin and `in` range-membership
- `range(from)` (DMN §10.3.4.6): parse a string such as `"[1..10)"` into a
`Value::Range`. It compiles the string, gates on the AST *shape* (must be a
range literal whose endpoints are literals — a number/string/`@"…"`/`null`,
or a temporal constructor on a string literal), then checks the evaluated
endpoints are non-null, same-typed and ascending. So `range("[1..3]")` is a
range, while `range("[date(string(\"…\"))..…]")`, `range("[3..1]")`,
`range(">=10")`, `range("")`, `range([1..3])` and friends are all null —
matching `1156-range-function`.
- `in` now accepts a bare endpoint expression on its RHS: `2 in range("[1..3]")`
is range *membership*, `1 in 1` is `1 = 1`. A *written* interval literal
`x in [a..b]` still routes to the dedicated interval test (unchanged), so the
whole fixture suite stays green. The membership inclusivity logic is factored
into `range_contains`, shared by the literal-interval and range-value paths.
65 lib tests + the 2598-case fixture suite pass.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
| Changeset | ecf7bb9fce5de4c4d50782f1e4e16b6754f23d9f |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | fb7b9b820768 |
| Children | |
| Pushlog | by timo via ssh |
modified crates/feel-core/src/ast.rs +19 −1
| @@ -190,6 +190,24 @@ | ||
| 190 | 190 | Compare(CmpOp, Box<Expr>), |
| 191 | 191 | /// An interval test `[a..b]` / `(a..b)` / … (the bracket openness in [`Interval`]). |
| 192 | 192 | Interval(Interval), |
| 193 | + /// A bare endpoint expression on the right of `in`, e.g. `x in e`. Evaluated as | |
| 194 | + /// equality `x = e` when `e` is a scalar, or as range *membership* when `e` | |
| 195 | + /// evaluates to a [`range`](crate::Value::Range) value — so `2 in range("[1..3]")` | |
| 196 | + /// is a containment test, not `2 = <range>` (DMN §10.3.2.6). A *written* interval | |
| 197 | + /// literal `[a..b]` keeps the dedicated [`UnaryTest::Interval`] form instead (see | |
| 198 | + /// [`unary_test_from_expr`]), so existing interval tests are unchanged. | |
| 199 | + Endpoint(Box<Expr>), | |
| 200 | +} | |
| 201 | + | |
| 202 | +/// Build the unary test for a bare RHS expression `x in e`. A written interval | |
| 203 | +/// literal keeps the dedicated [`UnaryTest::Interval`] test (so `x in [a..b]` is | |
| 204 | +/// byte-for-byte unchanged); every other expression becomes an | |
| 205 | +/// [`UnaryTest::Endpoint`] (equality, or range membership if it evaluates to a range). | |
| 206 | +pub fn unary_test_from_expr(e: Expr) -> UnaryTest { | |
| 207 | + match e { | |
| 208 | + Expr::RangeLit(iv) => UnaryTest::Interval(iv), | |
| 209 | + other => UnaryTest::Endpoint(Box::new(other)), | |
| 210 | + } | |
| 193 | 211 | } |
| 194 | 212 | |
| 195 | 213 | /// A node in the FEEL type lattice **L** (DMN §10.3.2.9), the right operand of |
| @@ -368,7 +386,7 @@ | ||
| 368 | 386 | impl UnaryTest { |
| 369 | 387 | fn is_clock_free(&self) -> bool { |
| 370 | 388 | match self { |
| 371 | - UnaryTest::Compare(_, e) => e.is_clock_free(), | |
| 389 | + UnaryTest::Compare(_, e) | UnaryTest::Endpoint(e) => e.is_clock_free(), | |
| 372 | 390 | UnaryTest::Interval(iv) => iv.start.is_clock_free() && iv.end.is_clock_free(), |
| 373 | 391 | } |
| 374 | 392 | } |
modified crates/feel-core/src/builtins.rs +70 −0
| @@ -161,6 +161,9 @@ | ||
| 161 | 161 | // --- boolean (spec §10.3.4.5) --- |
| 162 | 162 | "is" => is_fn(args), |
| 163 | 163 | |
| 164 | + // --- range (spec §10.3.4.6) --- | |
| 165 | + "range" => range_fn(args, env), | |
| 166 | + | |
| 164 | 167 | // Not a built-in: let the caller try a host function (ADR-23). |
| 165 | 168 | _ => return None, |
| 166 | 169 | }) |
| @@ -208,6 +211,9 @@ | ||
| 208 | 211 | // --- boolean (spec §10.3.4.5) --- |
| 209 | 212 | "is" => &["value1", "value2"], |
| 210 | 213 | |
| 214 | + // --- range (spec §10.3.4.6) --- | |
| 215 | + "range" => &["from"], | |
| 216 | + | |
| 211 | 217 | // --- string functions (spec §10.3.4.3) --- |
| 212 | 218 | "substring" => &["string", "start position", "length"], |
| 213 | 219 | "string length" => &["string"], |
| @@ -575,6 +581,70 @@ | ||
| 575 | 581 | [a] => Value::Boolean(*a == Value::Null), |
| 576 | 582 | [a, b] => Value::Boolean(a == b), |
| 577 | 583 | _ => Value::Error, // wrong arity (0 or >2) |
| 584 | + } | |
| 585 | +} | |
| 586 | + | |
| 587 | +// --------------------------------------------------------------------------- // | |
| 588 | +// Range (spec §10.3.4.6) | |
| 589 | +// --------------------------------------------------------------------------- // | |
| 590 | + | |
| 591 | +/// `range(from)` (spec §10.3.4.6): parse a string such as `"[1..10)"` into a | |
| 592 | +/// [`Value::Range`]. The argument must be a single string whose content is a range | |
| 593 | +/// *literal* with self-contained literal endpoints (see [`range_endpoint_is_literal`]); | |
| 594 | +/// the resulting range must have two non-null, same-typed, ascending endpoints. Every | |
| 595 | +/// other case — wrong arity, a non-string argument, an unparseable or non-range | |
| 596 | +/// string, a non-literal endpoint, mismatched endpoint types, or a reversed range — | |
| 597 | +/// is an error-null (the TCK's `1156-range-function` expects `null` for all of them). | |
| 598 | +fn range_fn(args: Vec<Value>, env: &EvalEnv) -> Value { | |
| 599 | + let s = match args.as_slice() { | |
| 600 | + [Value::String(s)] => s, | |
| 601 | + _ => return Value::Error, // wrong arity or non-string argument | |
| 602 | + }; | |
| 603 | + let compiled = match crate::compile(s) { | |
| 604 | + Ok(c) => c, | |
| 605 | + Err(_) => return Value::Error, // not a parseable FEEL expression | |
| 606 | + }; | |
| 607 | + // Shape gate: the string must be a range literal whose endpoints are literals. | |
| 608 | + // This is why we inspect the AST rather than only evaluating — `date(string("…"))` | |
| 609 | + // *evaluates* to a date but is not a literal, so the spec wants it to be null. | |
| 610 | + match compiled.ast() { | |
| 611 | + crate::ast::Expr::RangeLit(iv) => { | |
| 612 | + if !range_endpoint_is_literal(&iv.start) || !range_endpoint_is_literal(&iv.end) { | |
| 613 | + return Value::Error; | |
| 614 | + } | |
| 615 | + } | |
| 616 | + _ => return Value::Error, // a non-range expression (`">=10"`, `"[1,2,3]"`, …) | |
| 617 | + } | |
| 618 | + // Endpoints are literals, so an empty context suffices; the env still carries the | |
| 619 | + // (unused) clock/zone policy the temporal constructors expect. | |
| 620 | + let r = match compiled.evaluate_with_env(&crate::Context::empty(), env) { | |
| 621 | + Ok(Value::Range(r)) => r, | |
| 622 | + _ => return Value::Error, | |
| 623 | + }; | |
| 624 | + // A well-formed range has two comparable (same orderable type, non-null) endpoints | |
| 625 | + // in non-descending order. `feel_order` returns `None` for null/mismatched types. | |
| 626 | + match feel_order(&r.start, &r.end) { | |
| 627 | + Some(ord) if ord != Ordering::Greater => Value::Range(r), | |
| 628 | + _ => Value::Error, | |
| 629 | + } | |
| 630 | +} | |
| 631 | + | |
| 632 | +/// Is `e` an admissible *literal* endpoint for [`range_fn`] (DMN §10.3.4.6)? Allowed: | |
| 633 | +/// a number / string / `@"…"` temporal literal / `null`, or a temporal *constructor* | |
| 634 | +/// applied directly to a single string literal (`date("…")`, `time("…")`, | |
| 635 | +/// `duration("…")`, `date and time("…")`). Anything richer — a variable, an | |
| 636 | +/// arithmetic expression, or a nested call like `date(string("…"))` — is rejected, so | |
| 637 | +/// `range("[date(input)..…]")` and `range("[date(string(\"…\"))..…]")` are null. | |
| 638 | +fn range_endpoint_is_literal(e: &crate::ast::Expr) -> bool { | |
| 639 | + use crate::ast::Expr; | |
| 640 | + match e { | |
| 641 | + Expr::Number(_) | Expr::Str(_) | Expr::TemporalLit(_) | Expr::Null => true, | |
| 642 | + Expr::FnCall(name, args) => { | |
| 643 | + matches!(name.as_str(), "date" | "time" | "duration" | "date and time") | |
| 644 | + && args.named.is_empty() | |
| 645 | + && matches!(args.positional.as_slice(), [Expr::Str(_)]) | |
| 646 | + } | |
| 647 | + _ => false, | |
| 578 | 648 | } |
| 579 | 649 | } |
| 580 | 650 | |
modified crates/feel-core/src/eval.rs +27 −15
| @@ -544,23 +544,35 @@ | ||
| 544 | 544 | fn eval_unary_test(&self, o: &Value, test: &UnaryTest, ctx: &Context) -> EvalResult { |
| 545 | 545 | Ok(match test { |
| 546 | 546 | UnaryTest::Compare(op, e) => eval_compare(*op, o, &self.eval(e, ctx)?.forced()), |
| 547 | - UnaryTest::Interval(iv) => { | |
| 548 | - let lo = self.eval(&iv.start, ctx)?.forced(); | |
| 549 | - let hi = self.eval(&iv.end, ctx)?.forced(); | |
| 550 | - let lower = eval_compare( | |
| 551 | - if iv.start_open { CmpOp::Lt } else { CmpOp::Le }, | |
| 552 | - &lo, | |
| 553 | - o, | |
| 554 | - ); | |
| 555 | - let upper = eval_compare( | |
| 556 | - if iv.end_open { CmpOp::Lt } else { CmpOp::Le }, | |
| 557 | - o, | |
| 558 | - &hi, | |
| 559 | - ); | |
| 560 | - and3(lower, upper) | |
| 561 | - } | |
| 547 | + // A *written* interval literal `[a..b]`: evaluate its endpoints in the | |
| 548 | + // test context and check containment (unchanged from before ranges). | |
| 549 | + UnaryTest::Interval(iv) => range_contains( | |
| 550 | + o, | |
| 551 | + &self.eval(&iv.start, ctx)?.forced(), | |
| 552 | + iv.start_open, | |
| 553 | + &self.eval(&iv.end, ctx)?.forced(), | |
| 554 | + iv.end_open, | |
| 555 | + ), | |
| 556 | + // A bare endpoint expression `x in e`: range *membership* when `e` is a | |
| 557 | + // range value (e.g. `range("[1..3]")`), otherwise equality `x = e`. | |
| 558 | + UnaryTest::Endpoint(e) => match self.eval(e, ctx)?.forced() { | |
| 559 | + Value::Range(r) => { | |
| 560 | + range_contains(o, &r.start, r.start_open, &r.end, r.end_open) | |
| 561 | + } | |
| 562 | + t => eval_compare(CmpOp::Eq, o, &t), | |
| 563 | + }, | |
| 562 | 564 | }) |
| 563 | 565 | } |
| 566 | +} | |
| 567 | + | |
| 568 | +/// S-FEEL interval inclusivity for an input `o` against a `[start..end]` range: | |
| 569 | +/// `[a..b]` -> a <= o <= b ; `(a..b]` -> a < o <= b ; `[a..b)` -> a <= o < b ; | |
| 570 | +/// `(a..b)` -> a < o < b. Three-valued: a null/error endpoint makes the side it | |
| 571 | +/// bounds unknown, and `and3` combines the two sides with sticky error provenance. | |
| 572 | +fn range_contains(o: &Value, start: &Value, start_open: bool, end: &Value, end_open: bool) -> Value { | |
| 573 | + let lower = eval_compare(if start_open { CmpOp::Lt } else { CmpOp::Le }, start, o); | |
| 574 | + let upper = eval_compare(if end_open { CmpOp::Lt } else { CmpOp::Le }, o, end); | |
| 575 | + and3(lower, upper) | |
| 564 | 576 | } |
| 565 | 577 | |
| 566 | 578 | // --------------------------------------------------------------------------- // |
modified crates/feel-core/src/feel.lalrpop +16 −22
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | // left-recursive on purpose; lalrpop (LR(1)) handles that natively, which is the |
| 14 | 14 | // reason we chose it. |
| 15 | 15 | |
| 16 | -use crate::ast::{ArgEntry, ArithOp, CallArgs, CmpOp, Expr, FeelType, Interval, IterSource, Quantifier, TypeArg, UnaryTest, callargs_from, generic_type, simple_type}; | |
| 16 | +use crate::ast::{ArgEntry, ArithOp, CallArgs, CmpOp, Expr, FeelType, Interval, IterSource, Quantifier, TypeArg, UnaryTest, callargs_from, generic_type, simple_type, unary_test_from_expr}; | |
| 17 | 17 | use crate::lexer::{LexError, Tok}; |
| 18 | 18 | |
| 19 | 19 | grammar; |
| @@ -295,29 +295,23 @@ | ||
| 295 | 295 | }; |
| 296 | 296 | |
| 297 | 297 | // The right-hand side of membership `in` — positive unary tests (DMN rule 49). |
| 298 | -// This slice covers the two LR(1)-clean forms: a single comparison test | |
| 299 | -// `<op> endpoint` (`< 10`, `= e`, `!= e`, with any endpoint expression including a | |
| 300 | -// list `=[1,2,3]` or a temporal `=@"…"`), and a single interval `[a..b]` / `(a..b)` | |
| 301 | -// (with any endpoints, e.g. `date(…)`). The comma-separated *list* forms | |
| 302 | -// (`[2,3,1]`, `(false, true)`, `[[a..b],[c..d]]`) need the interval-vs-list bracket | |
| 303 | -// disambiguation that LR(1) cannot do here without inlining the whole expression | |
| 304 | -// grammar; they are deferred (see ROADMAP). `not(…)` negation is out too (it | |
| 305 | -// collides with the `not(…)` boolean built-in). | |
| 298 | +// Two LR(1)-clean forms: a comparison test `<op> endpoint` (`< 10`, `= e`, `!= e`, | |
| 299 | +// any endpoint expression, incl. a list `=[1,2,3]` or a temporal `=@"…"`), and a | |
| 300 | +// single bare endpoint expression `e`. The bare form is a full `Sum`, so it covers | |
| 301 | +// a written interval literal `[a..b]` / `(a..b]` (now a first-class `RangeLit` | |
| 302 | +// value), an expression yielding a range (`range("[1..3]")`, a range-typed | |
| 303 | +// variable), and a plain scalar (`1 in 1` is `1 = 1`). `unary_test_from_expr` routes | |
| 304 | +// a written interval back to the dedicated `Interval` *test* (byte-for-byte the old | |
| 305 | +// behaviour); anything else becomes an `Endpoint` (equality, or range membership). | |
| 306 | +// Because `[a..b]`/`[1,2,3]` are ordinary `Primary`s now, there is no separate | |
| 307 | +// `IntervalStart` nonterminal here — which is exactly what used to clash with the | |
| 308 | +// list literal on the bare `[` (build.rs's no-conflict gate proves it stays clean). | |
| 309 | +// The comma-separated *list-of-tests* forms (`x in [1,2,3]`, `x in (false,true)`, | |
| 310 | +// `x in [[a..b],[c..d]]`) — where the brackets are a list of tests, not one value — | |
| 311 | +// remain deferred (they need the test-list-vs-value bracket split; see ROADMAP). | |
| 306 | 312 | InRhs: Vec<UnaryTest> = { |
| 307 | 313 | <op:CmpOp> <e:Sum> => vec![UnaryTest::Compare(op, Box::new(e))], |
| 308 | - <iv:Interval> => vec![UnaryTest::Interval(iv)], | |
| 309 | -}; | |
| 310 | - | |
| 311 | -// Interval / range literal (only reachable after membership `in`). The boolean | |
| 312 | -// carries the openness of each endpoint. | |
| 313 | -Interval: Interval = { | |
| 314 | - <so:IntervalStart> <lo:Sum> ".." <hi:Sum> <eo:IntervalEnd> => | |
| 315 | - Interval { start_open: so, start: Box::new(lo), end: Box::new(hi), end_open: eo }, | |
| 316 | -}; | |
| 317 | - | |
| 318 | -IntervalStart: bool = { | |
| 319 | - "[" => false, // closed | |
| 320 | - "(" => true, // open | |
| 314 | + <e:Sum> => vec![unary_test_from_expr(e)], | |
| 321 | 315 | }; |
| 322 | 316 | |
| 323 | 317 | IntervalEnd: bool = { |
modified crates/feel-core/src/lib.rs +47 −0
| @@ -121,6 +121,13 @@ | ||
| 121 | 121 | /// deterministic in tests. |
| 122 | 122 | pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> { |
| 123 | 123 | eval::Evaluator::new(env).eval(&self.0, context) |
| 124 | + } | |
| 125 | + | |
| 126 | + /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a | |
| 127 | + /// freshly-parsed range literal's *shape* (its endpoints must be literals, not | |
| 128 | + /// arbitrary expressions — DMN §10.3.4.6) before evaluating it. | |
| 129 | + pub(crate) fn ast(&self) -> &ast::Expr { | |
| 130 | + &self.0 | |
| 124 | 131 | } |
| 125 | 132 | |
| 126 | 133 | /// `true` if this expression never reads the wall clock — it calls neither |
| @@ -411,6 +418,46 @@ | ||
| 411 | 418 | } |
| 412 | 419 | |
| 413 | 420 | #[test] |
| 421 | + fn range_builtin() { | |
| 422 | + // Representative cases from DMN-TCK 1156-range-function. | |
| 423 | + // --- construction + equality with a literal / membership / instance of --- | |
| 424 | + assert_eq!(ev(r#"range("[18..21]") = [18..21]"#), b(true)); | |
| 425 | + assert_eq!(ev(r#"range("(18..21]") = (18..21]"#), b(true)); | |
| 426 | + assert_eq!(ev(r#"range("[18..21)") = [18..21)"#), b(true)); | |
| 427 | + assert_eq!(ev(r#"range(" [ 1 .. 3 ] ") = [1..3]"#), b(true)); // whitespace tolerant | |
| 428 | + assert_eq!(ev(r#"2 in range("[1..3]")"#), b(true)); | |
| 429 | + assert_eq!(ev(r#"range("[1..3]") instance of range<number>"#), b(true)); | |
| 430 | + assert_eq!(ev(r#"range(string("[1..3]")) instance of range<number>"#), b(true)); | |
| 431 | + assert_eq!(ev(r#"range("[\"a\"..\"c\"]") instance of range<string>"#), b(true)); | |
| 432 | + assert_eq!(ev(r#"range(from: "[1..3]") = [1..3]"#), b(true)); | |
| 433 | + // temporal endpoints (via `@"…"` and direct constructors on string literals) | |
| 434 | + assert_eq!( | |
| 435 | + ev(r#"range("[date(\"1970-01-01\")..date(\"1970-01-02\")]") = [date("1970-01-01")..date("1970-01-02")]"#), | |
| 436 | + b(true) | |
| 437 | + ); | |
| 438 | + assert_eq!(ev(r#"range("[@\"P1D\"..@\"P2D\"]") instance of range<days and time duration>"#), b(true)); | |
| 439 | + | |
| 440 | + // --- error/null cases (lenient view collapses error-null to null) --- | |
| 441 | + for src in [ | |
| 442 | + r#"range("")"#, | |
| 443 | + r#"range(" ")"#, | |
| 444 | + r#"range()"#, | |
| 445 | + r#"range("[1..3]", "foo")"#, | |
| 446 | + r#"range([1..3])"#, // argument is a range value, not a string | |
| 447 | + r#"range(">=10")"#, // not a range literal | |
| 448 | + r#"range("[1..\"b\"]")"#, // mismatched endpoint types | |
| 449 | + r#"range("[3..1]")"#, // reversed | |
| 450 | + r#"range("[null..null]")"#, // null endpoints | |
| 451 | + r#"range("[..2]")"#, // missing lower endpoint | |
| 452 | + r#"range("[1..]")"#, // missing upper endpoint | |
| 453 | + r#"range("[date(string(\"1970-01-01\"))..date(\"1970-01-02\")]")"#, // non-literal endpoint | |
| 454 | + r#"range(fron: "[1..3]")"#, // unknown named parameter | |
| 455 | + ] { | |
| 456 | + assert_eq!(ev(src), Value::Null, "expected null for `{src}`"); | |
| 457 | + } | |
| 458 | + } | |
| 459 | + | |
| 460 | + #[test] | |
| 414 | 461 | fn arithmetic_and_precedence() { |
| 415 | 462 | assert_eq!(ev("1 + 1"), num(2.0)); |
| 416 | 463 | assert_eq!(ev("1 + 2 * 3"), num(7.0)); // * binds tighter than + |