| @@ -81,20 +81,28 @@ |
| 81 | 81 | } |
| 82 | 82 | } |
| 83 | 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. |
| 84 | +/// The parse-time "name oracle" for special-character names (§10.3.1.6, |
| 85 | +/// ADR-47/48): decides which candidate names are in scope, so the lexer can fuse |
| 86 | +/// FEEL's additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names. |
| 87 | 87 | /// |
| 88 | 88 | /// std-only (ADR-1), like the other host seams. The canonical implementation is |
| 89 | 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). |
| 90 | +/// [`contains`](ScopeProbe::contains) mirrors `Expr::Var` resolution exactly: a |
| 91 | +/// context binding or a built-in function name. |
| 94 | 92 | pub trait ScopeProbe { |
| 95 | 93 | /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would |
| 96 | 94 | /// find a value (a context binding or a built-in function name). |
| 97 | 95 | fn contains(&self, name: &str) -> bool; |
| 96 | + |
| 97 | + /// Whether the value reached by the **static** path `path` (root name first, |
| 98 | + /// e.g. `["applicant"]` for `applicant.first-name`) has a member `name` |
| 99 | + /// (ADR-48). A list on the way is mapped over, as the FEEL dot does; the |
| 100 | + /// member counts if **any** element has it. The default — `false` — keeps |
| 101 | + /// member positions arithmetic (`applicant.first - name`). |
| 102 | + fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 103 | + let _ = (path, name); |
| 104 | + false |
| 105 | + } |
| 98 | 106 | } |
| 99 | 107 | |
| 100 | 108 | impl ScopeProbe for Context { |
| @@ -104,13 +112,38 @@ |
| 104 | 112 | // about the first two. |
| 105 | 113 | self.get(name).is_some() || crate::builtins::is_builtin(name) |
| 106 | 114 | } |
| 115 | + |
| 116 | + fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 117 | + let Some((root, rest)) = path.split_first() else { |
| 118 | + return false; |
| 119 | + }; |
| 120 | + self.get(root).is_some_and(|v| has_member(v, rest, name)) |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/// Navigate `rest` from `v` like the FEEL dot (a list maps over its elements) |
| 125 | +/// and report whether the end has a member `name` — for a list: any element. |
| 126 | +/// Navigation is by reference for owned values; a lazy [`Foreign`] node is asked |
| 127 | +/// via [`ForeignObject::get`] one segment at a time (feel-pg's jsonb, the |
| 128 | +/// wrappers' host objects), so only the probed path is touched. |
| 129 | +fn has_member(v: &Value, rest: &[&str], name: &str) -> bool { |
| 130 | + match (v, rest.split_first()) { |
| 131 | + (Value::List(items), _) => items.iter().any(|it| has_member(it, rest, name)), |
| 132 | + (Value::Context(map), None) => map.contains_key(name), |
| 133 | + (Value::Context(map), Some((seg, more))) => { |
| 134 | + map.get(*seg).is_some_and(|next| has_member(next, more, name)) |
| 135 | + } |
| 136 | + (Value::Foreign(f), None) => !matches!(f.0.get(name), Value::Null), |
| 137 | + (Value::Foreign(f), Some((seg, more))) => has_member(&f.0.get(seg), more, name), |
| 138 | + _ => false, |
| 139 | + } |
| 107 | 140 | } |
| 108 | 141 | |
| 109 | 142 | /// A [`Context`] plus an ambient [`FunctionRegistry`] (ADR-23) as one parse-time |
| 110 | 143 | /// scope (ADR-47): a call head resolves against context, built-ins and — third — |
| 111 | 144 | /// the registry (`eval_call`), so a hyphen-named host function (`my-fn(1)`) must |
| 112 | | -/// be in scope for the fusion too. The wrappers' one-shot `evaluate` parses |
| 113 | | -/// against this when a `functions` registry is supplied. |
| 145 | +/// be in scope for the fusion too. [`CompiledExpr::evaluate_with_env`] probes |
| 146 | +/// this automatically with the env's registry. |
| 114 | 147 | /// |
| 115 | 148 | /// Slightly wider than `Expr::Var` (which never consults the registry): a bare, |
| 116 | 149 | /// uncalled `my-fn` fuses to a name that evaluates to null — the same null the |
| @@ -124,9 +157,59 @@ |
| 124 | 157 | |
| 125 | 158 | impl ScopeProbe for ScopeWithFunctions<'_> { |
| 126 | 159 | fn contains(&self, name: &str) -> bool { |
| 127 | | - self.context.contains(name) || self.functions.get(name).is_some() |
| 160 | + self.context.contains(name) || self.functions.contains(name) |
| 161 | + } |
| 162 | + |
| 163 | + fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 164 | + self.context.contains_member(path, name) |
| 128 | 165 | } |
| 129 | 166 | } |
| 167 | + |
| 168 | +/// How far the parser goes in reading FEEL's ambiguous names (ADR-48) — a parse |
| 169 | +/// option ([`ParseOptions`]). Backtick-quoted names (`` `a-b` ``, the feel-scala |
| 170 | +/// extension) work at every level. |
| 171 | +#[non_exhaustive] |
| 172 | +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] |
| 173 | +pub enum NameResolution { |
| 174 | + /// Only backtick-quoted names are special; `a-b` is always subtraction — |
| 175 | + /// Camunda/feel-scala semantics. No scope checks at all: the cheapest level. |
| 176 | + Quoted, |
| 177 | + /// Backticks plus §10.3.1.6 runs over `- + * / .`, resolved against the |
| 178 | + /// scope (ADR-47) and, on static paths, against the navigated value (ADR-48). |
| 179 | + #[default] |
| 180 | + Symbols, |
| 181 | +} |
| 182 | + |
| 183 | +impl NameResolution { |
| 184 | + /// Parse the textual level used by the wrappers and feel-pg |
| 185 | + /// (`"quoted"` | `"symbols"`, case-insensitive). |
| 186 | + pub fn from_name(s: &str) -> Option<Self> { |
| 187 | + match s.to_ascii_lowercase().as_str() { |
| 188 | + "quoted" => Some(Self::Quoted), |
| 189 | + "symbols" => Some(Self::Symbols), |
| 190 | + _ => None, |
| 191 | + } |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +/// Options for [`compile_with`] / [`evaluate_with`] (ADR-48). |
| 196 | +#[non_exhaustive] |
| 197 | +#[derive(Debug, Default, Clone, PartialEq, Eq)] |
| 198 | +pub struct ParseOptions { |
| 199 | + /// The name-resolution level (default [`NameResolution::Symbols`]). |
| 200 | + pub names: NameResolution, |
| 201 | +} |
| 202 | + |
| 203 | +impl ParseOptions { |
| 204 | + /// Options with the given name-resolution level. |
| 205 | + pub fn names(names: NameResolution) -> Self { |
| 206 | + Self { names } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +/// How many scope-specific parses a [`CompiledExpr`] keeps (LRU). One per |
| 211 | +/// distinct probe-answer trace; real workloads see one or two. |
| 212 | +const SCOPED_PARSE_CACHE: usize = 8; |
| 130 | 213 | |
| 131 | 214 | /// A parsed FEEL expression, ready to be evaluated repeatedly. |
| 132 | 215 | /// |
| @@ -134,6 +217,12 @@ |
| 134 | 217 | /// that evaluate the same expression against many contexts (e.g. one decision |
| 135 | 218 | /// over many rows) should [`compile`] once and reuse the result. The wrapped AST |
| 136 | 219 | /// is fully owning, so a `CompiledExpr` carries no borrow of the source string. |
| 220 | +/// |
| 221 | +/// **Scope-adaptive** (ADR-48): when the text contains special-character runs |
| 222 | +/// (`a-b`, `x.y`), each evaluation checks them against the context — one lookup |
| 223 | +/// per candidate — and picks the parse for that scope. The parse is a pure |
| 224 | +/// function of the text and the probe's answers, so it is cached per answer set |
| 225 | +/// (bounded, LRU); a text without runs never checks anything. |
| 137 | 226 | /// |
| 138 | 227 | /// ``` |
| 139 | 228 | /// use feel_core::{compile, Context, Value}; |
| @@ -144,14 +233,23 @@ |
| 144 | 233 | /// ``` |
| 145 | 234 | #[derive(Debug, Clone)] |
| 146 | 235 | pub struct CompiledExpr { |
| 147 | | - /// The parsed program. |
| 148 | | - expr: ast::Expr, |
| 149 | | - /// Whether the parse consulted a scope probe on a special-character name |
| 150 | | - /// run (`a-b`, `Date-Time`, …) — i.e. is **scope-dependent**: another scope |
| 151 | | - /// could fuse the same text differently (ADR-47). Only a probe-aware parse |
| 152 | | - /// (`compile_with_probe`/`evaluate`) sets it; `compile` is probe-free and |
| 153 | | - /// reports `false`. |
| 154 | | - name_runs: bool, |
| 236 | + /// The scope-free parse: no run fused. Correct for every scope that binds |
| 237 | + /// none of the run candidates — the overwhelming case. |
| 238 | + base: std::sync::Arc<ast::Expr>, |
| 239 | + /// Present iff some scope could fuse a run (see [`Scoped`]); `None` for |
| 240 | + /// run-free texts, [`NameResolution::Quoted`] and probe-pinned parses. |
| 241 | + scoped: Option<std::sync::Arc<Scoped>>, |
| 242 | + /// The level this was compiled at. |
| 243 | + names: NameResolution, |
| 244 | +} |
| 245 | + |
| 246 | +/// The scope-dependent half of a [`CompiledExpr`]: the pre-fusion tokens to |
| 247 | +/// re-fuse against each evaluation's scope, and the parses already built, keyed |
| 248 | +/// by the fusion's probe-answer trace. Shared between clones. |
| 249 | +#[derive(Debug)] |
| 250 | +struct Scoped { |
| 251 | + toks: Vec<lexer::Spanned>, |
| 252 | + cache: std::sync::Mutex<Vec<(lexer::Trace, std::sync::Arc<ast::Expr>)>>, |
| 155 | 253 | } |
| 156 | 254 | |
| 157 | 255 | impl CompiledExpr { |
| @@ -176,15 +274,51 @@ |
| 176 | 274 | /// `now()`/`today()` read (ADR-18). The wrappers inject their host's clock |
| 177 | 275 | /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()` |
| 178 | 276 | /// deterministic in tests. |
| 277 | + /// |
| 278 | + /// The scope for special-character names is `context` plus the env's |
| 279 | + /// function registry ([`ScopeWithFunctions`]; ADR-48). |
| 179 | 280 | pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> { |
| 180 | | - eval::Evaluator::new(env).eval(&self.expr, context) |
| 181 | | - } |
| 182 | | - |
| 183 | | - /// The parsed AST. `pub(crate)` so the `range(string)` built-in can inspect a |
| 184 | | - /// freshly-parsed range literal's *shape* (its endpoints must be literals, not |
| 185 | | - /// arbitrary expressions — DMN §10.3.4.6) before evaluating it. |
| 281 | + let scope = ScopeWithFunctions { |
| 282 | + context, |
| 283 | + functions: env.functions, |
| 284 | + }; |
| 285 | + let expr = self.resolve(&scope)?; |
| 286 | + eval::Evaluator::new(env).eval(&expr, context) |
| 287 | + } |
| 288 | + |
| 289 | + /// The parse for `probe`'s scope: the base parse when no run fuses, else |
| 290 | + /// the cached (or newly built) parse for this probe-answer trace. |
| 291 | + fn resolve(&self, probe: &dyn ScopeProbe) -> Result<std::sync::Arc<ast::Expr>, FeelError> { |
| 292 | + let Some(scoped) = &self.scoped else { |
| 293 | + return Ok(self.base.clone()); |
| 294 | + }; |
| 295 | + let mut trace = lexer::Trace::new(); |
| 296 | + lexer::fusion_trace(&scoped.toks, probe, &mut trace); |
| 297 | + if !trace.iter().any(|&hit| hit) { |
| 298 | + return Ok(self.base.clone()); |
| 299 | + } |
| 300 | + { |
| 301 | + let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner()); |
| 302 | + if let Some(pos) = cache.iter().position(|(t, _)| *t == trace) { |
| 303 | + let hit = cache.remove(pos); |
| 304 | + let expr = hit.1.clone(); |
| 305 | + cache.insert(0, hit); |
| 306 | + return Ok(expr); |
| 307 | + } |
| 308 | + } |
| 309 | + let expr = std::sync::Arc::new(parse_tokens(lexer::fuse(&scoped.toks, probe))?); |
| 310 | + let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner()); |
| 311 | + cache.insert(0, (trace, expr.clone())); |
| 312 | + cache.truncate(SCOPED_PARSE_CACHE); |
| 313 | + Ok(expr) |
| 314 | + } |
| 315 | + |
| 316 | + /// The parsed AST (the base parse). `pub(crate)` so the `range(string)` |
| 317 | + /// built-in can inspect a freshly-parsed range literal's *shape* (its |
| 318 | + /// endpoints must be literals, not arbitrary expressions — DMN §10.3.4.6) |
| 319 | + /// before evaluating it. |
| 186 | 320 | pub(crate) fn ast(&self) -> &ast::Expr { |
| 187 | | - &self.expr |
| 321 | + &self.base |
| 188 | 322 | } |
| 189 | 323 | |
| 190 | 324 | /// `true` if this expression never reads the wall clock — it calls neither |
| @@ -193,23 +327,28 @@ |
| 193 | 327 | /// expression indexes; RD-10) gate on this: a non-clock-free expression cannot |
| 194 | 328 | /// be IMMUTABLE because `now()`/`today()` vary over time. |
| 195 | 329 | /// |
| 330 | + /// Judged on the base parse, which is conservative: a scope can only fuse a |
| 331 | + /// call head *into* a special name (`x-now()`), never create a `now()` call. |
| 332 | + /// |
| 196 | 333 | /// This is the *static* half. The runtime half — forbidding *named* time zones, |
| 197 | 334 | /// whose offsets depend on the updatable IANA tzdb — is |
| 198 | 335 | /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope |
| 199 | 336 | /// here (the embedder's concern; feel-pg has no host-function seam). |
| 200 | 337 | pub fn is_clock_free(&self) -> bool { |
| 201 | | - self.expr.is_clock_free() |
| 202 | | - } |
| 203 | | - |
| 204 | | - /// `true` if parsing consulted a scope probe on a special-character name run |
| 205 | | - /// (`a-b`, `Date-Time`, …; §10.3.1.6, ADR-47): this parse is |
| 206 | | - /// **scope-dependent** — the same text could parse differently under another |
| 207 | | - /// scope. Only a probe-aware parse sets it; [`compile`] is probe-free and |
| 208 | | - /// reports `false`. Hosts that cache parses across contexts can instead check |
| 209 | | - /// [`name_run_candidates`] against each context, which distinguishes "could |
| 210 | | - /// be ambiguous" from "this scope actually changes the parse". |
| 211 | | - pub fn has_name_runs(&self) -> bool { |
| 212 | | - self.name_runs |
| 338 | + self.base.is_clock_free() |
| 339 | + } |
| 340 | + |
| 341 | + /// The name-resolution level this was compiled at (ADR-48). |
| 342 | + pub fn name_resolution(&self) -> NameResolution { |
| 343 | + self.names |
| 344 | + } |
| 345 | + |
| 346 | + /// How many scope-specific parses are cached right now (≤ 8; ADR-48) — a |
| 347 | + /// diagnostic for tests and benchmarks. |
| 348 | + pub fn scoped_parses(&self) -> usize { |
| 349 | + self.scoped |
| 350 | + .as_ref() |
| 351 | + .map_or(0, |s| s.cache.lock().unwrap_or_else(|e| e.into_inner()).len()) |
| 213 | 352 | } |
| 214 | 353 | } |
| 215 | 354 | |
| @@ -223,6 +362,14 @@ |
| 223 | 362 | /// Resolve a host function by name. Absent -> `None` (the call is then a |
| 224 | 363 | /// built-in or, failing that, an error-null). |
| 225 | 364 | fn get(&self, name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>>; |
| 365 | + |
| 366 | + /// Whether a host function `name` exists — the scope check for |
| 367 | + /// special-character call heads (ADR-48), run once per candidate per |
| 368 | + /// evaluation. Override with an allocation-free lookup; the default builds |
| 369 | + /// the callable via [`get`](FunctionRegistry::get). |
| 370 | + fn contains(&self, name: &str) -> bool { |
| 371 | + self.get(name).is_some() |
| 372 | + } |
| 226 | 373 | } |
| 227 | 374 | |
| 228 | 375 | /// The empty registry: no ambient host functions. Used as the default in |
| @@ -309,69 +456,99 @@ |
| 309 | 456 | jiff::Zoned::now() |
| 310 | 457 | } |
| 311 | 458 | |
| 312 | | -/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it. |
| 459 | +/// Run the lalrpop parser over a finished-or-not token stream. |
| 460 | +fn parse_tokens(toks: Vec<lexer::Spanned>) -> Result<ast::Expr, FeelError> { |
| 461 | + feel::ExprParser::new() |
| 462 | + .parse(lexer::finish(toks)) |
| 463 | + .map_err(|e| FeelError::Parse(e.to_string())) |
| 464 | +} |
| 465 | + |
| 466 | +/// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating |
| 467 | +/// it, at the default [`NameResolution::Symbols`] level. |
| 313 | 468 | /// |
| 314 | 469 | /// Returns [`FeelError::Parse`] if the expression is syntactically invalid. |
| 315 | 470 | /// |
| 316 | | -/// **Probe-free** (ADR-47): special-character name runs (`a-b`, `Date-Time`) |
| 317 | | -/// parse as arithmetic here — a compiled program must not pin one scope. Use |
| 318 | | -/// [`compile_with_probe`] when the scope is known at parse time, or the one-shot |
| 319 | | -/// [`evaluate`], which uses the context as the probe (§10.3.1.6). |
| 471 | +/// **Scope-adaptive** (ADR-48): special-character names (`a-b`, `Date-Time`, |
| 472 | +/// `applicant.first-name`) resolve per evaluation against the context, exactly |
| 473 | +/// like the one-shot [`evaluate`] — see [`CompiledExpr`]. |
| 320 | 474 | /// |
| 321 | 475 | /// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime |
| 322 | 476 | /// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the |
| 323 | 477 | /// per-call parse itself, which [`CompiledExpr`] lets callers pay once. |
| 324 | 478 | pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> { |
| 325 | | - feel::ExprParser::new() |
| 326 | | - .parse(lexer::lex(expr)) |
| 327 | | - .map(|expr| CompiledExpr { expr, name_runs: false }) |
| 328 | | - .map_err(|e| FeelError::Parse(e.to_string())) |
| 479 | + compile_with(expr, &ParseOptions::default()) |
| 329 | 480 | } |
| 330 | 481 | |
| 331 | | -/// Parse a FEEL expression with scope-dependent name resolution (§10.3.1.6, |
| 332 | | -/// ADR-47): special-character name runs (`a-b`, `Date-Time`, `x.y`) are fused |
| 333 | | -/// into single names when — and only when — the joined candidate is in scope |
| 334 | | -/// per `probe`, longest in-scope match preferred, left to right. Spaces are not |
| 335 | | -/// part of the name (`a - b` is the same candidate as `a-b`); `(a)-(b)` forces |
| 336 | | -/// the operator reading. |
| 337 | | -/// |
| 338 | | -/// The result's [`CompiledExpr::has_name_runs`] tells whether the parse |
| 339 | | -/// consulted the scope at all. For expressions with no name-run *pattern* |
| 340 | | -/// (see [`name_run_candidates`]), this is byte-identical to [`compile`]. |
| 482 | +/// [`compile`] with explicit [`ParseOptions`] (ADR-48). |
| 483 | +pub fn compile_with(expr: &str, options: &ParseOptions) -> Result<CompiledExpr, FeelError> { |
| 484 | + let toks = lexer::lex_base(expr); |
| 485 | + let scoped = (options.names == NameResolution::Symbols && lexer::may_fuse(&toks)) |
| 486 | + .then(|| Scoped { |
| 487 | + toks: toks.clone(), |
| 488 | + cache: std::sync::Mutex::new(Vec::new()), |
| 489 | + }) |
| 490 | + .map(std::sync::Arc::new); |
| 491 | + Ok(CompiledExpr { |
| 492 | + base: std::sync::Arc::new(parse_tokens(toks)?), |
| 493 | + scoped, |
| 494 | + names: options.names, |
| 495 | + }) |
| 496 | +} |
| 497 | + |
| 498 | +/// Parse a FEEL expression **pinned** to one scope (§10.3.1.6, ADR-47/48): |
| 499 | +/// special-character runs (`a-b`, `Date-Time`, `x.y`, `applicant.first-name`) |
| 500 | +/// are fused into names exactly when `probe` has them in scope, longest match |
| 501 | +/// first, left to right; `(a)-(b)` forces the operator reading. The result does |
| 502 | +/// **not** adapt to later contexts — use it when the scope is known up front |
| 503 | +/// (a one-shot evaluation, a host with a fixed schema); otherwise prefer the |
| 504 | +/// adaptive [`compile`]. At [`NameResolution::Quoted`] the probe is ignored. |
| 341 | 505 | pub fn compile_with_probe( |
| 342 | 506 | expr: &str, |
| 343 | 507 | probe: &dyn ScopeProbe, |
| 508 | + options: &ParseOptions, |
| 344 | 509 | ) -> Result<CompiledExpr, FeelError> { |
| 345 | | - let (toks, name_runs) = lexer::lex_with_probe(expr, probe); |
| 346 | | - feel::ExprParser::new() |
| 347 | | - .parse(toks) |
| 348 | | - .map(|expr| CompiledExpr { expr, name_runs }) |
| 349 | | - .map_err(|e| FeelError::Parse(e.to_string())) |
| 510 | + let toks = lexer::lex_base(expr); |
| 511 | + let toks = match options.names { |
| 512 | + NameResolution::Symbols => lexer::fuse(&toks, probe), |
| 513 | + NameResolution::Quoted => toks, |
| 514 | + }; |
| 515 | + Ok(CompiledExpr { |
| 516 | + base: std::sync::Arc::new(parse_tokens(toks)?), |
| 517 | + scoped: None, |
| 518 | + names: options.names, |
| 519 | + }) |
| 350 | 520 | } |
| 351 | 521 | |
| 352 | 522 | /// Parse and evaluate a FEEL expression against a context. |
| 353 | 523 | /// |
| 354 | | -/// Convenience for `compile_with_probe(expr, context)?.evaluate(context)`; |
| 355 | | -/// prefer [`compile_with_probe`] when evaluating the same expression more than |
| 356 | | -/// once against the same scope. The context **is** the scope for §10.3.1.6 |
| 357 | | -/// name resolution (ADR-47): a name like `a-b` resolves to the context binding |
| 358 | | -/// when one exists, and to subtraction otherwise. |
| 524 | +/// One parse, pinned to `context` as the §10.3.1.6 scope (ADR-47): a name like |
| 525 | +/// `a-b` resolves to the context binding when one exists, and to subtraction |
| 526 | +/// otherwise. Prefer [`compile`] when evaluating the same expression more than |
| 527 | +/// once. |
| 359 | 528 | /// |
| 360 | 529 | /// ``` |
| 361 | 530 | /// use feel_core::{evaluate, Context, Value}; |
| 362 | 531 | /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0)); |
| 363 | 532 | /// ``` |
| 364 | 533 | pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> { |
| 365 | | - compile_with_probe(expr, context)?.evaluate(context) |
| 534 | + evaluate_with(expr, context, &ParseOptions::default()) |
| 366 | 535 | } |
| 367 | 536 | |
| 368 | | -/// Every special-character name candidate `expr` could fuse under *some* scope |
| 369 | | -/// (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, `a-b`, `b-c`. Probe-free |
| 370 | | -/// and cheap; the use case is a host that caches a probe-free parse across |
| 371 | | -/// contexts (feel-pg's `fn_extra` slot): if none of the candidates is bound in |
| 372 | | -/// a given context, the cached parse is already scope-correct; if any is bound, |
| 373 | | -/// re-parse that context with [`compile_with_probe`]. An empty result means the |
| 374 | | -/// expression's parse is scope-independent for every possible context. |
| 537 | +/// [`evaluate`] with explicit [`ParseOptions`] (ADR-48). |
| 538 | +pub fn evaluate_with( |
| 539 | + expr: &str, |
| 540 | + context: &Context, |
| 541 | + options: &ParseOptions, |
| 542 | +) -> Result<Value, FeelError> { |
| 543 | + compile_with_probe(expr, context, options)?.evaluate(context) |
| 544 | +} |
| 545 | + |
| 546 | +/// Every **root-level** special-character name candidate `expr` could fuse |
| 547 | +/// under *some* scope (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, |
| 548 | +/// `a-b`, `b-c`. A diagnostic: its length is the number of root-scope lookups |
| 549 | +/// one evaluation of the compiled expression pays (path-member candidates, |
| 550 | +/// ADR-48, come on top and are not listed). Empty ⇒ the parse is |
| 551 | +/// scope-independent at the root level. |
| 375 | 552 | pub fn name_run_candidates(expr: &str) -> Vec<String> { |
| 376 | 553 | lexer::name_run_candidates(expr) |
| 377 | 554 | } |
| @@ -550,33 +727,27 @@ |
| 550 | 727 | } |
| 551 | 728 | |
| 552 | 729 | #[test] |
| 553 | | - fn compile_is_probe_free_and_reports_name_runs() { |
| 554 | | - // `compile` never fuses: `a-b` stays subtraction even when bound in the |
| 555 | | - // context it is later evaluated against (a compiled program pins no |
| 556 | | - // scope — the documented compile-once policy, ADR-47). |
| 730 | + fn compile_is_scope_adaptive_and_pinned_parse_is_not() { |
| 731 | + // ADR-48: `compile` follows each evaluation's scope, exactly like the |
| 732 | + // one-shot `evaluate` — one compiled program, both readings. |
| 557 | 733 | let bound = ctx_of(&[("a-b", num(10.0))]); |
| 558 | | - assert_eq!( |
| 559 | | - compile("a-b").unwrap().evaluate(&bound).unwrap().into_lenient(), |
| 560 | | - Value::Null |
| 561 | | - ); |
| 562 | | - assert_eq!( |
| 563 | | - compile_with_probe("a-b", &bound) |
| 564 | | - .unwrap() |
| 565 | | - .evaluate(&bound) |
| 566 | | - .unwrap() |
| 567 | | - .into_lenient(), |
| 568 | | - num(10.0) |
| 569 | | - ); |
| 570 | | - |
| 571 | | - // `has_name_runs`: set when a probe-aware parse SAW a run (fused or |
| 572 | | - // not) — the parse consulted the scope; false without a run pattern. |
| 573 | | - let empty = Context::empty(); |
| 574 | | - assert!(compile_with_probe("a-b", &empty).unwrap().has_name_runs()); |
| 575 | | - assert!(!compile_with_probe("a + 1", &empty).unwrap().has_name_runs()); // `1` is no word |
| 576 | | - assert!(!compile("a-b").unwrap().has_name_runs()); // probe-free parse never consults |
| 577 | | - // Adjacency never forms a run (`a and b`, `for x in y` are untouched). |
| 578 | | - assert!(!compile_with_probe("a and b", &empty).unwrap().has_name_runs()); |
| 579 | | - assert!(!compile_with_probe("for x in y return x", &empty).unwrap().has_name_runs()); |
| 734 | + let parts = ctx_of(&[("a", num(7.0)), ("b", num(3.0))]); |
| 735 | + let prog = compile("a-b").unwrap(); |
| 736 | + assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 737 | + assert_eq!(prog.evaluate(&parts).unwrap().into_lenient(), num(4.0)); |
| 738 | + assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 739 | + // One scoped parse cached (the `a-b` reading); the base serves `parts`. |
| 740 | + assert_eq!(prog.scoped_parses(), 1); |
| 741 | + |
| 742 | + // `compile_with_probe` PINS its probe's scope: no adaptation later. |
| 743 | + let pinned = compile_with_probe("a-b", &bound, &ParseOptions::default()).unwrap(); |
| 744 | + assert_eq!(pinned.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 745 | + assert_eq!(pinned.evaluate(&parts).unwrap().into_lenient(), Value::Null); |
| 746 | + |
| 747 | + // Run-free texts never build a scoped half. |
| 748 | + let plain = compile("a + 1").unwrap(); |
| 749 | + assert_eq!(plain.evaluate(&parts).unwrap().into_lenient(), num(8.0)); |
| 750 | + assert_eq!(plain.scoped_parses(), 0); |
| 580 | 751 | |
| 581 | 752 | // `name_run_candidates`: every fusable candidate, from every unit |
| 582 | 753 | // position — the probe-free "could this parse be scope-dependent" set |
| @@ -662,16 +833,15 @@ |
| 662 | 833 | ("r-s", num(1.0)), |
| 663 | 834 | ]); |
| 664 | 835 | assert_eq!(evaluate("p.q.r-s", &deep).unwrap().into_lenient(), num(-3.0)); |
| 665 | | - // Pinned v1 gap (ADR-47 deviation "names in inner scopes"): only the root |
| 666 | | - // level is probed, so a nested hyphen KEY is not reachable as a member — |
| 667 | | - // `applicant.first-name` stays `applicant.first - name`. |
| 836 | + // ADR-48 lifts the ADR-47 root-only gap: on a static path the navigated |
| 837 | + // value is probed, so a nested hyphen KEY is reachable as a member. |
| 668 | 838 | let nested = ctx_of(&[( |
| 669 | 839 | "applicant", |
| 670 | 840 | ctx_value(&[("first-name", Value::String("Ada".into()))]), |
| 671 | 841 | )]); |
| 672 | 842 | assert_eq!( |
| 673 | 843 | evaluate("applicant.first-name", &nested).unwrap().into_lenient(), |
| 674 | | - Value::Null |
| 844 | + Value::String("Ada".into()) |
| 675 | 845 | ); |
| 676 | 846 | } |
| 677 | 847 | |
| @@ -693,11 +863,6 @@ |
| 693 | 863 | .into_lenient(), |
| 694 | 864 | list(vec![num(-1.0), num(-2.0)]) |
| 695 | 865 | ); |
| 696 | | - assert!( |
| 697 | | - !compile_with_probe("for i in [1,2] return -i", &ctx) |
| 698 | | - .unwrap() |
| 699 | | - .has_name_runs() |
| 700 | | - ); |
| 701 | 866 | // Value keywords do not start runs either: a bound `if-then` is not a |
| 702 | 867 | // name (it stays the — invalid — `if - then`), nor is `true-x`. |
| 703 | 868 | let if_then = ctx_of(&[("if-then", b(true))]); |
| @@ -706,6 +871,166 @@ |
| 706 | 871 | // Keywords stay legal as NON-starting run words (`x-in`, `a-if`). |
| 707 | 872 | assert_eq!(eval_in("x-in", &[("x-in", num(4.0))]), num(4.0)); |
| 708 | 873 | assert_eq!(eval_in("a-if", &[("a-if", num(5.0))]), num(5.0)); |
| 874 | + } |
| 875 | + |
| 876 | + // ----------------------------------------------------------------------- // |
| 877 | + // ADR-48: backtick-quoted names, resolution levels, adaptive compile cache, |
| 878 | + // path-member probe |
| 879 | + // ----------------------------------------------------------------------- // |
| 880 | + |
| 881 | + fn s(v: &str) -> Value { |
| 882 | + Value::String(v.into()) |
| 883 | + } |
| 884 | + |
| 885 | + #[test] |
| 886 | + fn backtick_names_work_in_every_name_slot() { |
| 887 | + // Scope-independent: decided by the text, so it needs no binding to parse. |
| 888 | + assert_eq!(eval_in("`a-b`", &[("a-b", num(5.0))]), num(5.0)); |
| 889 | + assert_eq!(eval_in("`Profit and loss`", &[("Profit and loss", num(9.0))]), num(9.0)); |
| 890 | + assert_eq!(eval_in("`what if?`", &[("what if?", b(true))]), b(true)); |
| 891 | + assert_eq!(eval_in("`if`", &[("if", num(1.0))]), num(1.0)); // a keyword, quoted |
| 892 | + // Content is verbatim: no space normalisation inside backticks. |
| 893 | + assert_eq!(eval_in("`a b`", &[("a b", num(2.0))]), num(2.0)); |
| 894 | + // Path member, context key + reference, loop variable, call head. |
| 895 | + let app = &[("applicant", ctx_value(&[("first-name", s("Ada"))]))]; |
| 896 | + assert_eq!(eval_in("applicant.`first-name`", app), s("Ada")); |
| 897 | + assert_eq!(eval_in("{`a-b`: 5, c: `a-b` + 1}.c", &[]), num(6.0)); |
| 898 | + assert_eq!( |
| 899 | + eval_in("for `x-y` in [1, 2] return `x-y` * 2", &[]), |
| 900 | + list(vec![num(2.0), num(4.0)]) |
| 901 | + ); |
| 902 | + assert_eq!(eval_in("{`my-fn`: function(x) x * 2, r: `my-fn`(3)}.r", &[]), num(6.0)); |
| 903 | + // A quoted path base feeds the member probe's static path. |
| 904 | + let quoted_base = &[("the app", ctx_value(&[("net-income", num(3.0))]))]; |
| 905 | + assert_eq!(eval_in("`the app`.net-income", quoted_base), num(3.0)); |
| 906 | + } |
| 907 | + |
| 908 | + #[test] |
| 909 | + fn backtick_names_are_never_joined_or_fused() { |
| 910 | + // Not fused: `` `a`-b `` is `a` minus `b`, even with `a-b` bound. |
| 911 | + let ctx = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]; |
| 912 | + assert_eq!(eval_in("`a`-b", ctx), num(4.0)); |
| 913 | + // Not joined with an adjacent word: two names side by side is no FEEL. |
| 914 | + assert!(evaluate("`a b` c", &Context::empty()).is_err()); |
| 915 | + // Unterminated or empty quotes are lex errors. |
| 916 | + assert!(evaluate("`a-b", &Context::empty()).is_err()); |
| 917 | + assert!(evaluate("``", &Context::empty()).is_err()); |
| 918 | + } |
| 919 | + |
| 920 | + #[test] |
| 921 | + fn name_resolution_levels() { |
| 922 | + let quoted = ParseOptions::names(NameResolution::Quoted); |
| 923 | + let ctx = ctx_of(&[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]); |
| 924 | + // Quoted: `a-b` is always subtraction (Camunda semantics) ... |
| 925 | + assert_eq!(evaluate_with("a-b", &ctx, "ed).unwrap(), num(4.0)); |
| 926 | + let prog = compile_with("a-b", "ed).unwrap(); |
| 927 | + assert_eq!(prog.evaluate(&ctx).unwrap(), num(4.0)); |
| 928 | + assert_eq!(prog.scoped_parses(), 0); |
| 929 | + assert_eq!(prog.name_resolution(), NameResolution::Quoted); |
| 930 | + // ... backticks still work ... |
| 931 | + assert_eq!(evaluate_with("`a-b`", &ctx, "ed).unwrap(), num(100.0)); |
| 932 | + // ... and member runs are not probed either. |
| 933 | + let app = ctx_of(&[("applicant", ctx_value(&[("first-name", s("Ada"))]))]); |
| 934 | + assert_eq!( |
| 935 | + evaluate_with("applicant.first-name", &app, "ed).unwrap().into_lenient(), |
| 936 | + Value::Null |
| 937 | + ); |
| 938 | + // Symbols (the default) resolves against the scope. |
| 939 | + assert_eq!(evaluate("a-b", &ctx).unwrap(), num(100.0)); |
| 940 | + assert_eq!(NameResolution::from_name("Quoted"), Some(NameResolution::Quoted)); |
| 941 | + assert_eq!(NameResolution::from_name("symbols"), Some(NameResolution::Symbols)); |
| 942 | + assert_eq!(NameResolution::from_name("full"), None); |
| 943 | + } |
| 944 | + |
| 945 | + #[test] |
| 946 | + fn compiled_parse_cache_is_bounded_and_always_correct() { |
| 947 | + // Four independent runs -> 16 binding combinations, more than the |
| 948 | + // 8-entry cache holds: every evaluation must still be scope-correct. |
| 949 | + let src = "a-b + c-d + e-f + g-h"; |
| 950 | + let prog = compile(src).unwrap(); |
| 951 | + for mask in 0..16u32 { |
| 952 | + for _round in 0..2 { |
| 953 | + let mut ctx = Context::empty(); |
| 954 | + for (bit, (l, r)) in [("a", "b"), ("c", "d"), ("e", "f"), ("g", "h")] |
| 955 | + .into_iter() |
| 956 | + .enumerate() |
| 957 | + { |
| 958 | + ctx.insert(l, num(10.0)); |
| 959 | + ctx.insert(r, num(1.0)); |
| 960 | + if mask & (1 << bit) != 0 { |
| 961 | + ctx.insert(format!("{l}-{r}"), num(100.0)); |
| 962 | + } |
| 963 | + } |
| 964 | + let expected = evaluate(src, &ctx).unwrap(); |
| 965 | + assert_eq!(prog.evaluate(&ctx).unwrap(), expected, "mask {mask}"); |
| 966 | + } |
| 967 | + } |
| 968 | + assert!(prog.scoped_parses() <= 8); |
| 969 | + } |
| 970 | + |
| 971 | + #[test] |
| 972 | + fn path_members_resolve_against_the_navigated_value() { |
| 973 | + let app = ctx_value(&[("net-income", num(100.0)), ("age", num(30.0))]); |
| 974 | + let ctx = &[("applicant", app.clone()), ("total", num(150.0))]; |
| 975 | + assert_eq!(eval_in("applicant.net-income", ctx), num(100.0)); |
| 976 | + // A member run after an operator and as an operand. |
| 977 | + assert_eq!(eval_in("total - applicant.net-income", ctx), num(50.0)); |
| 978 | + assert_eq!(eval_in("applicant.net-income / 4", ctx), num(25.0)); |
| 979 | + // Deeper static chains. |
| 980 | + let deep = &[("p", ctx_value(&[("q", ctx_value(&[("r-s", num(7.0))]))]))]; |
| 981 | + assert_eq!(eval_in("p.q.r-s", deep), num(7.0)); |
| 982 | + // A member of a fused root name. |
| 983 | + let dt = &[("Date-Time2", ctx_value(&[("time-zone", s("Z"))]))]; |
| 984 | + assert_eq!(eval_in("Date-Time2.time-zone", dt), s("Z")); |
| 985 | + // A list step maps over the elements; ANY element having the key counts. |
| 986 | + let orders = Value::List(vec![ |
| 987 | + ctx_value(&[("unit-price", num(2.0))]), |
| 988 | + ctx_value(&[("unit-price", num(3.0))]), |
| 989 | + ]); |
| 990 | + assert_eq!( |
| 991 | + eval_in("orders.unit-price", &[("orders", orders)]), |
| 992 | + list(vec![num(2.0), num(3.0)]) |
| 993 | + ); |
| 994 | + // No such member -> the arithmetic reading stands. |
| 995 | + let plain = &[("x", ctx_value(&[("y", num(10.0))])), ("z", num(3.0))]; |
| 996 | + assert_eq!(eval_in("x.y-z", plain), num(7.0)); |
| 997 | + // A dynamic base is never probed: `(applicant).net-income` stays |
| 998 | + // `(applicant).net - income` (backticks cover it). |
| 999 | + assert_eq!(eval_in("(applicant).net-income", ctx), Value::Null); |
| 1000 | + assert_eq!(eval_in("(applicant).`net-income`", ctx), num(100.0)); |
| 1001 | + // The adaptive compile path probes members too. |
| 1002 | + let prog = compile("applicant.net-income").unwrap(); |
| 1003 | + assert_eq!(prog.evaluate(&ctx_of(ctx)).unwrap().into_lenient(), num(100.0)); |
| 1004 | + let other = ctx_of(&[("applicant", ctx_value(&[("net", num(5.0))])), ("income", num(1.0))]); |
| 1005 | + assert_eq!(prog.evaluate(&other).unwrap().into_lenient(), num(4.0)); |
| 1006 | + } |
| 1007 | + |
| 1008 | + #[test] |
| 1009 | + fn plain_paths_and_dotted_members_never_probe_members() { |
| 1010 | + // At a member position `.` is navigation, not a name symbol: a plain |
| 1011 | + // path forms no member run (laziness, ADR-21). A dotted member key |
| 1012 | + // needs backticks. |
| 1013 | + let ctx = &[("o", ctx_value(&[("a.b", num(1.0)), ("a", ctx_value(&[("b", num(2.0))]))]))]; |
| 1014 | + assert_eq!(eval_in("o.a.b", ctx), num(2.0)); |
| 1015 | + assert_eq!(eval_in("o.`a.b`", ctx), num(1.0)); |
| 1016 | + } |
| 1017 | + |
| 1018 | + #[test] |
| 1019 | + fn no_builtin_name_contains_a_name_symbol() { |
| 1020 | + // Built-in names are in scope for the fusion probe. A built-in whose name |
| 1021 | + // contained `- + * / .` would silently change how existing expressions |
| 1022 | + // parse — and the values stored in feel-pg expression indexes (ADR-48). |
| 1023 | + let src = include_str!("builtins.rs"); |
| 1024 | + let start = src.find("pub(crate) fn is_builtin").expect("is_builtin present"); |
| 1025 | + let body = &src[start..start + src[start..].find("\n}\n").expect("end of fn")]; |
| 1026 | + let names: Vec<&str> = body.split('"').skip(1).step_by(2).collect(); |
| 1027 | + assert!(names.len() > 50, "parsed the is_builtin name list ({})", names.len()); |
| 1028 | + for n in names { |
| 1029 | + assert!( |
| 1030 | + !n.contains(['-', '+', '*', '/', '.']), |
| 1031 | + "built-in `{n}` contains a name symbol" |
| 1032 | + ); |
| 1033 | + } |
| 709 | 1034 | } |
| 710 | 1035 | |
| 711 | 1036 | #[test] |