| @@ -78,6 +78,31 @@ |
| 78 | 78 | let mut child = self.clone(); |
| 79 | 79 | child.insert(name, value); |
| 80 | 80 | child |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +/// The parse-time "name oracle" for special-character names (§10.3.1.6, ADR-47): |
| 85 | +/// decides which candidate names are in scope, so the lexer can fuse FEEL's |
| 86 | +/// additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names. |
| 87 | +/// |
| 88 | +/// std-only (ADR-1), like the other host seams. The canonical implementation is |
| 89 | +/// [`Context`] itself — parse and eval must agree on what "in scope" means, so |
| 90 | +/// the impl mirrors `Expr::Var` resolution exactly: a context binding or a |
| 91 | +/// built-in function name. A host that parses before its context exists can |
| 92 | +/// implement this against its own root-key view (e.g. a jsonb row's top-level |
| 93 | +/// keys — feel-pg just builds the `Context` first, which is already cheap). |
| 94 | +pub trait ScopeProbe { |
| 95 | + /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would |
| 96 | + /// find a value (a context binding or a built-in function name). |
| 97 | + fn contains(&self, name: &str) -> bool; |
| 98 | +} |
| 99 | + |
| 100 | +impl ScopeProbe for Context { |
| 101 | + fn contains(&self, name: &str) -> bool { |
| 102 | + // Mirrors `Expr::Var` (eval.rs): a context binding wins, then a built-in |
| 103 | + // name (a first-class function value, ADR-36), then null — the probe asks |
| 104 | + // about the first two. |
| 105 | + self.get(name).is_some() || crate::builtins::is_builtin(name) |
| 81 | 106 | } |
| 82 | 107 | } |
| 83 | 108 | |
| @@ -96,7 +121,16 @@ |
| 96 | 121 | /// assert_eq!(prog.evaluate(&ctx).unwrap(), Value::Number(2.0)); |
| 97 | 122 | /// ``` |
| 98 | 123 | #[derive(Debug, Clone)] |
| 99 | | -pub struct CompiledExpr(ast::Expr); |
| 124 | +pub struct CompiledExpr { |
| 125 | + /// The parsed program. |
| 126 | + expr: ast::Expr, |
| 127 | + /// Whether the parse consulted a scope probe on a special-character name |
| 128 | + /// run (`a-b`, `Date-Time`, …) — i.e. is **scope-dependent**: another scope |
| 129 | + /// could fuse the same text differently (ADR-47). Only a probe-aware parse |
| 130 | + /// (`compile_with_probe`/`evaluate`) sets it; `compile` is probe-free and |
| 131 | + /// reports `false`. |
| 132 | + name_runs: bool, |
| 133 | +} |
| 100 | 134 | |
| 101 | 135 | impl CompiledExpr { |
| 102 | 136 | /// Evaluate this already-parsed expression against a context, using the |
| @@ -121,14 +155,14 @@ |
| 121 | 155 | /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()` |
| 122 | 156 | /// deterministic in tests. |
| 123 | 157 | pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> { |
| 124 | | - eval::Evaluator::new(env).eval(&self.0, context) |
| 158 | + eval::Evaluator::new(env).eval(&self.expr, context) |
| 125 | 159 | } |
| 126 | 160 | |
| 127 | 161 | /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a |
| 128 | 162 | /// freshly-parsed range literal's *shape* (its endpoints must be literals, not |
| 129 | 163 | /// arbitrary expressions — DMN §10.3.4.6) before evaluating it. |
| 130 | 164 | pub(crate) fn ast(&self) -> &ast::Expr { |
| 131 | | - &self.0 |
| 165 | + &self.expr |
| 132 | 166 | } |
| 133 | 167 | |
| 134 | 168 | /// `true` if this expression never reads the wall clock — it calls neither |
| @@ -142,7 +176,18 @@ |
| 142 | 176 | /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope |
| 143 | 177 | /// here (the embedder's concern; feel-pg has no host-function seam). |
| 144 | 178 | pub fn is_clock_free(&self) -> bool { |
| 145 | | - self.0.is_clock_free() |
| 179 | + self.expr.is_clock_free() |
| 180 | + } |
| 181 | + |
| 182 | + /// `true` if parsing consulted a scope probe on a special-character name run |
| 183 | + /// (`a-b`, `Date-Time`, …; §10.3.1.6, ADR-47): this parse is |
| 184 | + /// **scope-dependent** — the same text could parse differently under another |
| 185 | + /// scope. Only a probe-aware parse sets it; [`compile`] is probe-free and |
| 186 | + /// reports `false`. Hosts that cache parses across contexts can instead check |
| 187 | + /// [`name_run_candidates`] against each context, which distinguishes "could |
| 188 | + /// be ambiguous" from "this scope actually changes the parse". |
| 189 | + pub fn has_name_runs(&self) -> bool { |
| 190 | + self.name_runs |
| 146 | 191 | } |
| 147 | 192 | } |
| 148 | 193 | |
| @@ -246,27 +291,67 @@ |
| 246 | 291 | /// |
| 247 | 292 | /// Returns [`FeelError::Parse`] if the expression is syntactically invalid. |
| 248 | 293 | /// |
| 294 | +/// **Probe-free** (ADR-47): special-character name runs (`a-b`, `Date-Time`) |
| 295 | +/// parse as arithmetic here — a compiled program must not pin one scope. Use |
| 296 | +/// [`compile_with_probe`] when the scope is known at parse time, or the one-shot |
| 297 | +/// [`evaluate`], which uses the context as the probe (§10.3.1.6). |
| 298 | +/// |
| 249 | 299 | /// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime |
| 250 | 300 | /// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the |
| 251 | 301 | /// per-call parse itself, which [`CompiledExpr`] lets callers pay once. |
| 252 | 302 | pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> { |
| 253 | 303 | feel::ExprParser::new() |
| 254 | 304 | .parse(lexer::lex(expr)) |
| 255 | | - .map(CompiledExpr) |
| 305 | + .map(|expr| CompiledExpr { expr, name_runs: false }) |
| 256 | 306 | .map_err(|e| FeelError::Parse(e.to_string())) |
| 257 | 307 | } |
| 258 | 308 | |
| 309 | +/// Parse a FEEL expression with scope-dependent name resolution (§10.3.1.6, |
| 310 | +/// ADR-47): special-character name runs (`a-b`, `Date-Time`, `x.y`) are fused |
| 311 | +/// into single names when — and only when — the joined candidate is in scope |
| 312 | +/// per `probe`, longest in-scope match preferred, left to right. Spaces are not |
| 313 | +/// part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces |
| 314 | +/// the operator reading. |
| 315 | +/// |
| 316 | +/// The result's [`CompiledExpr::has_name_runs`] tells whether the parse |
| 317 | +/// consulted the scope at all. For expressions with no name-run *pattern* |
| 318 | +/// (see [`name_run_candidates`]), this is byte-identical to [`compile`]. |
| 319 | +pub fn compile_with_probe( |
| 320 | + expr: &str, |
| 321 | + probe: &dyn ScopeProbe, |
| 322 | +) -> Result<CompiledExpr, FeelError> { |
| 323 | + let (toks, name_runs) = lexer::lex_with_probe(expr, probe); |
| 324 | + feel::ExprParser::new() |
| 325 | + .parse(toks) |
| 326 | + .map(|expr| CompiledExpr { expr, name_runs }) |
| 327 | + .map_err(|e| FeelError::Parse(e.to_string())) |
| 328 | +} |
| 329 | + |
| 259 | 330 | /// Parse and evaluate a FEEL expression against a context. |
| 260 | 331 | /// |
| 261 | | -/// Convenience for `compile(expr)?.evaluate(context)`; prefer [`compile`] when |
| 262 | | -/// evaluating the same expression more than once. |
| 332 | +/// Convenience for `compile_with_probe(expr, context)?.evaluate(context)`; |
| 333 | +/// prefer [`compile_with_probe`] when evaluating the same expression more than |
| 334 | +/// once against the same scope. The context **is** the scope for §10.3.1.6 |
| 335 | +/// name resolution (ADR-47): a name like `a-b` resolves to the context binding |
| 336 | +/// when one exists, and to subtraction otherwise. |
| 263 | 337 | /// |
| 264 | 338 | /// ``` |
| 265 | 339 | /// use feel_core::{evaluate, Context, Value}; |
| 266 | 340 | /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0)); |
| 267 | 341 | /// ``` |
| 268 | 342 | pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> { |
| 269 | | - compile(expr)?.evaluate(context) |
| 343 | + compile_with_probe(expr, context)?.evaluate(context) |
| 344 | +} |
| 345 | + |
| 346 | +/// Every special-character name candidate `expr` could fuse under *some* scope |
| 347 | +/// (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, `a-b`, `b-c`. Probe-free |
| 348 | +/// and cheap; the use case is a host that caches a probe-free parse across |
| 349 | +/// contexts (feel-pg's `fn_extra` slot): if none of the candidates is bound in |
| 350 | +/// a given context, the cached parse is already scope-correct; if any is bound, |
| 351 | +/// re-parse that context with [`compile_with_probe`]. An empty result means the |
| 352 | +/// expression's parse is scope-independent for every possible context. |
| 353 | +pub fn name_run_candidates(expr: &str) -> Vec<String> { |
| 354 | + lexer::name_run_candidates(expr) |
| 270 | 355 | } |
| 271 | 356 | |
| 272 | 357 | /// Parse a structural FEEL type expression (`number`, `list<string>`, |
| @@ -339,6 +424,184 @@ |
| 339 | 424 | #[test] |
| 340 | 425 | fn compile_reports_parse_error() { |
| 341 | 426 | assert!(matches!(compile("1 +"), Err(FeelError::Parse(_)))); |
| 427 | + } |
| 428 | + |
| 429 | + // ----------------------------------------------------------------------- // |
| 430 | + // Special-character names (§10.3.1.6, ADR-47) |
| 431 | + // ----------------------------------------------------------------------- // |
| 432 | + |
| 433 | + fn ctx_of(pairs: &[(&str, Value)]) -> Context { |
| 434 | + let mut c = Context::empty(); |
| 435 | + for (k, v) in pairs { |
| 436 | + c.insert(*k, v.clone()); |
| 437 | + } |
| 438 | + c |
| 439 | + } |
| 440 | + |
| 441 | + /// A FEEL context value from `(key, value)` pairs. |
| 442 | + fn ctx_value(pairs: &[(&str, Value)]) -> Value { |
| 443 | + Value::Context(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()) |
| 444 | + } |
| 445 | + |
| 446 | + /// One-shot evaluation against a scope built from `(name, value)` pairs — |
| 447 | + /// the §10.3.1.6 stance: the context is the name oracle. |
| 448 | + fn eval_in(src: &str, pairs: &[(&str, Value)]) -> Value { |
| 449 | + evaluate(src, &ctx_of(pairs)) |
| 450 | + .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 451 | + .into_lenient() |
| 452 | + } |
| 453 | + |
| 454 | + #[test] |
| 455 | + fn special_char_names_resolve_against_scope() { |
| 456 | + // `a-b` is the in-scope NAME when bound, subtraction otherwise — and |
| 457 | + // `a - b` is the same candidate: spaces are not part of the name. |
| 458 | + assert_eq!(eval_in("a-b", &[("a-b", num(10.0))]), num(10.0)); |
| 459 | + assert_eq!(eval_in("a - b", &[("a-b", num(10.0))]), num(10.0)); |
| 460 | + assert_eq!(eval_in("a-b", &[]), Value::Null); // unbound: subtraction of two nulls |
| 461 | + // All five additional name symbols (grammar rule 30). |
| 462 | + assert_eq!(eval_in("a+b", &[("a+b", num(1.0))]), num(1.0)); |
| 463 | + assert_eq!(eval_in("a*b", &[("a*b", num(2.0))]), num(2.0)); |
| 464 | + assert_eq!(eval_in("a/b", &[("a/b", num(3.0))]), num(3.0)); |
| 465 | + assert_eq!(eval_in("a.b", &[("a.b", num(4.0))]), num(4.0)); |
| 466 | + // Keywords are legal name parts in symbol runs (`if-then`; unfused, the |
| 467 | + // `if` keyword would make it a parse error). |
| 468 | + assert_eq!(eval_in("if-then", &[("if-then", b(true))]), b(true)); |
| 469 | + // A multi-word name part joins before fusion (`total price-total`). |
| 470 | + assert_eq!( |
| 471 | + eval_in("total price-total", &[("total price-total", num(5.0))]), |
| 472 | + num(5.0) |
| 473 | + ); |
| 474 | + // Fusion reaches every reference slot — call arguments: |
| 475 | + assert_eq!(eval_in("not(x-y)", &[("x-y", b(true))]), b(false)); |
| 476 | + } |
| 477 | + |
| 478 | + #[test] |
| 479 | + fn special_char_name_longest_match_left_to_right() { |
| 480 | + // Longest in-scope prefix wins: with `a-b-c` also bound, the whole run |
| 481 | + // is one name. |
| 482 | + assert_eq!( |
| 483 | + eval_in("a-b-c", &[("a-b", num(1.0)), ("a-b-c", num(2.0))]), |
| 484 | + num(2.0) |
| 485 | + ); |
| 486 | + // With only `a-b` bound, the run fuses `a-b` and subtracts the rest. |
| 487 | + assert_eq!( |
| 488 | + eval_in("a-b-c", &[("a-b", num(10.0)), ("c", num(4.0))]), |
| 489 | + num(6.0) |
| 490 | + ); |
| 491 | + // The scan resumes after a fused name: `Date-Time - Date-Time2` fuses |
| 492 | + // BOTH names and keeps the minus an operator — the TCK 0007 expectation |
| 493 | + // (subtraction), reproduced by longest-match at each position. |
| 494 | + let dt = &[("Date-Time", num(100.0)), ("Date-Time2", num(58.0))]; |
| 495 | + assert_eq!(eval_in("Date-Time - Date-Time2", dt), num(42.0)); |
| 496 | + // ... and after a miss the scan continues INSIDE the run: `b-c` bound |
| 497 | + // in `a-b-c` parses as `a - b-c`. |
| 498 | + assert_eq!( |
| 499 | + eval_in("a-b-c", &[("a", num(8.0)), ("b-c", num(3.0))]), |
| 500 | + num(5.0) |
| 501 | + ); |
| 502 | + // `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name. |
| 503 | + let esc = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]; |
| 504 | + assert_eq!(eval_in("(a)-(b)", esc), num(4.0)); |
| 505 | + } |
| 506 | + |
| 507 | + #[test] |
| 508 | + fn special_char_name_vs_path_and_members() { |
| 509 | + // `x.y` is ambiguous between one name and a path (§10.3.1.6): the |
| 510 | + // in-scope name wins when bound; otherwise the path stands. |
| 511 | + let nested = &[("x", ctx_value(&[("y", num(5.0))]))]; |
| 512 | + assert_eq!(eval_in("x.y", nested), num(5.0)); // path |
| 513 | + assert_eq!(eval_in("x.y", &[("x.y", num(9.0))]), num(9.0)); // name |
| 514 | + // A hyphen name as a PATH BASE: the whole-run candidate `Date-Time2.hour` |
| 515 | + // is not in scope, so `Date-Time2` fuses and `.hour` stays a member. |
| 516 | + let dt2 = &[("Date-Time2", ctx_value(&[("hour", num(3.0))]))]; |
| 517 | + assert_eq!(eval_in("Date-Time2.hour", dt2), num(3.0)); |
| 518 | + // A multi-word member stays a member: `Date-Time2.time offset`. |
| 519 | + let off = &[("Date-Time2", ctx_value(&[("time offset", num(2.0))]))]; |
| 520 | + assert_eq!(eval_in("Date-Time2.time offset", off), num(2.0)); |
| 521 | + // But a bound name of the WHOLE dotted run wins over the path (longest |
| 522 | + // match at the run start). |
| 523 | + let whole = &[ |
| 524 | + ("Date-Time2", ctx_value(&[("hour", num(3.0))])), |
| 525 | + ("Date-Time2.hour", num(7.0)), |
| 526 | + ]; |
| 527 | + assert_eq!(eval_in("Date-Time2.hour", whole), num(7.0)); |
| 528 | + } |
| 529 | + |
| 530 | + #[test] |
| 531 | + fn compile_is_probe_free_and_reports_name_runs() { |
| 532 | + // `compile` never fuses: `a-b` stays subtraction even when bound in the |
| 533 | + // context it is later evaluated against (a compiled program pins no |
| 534 | + // scope — the documented compile-once policy, ADR-47). |
| 535 | + let bound = ctx_of(&[("a-b", num(10.0))]); |
| 536 | + assert_eq!( |
| 537 | + compile("a-b").unwrap().evaluate(&bound).unwrap().into_lenient(), |
| 538 | + Value::Null |
| 539 | + ); |
| 540 | + assert_eq!( |
| 541 | + compile_with_probe("a-b", &bound) |
| 542 | + .unwrap() |
| 543 | + .evaluate(&bound) |
| 544 | + .unwrap() |
| 545 | + .into_lenient(), |
| 546 | + num(10.0) |
| 547 | + ); |
| 548 | + |
| 549 | + // `has_name_runs`: set when a probe-aware parse SAW a run (fused or |
| 550 | + // not) — the parse consulted the scope; false without a run pattern. |
| 551 | + let empty = Context::empty(); |
| 552 | + assert!(compile_with_probe("a-b", &empty).unwrap().has_name_runs()); |
| 553 | + assert!(!compile_with_probe("a + 1", &empty).unwrap().has_name_runs()); // `1` is no word |
| 554 | + assert!(!compile("a-b").unwrap().has_name_runs()); // probe-free parse never consults |
| 555 | + // Adjacency never forms a run (`a and b`, `for x in y` are untouched). |
| 556 | + assert!(!compile_with_probe("a and b", &empty).unwrap().has_name_runs()); |
| 557 | + assert!(!compile_with_probe("for x in y return x", &empty).unwrap().has_name_runs()); |
| 558 | + |
| 559 | + // `name_run_candidates`: every fusable candidate, from every unit |
| 560 | + // position — the probe-free "could this parse be scope-dependent" set |
| 561 | + // (feel-pg's cache check). Empty for run-free texts. |
| 562 | + assert_eq!(name_run_candidates("a-b-c"), vec!["a-b-c", "a-b", "b-c"]); |
| 563 | + assert!(name_run_candidates("1 + 1").is_empty()); |
| 564 | + assert!(name_run_candidates("a and b").is_empty()); |
| 565 | + assert_eq!(name_run_candidates("x.y"), vec!["x.y"]); |
| 566 | + assert_eq!(name_run_candidates("if-then"), vec!["if-then"]); |
| 567 | + assert_eq!( |
| 568 | + name_run_candidates("Date-Time - Date-Time2"), |
| 569 | + vec![ |
| 570 | + "Date-Time-Date-Time2", |
| 571 | + "Date-Time-Date", |
| 572 | + "Date-Time", |
| 573 | + "Time-Date-Time2", |
| 574 | + "Time-Date", |
| 575 | + "Date-Time2" |
| 576 | + ] |
| 577 | + ); |
| 578 | + } |
| 579 | + |
| 580 | + #[test] |
| 581 | + fn special_char_name_run_free_shapes_stay_untouched() { |
| 582 | + // No candidate in scope: every one of these keeps its operator reading. |
| 583 | + let empty = Context::empty(); |
| 584 | + let ev0 = |src: &str| { |
| 585 | + evaluate(src, &empty) |
| 586 | + .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 587 | + .into_lenient() |
| 588 | + }; |
| 589 | + // Numeric operands never form runs (a name part cannot start with a digit). |
| 590 | + assert_eq!(ev0("1 + 1"), num(2.0)); |
| 591 | + assert_eq!(ev0("3 - 1"), num(2.0)); |
| 592 | + assert_eq!(ev0("a - 1"), Value::Null); // unbound `a`, minus 1 |
| 593 | + assert_eq!(ev0("x and y"), Value::Null); // adjacency: boolean and of nulls |
| 594 | + // Range/descendant/exponent separators are not name symbols. |
| 595 | + assert_eq!(ev0("5 in [1..10]"), b(true)); |
| 596 | + assert_eq!(ev0("2 ** 3"), num(8.0)); |
| 597 | + assert_eq!(ev0("for i in [1,2] return i"), list(vec![num(1.0), num(2.0)])); |
| 598 | + assert_eq!( |
| 599 | + ev0("for i in [2, 3] return i - 1"), |
| 600 | + list(vec![num(1.0), num(2.0)]) |
| 601 | + ); |
| 602 | + // Declaration slots are deferred (ADR-47): `for a-b in …` declares no |
| 603 | + // hyphen loop variable — it stays a parse error. |
| 604 | + assert!(compile("for a-b in [1] return a-b").is_err()); |
| 342 | 605 | } |
| 343 | 606 | |
| 344 | 607 | #[test] |