| 1 | //! `feel-core` — a pure (S-)FEEL expression engine. |
| 2 | //! |
| 3 | //! Cardinal rule: this crate has **no** target-specific dependency (no pgrx, |
| 4 | //! no wasm-bindgen). Target glue lives only in the wrapper crates. |
| 5 | |
| 6 | mod ast; |
| 7 | mod builtins; |
| 8 | mod error; |
| 9 | mod eval; |
| 10 | pub mod foreign; |
| 11 | pub mod function; |
| 12 | mod lexer; |
| 13 | mod regex_provider; |
| 14 | pub mod temporal; |
| 15 | mod types; |
| 16 | mod value; |
| 17 | |
| 18 | pub use ast::FeelType; |
| 19 | pub use error::FeelError; |
| 20 | pub use foreign::{Foreign, ForeignObject}; |
| 21 | pub use function::{Args, ForeignFunction, Func}; |
| 22 | pub use regex_provider::FeelRegex; |
| 23 | pub use temporal::temporal_from_iso; |
| 24 | pub use value::Value; |
| 25 | // `EvalEnv` is defined below; re-stated here for discoverability via the crate root. |
| 26 | |
| 27 | /// The Rust `regex` engine as a [`FeelRegex`] provider (available when the |
| 28 | /// default `rust-regex` feature is on). Wrappers that bring their own host engine |
| 29 | /// can still opt back into it — e.g. `feel-wasm`'s `xpath-regex` feature uses it |
| 30 | /// for cross-target consistency at the cost of bundle size (ADR-16). |
| 31 | #[cfg(feature = "rust-regex")] |
| 32 | pub use regex_provider::RustRegex; |
| 33 | |
| 34 | use std::collections::HashMap; |
| 35 | |
| 36 | use lalrpop_util::lalrpop_mod; |
| 37 | |
| 38 | // Pull in the parser generated from `src/feel.lalrpop` by `build.rs`. |
| 39 | lalrpop_mod!( |
| 40 | #[allow(clippy::all, dead_code, unused_imports)] |
| 41 | feel |
| 42 | ); |
| 43 | |
| 44 | /// Evaluation context: a thin wrapper around a variable map. |
| 45 | /// |
| 46 | /// The grammar slice does not reference variables yet, so this is usually |
| 47 | /// empty; it exists so the public API is stable as the engine grows and so the |
| 48 | /// wrapper crates have a place to map their JSON boundary input into. |
| 49 | #[derive(Debug, Default, Clone, PartialEq)] |
| 50 | pub struct Context { |
| 51 | vars: HashMap<String, Value>, |
| 52 | /// How many keys contain a name symbol (`- + * / .`) — the O(1) pre-check |
| 53 | /// that lets a special-character run skip its scope lookups when no such |
| 54 | /// key exists ([`ScopeProbe::may_bind_special`], ADR-48). |
| 55 | special_keys: usize, |
| 56 | } |
| 57 | |
| 58 | /// Whether `name` contains one of FEEL's additional name symbols (rule 30). |
| 59 | fn has_name_symbol(name: &str) -> bool { |
| 60 | name.contains(['-', '+', '*', '/', '.']) |
| 61 | } |
| 62 | |
| 63 | impl Context { |
| 64 | /// An empty context. |
| 65 | pub fn new() -> Self { |
| 66 | Self::default() |
| 67 | } |
| 68 | |
| 69 | /// Alias for [`Context::new`], reads nicely in tests. |
| 70 | pub fn empty() -> Self { |
| 71 | Self::default() |
| 72 | } |
| 73 | |
| 74 | /// Bind a name to a value. |
| 75 | pub fn insert(&mut self, name: impl Into<String>, value: Value) { |
| 76 | let name = name.into(); |
| 77 | let special = has_name_symbol(&name); |
| 78 | if self.vars.insert(name, value).is_none() && special { |
| 79 | self.special_keys += 1; |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Look up a bound value. |
| 84 | pub fn get(&self, name: &str) -> Option<&Value> { |
| 85 | self.vars.get(name) |
| 86 | } |
| 87 | |
| 88 | /// Return a child context with `name` additionally bound to `value`, leaving |
| 89 | /// `self` unchanged. Used to scope `for`/`some`/`every` loop variables. |
| 90 | pub fn with(&self, name: impl Into<String>, value: Value) -> Context { |
| 91 | let mut child = self.clone(); |
| 92 | child.insert(name, value); |
| 93 | child |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// The parse-time "name oracle" for special-character names (§10.3.1.6, |
| 98 | /// ADR-47/48): decides which candidate names are in scope, so the lexer can fuse |
| 99 | /// FEEL's additional name symbols (`a-b`, `Date-Time`, `x.y`) into single names. |
| 100 | /// |
| 101 | /// std-only (ADR-1), like the other host seams. The canonical implementation is |
| 102 | /// [`Context`] itself — parse and eval must agree on what "in scope" means, so |
| 103 | /// [`contains`](ScopeProbe::contains) mirrors `Expr::Var` resolution exactly: a |
| 104 | /// context binding or a built-in function name. |
| 105 | pub trait ScopeProbe { |
| 106 | /// Whether `name` resolves at evaluation time — i.e. `Expr::Var(name)` would |
| 107 | /// find a value (a context binding or a built-in function name). |
| 108 | fn contains(&self, name: &str) -> bool; |
| 109 | |
| 110 | /// Whether the value reached by the **static** path `path` (root name first, |
| 111 | /// e.g. `["applicant"]` for `applicant.first-name`) has a member `name` |
| 112 | /// (ADR-48). A list on the way is mapped over, as the FEEL dot does; the |
| 113 | /// member counts if **any** element has it. The default — `false` — keeps |
| 114 | /// member positions arithmetic (`applicant.first - name`). |
| 115 | fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 116 | let _ = (path, name); |
| 117 | false |
| 118 | } |
| 119 | |
| 120 | /// A fast pre-check (ADR-48): `false` only if **no** name containing a name |
| 121 | /// symbol (`- + * / .`) can be in scope — then no root candidate can be |
| 122 | /// bound and the fusion skips its root lookups. Every candidate contains |
| 123 | /// such a symbol. The default is the safe `true`. |
| 124 | fn may_bind_special(&self) -> bool { |
| 125 | true |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | impl ScopeProbe for Context { |
| 130 | fn contains(&self, name: &str) -> bool { |
| 131 | // Mirrors `Expr::Var` (eval.rs): a context binding wins, then a built-in |
| 132 | // name (a first-class function value, ADR-36), then null — the probe asks |
| 133 | // about the first two. |
| 134 | self.get(name).is_some() || crate::builtins::is_builtin(name) |
| 135 | } |
| 136 | |
| 137 | fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 138 | let Some((root, rest)) = path.split_first() else { |
| 139 | return false; |
| 140 | }; |
| 141 | self.get(root).is_some_and(|v| has_member(v, rest, name)) |
| 142 | } |
| 143 | |
| 144 | /// No key with a name symbol, and — guarded by a test — no built-in name |
| 145 | /// has one either. |
| 146 | fn may_bind_special(&self) -> bool { |
| 147 | self.special_keys > 0 |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// Navigate `rest` from `v` like the FEEL dot (a list maps over its elements) |
| 152 | /// and report whether the end has a member `name` — for a list: any element. |
| 153 | /// Navigation is by reference for owned values; a lazy [`Foreign`] node is asked |
| 154 | /// via [`ForeignObject::get`] one segment at a time (feel-pg's jsonb, the |
| 155 | /// wrappers' host objects), so only the probed path is touched. |
| 156 | fn has_member(v: &Value, rest: &[&str], name: &str) -> bool { |
| 157 | match (v, rest.split_first()) { |
| 158 | (Value::List(items), _) => items.iter().any(|it| has_member(it, rest, name)), |
| 159 | (Value::Context(map), None) => map.contains_key(name), |
| 160 | (Value::Context(map), Some((seg, more))) => { |
| 161 | map.get(*seg).is_some_and(|next| has_member(next, more, name)) |
| 162 | } |
| 163 | (Value::Foreign(f), None) => match f.0.get(name) { |
| 164 | Value::Null => false, |
| 165 | // A lazy host *list* answers a key with the per-element selections |
| 166 | // (§10.3.2.5), a lazy *object* with the member's value — which may |
| 167 | // itself be a list. Only in that ambiguous case force one level to |
| 168 | // tell them apart. |
| 169 | Value::List(selected) => match f.0.force() { |
| 170 | Value::List(_) => selected.iter().any(|v| !matches!(v, Value::Null)), |
| 171 | _ => true, |
| 172 | }, |
| 173 | _ => true, |
| 174 | }, |
| 175 | (Value::Foreign(f), Some((seg, more))) => has_member(&f.0.get(seg), more, name), |
| 176 | _ => false, |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// A [`Context`] plus an ambient [`FunctionRegistry`] (ADR-23) as one parse-time |
| 181 | /// scope (ADR-47): a call head resolves against context, built-ins and — third — |
| 182 | /// the registry (`eval_call`), so a hyphen-named host function (`my-fn(1)`) must |
| 183 | /// be in scope for the fusion too. [`CompiledExpr::evaluate_with_env`] probes |
| 184 | /// this automatically with the env's registry. |
| 185 | /// |
| 186 | /// Slightly wider than `Expr::Var` (which never consults the registry): a bare, |
| 187 | /// uncalled `my-fn` fuses to a name that evaluates to null — the same null the |
| 188 | /// arithmetic reading `my - fn` would give. |
| 189 | pub struct ScopeWithFunctions<'a> { |
| 190 | /// The root-level bindings. |
| 191 | pub context: &'a Context, |
| 192 | /// The ambient host functions. |
| 193 | pub functions: &'a dyn FunctionRegistry, |
| 194 | } |
| 195 | |
| 196 | impl ScopeProbe for ScopeWithFunctions<'_> { |
| 197 | fn contains(&self, name: &str) -> bool { |
| 198 | self.context.contains(name) || self.functions.contains(name) |
| 199 | } |
| 200 | |
| 201 | fn contains_member(&self, path: &[&str], name: &str) -> bool { |
| 202 | self.context.contains_member(path, name) |
| 203 | } |
| 204 | |
| 205 | fn may_bind_special(&self) -> bool { |
| 206 | self.context.may_bind_special() || self.functions.may_have_special_names() |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /// How far the parser goes in reading FEEL's ambiguous names (ADR-48) — a parse |
| 211 | /// option ([`ParseOptions`]). Backtick-quoted names (`` `a-b` ``, the feel-scala |
| 212 | /// extension) work at every level. |
| 213 | /// |
| 214 | /// The default is [`Quoted`](NameResolution::Quoted): the meaning of an |
| 215 | /// expression then comes from its text alone, never from the data. Opt into |
| 216 | /// [`Symbols`](NameResolution::Symbols) for the DMN spec's scope-dependent |
| 217 | /// reading (unquoted names from third-party DMN models, the TCK). |
| 218 | #[non_exhaustive] |
| 219 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] |
| 220 | pub enum NameResolution { |
| 221 | /// Only backtick-quoted names are special; `a-b` is always subtraction — |
| 222 | /// Camunda/feel-scala semantics. No scope checks at all: the cheapest level, |
| 223 | /// and the default. |
| 224 | #[default] |
| 225 | Quoted, |
| 226 | /// The spec mode (§10.3.1.6): backticks plus runs over `- + * / .`, |
| 227 | /// resolved against the root scope (ADR-47) and, on static paths, against |
| 228 | /// the navigated value (ADR-48). Names bound inside the expression (loop |
| 229 | /// variables, parameters, filter elements) are not consulted. |
| 230 | Symbols, |
| 231 | } |
| 232 | |
| 233 | impl NameResolution { |
| 234 | /// Parse the textual level used by the wrappers and feel-pg |
| 235 | /// (`"quoted"` | `"symbols"`, case-insensitive). |
| 236 | pub fn from_name(s: &str) -> Option<Self> { |
| 237 | match s.to_ascii_lowercase().as_str() { |
| 238 | "quoted" => Some(Self::Quoted), |
| 239 | "symbols" => Some(Self::Symbols), |
| 240 | _ => None, |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /// Options for [`compile_with`] / [`evaluate_with`] (ADR-48). |
| 246 | #[non_exhaustive] |
| 247 | #[derive(Debug, Default, Clone, PartialEq, Eq)] |
| 248 | pub struct ParseOptions { |
| 249 | /// The name-resolution level (default [`NameResolution::Quoted`]). |
| 250 | pub names: NameResolution, |
| 251 | } |
| 252 | |
| 253 | impl ParseOptions { |
| 254 | /// Options with the given name-resolution level. |
| 255 | pub fn names(names: NameResolution) -> Self { |
| 256 | Self { names } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | /// How many scope-specific parses a [`CompiledExpr`] keeps (LRU). One per |
| 261 | /// distinct probe-answer trace; real workloads see one or two. |
| 262 | const SCOPED_PARSE_CACHE: usize = 8; |
| 263 | |
| 264 | /// A parsed FEEL expression, ready to be evaluated repeatedly. |
| 265 | /// |
| 266 | /// Parsing is the per-call cost that does not depend on the context, so callers |
| 267 | /// that evaluate the same expression against many contexts (e.g. one decision |
| 268 | /// over many rows) should [`compile`] once and reuse the result. The wrapped AST |
| 269 | /// is fully owning, so a `CompiledExpr` carries no borrow of the source string. |
| 270 | /// |
| 271 | /// **Scope-adaptive** (ADR-48): when the text contains special-character runs |
| 272 | /// (`a-b`, `x.y`), each evaluation checks them against the context — one lookup |
| 273 | /// per candidate — and picks the parse for that scope. The parse is a pure |
| 274 | /// function of the text and the probe's answers, so it is cached per answer set |
| 275 | /// (bounded, LRU); a text without runs never checks anything. |
| 276 | /// |
| 277 | /// ``` |
| 278 | /// use feel_core::{compile, Context, Value}; |
| 279 | /// let prog = compile("a + 1").unwrap(); |
| 280 | /// let mut ctx = Context::empty(); |
| 281 | /// ctx.insert("a", Value::Number(1.0)); |
| 282 | /// assert_eq!(prog.evaluate(&ctx).unwrap(), Value::Number(2.0)); |
| 283 | /// ``` |
| 284 | #[derive(Debug, Clone)] |
| 285 | pub struct CompiledExpr { |
| 286 | /// The scope-free parse: no run fused. Correct for every scope that binds |
| 287 | /// none of the run candidates — the overwhelming case. |
| 288 | base: std::sync::Arc<ast::Expr>, |
| 289 | /// Present iff some scope could fuse a run (see [`Scoped`]); `None` for |
| 290 | /// run-free texts, [`NameResolution::Quoted`] and probe-pinned parses. |
| 291 | scoped: Option<std::sync::Arc<Scoped>>, |
| 292 | /// The level this was compiled at. |
| 293 | names: NameResolution, |
| 294 | } |
| 295 | |
| 296 | /// The scope-dependent half of a [`CompiledExpr`]: the pre-fusion tokens to |
| 297 | /// re-fuse against each evaluation's scope, and the parses already built, keyed |
| 298 | /// by the fusion's probe-answer trace. Shared between clones. |
| 299 | #[derive(Debug)] |
| 300 | struct Scoped { |
| 301 | toks: Vec<lexer::Spanned>, |
| 302 | /// Whether any member position starts a run (`applicant.net-income`). Without |
| 303 | /// one, a scope whose [`ScopeProbe::may_bind_special`] is `false` cannot |
| 304 | /// change the parse — no fusion replay needed. |
| 305 | member_sites: bool, |
| 306 | cache: std::sync::Mutex<Vec<(lexer::Trace, std::sync::Arc<ast::Expr>)>>, |
| 307 | } |
| 308 | |
| 309 | impl CompiledExpr { |
| 310 | /// Evaluate this already-parsed expression against a context, using the |
| 311 | /// default regex provider (`RustRegex` with the `rust-regex` feature on, |
| 312 | /// otherwise a no-op provider whose regex builtins yield an error-null) and |
| 313 | /// the wall-clock instant for `now()`/`today()`. |
| 314 | /// |
| 315 | /// Use [`CompiledExpr::evaluate_with_env`] to control the regex provider or |
| 316 | /// the `now()`/`today()` instant (the wrappers inject their host's there). |
| 317 | pub fn evaluate(&self, context: &Context) -> Result<Value, FeelError> { |
| 318 | self.evaluate_with_env( |
| 319 | context, |
| 320 | &EvalEnv::new(®ex_provider::DEFAULT, default_now()), |
| 321 | ) |
| 322 | } |
| 323 | |
| 324 | /// Evaluate against a context using a fully caller-supplied [`EvalEnv`] — |
| 325 | /// the single general entry point the wrappers use. The env carries both |
| 326 | /// seams: the host regex provider (ADR-16: only `matches`/`replace`/`split` |
| 327 | /// consult it; every other result is provider-independent) and the instant |
| 328 | /// `now()`/`today()` read (ADR-18). The wrappers inject their host's clock |
| 329 | /// here (e.g. feel-pg's transaction start), which also makes `now()`/`today()` |
| 330 | /// deterministic in tests. |
| 331 | /// |
| 332 | /// The scope for special-character names is `context` plus the env's |
| 333 | /// function registry ([`ScopeWithFunctions`]; ADR-48). |
| 334 | pub fn evaluate_with_env(&self, context: &Context, env: &EvalEnv) -> Result<Value, FeelError> { |
| 335 | let scope = ScopeWithFunctions { |
| 336 | context, |
| 337 | functions: env.functions, |
| 338 | }; |
| 339 | let expr = self.resolve(&scope)?; |
| 340 | eval::Evaluator::new(env).eval(&expr, context) |
| 341 | } |
| 342 | |
| 343 | /// The parse for `probe`'s scope: the base parse when no run fuses, else |
| 344 | /// the cached (or newly built) parse for this probe-answer trace. |
| 345 | fn resolve(&self, probe: &dyn ScopeProbe) -> Result<std::sync::Arc<ast::Expr>, FeelError> { |
| 346 | let Some(scoped) = &self.scoped else { |
| 347 | return Ok(self.base.clone()); |
| 348 | }; |
| 349 | if !scoped.member_sites && !probe.may_bind_special() { |
| 350 | return Ok(self.base.clone()); |
| 351 | } |
| 352 | let mut trace = lexer::Trace::new(); |
| 353 | lexer::fusion_trace(&scoped.toks, probe, &mut trace); |
| 354 | if !trace.iter().any(|&hit| hit) { |
| 355 | return Ok(self.base.clone()); |
| 356 | } |
| 357 | { |
| 358 | let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner()); |
| 359 | if let Some(pos) = cache.iter().position(|(t, _)| *t == trace) { |
| 360 | let hit = cache.remove(pos); |
| 361 | let expr = hit.1.clone(); |
| 362 | cache.insert(0, hit); |
| 363 | return Ok(expr); |
| 364 | } |
| 365 | } |
| 366 | let expr = std::sync::Arc::new(parse_tokens(lexer::fuse(&scoped.toks, probe))?); |
| 367 | let mut cache = scoped.cache.lock().unwrap_or_else(|e| e.into_inner()); |
| 368 | cache.insert(0, (trace, expr.clone())); |
| 369 | cache.truncate(SCOPED_PARSE_CACHE); |
| 370 | Ok(expr) |
| 371 | } |
| 372 | |
| 373 | /// The parsed AST (the base parse). `pub(crate)` so the `range(string)` |
| 374 | /// built-in can inspect a freshly-parsed range literal's *shape* (its |
| 375 | /// endpoints must be literals, not arbitrary expressions — DMN §10.3.4.6) |
| 376 | /// before evaluating it. |
| 377 | pub(crate) fn ast(&self) -> &ast::Expr { |
| 378 | &self.base |
| 379 | } |
| 380 | |
| 381 | /// `true` if this expression never reads the wall clock — it calls neither |
| 382 | /// `now()` nor `today()` anywhere (ADR-18). Wrappers exposing a deterministic, |
| 383 | /// IMMUTABLE evaluation surface (e.g. feel-pg's `feel_eval_immutable`, for |
| 384 | /// expression indexes; RD-10) gate on this: a non-clock-free expression cannot |
| 385 | /// be IMMUTABLE because `now()`/`today()` vary over time. |
| 386 | /// |
| 387 | /// Judged on the base parse, which is conservative: a scope can only fuse a |
| 388 | /// call head *into* a special name (`x-now()`), never create a `now()` call. |
| 389 | /// |
| 390 | /// This is the *static* half. The runtime half — forbidding *named* time zones, |
| 391 | /// whose offsets depend on the updatable IANA tzdb — is |
| 392 | /// [`EvalEnv::forbidding_named_zones`]. Host functions/objects are out of scope |
| 393 | /// here (the embedder's concern; feel-pg has no host-function seam). |
| 394 | pub fn is_clock_free(&self) -> bool { |
| 395 | self.base.is_clock_free() |
| 396 | } |
| 397 | |
| 398 | /// The name-resolution level this was compiled at (ADR-48). |
| 399 | pub fn name_resolution(&self) -> NameResolution { |
| 400 | self.names |
| 401 | } |
| 402 | |
| 403 | /// How many scope-specific parses are cached right now (≤ 8; ADR-48) — a |
| 404 | /// diagnostic for tests and benchmarks. |
| 405 | pub fn scoped_parses(&self) -> usize { |
| 406 | self.scoped |
| 407 | .as_ref() |
| 408 | .map_or(0, |s| s.cache.lock().unwrap_or_else(|e| e.into_inner()).len()) |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// A registry of host-provided ("ambient") functions, looked up by name when a |
| 413 | /// call resolves to neither a context-bound function value nor a built-in (ADR-23). |
| 414 | /// This is the second way a host injects callables — the first is binding a |
| 415 | /// [`Value::Function`] directly in the [`Context`]. Implemented per target |
| 416 | /// (feel-py's `PyFunctionRegistry`, feel-wasm's `JsFunctionRegistry`); the default |
| 417 | /// is empty, so a pure-Rust embedder pays nothing. |
| 418 | pub trait FunctionRegistry { |
| 419 | /// Resolve a host function by name. Absent -> `None` (the call is then a |
| 420 | /// built-in or, failing that, an error-null). |
| 421 | fn get(&self, name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>>; |
| 422 | |
| 423 | /// Whether a host function `name` exists — the scope check for |
| 424 | /// special-character call heads (ADR-48), run once per candidate per |
| 425 | /// evaluation. Override with an allocation-free lookup; the default builds |
| 426 | /// the callable via [`get`](FunctionRegistry::get). |
| 427 | fn contains(&self, name: &str) -> bool { |
| 428 | self.get(name).is_some() |
| 429 | } |
| 430 | |
| 431 | /// `false` only if no function name contains a name symbol (`- + * / .`) — |
| 432 | /// the registry half of [`ScopeProbe::may_bind_special`]. The default is the |
| 433 | /// safe `true`; the empty registry says `false`. |
| 434 | fn may_have_special_names(&self) -> bool { |
| 435 | true |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /// The empty registry: no ambient host functions. Used as the default in |
| 440 | /// [`EvalEnv::new`] so existing callers (and pure-Rust embedders) are unaffected. |
| 441 | struct EmptyRegistry; |
| 442 | impl FunctionRegistry for EmptyRegistry { |
| 443 | fn get(&self, _name: &str) -> Option<std::sync::Arc<dyn ForeignFunction>> { |
| 444 | None |
| 445 | } |
| 446 | |
| 447 | fn may_have_special_names(&self) -> bool { |
| 448 | false |
| 449 | } |
| 450 | } |
| 451 | static EMPTY_REGISTRY: EmptyRegistry = EmptyRegistry; |
| 452 | |
| 453 | /// The evaluation environment threaded through the engine: the host regex |
| 454 | /// provider (ADR-16), the instant `now()`/`today()` read (ADR-18), and the host |
| 455 | /// function registry (ADR-23). Held by reference during evaluation (never cloned |
| 456 | /// per loop iteration), so building one is cheap and the clock is fixed for the |
| 457 | /// whole evaluation. |
| 458 | pub struct EvalEnv<'a> { |
| 459 | /// The host regex provider consulted by `matches`/`replace`/`split`. |
| 460 | pub regex: &'a dyn FeelRegex, |
| 461 | /// The instant `now()` returns (and whose date `today()` returns). |
| 462 | pub now: jiff::Zoned, |
| 463 | /// Ambient host functions, consulted after context bindings and built-ins. |
| 464 | pub functions: &'a dyn FunctionRegistry, |
| 465 | /// When set, constructing a temporal value with a *named* IANA zone (e.g. |
| 466 | /// `time("09:00:00@Europe/Berlin")`) yields an error-null instead; fixed |
| 467 | /// offsets (`+02:00`) and `Z` are unaffected. Hosts needing tzdb-independent, |
| 468 | /// IMMUTABLE-safe evaluation turn it on via [`EvalEnv::forbidding_named_zones`] |
| 469 | /// (feel-pg's `feel_eval_immutable`; RD-10). Default `false`. |
| 470 | pub reject_named_zones: bool, |
| 471 | } |
| 472 | |
| 473 | impl<'a> EvalEnv<'a> { |
| 474 | /// Build an environment from a regex provider and an evaluation instant, with |
| 475 | /// no ambient host functions. |
| 476 | pub fn new(regex: &'a dyn FeelRegex, now: jiff::Zoned) -> Self { |
| 477 | Self { |
| 478 | regex, |
| 479 | now, |
| 480 | functions: &EMPTY_REGISTRY, |
| 481 | reject_named_zones: false, |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /// Build an environment that also exposes a host [`FunctionRegistry`] (ADR-23). |
| 486 | pub fn with_functions( |
| 487 | regex: &'a dyn FeelRegex, |
| 488 | now: jiff::Zoned, |
| 489 | functions: &'a dyn FunctionRegistry, |
| 490 | ) -> Self { |
| 491 | Self { |
| 492 | regex, |
| 493 | now, |
| 494 | functions, |
| 495 | reject_named_zones: false, |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// Return this env with the *named*-zone policy on: any temporal value carrying |
| 500 | /// a named IANA zone becomes an error-null during evaluation, while fixed |
| 501 | /// offsets and `Z` pass through. Used for IMMUTABLE evaluation, where a named |
| 502 | /// zone's offset would depend on the updatable IANA tzdb (RD-10). Pair it with |
| 503 | /// [`CompiledExpr::is_clock_free`] for a fully deterministic surface. |
| 504 | pub fn forbidding_named_zones(mut self) -> Self { |
| 505 | self.reject_named_zones = true; |
| 506 | self |
| 507 | } |
| 508 | |
| 509 | /// Apply the named-zone policy to a freshly-constructed temporal value: a |
| 510 | /// named-zone `time`/`date and time` becomes an error-null when the policy is |
| 511 | /// on; everything else passes through unchanged. A single tag test when the |
| 512 | /// policy is off, so the default path pays nothing. |
| 513 | pub(crate) fn vet_named_zone(&self, v: Value) -> Value { |
| 514 | if self.reject_named_zones && temporal::has_named_zone(&v) { |
| 515 | Value::Error |
| 516 | } else { |
| 517 | v |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | /// The default evaluation instant: the system wall clock in the system zone. |
| 523 | fn default_now() -> jiff::Zoned { |
| 524 | jiff::Zoned::now() |
| 525 | } |
| 526 | |
| 527 | /// Run the lalrpop parser over a finished-or-not token stream. |
| 528 | fn parse_tokens(toks: Vec<lexer::Spanned>) -> Result<ast::Expr, FeelError> { |
| 529 | feel::ExprParser::new() |
| 530 | .parse(lexer::finish(toks)) |
| 531 | .map_err(|e| FeelError::Parse(e.to_string())) |
| 532 | } |
| 533 | |
| 534 | /// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating |
| 535 | /// it, at the default [`NameResolution::Quoted`] level: `a-b` is subtraction, |
| 536 | /// `` `a-b` `` the name. |
| 537 | /// |
| 538 | /// Returns [`FeelError::Parse`] if the expression is syntactically invalid. |
| 539 | /// |
| 540 | /// With [`compile_with`] at [`NameResolution::Symbols`] the result is |
| 541 | /// **scope-adaptive** (ADR-48): special-character names (`a-b`, `Date-Time`, |
| 542 | /// `applicant.first-name`) resolve per evaluation against the context, exactly |
| 543 | /// like the one-shot [`evaluate_with`] — see [`CompiledExpr`]. |
| 544 | /// |
| 545 | /// `ExprParser::new()` is now cheap (the external `logos` lexer builds no runtime |
| 546 | /// matcher — see `lexer.rs`), so there is no parser to cache; the cost is the |
| 547 | /// per-call parse itself, which [`CompiledExpr`] lets callers pay once. |
| 548 | pub fn compile(expr: &str) -> Result<CompiledExpr, FeelError> { |
| 549 | compile_with(expr, &ParseOptions::default()) |
| 550 | } |
| 551 | |
| 552 | /// [`compile`] with explicit [`ParseOptions`] (ADR-48). |
| 553 | pub fn compile_with(expr: &str, options: &ParseOptions) -> Result<CompiledExpr, FeelError> { |
| 554 | let toks = lexer::lex_base(expr); |
| 555 | let scoped = (options.names == NameResolution::Symbols && lexer::may_fuse(&toks)) |
| 556 | .then(|| Scoped { |
| 557 | member_sites: lexer::has_member_sites(&toks), |
| 558 | toks: toks.clone(), |
| 559 | cache: std::sync::Mutex::new(Vec::new()), |
| 560 | }) |
| 561 | .map(std::sync::Arc::new); |
| 562 | Ok(CompiledExpr { |
| 563 | base: std::sync::Arc::new(parse_tokens(toks)?), |
| 564 | scoped, |
| 565 | names: options.names, |
| 566 | }) |
| 567 | } |
| 568 | |
| 569 | /// Parse a FEEL expression **pinned** to one scope (§10.3.1.6, ADR-47/48): |
| 570 | /// special-character runs (`a-b`, `Date-Time`, `x.y`, `applicant.first-name`) |
| 571 | /// are fused into names exactly when `probe` has them in scope, longest match |
| 572 | /// first, left to right; `(a)-(b)` forces the operator reading. The result does |
| 573 | /// **not** adapt to later contexts — use it when the scope is known up front |
| 574 | /// (a one-shot evaluation, a host with a fixed schema); otherwise prefer the |
| 575 | /// adaptive [`compile`]. At [`NameResolution::Quoted`] the probe is ignored. |
| 576 | pub fn compile_with_probe( |
| 577 | expr: &str, |
| 578 | probe: &dyn ScopeProbe, |
| 579 | options: &ParseOptions, |
| 580 | ) -> Result<CompiledExpr, FeelError> { |
| 581 | let toks = lexer::lex_base(expr); |
| 582 | let toks = match options.names { |
| 583 | // The O(1) pre-check: no special name in scope and no member run means |
| 584 | // no fusion can happen — skip the pass. |
| 585 | NameResolution::Symbols if probe.may_bind_special() || lexer::has_member_sites(&toks) => { |
| 586 | lexer::fuse(&toks, probe) |
| 587 | } |
| 588 | _ => toks, |
| 589 | }; |
| 590 | Ok(CompiledExpr { |
| 591 | base: std::sync::Arc::new(parse_tokens(toks)?), |
| 592 | scoped: None, |
| 593 | names: options.names, |
| 594 | }) |
| 595 | } |
| 596 | |
| 597 | /// Parse and evaluate a FEEL expression against a context. |
| 598 | /// |
| 599 | /// At the default [`NameResolution::Quoted`] level `a-b` is subtraction and |
| 600 | /// `` `a-b` `` the name. With [`evaluate_with`] at [`NameResolution::Symbols`] |
| 601 | /// the context is the §10.3.1.6 scope (ADR-47): `a-b` resolves to the context |
| 602 | /// binding when one exists. Prefer [`compile`] when evaluating the same |
| 603 | /// expression more than once. |
| 604 | /// |
| 605 | /// ``` |
| 606 | /// use feel_core::{evaluate, Context, Value}; |
| 607 | /// assert_eq!(evaluate("1 + 1", &Context::empty()).unwrap(), Value::Number(2.0)); |
| 608 | /// ``` |
| 609 | pub fn evaluate(expr: &str, context: &Context) -> Result<Value, FeelError> { |
| 610 | evaluate_with(expr, context, &ParseOptions::default()) |
| 611 | } |
| 612 | |
| 613 | /// [`evaluate`] with explicit [`ParseOptions`] (ADR-48). |
| 614 | pub fn evaluate_with( |
| 615 | expr: &str, |
| 616 | context: &Context, |
| 617 | options: &ParseOptions, |
| 618 | ) -> Result<Value, FeelError> { |
| 619 | compile_with_probe(expr, context, options)?.evaluate(context) |
| 620 | } |
| 621 | |
| 622 | /// Every **root-level** special-character name candidate `expr` could fuse |
| 623 | /// under *some* scope (§10.3.1.6, ADR-47) — e.g. `a-b-c` yields `a-b-c`, |
| 624 | /// `a-b`, `b-c`. A diagnostic: its length is the number of root-scope lookups |
| 625 | /// one evaluation of the compiled expression pays (path-member candidates, |
| 626 | /// ADR-48, come on top and are not listed). Empty ⇒ the parse is |
| 627 | /// scope-independent at the root level. |
| 628 | pub fn name_run_candidates(expr: &str) -> Vec<String> { |
| 629 | lexer::name_run_candidates(expr) |
| 630 | } |
| 631 | |
| 632 | /// Parse a structural FEEL type expression (`number`, `list<string>`, |
| 633 | /// `context<a: number, b: string>`, `function<number> -> boolean`, …) into a |
| 634 | /// [`FeelType`]. Returns `None` if the input is syntactically invalid or |
| 635 | /// contains an unmappable name (one that maps to [`FeelType::Unknown`]). |
| 636 | pub fn parse_type(s: &str) -> Option<FeelType> { |
| 637 | feel::TypeParser::new() |
| 638 | .parse(lexer::lex(s)) |
| 639 | .ok() |
| 640 | .filter(|t| t.is_mappable()) |
| 641 | } |
| 642 | |
| 643 | /// Apply the §10.3.2.9.4 implicit conversion from `v` toward target type `t`. |
| 644 | /// |
| 645 | /// Returns `Value::Null` when the conversion is mandatory but cannot be |
| 646 | /// performed (type mismatch, null input, or unknown target type). The five |
| 647 | /// rules — null/error pass-through, from-singleton-list, to-singleton-list, |
| 648 | /// and conforms-to — are documented on [`types::coerce`]. |
| 649 | pub fn coerce(v: Value, t: &FeelType) -> Value { |
| 650 | types::coerce(v, t) |
| 651 | } |
| 652 | |
| 653 | #[cfg(test)] |
| 654 | mod tests { |
| 655 | // The spec tests below exercise the scope-dependent reading: shadow the |
| 656 | // crate's `evaluate`/`compile` (default `Quoted`, ADR-48) with |
| 657 | // `Symbols`-mode versions. `default_level_is_quoted` uses `super::`. |
| 658 | fn evaluate(src: &str, ctx: &Context) -> Result<Value, FeelError> { |
| 659 | super::evaluate_with(src, ctx, &ParseOptions::names(NameResolution::Symbols)) |
| 660 | } |
| 661 | fn compile(src: &str) -> Result<CompiledExpr, FeelError> { |
| 662 | super::compile_with(src, &ParseOptions::names(NameResolution::Symbols)) |
| 663 | } |
| 664 | use super::*; |
| 665 | |
| 666 | /// Evaluate against an empty context, panicking on error, and collapse error |
| 667 | /// provenance — this is the lenient/observable view, so these tests assert |
| 668 | /// plain FEEL value semantics where an error-null and a value-null coincide. |
| 669 | /// (See `error_provenance` for the raw, provenance-aware assertions.) |
| 670 | fn ev(src: &str) -> Value { |
| 671 | evaluate(src, &Context::empty()) |
| 672 | .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 673 | .into_lenient() |
| 674 | } |
| 675 | |
| 676 | fn num(n: f64) -> Value { |
| 677 | Value::Number(n) |
| 678 | } |
| 679 | fn b(v: bool) -> Value { |
| 680 | Value::Boolean(v) |
| 681 | } |
| 682 | fn list(items: Vec<Value>) -> Value { |
| 683 | Value::List(items) |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn compile_matches_evaluate() { |
| 688 | // The compiled path and the one-shot path must agree. |
| 689 | for src in ["1 + 1", "5 in [1..10]", "if 1 < 2 then 10 else 20"] { |
| 690 | let one_shot = evaluate(src, &Context::empty()).unwrap(); |
| 691 | let compiled = compile(src).unwrap().evaluate(&Context::empty()).unwrap(); |
| 692 | assert_eq!(one_shot, compiled, "mismatch for `{src}`"); |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn compiled_expr_reused_across_contexts() { |
| 698 | // One parse, evaluated against two different contexts. |
| 699 | let prog = compile("a + 1").unwrap(); |
| 700 | let mut c1 = Context::empty(); |
| 701 | c1.insert("a", num(1.0)); |
| 702 | let mut c2 = Context::empty(); |
| 703 | c2.insert("a", num(41.0)); |
| 704 | assert_eq!(prog.evaluate(&c1).unwrap().into_lenient(), num(2.0)); |
| 705 | assert_eq!(prog.evaluate(&c2).unwrap().into_lenient(), num(42.0)); |
| 706 | } |
| 707 | |
| 708 | #[test] |
| 709 | fn compile_reports_parse_error() { |
| 710 | assert!(matches!(compile("1 +"), Err(FeelError::Parse(_)))); |
| 711 | } |
| 712 | |
| 713 | // ----------------------------------------------------------------------- // |
| 714 | // Special-character names (§10.3.1.6, ADR-47) |
| 715 | // ----------------------------------------------------------------------- // |
| 716 | |
| 717 | fn ctx_of(pairs: &[(&str, Value)]) -> Context { |
| 718 | let mut c = Context::empty(); |
| 719 | for (k, v) in pairs { |
| 720 | c.insert(*k, v.clone()); |
| 721 | } |
| 722 | c |
| 723 | } |
| 724 | |
| 725 | /// A FEEL context value from `(key, value)` pairs. |
| 726 | fn ctx_value(pairs: &[(&str, Value)]) -> Value { |
| 727 | Value::Context(pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()) |
| 728 | } |
| 729 | |
| 730 | /// One-shot evaluation against a scope built from `(name, value)` pairs — |
| 731 | /// the §10.3.1.6 stance: the context is the name oracle. |
| 732 | fn eval_in(src: &str, pairs: &[(&str, Value)]) -> Value { |
| 733 | evaluate(src, &ctx_of(pairs)) |
| 734 | .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 735 | .into_lenient() |
| 736 | } |
| 737 | |
| 738 | #[test] |
| 739 | fn special_char_names_resolve_against_scope() { |
| 740 | // `a-b` is the in-scope NAME when bound, subtraction otherwise — and |
| 741 | // `a - b` is the same candidate: spaces are not part of the name. |
| 742 | assert_eq!(eval_in("a-b", &[("a-b", num(10.0))]), num(10.0)); |
| 743 | assert_eq!(eval_in("a - b", &[("a-b", num(10.0))]), num(10.0)); |
| 744 | assert_eq!(eval_in("a-b", &[]), Value::Null); // unbound: subtraction of two nulls |
| 745 | // All five additional name symbols (grammar rule 30). |
| 746 | assert_eq!(eval_in("a+b", &[("a+b", num(1.0))]), num(1.0)); |
| 747 | assert_eq!(eval_in("a*b", &[("a*b", num(2.0))]), num(2.0)); |
| 748 | assert_eq!(eval_in("a/b", &[("a/b", num(3.0))]), num(3.0)); |
| 749 | assert_eq!(eval_in("a.b", &[("a.b", num(4.0))]), num(4.0)); |
| 750 | // Keywords are legal name PARTS in symbol runs (`x-in`; unfused, `in` |
| 751 | // would make it a membership test) — but never a name START (§10.3.1.4). |
| 752 | assert_eq!(eval_in("x-in", &[("x-in", b(true))]), b(true)); |
| 753 | // A multi-word name part joins before fusion (`total price-total`). |
| 754 | assert_eq!( |
| 755 | eval_in("total price-total", &[("total price-total", num(5.0))]), |
| 756 | num(5.0) |
| 757 | ); |
| 758 | // Fusion reaches every reference slot — call arguments: |
| 759 | assert_eq!(eval_in("not(x-y)", &[("x-y", b(true))]), b(false)); |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn special_char_name_longest_match_left_to_right() { |
| 764 | // Longest in-scope prefix wins: with `a-b-c` also bound, the whole run |
| 765 | // is one name. |
| 766 | assert_eq!( |
| 767 | eval_in("a-b-c", &[("a-b", num(1.0)), ("a-b-c", num(2.0))]), |
| 768 | num(2.0) |
| 769 | ); |
| 770 | // With only `a-b` bound, the run fuses `a-b` and subtracts the rest. |
| 771 | assert_eq!( |
| 772 | eval_in("a-b-c", &[("a-b", num(10.0)), ("c", num(4.0))]), |
| 773 | num(6.0) |
| 774 | ); |
| 775 | // The scan resumes after a fused name: `Date-Time - Date-Time2` fuses |
| 776 | // BOTH names and keeps the minus an operator — the TCK 0007 expectation |
| 777 | // (subtraction), reproduced by longest-match at each position. |
| 778 | let dt = &[("Date-Time", num(100.0)), ("Date-Time2", num(58.0))]; |
| 779 | assert_eq!(eval_in("Date-Time - Date-Time2", dt), num(42.0)); |
| 780 | // ... and after a miss the scan continues INSIDE the run: `b-c` bound |
| 781 | // in `a-b-c` parses as `a - b-c`. |
| 782 | assert_eq!( |
| 783 | eval_in("a-b-c", &[("a", num(8.0)), ("b-c", num(3.0))]), |
| 784 | num(5.0) |
| 785 | ); |
| 786 | // `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name. |
| 787 | let esc = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]; |
| 788 | assert_eq!(eval_in("(a)-(b)", esc), num(4.0)); |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn special_char_name_vs_path_and_members() { |
| 793 | // `x.y` is ambiguous between one name and a path (§10.3.1.6): the |
| 794 | // in-scope name wins when bound; otherwise the path stands. |
| 795 | let nested = &[("x", ctx_value(&[("y", num(5.0))]))]; |
| 796 | assert_eq!(eval_in("x.y", nested), num(5.0)); // path |
| 797 | assert_eq!(eval_in("x.y", &[("x.y", num(9.0))]), num(9.0)); // name |
| 798 | // A hyphen name as a PATH BASE: the whole-run candidate `Date-Time2.hour` |
| 799 | // is not in scope, so `Date-Time2` fuses and `.hour` stays a member. |
| 800 | let dt2 = &[("Date-Time2", ctx_value(&[("hour", num(3.0))]))]; |
| 801 | assert_eq!(eval_in("Date-Time2.hour", dt2), num(3.0)); |
| 802 | // A multi-word member stays a member: `Date-Time2.time offset`. |
| 803 | let off = &[("Date-Time2", ctx_value(&[("time offset", num(2.0))]))]; |
| 804 | assert_eq!(eval_in("Date-Time2.time offset", off), num(2.0)); |
| 805 | // But a bound name of the WHOLE dotted run wins over the path (longest |
| 806 | // match at the run start). |
| 807 | let whole = &[ |
| 808 | ("Date-Time2", ctx_value(&[("hour", num(3.0))])), |
| 809 | ("Date-Time2.hour", num(7.0)), |
| 810 | ]; |
| 811 | assert_eq!(eval_in("Date-Time2.hour", whole), num(7.0)); |
| 812 | } |
| 813 | |
| 814 | #[test] |
| 815 | fn compile_is_scope_adaptive_and_pinned_parse_is_not() { |
| 816 | // ADR-48: `compile` follows each evaluation's scope, exactly like the |
| 817 | // one-shot `evaluate` — one compiled program, both readings. |
| 818 | let bound = ctx_of(&[("a-b", num(10.0))]); |
| 819 | let parts = ctx_of(&[("a", num(7.0)), ("b", num(3.0))]); |
| 820 | let prog = compile("a-b").unwrap(); |
| 821 | assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 822 | assert_eq!(prog.evaluate(&parts).unwrap().into_lenient(), num(4.0)); |
| 823 | assert_eq!(prog.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 824 | // One scoped parse cached (the `a-b` reading); the base serves `parts`. |
| 825 | assert_eq!(prog.scoped_parses(), 1); |
| 826 | |
| 827 | // `compile_with_probe` PINS its probe's scope: no adaptation later. |
| 828 | let pinned = compile_with_probe("a-b", &bound, &ParseOptions::names(NameResolution::Symbols)).unwrap(); |
| 829 | assert_eq!(pinned.evaluate(&bound).unwrap().into_lenient(), num(10.0)); |
| 830 | assert_eq!(pinned.evaluate(&parts).unwrap().into_lenient(), Value::Null); |
| 831 | |
| 832 | // Run-free texts never build a scoped half. |
| 833 | let plain = compile("a + 1").unwrap(); |
| 834 | assert_eq!(plain.evaluate(&parts).unwrap().into_lenient(), num(8.0)); |
| 835 | assert_eq!(plain.scoped_parses(), 0); |
| 836 | |
| 837 | // `name_run_candidates`: every fusable candidate, from every unit |
| 838 | // position — the probe-free "could this parse be scope-dependent" set |
| 839 | // (feel-pg's cache check). Empty for run-free texts. |
| 840 | assert_eq!(name_run_candidates("a-b-c"), vec!["a-b-c", "a-b", "b-c"]); |
| 841 | assert!(name_run_candidates("1 + 1").is_empty()); |
| 842 | assert!(name_run_candidates("a and b").is_empty()); |
| 843 | assert_eq!(name_run_candidates("x.y"), vec!["x.y"]); |
| 844 | assert_eq!(name_run_candidates("x-in"), vec!["x-in"]); |
| 845 | assert!(name_run_candidates("if-then").is_empty()); // keyword start |
| 846 | assert_eq!( |
| 847 | name_run_candidates("Date-Time - Date-Time2"), |
| 848 | vec![ |
| 849 | "Date-Time-Date-Time2", |
| 850 | "Date-Time-Date", |
| 851 | "Date-Time", |
| 852 | "Time-Date-Time2", |
| 853 | "Time-Date", |
| 854 | "Date-Time2" |
| 855 | ] |
| 856 | ); |
| 857 | } |
| 858 | |
| 859 | #[test] |
| 860 | fn special_char_name_run_free_shapes_stay_untouched() { |
| 861 | // No candidate in scope: every one of these keeps its operator reading. |
| 862 | let empty = Context::empty(); |
| 863 | let ev0 = |src: &str| { |
| 864 | evaluate(src, &empty) |
| 865 | .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 866 | .into_lenient() |
| 867 | }; |
| 868 | // Numeric operands never form runs (a name part cannot start with a digit). |
| 869 | assert_eq!(ev0("1 + 1"), num(2.0)); |
| 870 | assert_eq!(ev0("3 - 1"), num(2.0)); |
| 871 | assert_eq!(ev0("a - 1"), Value::Null); // unbound `a`, minus 1 |
| 872 | assert_eq!(ev0("x and y"), Value::Null); // adjacency: boolean and of nulls |
| 873 | // Range/descendant/exponent separators are not name symbols. |
| 874 | assert_eq!(ev0("5 in [1..10]"), b(true)); |
| 875 | assert_eq!(ev0("2 ** 3"), num(8.0)); |
| 876 | assert_eq!(ev0("for i in [1,2] return i"), list(vec![num(1.0), num(2.0)])); |
| 877 | assert_eq!( |
| 878 | ev0("for i in [2, 3] return i - 1"), |
| 879 | list(vec![num(1.0), num(2.0)]) |
| 880 | ); |
| 881 | // Declaration slots are deferred (ADR-47): `for a-b in …` declares no |
| 882 | // hyphen loop variable — it stays a parse error. |
| 883 | assert!(compile("for a-b in [1] return a-b").is_err()); |
| 884 | } |
| 885 | |
| 886 | #[test] |
| 887 | fn path_member_word_never_fuses_against_outer_scope() { |
| 888 | // A word directly after an unfused `.` is a MEMBER position, not a |
| 889 | // variable reference: it must never start a name run. A root key may not |
| 890 | // change how a member access parses (ADR-47; the base of the path still |
| 891 | // forms legitimate run candidates, so a root key `x.y` keeps beating the |
| 892 | // path by longest-match — see `special_char_name_vs_path_and_members`). |
| 893 | let ctx = ctx_of(&[ |
| 894 | ("x", ctx_value(&[("y", num(10.0))])), |
| 895 | ("z", num(3.0)), |
| 896 | ("y-z", num(1.0)), |
| 897 | ]); |
| 898 | // `x.y-z` is (x.y) - z = 7 — even though the root binds `y-z`. |
| 899 | assert_eq!(evaluate("x.y-z", &ctx).unwrap().into_lenient(), num(7.0)); |
| 900 | // And identically without the root key (the two parses agree again). |
| 901 | let no_key = ctx_of(&[("x", ctx_value(&[("y", num(10.0))])), ("z", num(3.0))]); |
| 902 | assert_eq!(evaluate("x.y-z", &no_key).unwrap().into_lenient(), num(7.0)); |
| 903 | // The member-position rule also holds after a fused path base: the |
| 904 | // `hour` in `Date-Time2.hour - z` never starts a run. |
| 905 | let dt = ctx_of(&[ |
| 906 | ("Date-Time2", ctx_value(&[("hour", num(3.0))])), |
| 907 | ("z", num(4.0)), |
| 908 | ("hour-z", num(99.0)), |
| 909 | ]); |
| 910 | assert_eq!( |
| 911 | evaluate("Date-Time2.hour - z", &dt).unwrap().into_lenient(), |
| 912 | num(-1.0) |
| 913 | ); |
| 914 | // Deeper chains: only the base is a variable position (`p.q - s`). |
| 915 | let deep = ctx_of(&[ |
| 916 | ("p", ctx_value(&[("q", ctx_value(&[("r", num(2.0))]))])), |
| 917 | ("s", num(5.0)), |
| 918 | ("r-s", num(1.0)), |
| 919 | ]); |
| 920 | assert_eq!(evaluate("p.q.r-s", &deep).unwrap().into_lenient(), num(-3.0)); |
| 921 | // ADR-48 lifts the ADR-47 root-only gap: on a static path the navigated |
| 922 | // value is probed, so a nested hyphen KEY is reachable as a member. |
| 923 | let nested = ctx_of(&[( |
| 924 | "applicant", |
| 925 | ctx_value(&[("first-name", Value::String("Ada".into()))]), |
| 926 | )]); |
| 927 | assert_eq!( |
| 928 | evaluate("applicant.first-name", &nested).unwrap().into_lenient(), |
| 929 | Value::String("Ada".into()) |
| 930 | ); |
| 931 | } |
| 932 | |
| 933 | #[test] |
| 934 | fn keywords_never_start_name_runs() { |
| 935 | // A run must start at a Name: §10.3.1.4 — "A name start SHALL NOT be a |
| 936 | // literal terminal symbol", so no keyword starts a run. `return -i` |
| 937 | // must not produce the candidate `return-i` (which, if bound, would |
| 938 | // corrupt the loop parse; and in feel-pg would force per-row |
| 939 | // re-parses / IMMUTABLE errors). |
| 940 | assert!(name_run_candidates("for i in [1,2] return -i").is_empty()); |
| 941 | assert!(name_run_candidates("if a then -b else -c").is_empty()); |
| 942 | assert!(name_run_candidates("some i in xs satisfies -i > 0").is_empty()); |
| 943 | // A bound `return-i` changes nothing (the candidate no longer exists). |
| 944 | let ctx = ctx_of(&[("return-i", num(100.0))]); |
| 945 | assert_eq!( |
| 946 | evaluate("for i in [1,2] return -i", &ctx) |
| 947 | .unwrap() |
| 948 | .into_lenient(), |
| 949 | list(vec![num(-1.0), num(-2.0)]) |
| 950 | ); |
| 951 | // Value keywords do not start runs either: a bound `if-then` is not a |
| 952 | // name (it stays the — invalid — `if - then`), nor is `true-x`. |
| 953 | let if_then = ctx_of(&[("if-then", b(true))]); |
| 954 | assert!(evaluate("if-then", &if_then).is_err()); |
| 955 | assert_eq!(eval_in("true-x", &[("true-x", num(1.0))]), Value::Null); |
| 956 | // Keywords stay legal as NON-starting run words (`x-in`, `a-if`). |
| 957 | assert_eq!(eval_in("x-in", &[("x-in", num(4.0))]), num(4.0)); |
| 958 | assert_eq!(eval_in("a-if", &[("a-if", num(5.0))]), num(5.0)); |
| 959 | } |
| 960 | |
| 961 | // ----------------------------------------------------------------------- // |
| 962 | // ADR-48: backtick-quoted names, resolution levels, adaptive compile cache, |
| 963 | // path-member probe |
| 964 | // ----------------------------------------------------------------------- // |
| 965 | |
| 966 | fn s(v: &str) -> Value { |
| 967 | Value::String(v.into()) |
| 968 | } |
| 969 | |
| 970 | #[test] |
| 971 | fn backtick_names_work_in_every_name_slot() { |
| 972 | // Scope-independent: decided by the text, so it needs no binding to parse. |
| 973 | assert_eq!(eval_in("`a-b`", &[("a-b", num(5.0))]), num(5.0)); |
| 974 | assert_eq!(eval_in("`Profit and loss`", &[("Profit and loss", num(9.0))]), num(9.0)); |
| 975 | assert_eq!(eval_in("`what if?`", &[("what if?", b(true))]), b(true)); |
| 976 | assert_eq!(eval_in("`if`", &[("if", num(1.0))]), num(1.0)); // a keyword, quoted |
| 977 | // Content is verbatim: no space normalisation inside backticks. |
| 978 | assert_eq!(eval_in("`a b`", &[("a b", num(2.0))]), num(2.0)); |
| 979 | // Path member, context key + reference, loop variable, call head. |
| 980 | let app = &[("applicant", ctx_value(&[("first-name", s("Ada"))]))]; |
| 981 | assert_eq!(eval_in("applicant.`first-name`", app), s("Ada")); |
| 982 | assert_eq!(eval_in("{`a-b`: 5, c: `a-b` + 1}.c", &[]), num(6.0)); |
| 983 | assert_eq!( |
| 984 | eval_in("for `x-y` in [1, 2] return `x-y` * 2", &[]), |
| 985 | list(vec![num(2.0), num(4.0)]) |
| 986 | ); |
| 987 | assert_eq!(eval_in("{`my-fn`: function(x) x * 2, r: `my-fn`(3)}.r", &[]), num(6.0)); |
| 988 | // A quoted path base feeds the member probe's static path. |
| 989 | let quoted_base = &[("the app", ctx_value(&[("net-income", num(3.0))]))]; |
| 990 | assert_eq!(eval_in("`the app`.net-income", quoted_base), num(3.0)); |
| 991 | } |
| 992 | |
| 993 | #[test] |
| 994 | fn backtick_names_are_never_joined_or_fused() { |
| 995 | // Not fused: `` `a`-b `` is `a` minus `b`, even with `a-b` bound. |
| 996 | let ctx = &[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]; |
| 997 | assert_eq!(eval_in("`a`-b", ctx), num(4.0)); |
| 998 | // Not joined with an adjacent word: two names side by side is no FEEL. |
| 999 | assert!(evaluate("`a b` c", &Context::empty()).is_err()); |
| 1000 | // Unterminated or empty quotes are lex errors. |
| 1001 | assert!(evaluate("`a-b", &Context::empty()).is_err()); |
| 1002 | assert!(evaluate("``", &Context::empty()).is_err()); |
| 1003 | } |
| 1004 | |
| 1005 | #[test] |
| 1006 | fn name_resolution_levels() { |
| 1007 | let quoted = ParseOptions::names(NameResolution::Quoted); |
| 1008 | let ctx = ctx_of(&[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]); |
| 1009 | // Quoted: `a-b` is always subtraction (Camunda semantics) ... |
| 1010 | assert_eq!(evaluate_with("a-b", &ctx, "ed).unwrap(), num(4.0)); |
| 1011 | let prog = compile_with("a-b", "ed).unwrap(); |
| 1012 | assert_eq!(prog.evaluate(&ctx).unwrap(), num(4.0)); |
| 1013 | assert_eq!(prog.scoped_parses(), 0); |
| 1014 | assert_eq!(prog.name_resolution(), NameResolution::Quoted); |
| 1015 | // ... backticks still work ... |
| 1016 | assert_eq!(evaluate_with("`a-b`", &ctx, "ed).unwrap(), num(100.0)); |
| 1017 | // ... and member runs are not probed either. |
| 1018 | let app = ctx_of(&[("applicant", ctx_value(&[("first-name", s("Ada"))]))]); |
| 1019 | assert_eq!( |
| 1020 | evaluate_with("applicant.first-name", &app, "ed).unwrap().into_lenient(), |
| 1021 | Value::Null |
| 1022 | ); |
| 1023 | // Symbols resolves against the scope. |
| 1024 | assert_eq!(evaluate("a-b", &ctx).unwrap(), num(100.0)); |
| 1025 | assert_eq!(NameResolution::from_name("Quoted"), Some(NameResolution::Quoted)); |
| 1026 | assert_eq!(NameResolution::from_name("symbols"), Some(NameResolution::Symbols)); |
| 1027 | assert_eq!(NameResolution::from_name("full"), None); |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn default_level_is_quoted() { |
| 1032 | // ADR-48 (revised): the crate default reads the text, not the data. |
| 1033 | let ctx = ctx_of(&[("a", num(7.0)), ("b", num(3.0)), ("a-b", num(100.0))]); |
| 1034 | assert_eq!(super::evaluate("a-b", &ctx).unwrap(), num(4.0)); |
| 1035 | assert_eq!(super::evaluate("`a-b`", &ctx).unwrap(), num(100.0)); |
| 1036 | let prog = super::compile("a-b").unwrap(); |
| 1037 | assert_eq!(prog.name_resolution(), NameResolution::Quoted); |
| 1038 | assert_eq!(prog.evaluate(&ctx).unwrap(), num(4.0)); |
| 1039 | let app = ctx_of(&[("applicant", ctx_value(&[("first-name", s("Ada"))]))]); |
| 1040 | assert_eq!(super::evaluate("applicant.`first-name`", &app).unwrap(), s("Ada")); |
| 1041 | assert_eq!(ParseOptions::default().names, NameResolution::Quoted); |
| 1042 | } |
| 1043 | |
| 1044 | #[test] |
| 1045 | fn compiled_parse_cache_is_bounded_and_always_correct() { |
| 1046 | // Four independent runs -> 16 binding combinations, more than the |
| 1047 | // 8-entry cache holds: every evaluation must still be scope-correct. |
| 1048 | let src = "a-b + c-d + e-f + g-h"; |
| 1049 | let prog = compile(src).unwrap(); |
| 1050 | for mask in 0..16u32 { |
| 1051 | for _round in 0..2 { |
| 1052 | let mut ctx = Context::empty(); |
| 1053 | for (bit, (l, r)) in [("a", "b"), ("c", "d"), ("e", "f"), ("g", "h")] |
| 1054 | .into_iter() |
| 1055 | .enumerate() |
| 1056 | { |
| 1057 | ctx.insert(l, num(10.0)); |
| 1058 | ctx.insert(r, num(1.0)); |
| 1059 | if mask & (1 << bit) != 0 { |
| 1060 | ctx.insert(format!("{l}-{r}"), num(100.0)); |
| 1061 | } |
| 1062 | } |
| 1063 | let expected = evaluate(src, &ctx).unwrap(); |
| 1064 | assert_eq!(prog.evaluate(&ctx).unwrap(), expected, "mask {mask}"); |
| 1065 | } |
| 1066 | } |
| 1067 | assert!(prog.scoped_parses() <= 8); |
| 1068 | } |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn path_members_resolve_against_the_navigated_value() { |
| 1072 | let app = ctx_value(&[("net-income", num(100.0)), ("age", num(30.0))]); |
| 1073 | let ctx = &[("applicant", app.clone()), ("total", num(150.0))]; |
| 1074 | assert_eq!(eval_in("applicant.net-income", ctx), num(100.0)); |
| 1075 | // A member run after an operator and as an operand. |
| 1076 | assert_eq!(eval_in("total - applicant.net-income", ctx), num(50.0)); |
| 1077 | assert_eq!(eval_in("applicant.net-income / 4", ctx), num(25.0)); |
| 1078 | // Deeper static chains. |
| 1079 | let deep = &[("p", ctx_value(&[("q", ctx_value(&[("r-s", num(7.0))]))]))]; |
| 1080 | assert_eq!(eval_in("p.q.r-s", deep), num(7.0)); |
| 1081 | // A member of a fused root name. |
| 1082 | let dt = &[("Date-Time2", ctx_value(&[("time-zone", s("Z"))]))]; |
| 1083 | assert_eq!(eval_in("Date-Time2.time-zone", dt), s("Z")); |
| 1084 | // A list step maps over the elements; ANY element having the key counts. |
| 1085 | let orders = Value::List(vec![ |
| 1086 | ctx_value(&[("unit-price", num(2.0))]), |
| 1087 | ctx_value(&[("unit-price", num(3.0))]), |
| 1088 | ]); |
| 1089 | assert_eq!( |
| 1090 | eval_in("orders.unit-price", &[("orders", orders)]), |
| 1091 | list(vec![num(2.0), num(3.0)]) |
| 1092 | ); |
| 1093 | // No such member -> the arithmetic reading stands. |
| 1094 | let plain = &[("x", ctx_value(&[("y", num(10.0))])), ("z", num(3.0))]; |
| 1095 | assert_eq!(eval_in("x.y-z", plain), num(7.0)); |
| 1096 | // A dynamic base is never probed: `(applicant).net-income` stays |
| 1097 | // `(applicant).net - income` (backticks cover it). |
| 1098 | assert_eq!(eval_in("(applicant).net-income", ctx), Value::Null); |
| 1099 | assert_eq!(eval_in("(applicant).`net-income`", ctx), num(100.0)); |
| 1100 | // The adaptive compile path probes members too. |
| 1101 | let prog = compile("applicant.net-income").unwrap(); |
| 1102 | assert_eq!(prog.evaluate(&ctx_of(ctx)).unwrap().into_lenient(), num(100.0)); |
| 1103 | let other = ctx_of(&[("applicant", ctx_value(&[("net", num(5.0))])), ("income", num(1.0))]); |
| 1104 | assert_eq!(prog.evaluate(&other).unwrap().into_lenient(), num(4.0)); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn plain_paths_and_dotted_members_never_probe_members() { |
| 1109 | // At a member position `.` is navigation, not a name symbol: a plain |
| 1110 | // path forms no member run (laziness, ADR-21). A dotted member key |
| 1111 | // needs backticks. |
| 1112 | let ctx = &[("o", ctx_value(&[("a.b", num(1.0)), ("a", ctx_value(&[("b", num(2.0))]))]))]; |
| 1113 | assert_eq!(eval_in("o.a.b", ctx), num(2.0)); |
| 1114 | assert_eq!(eval_in("o.`a.b`", ctx), num(1.0)); |
| 1115 | } |
| 1116 | |
| 1117 | #[test] |
| 1118 | fn member_probe_never_uses_a_shadowed_root() { |
| 1119 | // Each case has a ROOT binding of the path's root name WITH the hyphen |
| 1120 | // key, while the name actually in play (loop element, parameter, |
| 1121 | // sibling entry, filter element) has only `net`: the root value must |
| 1122 | // not decide the parse — the arithmetic reading `….net - income` stands. |
| 1123 | let shadowed = ctx_value(&[("net-income", num(999.0))]); |
| 1124 | let local = ctx_value(&[("net", num(10.0))]); |
| 1125 | let base = |root: &str| { |
| 1126 | ctx_of(&[ |
| 1127 | (root, shadowed.clone()), |
| 1128 | ("income", num(1.0)), |
| 1129 | ("x", local.clone()), |
| 1130 | ("items", Value::List(vec![local.clone()])), |
| 1131 | ("rows", Value::List(vec![ctx_value(&[("detail", local.clone())])])), |
| 1132 | ]) |
| 1133 | }; |
| 1134 | let ev = |src: &str, ctx: &Context| evaluate(src, ctx).unwrap().into_lenient(); |
| 1135 | // Loop variable. |
| 1136 | assert_eq!( |
| 1137 | ev("for item in items return item.net-income", &base("item")), |
| 1138 | list(vec![num(9.0)]) |
| 1139 | ); |
| 1140 | assert_eq!(ev("some item in items satisfies item.net-income = 9", &base("item")), b(true)); |
| 1141 | // Function parameter. |
| 1142 | assert_eq!(ev("{f: function(p) p.net-income, r: f(x)}.r", &base("p")), num(9.0)); |
| 1143 | // Context-literal key. |
| 1144 | assert_eq!(ev("{applicant: x, r: applicant.net-income}.r", &base("applicant")), num(9.0)); |
| 1145 | // Inside a filter bracket (`detail` is an element key there). |
| 1146 | assert_eq!( |
| 1147 | ev("count(rows[detail.net-income > 5])", &base("detail")), |
| 1148 | num(1.0) |
| 1149 | ); |
| 1150 | // The compiled path agrees. |
| 1151 | let prog = compile("for item in items return item.net-income").unwrap(); |
| 1152 | assert_eq!(prog.evaluate(&base("item")).unwrap().into_lenient(), list(vec![num(9.0)])); |
| 1153 | // Backticks still reach the member explicitly. |
| 1154 | let keyed = ctx_of(&[("items", Value::List(vec![ctx_value(&[("net-income", num(3.0))])]))]); |
| 1155 | assert_eq!( |
| 1156 | ev("for item in items return item.`net-income`", &keyed), |
| 1157 | list(vec![num(3.0)]) |
| 1158 | ); |
| 1159 | // A root path that is NOT shadowed is still probed. |
| 1160 | assert_eq!(ev("item.net-income", &base("item")), num(999.0)); |
| 1161 | } |
| 1162 | |
| 1163 | #[test] |
| 1164 | fn backtick_spaces_count() { |
| 1165 | // Inside backticks every space is part of the name — leading, trailing |
| 1166 | // and repeated — unlike unquoted multi-word names (one space). |
| 1167 | assert_eq!(eval_in("` a`", &[(" a", num(1.0))]), num(1.0)); |
| 1168 | assert_eq!(eval_in("`a `", &[("a ", num(2.0))]), num(2.0)); |
| 1169 | assert_eq!(eval_in("`a b`", &[("a b", num(3.0)), ("a b", num(4.0))]), num(3.0)); |
| 1170 | assert_eq!(eval_in("a b", &[("a b", num(3.0)), ("a b", num(4.0))]), num(4.0)); |
| 1171 | assert_eq!(eval_in("` a`", &[("a", num(5.0))]), Value::Null); |
| 1172 | } |
| 1173 | |
| 1174 | #[test] |
| 1175 | fn special_key_precheck_never_changes_results() { |
| 1176 | // The O(1) pre-check counts keys with a name symbol; re-inserting a key |
| 1177 | // must not double-count, and an unrelated special key still triggers |
| 1178 | // the full check (which then finds nothing bound). |
| 1179 | let mut c = Context::empty(); |
| 1180 | assert!(!c.may_bind_special()); |
| 1181 | c.insert("x-y", num(1.0)); |
| 1182 | c.insert("x-y", num(2.0)); |
| 1183 | assert!(c.may_bind_special()); |
| 1184 | c.insert("a", num(7.0)); |
| 1185 | c.insert("b", num(3.0)); |
| 1186 | let prog = compile("a-b").unwrap(); |
| 1187 | assert_eq!(prog.evaluate(&c).unwrap(), num(4.0)); |
| 1188 | assert_eq!(prog.scoped_parses(), 0); |
| 1189 | c.insert("a-b", num(9.0)); |
| 1190 | assert_eq!(prog.evaluate(&c).unwrap(), num(9.0)); |
| 1191 | // Member sites are checked even without special root keys. |
| 1192 | let app = ctx_of(&[("applicant", ctx_value(&[("net-income", num(5.0))]))]); |
| 1193 | assert!(!app.may_bind_special()); |
| 1194 | assert_eq!(compile("applicant.net-income").unwrap().evaluate(&app).unwrap(), num(5.0)); |
| 1195 | } |
| 1196 | |
| 1197 | #[test] |
| 1198 | fn no_builtin_name_contains_a_name_symbol() { |
| 1199 | // Built-in names are in scope for the fusion probe. A built-in whose name |
| 1200 | // contained `- + * / .` would silently change how existing expressions |
| 1201 | // parse — and the values stored in feel-pg expression indexes (ADR-48). |
| 1202 | let src = include_str!("builtins.rs"); |
| 1203 | let start = src.find("pub(crate) fn is_builtin").expect("is_builtin present"); |
| 1204 | let body = &src[start..start + src[start..].find("\n}\n").expect("end of fn")]; |
| 1205 | let names: Vec<&str> = body.split('"').skip(1).step_by(2).collect(); |
| 1206 | assert!(names.len() > 50, "parsed the is_builtin name list ({})", names.len()); |
| 1207 | for n in names { |
| 1208 | assert!( |
| 1209 | !n.contains(['-', '+', '*', '/', '.']), |
| 1210 | "built-in `{n}` contains a name symbol" |
| 1211 | ); |
| 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | #[test] |
| 1216 | fn is_clock_free_finds_now_and_today_anywhere() { |
| 1217 | // Pure expressions are clock-free, including temporal constructors and |
| 1218 | // named-zone literals (the clock check is orthogonal to zones). |
| 1219 | for src in [ |
| 1220 | "1 + 1", |
| 1221 | "date(2020, 1, 1)", |
| 1222 | r#"time("09:00:00@Europe/Berlin")"#, |
| 1223 | "for x in [1, 2, 3] return x + 1", |
| 1224 | ] { |
| 1225 | assert!( |
| 1226 | compile(src).unwrap().is_clock_free(), |
| 1227 | "expected clock-free: {src}" |
| 1228 | ); |
| 1229 | } |
| 1230 | // `now()`/`today()` make it not clock-free, however deeply nested. |
| 1231 | for src in [ |
| 1232 | "now()", |
| 1233 | "today()", |
| 1234 | "1 + now()", |
| 1235 | "if a then 1 else today()", |
| 1236 | "[1, now(), 3]", |
| 1237 | "{ a: now() }", |
| 1238 | "some x in [1, 2] satisfies x > today()", |
| 1239 | ] { |
| 1240 | assert!( |
| 1241 | !compile(src).unwrap().is_clock_free(), |
| 1242 | "expected clock-reading: {src}" |
| 1243 | ); |
| 1244 | } |
| 1245 | } |
| 1246 | |
| 1247 | #[test] |
| 1248 | fn forbidding_named_zones_rejects_named_keeps_offsets() { |
| 1249 | let forbid = |
| 1250 | EvalEnv::new(&crate::regex_provider::DEFAULT, default_now()).forbidding_named_zones(); |
| 1251 | let eval = |
| 1252 | |src: &str, ctx: &Context| compile(src).unwrap().evaluate_with_env(ctx, &forbid).unwrap(); |
| 1253 | let empty = Context::empty(); |
| 1254 | |
| 1255 | // Fixed offsets and `Z` are tzdb-independent -> always allowed. |
| 1256 | assert!(matches!(eval(r#"time("09:00:00+02:00")"#, &empty), Value::Time(_))); |
| 1257 | assert!(matches!(eval(r#"time("09:00:00Z")"#, &empty), Value::Time(_))); |
| 1258 | |
| 1259 | // A named zone is allowed by the default env (no policy) ... |
| 1260 | assert!(matches!( |
| 1261 | compile(r#"time("09:00:00@Europe/Berlin")"#) |
| 1262 | .unwrap() |
| 1263 | .evaluate(&empty) |
| 1264 | .unwrap(), |
| 1265 | Value::Time(_) |
| 1266 | )); |
| 1267 | // ... but becomes an error-null under the policy — whether the named zone |
| 1268 | // comes from a constructor literal, an `@"…"` literal, or runtime data. |
| 1269 | assert_eq!(eval(r#"time("09:00:00@Europe/Berlin")"#, &empty), Value::Error); |
| 1270 | assert_eq!(eval(r#"@"2017-08-10T12:00:00@Europe/Berlin""#, &empty), Value::Error); |
| 1271 | let mut ctx = Context::empty(); |
| 1272 | ctx.insert("s", Value::String("2017-08-10T12:00:00@Europe/Berlin".into())); |
| 1273 | assert_eq!(eval("date and time(s)", &ctx), Value::Error); |
| 1274 | } |
| 1275 | |
| 1276 | #[test] |
| 1277 | fn literals() { |
| 1278 | assert_eq!(ev("42"), num(42.0)); |
| 1279 | assert_eq!(ev("3.5"), num(3.5)); |
| 1280 | assert_eq!(ev(r#""foo""#), Value::String("foo".into())); |
| 1281 | assert_eq!(ev("true"), b(true)); |
| 1282 | assert_eq!(ev("false"), b(false)); |
| 1283 | assert_eq!(ev("null"), Value::Null); |
| 1284 | assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)])); |
| 1285 | assert_eq!(ev("[]"), list(vec![])); |
| 1286 | } |
| 1287 | |
| 1288 | // FEEL grammar rule 35 / §10.3.2.3.1: leading-dot mantissa and exponent forms. |
| 1289 | // These are exercised by the 0101-feel-constants TCK suite and checked here |
| 1290 | // directly so the lexer widening has coverage independent of the fixtures. |
| 1291 | #[test] |
| 1292 | fn number_literals_rule35() { |
| 1293 | // leading-dot mantissa (.digits) |
| 1294 | assert_eq!(ev(".872"), num(0.872)); |
| 1295 | assert_eq!(ev("-.872"), num(-0.872)); |
| 1296 | // exponent forms |
| 1297 | assert_eq!(ev("1.2e3"), num(1200.0)); |
| 1298 | assert_eq!(ev("1.2E3"), num(1200.0)); |
| 1299 | assert_eq!(ev("1E-3"), num(0.001)); |
| 1300 | assert_eq!(ev("1e+2"), num(100.0)); |
| 1301 | // leading-dot + exponent |
| 1302 | assert_eq!(ev(".5e2"), num(50.0)); |
| 1303 | // unchanged: digit-led mantissa still works |
| 1304 | assert_eq!(ev("3.5"), num(3.5)); |
| 1305 | } |
| 1306 | |
| 1307 | #[test] |
| 1308 | fn comments() { |
| 1309 | assert_eq!(ev("1 + /* 1 + */ 1"), num(2.0)); |
| 1310 | assert_eq!(ev("1 + // eol\n 1"), num(2.0)); |
| 1311 | assert_eq!(ev("/* intro */ 1 + 1 // trailing"), num(2.0)); |
| 1312 | assert_eq!(ev("6 / 3"), num(2.0)); // lone slash stays division |
| 1313 | } |
| 1314 | |
| 1315 | #[test] |
| 1316 | fn first_class_range_literals() { |
| 1317 | // A range literal in value position is a first-class value, equal to itself. |
| 1318 | assert_eq!(ev("[1..10] = [1..10]"), b(true)); |
| 1319 | assert_eq!(ev("(1..10] = (1..10]"), b(true)); |
| 1320 | assert_eq!(ev("[1..10) = [1..10)"), b(true)); |
| 1321 | // Openness and endpoints are part of identity. |
| 1322 | assert_eq!(ev("[1..10] = [1..10)"), b(false)); |
| 1323 | assert_eq!(ev("[1..10] = (1..10]"), b(false)); |
| 1324 | assert_eq!(ev("[1..10] = [1..11]"), b(false)); |
| 1325 | // Endpoints of any orderable type. |
| 1326 | assert_eq!(ev(r#"["a".."c"] = ["a".."c"]"#), b(true)); |
| 1327 | // `instance of range<T>` checks both endpoints' type. |
| 1328 | assert_eq!(ev("[1..10] instance of range<number>"), b(true)); |
| 1329 | assert_eq!(ev(r#"["a".."c"] instance of range<string>"#), b(true)); |
| 1330 | assert_eq!(ev("[1..10] instance of range<string>"), b(false)); |
| 1331 | // A range literal nests as a list element (list of ranges). |
| 1332 | assert_eq!(ev("[[1..2], [3..4]] = [[1..2], [3..4]]"), b(true)); |
| 1333 | // The `in` membership *test* form is unchanged (regression). |
| 1334 | assert_eq!(ev("5 in [1..10]"), b(true)); |
| 1335 | assert_eq!(ev("15 in [1..10]"), b(false)); |
| 1336 | // A plain list literal is still a list, not a range. |
| 1337 | assert_eq!(ev("[1, 2, 3]"), list(vec![num(1.0), num(2.0), num(3.0)])); |
| 1338 | } |
| 1339 | |
| 1340 | #[test] |
| 1341 | fn reverse_open_bracket_intervals() { |
| 1342 | // `]a..b]` is FEEL's exclusive-lower spelling of `(a..b]` — identical value. |
| 1343 | assert_eq!(ev("]1..10] = (1..10]"), b(true)); |
| 1344 | assert_eq!(ev("]1..10] = [1..10]"), b(false)); // start openness differs |
| 1345 | assert_eq!(ev("]1..10) = (1..10)"), b(true)); // reverse-open + open upper |
| 1346 | // Value position: a reverse-open literal nests as a list element. |
| 1347 | assert_eq!(ev("[]1..2], (1..2]] = [(1..2], (1..2]]"), b(true)); |
| 1348 | // Membership-test position: `x in ]a..b]` excludes the open lower bound. |
| 1349 | assert_eq!(ev("5 in ]1..10]"), b(true)); |
| 1350 | assert_eq!(ev("1 in ]1..10]"), b(false)); // open lower excludes |
| 1351 | assert_eq!(ev("10 in ]1..10]"), b(true)); // closed upper includes |
| 1352 | // The empty list `[]` is untouched by the opener retag (no `..` follows). |
| 1353 | assert_eq!(ev("[]"), list(vec![])); |
| 1354 | } |
| 1355 | |
| 1356 | #[test] |
| 1357 | fn reverse_close_bracket_intervals() { |
| 1358 | // `[a..b[` is FEEL's exclusive-upper spelling of `[a..b)` — identical value. |
| 1359 | assert_eq!(ev("[1..10[ = [1..10)"), b(true)); |
| 1360 | assert_eq!(ev("[1..10[ = [1..10]"), b(false)); // end openness differs |
| 1361 | assert_eq!(ev("(1..10[ = (1..10)"), b(true)); // open lower + reverse-close |
| 1362 | // Both reverse brackets at once: `]a..b[` ≡ `(a..b)`. |
| 1363 | assert_eq!(ev("]1..10[ = (1..10)"), b(true)); |
| 1364 | // Membership-test position: `x in [a..b[` excludes the open upper bound. |
| 1365 | assert_eq!(ev("9 in [1..10["), b(true)); |
| 1366 | assert_eq!(ev("10 in [1..10["), b(false)); // open upper excludes |
| 1367 | assert_eq!(ev("1 in [1..10["), b(true)); // closed lower includes |
| 1368 | // Arithmetic still works in the (filter-free) high endpoint. |
| 1369 | assert_eq!(ev("9 in [1..5+5["), b(true)); |
| 1370 | // Regression: a `[` after a completed value is still a filter subscript. |
| 1371 | assert_eq!(ev("[10, 20, 30][2]"), num(20.0)); |
| 1372 | } |
| 1373 | |
| 1374 | #[test] |
| 1375 | fn unbounded_ranges() { |
| 1376 | // An omitted endpoint is UNBOUNDED (±∞; ADR-31), satisfying its side of a |
| 1377 | // membership test unconditionally. Per FEEL grammar rule 66 an omitted endpoint |
| 1378 | // requires an OPEN bracket on that side: `[1..)` / `(..10]`, never `[1..]` / |
| 1379 | // `[..10]` (a closed bracket with no value is a parse error; see |
| 1380 | // `unbounded_closed_bracket_is_a_parse_error`). |
| 1381 | assert_eq!(ev("5 in [1..)"), b(true)); // everything ≥ 1 |
| 1382 | assert_eq!(ev("0 in [1..)"), b(false)); |
| 1383 | assert_eq!(ev("1 in [1..)"), b(true)); // closed lower includes |
| 1384 | assert_eq!(ev("1 in (1..)"), b(false)); // open lower excludes |
| 1385 | assert_eq!(ev("5 in (..10]"), b(true)); // everything ≤ 10 |
| 1386 | assert_eq!(ev("11 in (..10]"), b(false)); |
| 1387 | assert_eq!(ev("10 in (..10)"), b(false)); // open upper excludes |
| 1388 | |
| 1389 | // The crux: UNBOUNDED is NOT a `null` bound. `(..10]` includes everything ≤ 10; |
| 1390 | // `[null..10]` is a *present* null bound, so membership is three-valued unknown |
| 1391 | // (per DMN-TCK 0072) — they must stay distinct. |
| 1392 | assert_eq!(ev("5 in (..10]"), b(true)); |
| 1393 | assert_eq!(ev("5 in [null..10]"), Value::Null); |
| 1394 | assert_eq!(ev("5 in [1..)"), b(true)); |
| 1395 | assert_eq!(ev("5 in [1..null]"), Value::Null); |
| 1396 | |
| 1397 | // Value-position literals: a first-class unbounded range, equal to itself and |
| 1398 | // distinct from a bounded range. |
| 1399 | assert_eq!(ev("[1..) = [1..)"), b(true)); |
| 1400 | assert_eq!(ev("(..10] = (..10]"), b(true)); |
| 1401 | assert_eq!(ev("(..10] = ]..10]"), b(true)); // unbounded lower: spelling irrelevant |
| 1402 | assert_eq!(ev("[1..) = [1..10]"), b(false)); // unbounded ≠ bounded |
| 1403 | assert_eq!(ev("[1..) = [2..)"), b(false)); // different lower bound |
| 1404 | assert_eq!(ev("(..10] = (..11]"), b(false)); |
| 1405 | // UNBOUNDED ≠ a present `null` bound, even structurally. |
| 1406 | assert_eq!(ev("(..10] = [null..10]"), b(false)); |
| 1407 | |
| 1408 | // Range properties: an unbounded endpoint has no value and is never included. |
| 1409 | assert_eq!(ev("[1..).start"), num(1.0)); |
| 1410 | assert_eq!(ev("[1..).end"), Value::Null); |
| 1411 | assert_eq!(ev("[1..).end included"), b(false)); |
| 1412 | assert_eq!(ev("(..10].start"), Value::Null); |
| 1413 | assert_eq!(ev("(..10].start included"), b(false)); |
| 1414 | assert_eq!(ev("(..10].end"), num(10.0)); |
| 1415 | |
| 1416 | // `instance of`: the bounded side types the range; the unbounded side is vacuous. |
| 1417 | assert_eq!(ev("[1..) instance of range<number>"), b(true)); |
| 1418 | assert_eq!(ev("[1..) instance of range<string>"), b(false)); |
| 1419 | assert_eq!(ev(r#"["a"..) instance of range<string>"#), b(true)); |
| 1420 | |
| 1421 | // string() echoes the written bracket, rendering an unbounded side as nothing. |
| 1422 | assert_eq!(ev("string([1..))"), Value::String("[1..)".into())); |
| 1423 | assert_eq!(ev("string((..10))"), Value::String("(..10)".into())); |
| 1424 | |
| 1425 | // Allen relations (§10.3.4.6) over unbounded operands. |
| 1426 | assert_eq!(ev("before( (..5], [10..) )"), b(true)); // (-∞,5] before [10,+∞) |
| 1427 | assert_eq!(ev("before( (..5], [3..) )"), b(false)); // they overlap |
| 1428 | assert_eq!(ev("includes( (..7], [3..7] )"), b(true)); // unbounded-below includes all ≤ 7 |
| 1429 | assert_eq!(ev("includes( [1..), [3..7] )"), b(true)); |
| 1430 | assert_eq!(ev("includes( [1..), [0..7] )"), b(false)); // 0 < 1, escapes below |
| 1431 | assert_eq!(ev("during( 5, [1..) )"), b(true)); |
| 1432 | assert_eq!(ev("during( 5, (..10] )"), b(true)); |
| 1433 | assert_eq!(ev("coincides( (..5], (..5] )"), b(true)); |
| 1434 | assert_eq!(ev("coincides( (..5], ]..5] )"), b(true)); // unbounded lower: spelling ignored |
| 1435 | assert_eq!(ev("overlaps( (..5], [3..) )"), b(true)); |
| 1436 | } |
| 1437 | |
| 1438 | #[test] |
| 1439 | fn unbounded_closed_bracket_is_a_parse_error() { |
| 1440 | // Rule 66: an omitted endpoint behind a CLOSED bracket is invalid, and AT MOST |
| 1441 | // one endpoint may be omitted — these do not parse (a hard error, not a silent |
| 1442 | // misparse), consistent with `range("[1..]")` / `range("(..)")` being null. The |
| 1443 | // valid spellings are `[1..)` / `(..10]` (ADR-31). `(..)` (both omitted) has no |
| 1444 | // rule-66 alternative, so it is rejected too. |
| 1445 | for src in [ |
| 1446 | "[1..]", "[..10]", "[..10)", "[..]", "5 in [1..]", "5 in [..10]", "(..)", |
| 1447 | "5 in (..)", "(..)= (..)", |
| 1448 | ] { |
| 1449 | assert!( |
| 1450 | compile(src).is_err(), |
| 1451 | "expected a parse error for closed-bracket unbounded `{src}`" |
| 1452 | ); |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | #[test] |
| 1457 | fn value_position_comparison_test() { |
| 1458 | // A parenthesised comparison test in VALUE position — `(< 10)`, `(= 10)`, |
| 1459 | // `(!= 10)` — is an OPAQUE unary-test value (ADR-32), not a boolean and not a |
| 1460 | // promoted range. The measured TCK semantics (0068): it equals a *structurally |
| 1461 | // identical* test reflexively, but is NEVER equal to a `Range`. |
| 1462 | assert_eq!(ev("(<10) = (<10)"), b(true)); |
| 1463 | assert_eq!(ev("(=10) = (=10)"), b(true)); |
| 1464 | assert_eq!(ev("(!=10) = (!=10)"), b(true)); |
| 1465 | // Whitespace inside the parens is irrelevant; every operator spelling works. |
| 1466 | assert_eq!(ev("(<= 10) = (<= 10)"), b(true)); |
| 1467 | assert_eq!(ev("(>= 10) = (>= 10)"), b(true)); |
| 1468 | assert_eq!(ev("(> 10) = (> 10)"), b(true)); |
| 1469 | |
| 1470 | // Range-INCOMPATIBLE: equal to no `Range`, whatever the spelling — the crux that |
| 1471 | // falsified the desugar-to-range hypothesis (ADR-28). A definite `false`. |
| 1472 | assert_eq!(ev("(<10) = (null..10)"), b(false)); |
| 1473 | assert_eq!(ev("(=10) = [10..10]"), b(false)); |
| 1474 | assert_eq!(ev("(<10) = (..10)"), b(false)); // not even the unbounded `(..10)` |
| 1475 | |
| 1476 | // Structural, not loose: a different operator or endpoint is `false`. |
| 1477 | assert_eq!(ev("(<10) = (>10)"), b(false)); |
| 1478 | assert_eq!(ev("(<10) = (<=10)"), b(false)); |
| 1479 | assert_eq!(ev("(<10) = (<11)"), b(false)); |
| 1480 | // …and against anything else (a plain number, a list) it is `false`, not error. |
| 1481 | assert_eq!(ev("(<10) = 10"), b(false)); |
| 1482 | assert_eq!(ev("(=10) = [10]"), b(false)); |
| 1483 | |
| 1484 | // string() renders the written parenthesised form (endpoint quoted as a member). |
| 1485 | assert_eq!(ev("string((<10))"), Value::String("(< 10)".into())); |
| 1486 | assert_eq!(ev("string((!=10))"), Value::String("(!= 10)".into())); |
| 1487 | assert_eq!(ev(r#"string((="x"))"#), Value::String("(= \"x\")".into())); |
| 1488 | |
| 1489 | // REGRESSION: the `in`-position forms (ADR-28) are a *test*, unchanged — they |
| 1490 | // still membership-test, never construct an opaque value. |
| 1491 | assert_eq!(ev("10 in (=10)"), b(true)); |
| 1492 | assert_eq!(ev("5 in (=10)"), b(false)); |
| 1493 | assert_eq!(ev("5 in (!=10)"), b(true)); |
| 1494 | assert_eq!(ev("10 in (!=10)"), b(false)); |
| 1495 | assert_eq!(ev("5 in (<10)"), b(true)); |
| 1496 | assert_eq!(ev("15 in (<10)"), b(false)); |
| 1497 | } |
| 1498 | |
| 1499 | #[test] |
| 1500 | fn range_properties() { |
| 1501 | // The four range properties (DMN §10.3.2.6 / TCK 0074): endpoints + inclusivity. |
| 1502 | assert_eq!(ev("[1..10].start"), num(1.0)); |
| 1503 | assert_eq!(ev("[1..10].end"), num(10.0)); |
| 1504 | assert_eq!(ev("[1..10].start included"), b(true)); |
| 1505 | assert_eq!(ev("[1..10].end included"), b(true)); |
| 1506 | // Openness flows through to `start/end included`, across every bracket form. |
| 1507 | assert_eq!(ev("(1..10].start included"), b(false)); |
| 1508 | assert_eq!(ev("[1..10).end included"), b(false)); |
| 1509 | assert_eq!(ev("]1..10].start included"), b(false)); // reverse-open lower |
| 1510 | assert_eq!(ev("[1..10[.end included"), b(false)); // reverse-close upper |
| 1511 | assert_eq!(ev("]1..10].start"), num(1.0)); |
| 1512 | assert_eq!(ev("[1..10[.end"), num(10.0)); |
| 1513 | // Endpoints of any orderable type. |
| 1514 | assert_eq!(ev(r#"["a".."c"].end"#), Value::String("c".into())); |
| 1515 | // An unknown property of a range is a value-null (a range has properties). |
| 1516 | assert_eq!(ev("[1..10].foo"), Value::Null); |
| 1517 | |
| 1518 | // A comparison-test value `(< 10)` (ADR-32, ADR-33) is range-typed for these |
| 1519 | // projections (§10.3.2.7 / Table 42, TCK 0074 range_006-011): the operator's |
| 1520 | // missing endpoint is `null` and never included; the present endpoint's |
| 1521 | // inclusivity follows the operator. Despite identical properties to a range, |
| 1522 | // its equality stays OPAQUE — see `value_position_comparison_test`. |
| 1523 | assert_eq!(ev("(<10).start"), Value::Null); // range_006: (<10) |
| 1524 | assert_eq!(ev("(<10).end"), num(10.0)); |
| 1525 | assert_eq!(ev("(<10).start included"), b(false)); |
| 1526 | assert_eq!(ev("(<10).end included"), b(false)); |
| 1527 | assert_eq!(ev("(<=10).end included"), b(true)); // range_007: (<=10) |
| 1528 | assert_eq!(ev("(>10).start"), num(10.0)); // range_009: (>10) |
| 1529 | assert_eq!(ev("(>10).end"), Value::Null); |
| 1530 | assert_eq!(ev("(>10).start included"), b(false)); |
| 1531 | assert_eq!(ev("(>=10).start included"), b(true)); // range_010: (>=10) |
| 1532 | assert_eq!(ev("(=10).start"), num(10.0)); // range_011: (=10) ≡ [10..10] properties |
| 1533 | assert_eq!(ev("(=10).end"), num(10.0)); |
| 1534 | assert_eq!(ev("(=10).start included"), b(true)); |
| 1535 | assert_eq!(ev("(=10).end included"), b(true)); |
| 1536 | assert_eq!(ev("(!=10).start included"), b(false)); // (!=10): bare endpoint, open |
| 1537 | assert_eq!(ev("(!=10).end included"), b(false)); |
| 1538 | // An unknown property is still a value-null (it has range properties). |
| 1539 | assert_eq!(ev("(<10).foo"), Value::Null); |
| 1540 | |
| 1541 | // `(< 10)` is "a typed instance of the range type" (§10.3.2.7), so it conforms |
| 1542 | // to `range<T>` on its endpoint type — even though it is never *equal* to a range. |
| 1543 | assert_eq!(ev("(<10) instance of range<number>"), b(true)); |
| 1544 | assert_eq!(ev("(>=10) instance of range<number>"), b(true)); |
| 1545 | assert_eq!(ev(r#"(<"x") instance of range<string>"#), b(true)); |
| 1546 | assert_eq!(ev("(<10) instance of range<string>"), b(false)); // wrong endpoint type |
| 1547 | } |
| 1548 | |
| 1549 | #[test] |
| 1550 | fn range_builtin() { |
| 1551 | // Representative cases from DMN-TCK 1156-range-function. |
| 1552 | // --- construction + equality with a literal / membership / instance of --- |
| 1553 | assert_eq!(ev(r#"range("[18..21]") = [18..21]"#), b(true)); |
| 1554 | assert_eq!(ev(r#"range("(18..21]") = (18..21]"#), b(true)); |
| 1555 | assert_eq!(ev(r#"range("[18..21)") = [18..21)"#), b(true)); |
| 1556 | assert_eq!(ev(r#"range(" [ 1 .. 3 ] ") = [1..3]"#), b(true)); // whitespace tolerant |
| 1557 | assert_eq!(ev(r#"2 in range("[1..3]")"#), b(true)); |
| 1558 | assert_eq!(ev(r#"range("[1..3]") instance of range<number>"#), b(true)); |
| 1559 | assert_eq!(ev(r#"range(string("[1..3]")) instance of range<number>"#), b(true)); |
| 1560 | assert_eq!(ev(r#"range("[\"a\"..\"c\"]") instance of range<string>"#), b(true)); |
| 1561 | assert_eq!(ev(r#"range(from: "[1..3]") = [1..3]"#), b(true)); |
| 1562 | // temporal endpoints (via `@"…"` and direct constructors on string literals) |
| 1563 | assert_eq!( |
| 1564 | ev(r#"range("[date(\"1970-01-01\")..date(\"1970-01-02\")]") = [date("1970-01-01")..date("1970-01-02")]"#), |
| 1565 | b(true) |
| 1566 | ); |
| 1567 | assert_eq!(ev(r#"range("[@\"P1D\"..@\"P2D\"]") instance of range<days and time duration>"#), b(true)); |
| 1568 | // Unbounded via the OPEN-bracket spelling is valid per FEEL grammar rule 66 |
| 1569 | // (b)/(c): `range("[2..)")` ≡ `>=2`, `range("(..2)")` ≡ `<2` (spec §10.3.4.6 |
| 1570 | // examples). A CLOSED bracket on the omitted side is invalid (the null cases |
| 1571 | // below). See ADR-31. |
| 1572 | assert_eq!(ev(r#"range("[2..)") = [2..)"#), b(true)); |
| 1573 | assert_eq!(ev(r#"range("(..2)") = (..2)"#), b(true)); |
| 1574 | assert_eq!(ev(r#"5 in range("[2..)")"#), b(true)); |
| 1575 | assert_eq!(ev(r#"5 in range("(..2)")"#), b(false)); |
| 1576 | |
| 1577 | // --- error/null cases (lenient view collapses error-null to null) --- |
| 1578 | for src in [ |
| 1579 | r#"range("")"#, |
| 1580 | r#"range(" ")"#, |
| 1581 | r#"range()"#, |
| 1582 | r#"range("[1..3]", "foo")"#, |
| 1583 | r#"range([1..3])"#, // argument is a range value, not a string |
| 1584 | r#"range(">=10")"#, // not a range literal |
| 1585 | r#"range("[1..\"b\"]")"#, // mismatched endpoint types |
| 1586 | r#"range("[3..1]")"#, // reversed |
| 1587 | r#"range("[null..null]")"#, // null endpoints |
| 1588 | // Omitted endpoint with a CLOSED bracket is invalid (rule 66 needs an OPEN |
| 1589 | // bracket on the unbounded side); both-omitted has no rule-66 alternative. |
| 1590 | // Unlike the lenient unbounded *literal* `[..2]` (ADR-31, in |
| 1591 | // `unbounded_ranges`), the `range()` string is strict here. |
| 1592 | r#"range("[..2]")"#, // closed start, no value → null (TCK 004_e) |
| 1593 | r#"range("[1..]")"#, // closed end, no value → null (TCK 004_f) |
| 1594 | r#"range("[..]")"#, // both omitted, both closed → null |
| 1595 | r#"range("(..)")"#, // both omitted → null (no rule-66 case) |
| 1596 | r#"range("[null..)")"#, // present null lower bound → null |
| 1597 | r#"range("[date(string(\"1970-01-01\"))..date(\"1970-01-02\")]")"#, // non-literal endpoint |
| 1598 | r#"range(fron: "[1..3]")"#, // unknown named parameter |
| 1599 | ] { |
| 1600 | assert_eq!(ev(src), Value::Null, "expected null for `{src}`"); |
| 1601 | } |
| 1602 | } |
| 1603 | |
| 1604 | #[test] |
| 1605 | fn range_relations_tck_1130() { |
| 1606 | // The complete truth table of DMN-TCK 1130-feel-interval (every openness |
| 1607 | // edge case for the §10.3.4.6 Allen relations). 1130's decisions are boxed |
| 1608 | // contexts the fixture ingester does not read, so the suite is exercised here. |
| 1609 | let cases: &[(&str, bool)] = &[ |
| 1610 | ("before( 1, 10 )", true), |
| 1611 | ("before( 10, 1 )", false), |
| 1612 | ("before( 1, [1..10] )", false), |
| 1613 | ("before( 1, (1..10] )", true), |
| 1614 | ("before( 1, [5..10] )", true), |
| 1615 | ("before( [1..10], 10 )", false), |
| 1616 | ("before( [1..10), 10 )", true), |
| 1617 | ("before( [1..10], 15 )", true), |
| 1618 | ("before( [1..10], [15..20] )", true), |
| 1619 | ("before( [1..10], [10..20] )", false), |
| 1620 | ("before( [1..10), [10..20] )", true), |
| 1621 | ("before( [1..10], (10..20] )", true), |
| 1622 | ("after( 10, 5 )", true), |
| 1623 | ("after( 5, 10 )", false), |
| 1624 | ("after( 12, [1..10] )", true), |
| 1625 | ("after( 10, [1..10) )", true), |
| 1626 | ("after( 10, [1..10] )", false), |
| 1627 | ("after( [11..20], 12 )", false), |
| 1628 | ("after( [11..20], 10 )", true), |
| 1629 | ("after( (11..20], 11 )", true), |
| 1630 | ("after( [11..20], 11 )", false), |
| 1631 | ("after( [11..20], [1..10] )", true), |
| 1632 | ("after( [1..10], [11..20] )", false), |
| 1633 | ("after( [11..20], [1..11) )", true), |
| 1634 | ("after( (11..20], [1..11] )", true), |
| 1635 | ("meets( [1..5], [5..10] )", true), |
| 1636 | ("meets( [1..5), [5..10] )", false), |
| 1637 | ("meets( [1..5], (5..10] )", false), |
| 1638 | ("meets( [1..5], [6..10] )", false), |
| 1639 | ("met by( [5..10], [1..5] )", true), |
| 1640 | ("met by( [5..10], [1..5) )", false), |
| 1641 | ("met by( (5..10], [1..5] )", false), |
| 1642 | ("met by( [6..10], [1..5] )", false), |
| 1643 | ("overlaps before( [1..5], [3..8] )", true), |
| 1644 | ("overlaps before( [1..5], [6..8] )", false), |
| 1645 | ("overlaps before( [1..5], [5..8] )", true), |
| 1646 | ("overlaps before( [1..5], (5..8] )", false), |
| 1647 | ("overlaps before( [1..5), [5..8] )", false), |
| 1648 | ("overlaps before( [1..5), (1..5] )", true), |
| 1649 | ("overlaps before( [1..5], (1..5] )", true), |
| 1650 | ("overlaps before( [1..5), [1..5] )", false), |
| 1651 | ("overlaps before( [1..5], [1..5] )", false), |
| 1652 | ("overlaps after( [3..8], [1..5])", true), |
| 1653 | ("overlaps after( [6..8], [1..5])", false), |
| 1654 | ("overlaps after( [5..8], [1..5])", true), |
| 1655 | ("overlaps after( (5..8], [1..5])", false), |
| 1656 | ("overlaps after( [5..8], [1..5))", false), |
| 1657 | ("overlaps after( (1..5], [1..5) )", true), |
| 1658 | ("overlaps after( (1..5], [1..5] )", true), |
| 1659 | ("overlaps after( [1..5], [1..5) )", false), |
| 1660 | ("overlaps after( [1..5], [1..5] )", false), |
| 1661 | ("finishes( 10, [1..10] )", true), |
| 1662 | ("finishes( 10, [1..10) )", false), |
| 1663 | ("finishes( [5..10], [1..10] )", true), |
| 1664 | ("finishes( [5..10), [1..10] )", false), |
| 1665 | ("finishes( [5..10), [1..10) )", true), |
| 1666 | ("finishes( [1..10], [1..10] )", true), |
| 1667 | ("finishes( (1..10], [1..10] )", true), |
| 1668 | ("finished by( [1..10], 10 )", true), |
| 1669 | ("finished by( [1..10), 10 )", false), |
| 1670 | ("finished by( [1..10], [5..10] )", true), |
| 1671 | ("finished by( [1..10], [5..10) )", false), |
| 1672 | ("finished by( [1..10), [5..10) )", true), |
| 1673 | ("finished by( [1..10], (1..10] )", true), |
| 1674 | ("finished by( [1..10], [1..10] )", true), |
| 1675 | ("includes( [1..10], 5 )", true), |
| 1676 | ("includes( [1..10], 12 )", false), |
| 1677 | ("includes( [1..10], 1 )", true), |
| 1678 | ("includes( [1..10], 10 )", true), |
| 1679 | ("includes( (1..10], 1 )", false), |
| 1680 | ("includes( [1..10), 10 )", false), |
| 1681 | ("includes( [1..10], [4..6] )", true), |
| 1682 | ("includes( [1..10], [1..5] )", true), |
| 1683 | ("includes( (1..10], (1..5] )", true), |
| 1684 | ("includes( [1..10], (1..10) )", true), |
| 1685 | ("includes( [1..10), [5..10) )", true), |
| 1686 | ("includes( [1..10], [1..10) )", true), |
| 1687 | ("includes( [1..10], (1..10] )", true), |
| 1688 | ("includes( [1..10], [1..10] )", true), |
| 1689 | ("during( 5, [1..10] )", true), |
| 1690 | ("during( 12, [1..10] )", false), |
| 1691 | ("during( 1, [1..10] )", true), |
| 1692 | ("during( 10, [1..10] )", true), |
| 1693 | ("during( 1, (1..10] )", false), |
| 1694 | ("during( 10, [1..10) )", false), |
| 1695 | ("during( [4..6], [1..10] )", true), |
| 1696 | ("during( [1..5], [1..10] )", true), |
| 1697 | ("during( (1..5], (1..10] )", true), |
| 1698 | ("during( (1..10), [1..10] )", true), |
| 1699 | ("during( [5..10), [1..10) )", true), |
| 1700 | ("during( [1..10), [1..10] )", true), |
| 1701 | ("during( (1..10], [1..10] )", true), |
| 1702 | ("during( [1..10], [1..10] )", true), |
| 1703 | ("starts( 1, [1..10] )", true), |
| 1704 | ("starts( 1, (1..10] )", false), |
| 1705 | ("starts( 2, [1..10] )", false), |
| 1706 | ("starts( [1..5], [1..10] )", true), |
| 1707 | ("starts( (1..5], (1..10] )", true), |
| 1708 | ("starts( (1..5], [1..10] )", false), |
| 1709 | ("starts( [1..5], (1..10] )", false), |
| 1710 | ("starts( [1..10], [1..10] )", true), |
| 1711 | ("starts( [1..10), [1..10] )", true), |
| 1712 | ("starts( (1..10), (1..10) )", true), |
| 1713 | ("started by( [1..10], 1 )", true), |
| 1714 | ("started by( (1..10], 1 )", false), |
| 1715 | ("started by( [1..10], 2 )", false), |
| 1716 | ("started by( [1..10], [1..5] )", true), |
| 1717 | ("started by( (1..10], (1..5] )", true), |
| 1718 | ("started by( [1..10], (1..5] )", false), |
| 1719 | ("started by( (1..10], [1..5] )", false), |
| 1720 | ("started by( [1..10], [1..10] )", true), |
| 1721 | ("started by( [1..10], [1..10) )", true), |
| 1722 | ("started by( (1..10), (1..10) )", true), |
| 1723 | ("coincides( 5, 5 )", true), |
| 1724 | ("coincides( 3, 4 )", false), |
| 1725 | ("coincides( [1..5], [1..5] )", true), |
| 1726 | ("coincides( (1..5), [1..5] )", false), |
| 1727 | ("coincides( [1..5], [2..6] )", false), |
| 1728 | ("overlaps( [1..5], [3..8] )", true), |
| 1729 | ("overlaps( [3..8], [1..5] )", true), |
| 1730 | ("overlaps( [1..8], [3..5] )", true), |
| 1731 | ("overlaps( [3..5], [1..8] )", true), |
| 1732 | ("overlaps( [1..5], [6..8] )", false), |
| 1733 | ("overlaps( [6..8], [1..5] )", false), |
| 1734 | ("overlaps( [1..5], [5..8] )", true), |
| 1735 | ("overlaps( [1..5], (5..8] )", false), |
| 1736 | ("overlaps( [1..5), [5..8] )", false), |
| 1737 | ("overlaps( [1..5), (5..8] )", false), |
| 1738 | ("overlaps( [5..8], [1..5] )", true), |
| 1739 | ("overlaps( (5..8], [1..5] )", false), |
| 1740 | ("overlaps( [5..8], [1..5) )", false), |
| 1741 | ("overlaps( (5..8], [1..5) )", false), |
| 1742 | ]; |
| 1743 | for (src, want) in cases { |
| 1744 | assert_eq!(ev(src), b(*want), "`{src}`"); |
| 1745 | } |
| 1746 | } |
| 1747 | |
| 1748 | #[test] |
| 1749 | fn in_unary_test_lists_tck_0072() { |
| 1750 | // Comma-list-of-tests `in`-RHS forms (Form 1): a bracketed/parenthesised list |
| 1751 | // of positive unary tests is an OR of its elements. Endpoints, nested ranges, |
| 1752 | // comparison elements (`< 5`, `>= 10`), and the one-element paren tests |
| 1753 | // `(= e)` / `(!= e)` all flow through the dedicated test-mode `InRhs` |
| 1754 | // productions; the cases are lifted straight from 0072-feel-in. |
| 1755 | let cases: &[(&str, bool)] = &[ |
| 1756 | // bracket list of endpoints |
| 1757 | ("1 in [2,3,1]", true), |
| 1758 | ("1 in [2,3,4]", false), |
| 1759 | (r#""a" in ["b","c","a"]"#, true), |
| 1760 | (r#""a" in ["b","c","d"]"#, false), |
| 1761 | ("true in [true, false]", true), |
| 1762 | ("true in [false, false]", false), |
| 1763 | // bracket list of ranges (nested intervals reclassified to interval tests) |
| 1764 | ("1 in [[2..4], [1..3]]", true), |
| 1765 | ("1 in [[2..4], [5..7]]", false), |
| 1766 | (r#""b" in [["f".."h"], ["a".."c"]]"#, true), |
| 1767 | // paren list, incl. comparison elements |
| 1768 | ("10 in (1, < 5, >=10)", true), |
| 1769 | ("3 in (1, < 5, >=10)", true), |
| 1770 | ("7 in (1, < 5, >=10)", false), |
| 1771 | ("5 in (1, 5, 9)", true), |
| 1772 | ("10 in (1, 5, 9)", false), |
| 1773 | ("true in (false, true)", true), |
| 1774 | ("true in (false, false)", false), |
| 1775 | (r#""d" in ("c", < "c", >="d")"#, true), |
| 1776 | (r#""d" in ("c", >="e")"#, false), |
| 1777 | // one-element paren tests `(= e)` / `(!= e)` — Compare elements, no Form-4 desugar |
| 1778 | ("10 in (=10)", true), |
| 1779 | ("10 in (!=10)", false), |
| 1780 | ("5 in (!=10)", true), |
| 1781 | ("true in (=true)", true), |
| 1782 | ("true in (!=true)", false), |
| 1783 | (r#""a" in (="a")"#, true), |
| 1784 | (r#""a" in (!="a")"#, false), |
| 1785 | // list / context values as endpoints (same-type equality; a *cross*-type |
| 1786 | // endpoint like `[1,2,3] in [1,2,3]` is the ADR-14 error-null deviation, |
| 1787 | // tested elsewhere, not here) |
| 1788 | ("[1,2,3] in [[1,2,3,4], [1,2,3]]", true), |
| 1789 | ("[1,2,3] in ([1,2,3])", true), |
| 1790 | ("[1,2,3] in (=[1,2,3])", true), |
| 1791 | ("[1,2,3] in (!=[1,2,3])", false), |
| 1792 | (r#"{a: "foo"} in ({a: "bar"}, {a: "foo"})"#, true), |
| 1793 | (r#"{a: "foo"} in (={a: "foo"})"#, true), |
| 1794 | // single interval / comparison / bare endpoint still parse as before |
| 1795 | ("5 in [1..10]", true), |
| 1796 | ("5 in (5..10]", false), |
| 1797 | ("5 in [5..10]", true), |
| 1798 | ("5 in (1..10)", true), |
| 1799 | ("1 in (1..10)", false), |
| 1800 | ("3 in < 5", true), |
| 1801 | ("1 in 1", true), |
| 1802 | ("1 in 2", false), |
| 1803 | ]; |
| 1804 | for (src, want) in cases { |
| 1805 | assert_eq!(ev(src), b(*want), "`{src}`"); |
| 1806 | } |
| 1807 | } |
| 1808 | |
| 1809 | #[test] |
| 1810 | fn arithmetic_and_precedence() { |
| 1811 | assert_eq!(ev("1 + 1"), num(2.0)); |
| 1812 | assert_eq!(ev("1 + 2 * 3"), num(7.0)); // * binds tighter than + |
| 1813 | assert_eq!(ev("(1 + 2) * 3"), num(9.0)); |
| 1814 | assert_eq!(ev("10 - 4 - 3"), num(3.0)); // - is left-associative |
| 1815 | assert_eq!(ev("12 / 4"), num(3.0)); |
| 1816 | assert_eq!(ev("--10"), num(10.0)); // unary minus stacks |
| 1817 | } |
| 1818 | |
| 1819 | #[test] |
| 1820 | fn exponent_is_left_associative_and_below_unary_minus() { |
| 1821 | // Verified against DMN-TCK 0075-feel-exponent. |
| 1822 | assert_eq!(ev("3 ** 4 ** 5"), num(3486784401.0)); // (3**4)**5 |
| 1823 | assert_eq!(ev("-3 ** 2"), num(9.0)); // (-3)**2 |
| 1824 | assert_eq!(ev("2 * 3 ** 2"), num(18.0)); // ** tighter than * |
| 1825 | } |
| 1826 | |
| 1827 | #[test] |
| 1828 | fn type_errors_and_div_zero_are_null() { |
| 1829 | assert_eq!(ev("1 + true"), Value::Null); |
| 1830 | assert_eq!(ev(r#"1 + "x""#), Value::Null); |
| 1831 | assert_eq!(ev("1 / 0"), Value::Null); |
| 1832 | assert_eq!(ev("-true"), Value::Null); |
| 1833 | } |
| 1834 | |
| 1835 | #[test] |
| 1836 | fn comparison() { |
| 1837 | assert_eq!(ev("1 < 2"), b(true)); |
| 1838 | assert_eq!(ev("2 <= 2"), b(true)); |
| 1839 | assert_eq!(ev("3 > 5"), b(false)); |
| 1840 | assert_eq!(ev(r#""apple" < "banana""#), b(true)); // lexicographic |
| 1841 | assert_eq!(ev("1 < null"), Value::Null); // ordering with null -> null |
| 1842 | assert_eq!(ev("1 < true"), Value::Null); // incomparable types -> null |
| 1843 | } |
| 1844 | |
| 1845 | #[test] |
| 1846 | fn equality_three_valued() { |
| 1847 | // Values taken from DMN-TCK 0068-feel-equality. |
| 1848 | assert_eq!(ev("null = null"), b(true)); |
| 1849 | assert_eq!(ev("null != null"), b(false)); |
| 1850 | assert_eq!(ev("true = null"), b(false)); |
| 1851 | assert_eq!(ev("true = false"), b(false)); |
| 1852 | assert_eq!(ev("123 = 123"), b(true)); |
| 1853 | assert_eq!(ev("-1 = 1"), b(false)); |
| 1854 | assert_eq!(ev(r#""foo" = "foo""#), b(true)); |
| 1855 | assert_eq!(ev(r#""foo" != "Foo""#), b(true)); |
| 1856 | // Different non-null types compare to null, not false. |
| 1857 | assert_eq!(ev("false = 0"), Value::Null); |
| 1858 | assert_eq!(ev(r#"100 = "100""#), Value::Null); |
| 1859 | // Lists compare structurally. |
| 1860 | assert_eq!(ev("[1,2,3] = [1,2,3]"), b(true)); |
| 1861 | assert_eq!(ev("[1,1,1] = [1,1,1,1]"), b(false)); |
| 1862 | assert_eq!(ev("[1,2,3] = [3,2,1]"), b(false)); |
| 1863 | assert_eq!(ev("[] = []"), b(true)); |
| 1864 | assert_eq!(ev("[] = null"), b(false)); |
| 1865 | } |
| 1866 | |
| 1867 | #[test] |
| 1868 | fn between() { |
| 1869 | assert_eq!(ev("5 between 1 and 10"), b(true)); |
| 1870 | assert_eq!(ev("1 between 1 and 10"), b(true)); // inclusive |
| 1871 | assert_eq!(ev("0 between 1 and 10"), b(false)); |
| 1872 | assert_eq!(ev(r#""c" between "b" and "d""#), b(true)); |
| 1873 | } |
| 1874 | |
| 1875 | #[test] |
| 1876 | fn logic_three_valued() { |
| 1877 | // Values taken from DMN-TCK 0064/0065/0066. |
| 1878 | assert_eq!(ev("true and true"), b(true)); |
| 1879 | assert_eq!(ev("true and false"), b(false)); |
| 1880 | assert_eq!(ev("true and null"), Value::Null); |
| 1881 | assert_eq!(ev("false and null"), b(false)); // false dominates |
| 1882 | assert_eq!(ev("false and 123"), b(false)); |
| 1883 | assert_eq!(ev("true and 123"), Value::Null); // non-boolean -> null |
| 1884 | assert_eq!(ev("true or false"), b(true)); |
| 1885 | assert_eq!(ev("true or null"), b(true)); // true dominates |
| 1886 | assert_eq!(ev("false or null"), Value::Null); |
| 1887 | assert_eq!(ev("123 or true"), b(true)); |
| 1888 | assert_eq!(ev("not(true)"), b(false)); |
| 1889 | assert_eq!(ev("not(false)"), b(true)); |
| 1890 | assert_eq!(ev("not(null)"), Value::Null); |
| 1891 | assert_eq!(ev("not(0)"), Value::Null); |
| 1892 | } |
| 1893 | |
| 1894 | #[test] |
| 1895 | fn membership_and_interval_inclusivity() { |
| 1896 | assert_eq!(ev("5 in [1..10]"), b(true)); |
| 1897 | assert_eq!(ev("1 in [1..10]"), b(true)); // closed lower includes |
| 1898 | assert_eq!(ev("1 in (1..10]"), b(false)); // open lower excludes |
| 1899 | assert_eq!(ev("10 in [1..10)"), b(false)); // open upper excludes |
| 1900 | assert_eq!(ev("11 in [1..10]"), b(false)); // out of range |
| 1901 | // A null bound makes the test null (Kleene), per DMN-TCK 0072. |
| 1902 | assert_eq!(ev("5 in (null..10]"), Value::Null); |
| 1903 | } |
| 1904 | |
| 1905 | #[test] |
| 1906 | fn membership_unary_comparison_tests() { |
| 1907 | // `in <op> endpoint` — a positive unary test (DMN rule 49). |
| 1908 | assert_eq!(ev("1 in <= 10"), b(true)); |
| 1909 | assert_eq!(ev("11 in <= 10"), b(false)); |
| 1910 | assert_eq!(ev("11 in >= 10"), b(true)); |
| 1911 | assert_eq!(ev("1 in < 10"), b(true)); |
| 1912 | assert_eq!(ev("11 in > 10"), b(true)); |
| 1913 | assert_eq!(ev("10 in = 10"), b(true)); |
| 1914 | assert_eq!(ev("10 in != 10"), b(false)); |
| 1915 | // The endpoint is an arbitrary expression (a list value, a string). |
| 1916 | assert_eq!(ev("[1, 2, 3] in = [1, 2, 3]"), b(true)); |
| 1917 | assert_eq!(ev("[1, 2, 3] in != [1, 2, 3, 4]"), b(true)); |
| 1918 | assert_eq!(ev(r#""b" in > "a""#), b(true)); |
| 1919 | } |
| 1920 | |
| 1921 | #[test] |
| 1922 | fn membership_not_test_negation() { |
| 1923 | // `x in not(...)` is *test* negation (DMN rule 49), not the boolean built-in: |
| 1924 | // `x in not(t)` ≡ `not(x satisfies t)`, three-valued. |
| 1925 | // List negation: `not(1,2,3)` ≡ `not(x = 1 or x = 2 or x = 3)`. |
| 1926 | assert_eq!(ev("5 in not(1, 2, 3)"), b(true)); |
| 1927 | assert_eq!(ev("2 in not(1, 2, 3)"), b(false)); |
| 1928 | // Single bare endpoint: `not(5)` negates the `= 5` test. |
| 1929 | assert_eq!(ev("4 in not(5)"), b(true)); |
| 1930 | assert_eq!(ev("5 in not(5)"), b(false)); |
| 1931 | // Comparison test negation: `not(< 5)` ≡ `not(x < 5)`. |
| 1932 | assert_eq!(ev("7 in not(< 5)"), b(true)); |
| 1933 | assert_eq!(ev("3 in not(< 5)"), b(false)); |
| 1934 | // Interval test negation: `not([1..10])` ≡ `not(1 <= x <= 10)`. |
| 1935 | assert_eq!(ev("11 in not([1..10])"), b(true)); |
| 1936 | assert_eq!(ev("5 in not([1..10])"), b(false)); |
| 1937 | // Mixed inner tests OR-fold before negation. |
| 1938 | assert_eq!(ev("8 in not(< 5, > 10)"), b(true)); |
| 1939 | assert_eq!(ev("3 in not(< 5, > 10)"), b(false)); |
| 1940 | // Kleene: negating an unknown (a null bound) stays null, never a definite true. |
| 1941 | assert_eq!(ev("5 in not((null..10])"), Value::Null); |
| 1942 | } |
| 1943 | |
| 1944 | #[test] |
| 1945 | fn if_then_else() { |
| 1946 | assert_eq!(ev("if true then 1 else 2"), num(1.0)); |
| 1947 | assert_eq!(ev("if false then 1 else 2"), num(2.0)); |
| 1948 | assert_eq!(ev("if 1 < 2 then 10 else 20"), num(10.0)); |
| 1949 | // A null condition takes the else branch (null is a value -> "not true", |
| 1950 | // per DMN-TCK 0032 / ADR-13). |
| 1951 | assert_eq!(ev("if null then 1 else 2"), num(2.0)); |
| 1952 | // A wrong-TYPE condition is a type error and stays null (ADR-9/ADR-13). |
| 1953 | assert_eq!(ev("if 5 then 1 else 2"), Value::Null); |
| 1954 | assert_eq!(ev(r#"if "x" then 1 else 2"#), Value::Null); |
| 1955 | } |
| 1956 | |
| 1957 | #[test] |
| 1958 | fn error_provenance() { |
| 1959 | // Raw view: do NOT collapse error provenance (unlike `ev`). |
| 1960 | let raw = |src: &str| { |
| 1961 | evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 1962 | }; |
| 1963 | |
| 1964 | // Type / domain errors produce an error-null... |
| 1965 | assert_eq!(raw("1 + true"), Value::Error); |
| 1966 | assert_eq!(raw("1 / 0"), Value::Error); |
| 1967 | assert_eq!(raw("-true"), Value::Error); |
| 1968 | assert_eq!(raw("1 < true"), Value::Error); // incomparable types |
| 1969 | assert_eq!(raw(r#"100 = "100""#), Value::Error); // type mismatch in `=` |
| 1970 | assert_eq!(raw("if 5 then 1 else 2"), Value::Error); // wrong-type condition |
| 1971 | assert_eq!(raw("5 .a"), Value::Error); // path on a non-context |
| 1972 | assert_eq!(raw("not(0)"), Value::Error); // `not` of a non-boolean |
| 1973 | |
| 1974 | // ...while a genuine value-null stays a value-null. |
| 1975 | assert_eq!(raw("null"), Value::Null); |
| 1976 | assert_eq!(raw("missing"), Value::Null); // unbound variable |
| 1977 | assert_eq!(raw("1 < null"), Value::Null); // value-null operand: unknown |
| 1978 | assert_eq!(raw("if null then 1 else 2"), num(2.0)); // value-null -> else |
| 1979 | assert_eq!(raw("not(null)"), Value::Null); // not unknown = unknown |
| 1980 | assert_eq!(raw("true and null"), Value::Null); // value-null: untainted |
| 1981 | |
| 1982 | // error-null and value-null behave identically under FEEL equality. |
| 1983 | assert_eq!(raw("null = (1 + true)"), b(true)); |
| 1984 | |
| 1985 | // Design 1: a dominator swallows the error (truth value wins, TCK-safe)... |
| 1986 | assert_eq!(raw("false and (1 + true)"), b(false)); |
| 1987 | assert_eq!(raw("true or (1 + true)"), b(true)); |
| 1988 | // ...but provenance is sticky where the result is the unknown null. |
| 1989 | assert_eq!(raw("true and (1 + true)"), Value::Error); |
| 1990 | assert_eq!(raw("false or (1 + true)"), Value::Error); |
| 1991 | } |
| 1992 | |
| 1993 | #[test] |
| 1994 | fn for_loops() { |
| 1995 | assert_eq!( |
| 1996 | ev("for i in [1,2,3] return i + 1"), |
| 1997 | list(vec![num(2.0), num(3.0), num(4.0)]) |
| 1998 | ); |
| 1999 | assert_eq!(ev("for i in [] return i"), list(vec![])); |
| 2000 | assert_eq!( |
| 2001 | ev("for i in 2..4 return i"), |
| 2002 | list(vec![num(2.0), num(3.0), num(4.0)]) |
| 2003 | ); |
| 2004 | assert_eq!( |
| 2005 | ev("for i in 4..2 return i"), // descending |
| 2006 | list(vec![num(4.0), num(3.0), num(2.0)]) |
| 2007 | ); |
| 2008 | assert_eq!( |
| 2009 | ev("for i in -1..1 return i"), |
| 2010 | list(vec![num(-1.0), num(0.0), num(1.0)]) |
| 2011 | ); |
| 2012 | // body may itself be a control-flow expression |
| 2013 | assert_eq!( |
| 2014 | ev("for i in [1,2,3] return if i = 2 then 0 else i"), |
| 2015 | list(vec![num(1.0), num(0.0), num(3.0)]) |
| 2016 | ); |
| 2017 | // nested for |
| 2018 | assert_eq!( |
| 2019 | ev("for x in [[1,2],[3,4]] return for y in x return y"), |
| 2020 | list(vec![ |
| 2021 | list(vec![num(1.0), num(2.0)]), |
| 2022 | list(vec![num(3.0), num(4.0)]), |
| 2023 | ]) |
| 2024 | ); |
| 2025 | } |
| 2026 | |
| 2027 | #[test] |
| 2028 | fn for_multiple_iteration_contexts() { |
| 2029 | // Cartesian product, rightmost context varies fastest (FEEL rule 44). |
| 2030 | assert_eq!( |
| 2031 | ev("for x in [1,2,3], y in [10,20] return x + y"), |
| 2032 | list(vec![ |
| 2033 | num(11.0), |
| 2034 | num(21.0), |
| 2035 | num(12.0), |
| 2036 | num(22.0), |
| 2037 | num(13.0), |
| 2038 | num(23.0), |
| 2039 | ]) |
| 2040 | ); |
| 2041 | // Matches DMN-TCK 0033-for-loops: `for h in heights, w in widths`. |
| 2042 | assert_eq!( |
| 2043 | ev("for h in [10,20,30], w in [2,3] return h * w"), |
| 2044 | list(vec![ |
| 2045 | num(20.0), |
| 2046 | num(30.0), |
| 2047 | num(40.0), |
| 2048 | num(60.0), |
| 2049 | num(60.0), |
| 2050 | num(90.0), |
| 2051 | ]) |
| 2052 | ); |
| 2053 | // A later source may reference an earlier variable (left-to-right scope). |
| 2054 | assert_eq!( |
| 2055 | ev("for i in [1,2], j in i..3 return j"), |
| 2056 | list(vec![num(1.0), num(2.0), num(3.0), num(2.0), num(3.0)]) |
| 2057 | ); |
| 2058 | // An empty source anywhere yields an empty product. |
| 2059 | assert_eq!(ev("for i in [1,2], j in [] return i"), list(vec![])); |
| 2060 | assert_eq!(ev("for i in [], j in [1] return i"), list(vec![])); |
| 2061 | // Three contexts compose. |
| 2062 | assert_eq!( |
| 2063 | ev("for a in [1], b in [2,3], c in [4,5] return a + b + c"), |
| 2064 | list(vec![num(7.0), num(8.0), num(8.0), num(9.0)]) |
| 2065 | ); |
| 2066 | } |
| 2067 | |
| 2068 | #[test] |
| 2069 | fn quantifiers() { |
| 2070 | assert_eq!(ev("some i in [1,2,3] satisfies i > 2"), b(true)); |
| 2071 | assert_eq!(ev("some i in [1,2,3] satisfies i > 5"), b(false)); |
| 2072 | assert_eq!(ev("every i in [2,4,6] satisfies i > 1"), b(true)); |
| 2073 | assert_eq!(ev("every i in [1,2,3] satisfies i > 2"), b(false)); |
| 2074 | // empty list: some -> false, every -> true |
| 2075 | assert_eq!(ev("some i in [] satisfies i > 0"), b(false)); |
| 2076 | assert_eq!(ev("every i in [] satisfies i > 0"), b(true)); |
| 2077 | // range source |
| 2078 | assert_eq!(ev("every i in 1..5 satisfies i > 0"), b(true)); |
| 2079 | } |
| 2080 | |
| 2081 | #[test] |
| 2082 | fn quantifiers_multiple_iteration_contexts() { |
| 2083 | // `some` short-circuits to true on the first satisfying tuple (1+4 = 5). |
| 2084 | assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 5"), b(true)); |
| 2085 | assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 99"), b(false)); |
| 2086 | // `every` is true only when all product tuples satisfy the predicate. |
| 2087 | assert_eq!(ev("every x in [1,2], y in [3,4] satisfies x < y"), b(true)); |
| 2088 | assert_eq!(ev("every x in [1,2], y in [1,2] satisfies x <= y"), b(false)); |
| 2089 | // An empty source: the product is empty (some -> false, every -> true). |
| 2090 | assert_eq!(ev("some x in [1,2], y in [] satisfies x = y"), b(false)); |
| 2091 | assert_eq!(ev("every x in [1,2], y in [] satisfies x = y"), b(true)); |
| 2092 | } |
| 2093 | |
| 2094 | #[test] |
| 2095 | fn variable_resolution() { |
| 2096 | let mut ctx = Context::empty(); |
| 2097 | ctx.insert("preis", num(10.0)); |
| 2098 | ctx.insert("über", num(3.0)); // Unicode identifier (umlaut) |
| 2099 | let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}")); |
| 2100 | |
| 2101 | assert_eq!(ev("preis"), num(10.0)); |
| 2102 | assert_eq!(ev("preis + über"), num(13.0)); |
| 2103 | assert_eq!(ev("über * 2"), num(6.0)); |
| 2104 | // Unbound names resolve to null (FEEL-friendly), not an error. |
| 2105 | assert_eq!(ev("unbekannt"), Value::Null); |
| 2106 | // Loop variable still shadows correctly alongside context vars. |
| 2107 | assert_eq!( |
| 2108 | ev("for preis in [1,2] return preis + über"), |
| 2109 | list(vec![num(4.0), num(5.0)]) |
| 2110 | ); |
| 2111 | } |
| 2112 | |
| 2113 | #[test] |
| 2114 | fn context_literals_and_path_access() { |
| 2115 | use std::collections::BTreeMap; |
| 2116 | let ctx_val = |pairs: &[(&str, Value)]| { |
| 2117 | Value::Context( |
| 2118 | pairs |
| 2119 | .iter() |
| 2120 | .map(|(k, v)| (k.to_string(), v.clone())) |
| 2121 | .collect::<BTreeMap<_, _>>(), |
| 2122 | ) |
| 2123 | }; |
| 2124 | |
| 2125 | // Context literal builds a map; member access reads it back. |
| 2126 | assert_eq!( |
| 2127 | ev("{a: 1, b: 2}"), |
| 2128 | ctx_val(&[("a", num(1.0)), ("b", num(2.0))]) |
| 2129 | ); |
| 2130 | assert_eq!(ev("{a: 1, b: 2}.a"), num(1.0)); |
| 2131 | assert_eq!(ev("{}"), ctx_val(&[])); |
| 2132 | // String keys are allowed. |
| 2133 | assert_eq!(ev(r#"{"x": 10}.x"#), num(10.0)); |
| 2134 | // Progressive binding: a later entry sees an earlier one. |
| 2135 | assert_eq!(ev("{a: 1, b: a + 1}.b"), num(2.0)); |
| 2136 | // Missing member or path on a non-context -> null. |
| 2137 | assert_eq!(ev("{a: 1}.z"), Value::Null); |
| 2138 | assert_eq!(ev("5 .a"), Value::Null); |
| 2139 | // Nested contexts and chained paths. |
| 2140 | assert_eq!(ev("{a: {b: {c: 7}}}.a.b.c"), num(7.0)); |
| 2141 | } |
| 2142 | |
| 2143 | /// A context-`Value` builder for the filter/projection tests below. |
| 2144 | fn ctx_val(pairs: &[(&str, Value)]) -> Value { |
| 2145 | use std::collections::BTreeMap; |
| 2146 | Value::Context( |
| 2147 | pairs |
| 2148 | .iter() |
| 2149 | .map(|(k, v)| (k.to_string(), v.clone())) |
| 2150 | .collect::<BTreeMap<_, _>>(), |
| 2151 | ) |
| 2152 | } |
| 2153 | |
| 2154 | #[test] |
| 2155 | fn list_index_access() { |
| 2156 | // 1-based positional index; negative counts from the end (DMN §10.3.2.5). |
| 2157 | assert_eq!(ev("[1, 2, 3][1]"), num(1.0)); |
| 2158 | assert_eq!(ev("[1, 2, 3][3]"), num(3.0)); |
| 2159 | assert_eq!(ev("[1, 2, 3][-1]"), num(3.0)); |
| 2160 | assert_eq!(ev("[1, 2, 3][-3]"), num(1.0)); |
| 2161 | // Out of range (either direction), zero, and non-integer -> null. |
| 2162 | assert_eq!(ev("[1, 2, 3][4]"), Value::Null); |
| 2163 | assert_eq!(ev("[1, 2, 3][-4]"), Value::Null); |
| 2164 | assert_eq!(ev("[1, 2, 3][0]"), Value::Null); |
| 2165 | assert_eq!(ev("[1, 2, 3][1.5]"), Value::Null); |
| 2166 | // A non-list source is a singleton; a null source stays null. |
| 2167 | assert_eq!(ev("5[1]"), num(5.0)); |
| 2168 | assert_eq!(ev("5[2]"), Value::Null); |
| 2169 | assert_eq!(ev("null[1]"), Value::Null); |
| 2170 | // The index is an arbitrary expression evaluated in the outer scope. |
| 2171 | assert_eq!(ev("[10, 20, 30][1 + 1]"), num(20.0)); |
| 2172 | } |
| 2173 | |
| 2174 | #[test] |
| 2175 | fn list_boolean_filter() { |
| 2176 | // The predicate keeps elements where it is true; `item` is the element. |
| 2177 | assert_eq!(ev("[1, 2, 3, 4][item > 2]"), list(vec![num(3.0), num(4.0)])); |
| 2178 | assert_eq!(ev("[1, 2, 3][item > 9]"), list(vec![])); |
| 2179 | // A constant boolean filter selects all / none. |
| 2180 | assert_eq!( |
| 2181 | ev("[1, 2, 3][true]"), |
| 2182 | list(vec![num(1.0), num(2.0), num(3.0)]) |
| 2183 | ); |
| 2184 | assert_eq!(ev("[1, 2, 3][false]"), list(vec![])); |
| 2185 | // A non-list source filters as a singleton. |
| 2186 | assert_eq!(ev("5[item > 3]"), list(vec![num(5.0)])); |
| 2187 | assert_eq!(ev("5[item < 3]"), list(vec![])); |
| 2188 | } |
| 2189 | |
| 2190 | #[test] |
| 2191 | fn list_filter_over_contexts() { |
| 2192 | // A context element's entries are referenceable without an `item.` prefix... |
| 2193 | assert_eq!( |
| 2194 | ev("[{x: 1, y: 2}, {x: 2, y: 3}][x = 1]"), |
| 2195 | list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])]) |
| 2196 | ); |
| 2197 | // ...or via the explicit `item` binding. |
| 2198 | assert_eq!( |
| 2199 | ev("[{x: 1, y: 2}, {x: 2, y: 3}][item.x = 2]"), |
| 2200 | list(vec![ctx_val(&[("x", num(2.0)), ("y", num(3.0))])]) |
| 2201 | ); |
| 2202 | // A null key compares to null (not true), so that row is dropped. |
| 2203 | assert_eq!( |
| 2204 | ev("[{x: 1, y: 2}, {x: null, y: 3}][x < 2]"), |
| 2205 | list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])]) |
| 2206 | ); |
| 2207 | // When the element itself carries an `item` key, that key wins as `item`. |
| 2208 | assert_eq!( |
| 2209 | ev("[{item: 7, x: 1}][item = 7]"), |
| 2210 | list(vec![ctx_val(&[("item", num(7.0)), ("x", num(1.0))])]) |
| 2211 | ); |
| 2212 | } |
| 2213 | |
| 2214 | #[test] |
| 2215 | fn list_projection_over_contexts() { |
| 2216 | // `.field` over a list of contexts maps the access (DMN §10.3.2.5). |
| 2217 | assert_eq!( |
| 2218 | ev("[{x: 1, y: 2}, {x: 2, y: 3}].y"), |
| 2219 | list(vec![num(2.0), num(3.0)]) |
| 2220 | ); |
| 2221 | // A missing key yields a null in that slot. |
| 2222 | assert_eq!( |
| 2223 | ev("[{x: 1, y: 2}, {x: 2}].y"), |
| 2224 | list(vec![num(2.0), Value::Null]) |
| 2225 | ); |
| 2226 | // Projection then index composes left-to-right: `(xs.x)[2]`. |
| 2227 | assert_eq!(ev("[{x: 1}, {x: 2}, {x: 3}].x[2]"), num(2.0)); |
| 2228 | } |
| 2229 | |
| 2230 | #[test] |
| 2231 | fn is_function_value_identity() { |
| 2232 | // Same type & value -> true; different value -> false. |
| 2233 | assert_eq!(ev("is(1, 1)"), b(true)); |
| 2234 | assert_eq!(ev("is(1, 2)"), b(false)); |
| 2235 | assert_eq!(ev(r#"is("a", "a")"#), b(true)); |
| 2236 | // Different type -> false, never null (unlike `=`). |
| 2237 | assert_eq!(ev(r#"is(1, "1")"#), b(false)); |
| 2238 | assert_eq!(ev("is(1, null)"), b(false)); |
| 2239 | // Durations: same normalised value & type -> true; different type -> false. |
| 2240 | assert_eq!(ev(r#"is(@"P1D", @"PT24H")"#), b(true)); |
| 2241 | assert_eq!(ev(r#"is(@"P0Y", @"P0D")"#), b(false)); |
| 2242 | // `Z` and `+00:00` are the same; a zoneless time is not the same as a zoned one. |
| 2243 | assert_eq!(ev(r#"is(@"23:00:50Z", @"23:00:50+00:00")"#), b(true)); |
| 2244 | assert_eq!(ev(r#"is(@"23:00:50", @"23:00:50Z")"#), b(false)); |
| 2245 | // A single named operand makes the other a `null` (ADR-23 under-supply). |
| 2246 | assert_eq!(ev("is(value1: 1)"), b(false)); |
| 2247 | } |
| 2248 | |
| 2249 | #[test] |
| 2250 | fn string_escape_decoding() { |
| 2251 | // `\uXXXX` (incl. UTF-16 surrogate pairs), `\UXXXXXX`, and C-style escapes. |
| 2252 | assert_eq!(ev(r#"string length("\u0009")"#), num(1.0)); // tab via \u escape |
| 2253 | assert_eq!(ev(r#"string length("\U01F40E")"#), num(1.0)); // 🐎 (astral plane) |
| 2254 | assert_eq!(ev(r#"string length("\uD83D\uDCA9")"#), num(1.0)); // UTF-16 surrogate pair |
| 2255 | assert_eq!(ev(r#""a\nb""#), Value::String("a\nb".into())); |
| 2256 | // An escaped backslash is one backslash: `\\u0009` is 6 literal characters. |
| 2257 | assert_eq!(ev(r#"string length("\\u0009")"#), num(6.0)); |
| 2258 | // An unrecognised escape (e.g. a regex metacharacter) is preserved verbatim. |
| 2259 | assert_eq!(ev(r#""\d""#), Value::String("\\d".into())); |
| 2260 | } |
| 2261 | |
| 2262 | #[test] |
| 2263 | fn path_access_on_context_variable() { |
| 2264 | let mut inner = std::collections::BTreeMap::new(); |
| 2265 | inner.insert("age".to_string(), num(42.0)); |
| 2266 | let mut ctx = Context::empty(); |
| 2267 | ctx.insert("person", Value::Context(inner)); |
| 2268 | let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}")); |
| 2269 | |
| 2270 | assert_eq!(ev("person.age"), num(42.0)); |
| 2271 | assert_eq!(ev("person.age > 18"), b(true)); |
| 2272 | assert_eq!(ev("person.missing"), Value::Null); |
| 2273 | } |
| 2274 | |
| 2275 | #[test] |
| 2276 | fn context_equality_is_structural() { |
| 2277 | assert_eq!(ev("{a: 1, b: 2} = {a: 1, b: 2}"), b(true)); |
| 2278 | assert_eq!(ev("{a: 1, b: 2} = {b: 2, a: 1}"), b(true)); // order-insensitive |
| 2279 | assert_eq!(ev("{a: 1} = {a: 2}"), b(false)); |
| 2280 | assert_eq!(ev("{a: 1} = {a: 1, b: 2}"), b(false)); |
| 2281 | assert_eq!(ev("{a: 1} = 1"), Value::Null); // different types -> null |
| 2282 | } |
| 2283 | |
| 2284 | #[test] |
| 2285 | fn multi_word_names_as_identifiers() { |
| 2286 | // Full FEEL names may contain spaces (ADR-17). The lexer joins them. |
| 2287 | let mut ctx = Context::empty(); |
| 2288 | ctx.insert("full name", Value::String("Ada".into())); |
| 2289 | ctx.insert("year of birth", num(1815.0)); |
| 2290 | let ev = |src: &str| evaluate(src, &ctx).unwrap_or_else(|e| panic!("`{src}` failed: {e}")); |
| 2291 | |
| 2292 | assert_eq!(ev("full name"), Value::String("Ada".into())); |
| 2293 | assert_eq!(ev("year of birth + 1"), num(1816.0)); |
| 2294 | // Multi-word loop variable, referenced in the body. |
| 2295 | assert_eq!( |
| 2296 | ev("for my index in [1, 2] return my index + 1"), |
| 2297 | list(vec![num(2.0), num(3.0)]) |
| 2298 | ); |
| 2299 | // Multi-word context-literal key, read back via a multi-word path segment. |
| 2300 | assert_eq!(ev("{first name: 1}.first name"), num(1.0)); |
| 2301 | // An unbound multi-word name is a value-null, not a parse error. |
| 2302 | assert_eq!(ev("unbound display name"), Value::Null); |
| 2303 | } |
| 2304 | |
| 2305 | #[test] |
| 2306 | fn multi_word_join_is_backward_compatible() { |
| 2307 | // Keywords still break a name run: `and` stays the boolean operator. |
| 2308 | assert_eq!(ev("true and false"), b(false)); |
| 2309 | // Chained path access is unaffected. |
| 2310 | assert_eq!(ev("{a: {b: 1}}.a.b"), num(1.0)); |
| 2311 | // A single-word builtin call is unaffected by the join machinery; the |
| 2312 | // `(` lookahead keeps `string(1)` one word, not a merge with what follows. |
| 2313 | assert_eq!(ev("string(1)"), Value::String("1".into())); |
| 2314 | assert_eq!(ev("count([1, 2, 3])"), num(3.0)); |
| 2315 | } |
| 2316 | |
| 2317 | #[test] |
| 2318 | fn keyword_phrase_builtin_parses_in_call_position() { |
| 2319 | // A keyword-containing builtin name (`date and time`) is recognised as one |
| 2320 | // call head in call position and evaluates (ADR-18), NOT as |
| 2321 | // `date and (time(...))` (ADR-17). The lexer joins it as a single Name token |
| 2322 | // in every position, so `date and time` out of call position is the Name |
| 2323 | // `"date and time"` — which now evaluates to a first-class function value |
| 2324 | // (ADR-36) rather than null (which was the unbound-variable result before). |
| 2325 | assert_eq!( |
| 2326 | ev(r#"string(date and time("2018-12-08"))"#), |
| 2327 | Value::String("2018-12-08T00:00:00".into()) |
| 2328 | ); |
| 2329 | // Out of call position: resolves to the built-in function value (ADR-36). |
| 2330 | assert!(matches!(ev("date and time"), Value::Function(_))); |
| 2331 | } |
| 2332 | |
| 2333 | #[test] |
| 2334 | fn temporal_literals_and_ordering() { |
| 2335 | // `@"…"` literals parse by lexical form (ADR-18). `string(x)` gives the |
| 2336 | // canonical ISO form, so we round-trip through it to assert the value. |
| 2337 | let iso = |src: &str| ev(&format!("string({src})")); |
| 2338 | let s = |v: &str| Value::String(v.to_string()); |
| 2339 | |
| 2340 | assert_eq!(iso(r#"@"2017-08-03""#), s("2017-08-03")); |
| 2341 | assert_eq!(iso(r#"@"-2017-01-01""#), s("-2017-01-01")); // negative year |
| 2342 | assert_eq!(iso(r#"@"10:30:05""#), s("10:30:05")); |
| 2343 | assert_eq!(iso(r#"@"10:30:05+02:00""#), s("10:30:05+02:00")); |
| 2344 | assert_eq!(iso(r#"@"2017-01-01T23:59:01""#), s("2017-01-01T23:59:01")); |
| 2345 | assert_eq!(iso(r#"@"2017-01-01T23:59:01Z""#), s("2017-01-01T23:59:01Z")); |
| 2346 | assert_eq!( |
| 2347 | iso(r#"@"2017-01-01T23:59:01+02:00""#), |
| 2348 | s("2017-01-01T23:59:01+02:00") |
| 2349 | ); |
| 2350 | assert_eq!( |
| 2351 | iso(r#"@"2017-08-10T23:59:01.987654321""#), |
| 2352 | s("2017-08-10T23:59:01.987654321") |
| 2353 | ); |
| 2354 | // durations: years-months vs days-time, with sign and zero forms. |
| 2355 | assert_eq!(iso(r#"@"P1Y2M""#), s("P1Y2M")); |
| 2356 | assert_eq!(iso(r#"@"P0M""#), s("P0M")); |
| 2357 | assert_eq!(iso(r#"@"-P1Y8M""#), s("-P1Y8M")); |
| 2358 | assert_eq!(iso(r#"@"P2DT1H40M""#), s("P2DT1H40M")); |
| 2359 | assert_eq!(iso(r#"@"P1DT2H3M4.123456789S""#), s("P1DT2H3M4.123456789S")); |
| 2360 | // a named IANA zone resolves (bundled tzdb). |
| 2361 | assert_eq!( |
| 2362 | iso(r#"@"2017-06-23T11:23:00@Europe/Paris""#), |
| 2363 | s("2017-06-23T11:23:00@Europe/Paris") |
| 2364 | ); |
| 2365 | |
| 2366 | // malformed literal -> error-null (lenient view: null). |
| 2367 | assert_eq!(ev(r#"@"not-a-date""#), Value::Null); |
| 2368 | assert_eq!(ev(r#"@"2017-06-23T11:23:00@xyz/abc""#), Value::Null); |
| 2369 | |
| 2370 | // ordering & equality within a type. |
| 2371 | assert_eq!(ev(r#"@"2017-01-01" < @"2017-12-31""#), b(true)); |
| 2372 | assert_eq!(ev(r#"@"2017-01-01" = @"2017-01-01""#), b(true)); |
| 2373 | assert_eq!(ev(r#"@"P1Y" < @"P2Y""#), b(true)); |
| 2374 | assert_eq!(ev(r#"@"PT1H" < @"PT2H""#), b(true)); |
| 2375 | // same instant, different offset -> equal date-times. |
| 2376 | assert_eq!( |
| 2377 | ev(r#"@"2017-01-01T12:00:00+02:00" = @"2017-01-01T11:00:00+01:00""#), |
| 2378 | b(true) |
| 2379 | ); |
| 2380 | // cross temporal types are a type mismatch -> null (lenient). |
| 2381 | assert_eq!(ev(r#"@"2017-01-01" = @"P1Y""#), Value::Null); |
| 2382 | assert_eq!(ev(r#"@"P1Y" < @"PT1H""#), Value::Null); |
| 2383 | } |
| 2384 | |
| 2385 | #[test] |
| 2386 | fn temporal_arithmetic_negation_and_properties() { |
| 2387 | let iso = |src: &str| ev(&format!("string({src})")); |
| 2388 | let s = |v: &str| Value::String(v.to_string()); |
| 2389 | |
| 2390 | // date/datetime + duration |
| 2391 | assert_eq!(iso(r#"@"2017-01-01" + @"P1Y2M""#), s("2018-03-01")); // date + ymd -> date |
| 2392 | assert_eq!(iso(r#"@"2017-01-01" + @"P1D""#), s("2017-01-02")); // date + dtd -> date |
| 2393 | assert_eq!(iso(r#"@"2017-01-01" + @"PT36H""#), s("2017-01-02")); // dtd added, date part kept |
| 2394 | assert_eq!( |
| 2395 | iso(r#"@"2017-01-01T10:00:00" + @"P1M""#), |
| 2396 | s("2017-02-01T10:00:00") |
| 2397 | ); |
| 2398 | assert_eq!(iso(r#"@"23:00:00" + @"PT2H""#), s("01:00:00")); // time wraps mod 24h |
| 2399 | |
| 2400 | // duration ± duration (same family) |
| 2401 | assert_eq!(iso(r#"@"P1Y" + @"P2M""#), s("P1Y2M")); |
| 2402 | assert_eq!(iso(r#"@"PT1H" + @"PT30M""#), s("PT1H30M")); |
| 2403 | |
| 2404 | // date/datetime − date/datetime -> days-and-time duration |
| 2405 | assert_eq!(iso(r#"@"2017-01-10" - @"2017-01-01""#), s("P9D")); |
| 2406 | assert_eq!( |
| 2407 | iso(r#"@"2017-01-01T12:00:00" - @"2017-01-01T10:00:00""#), |
| 2408 | s("PT2H") |
| 2409 | ); |
| 2410 | |
| 2411 | // duration * / number, and duration / duration -> number |
| 2412 | assert_eq!(iso(r#"@"P1Y" * 2"#), s("P2Y")); |
| 2413 | assert_eq!(iso(r#"@"PT1H" * 3"#), s("PT3H")); |
| 2414 | assert_eq!(iso(r#"@"P2Y" / 2"#), s("P1Y")); |
| 2415 | assert_eq!(ev(r#"@"PT2H" / @"PT1H""#), num(2.0)); |
| 2416 | |
| 2417 | // negation of a duration |
| 2418 | assert_eq!(iso(r#"-@"P1Y""#), s("-P1Y")); |
| 2419 | |
| 2420 | // invalid combinations -> null (lenient view of error-null) |
| 2421 | assert_eq!(ev(r#"@"2017-01-01" + @"2017-01-02""#), Value::Null); // date + date |
| 2422 | assert_eq!(ev(r#"@"P1Y" + @"PT1H""#), Value::Null); // mixed duration families |
| 2423 | |
| 2424 | // property / component access |
| 2425 | assert_eq!(ev(r#"@"2017-08-03".year"#), num(2017.0)); |
| 2426 | assert_eq!(ev(r#"@"2017-08-03".month"#), num(8.0)); |
| 2427 | assert_eq!(ev(r#"@"2017-08-03".day"#), num(3.0)); |
| 2428 | assert_eq!(ev(r#"@"2017-08-03".weekday"#), num(4.0)); // Thursday |
| 2429 | assert_eq!(ev(r#"@"10:30:05".hour"#), num(10.0)); |
| 2430 | assert_eq!(ev(r#"@"10:30:05".minute"#), num(30.0)); |
| 2431 | assert_eq!(ev(r#"@"10:30:05".second"#), num(5.0)); |
| 2432 | assert_eq!(ev(r#"string(@"10:30:05+02:00".time offset)"#), s("PT2H")); |
| 2433 | assert_eq!(ev(r#"@"10:30:05".timezone"#), Value::Null); |
| 2434 | assert_eq!( |
| 2435 | ev(r#"@"2017-06-23T11:23:00@Europe/Paris".timezone"#), |
| 2436 | s("Europe/Paris") |
| 2437 | ); |
| 2438 | assert_eq!(ev(r#"@"P1Y2M".years"#), num(1.0)); |
| 2439 | assert_eq!(ev(r#"@"P1Y2M".months"#), num(2.0)); |
| 2440 | assert_eq!(ev(r#"@"P2DT3H".days"#), num(2.0)); |
| 2441 | assert_eq!(ev(r#"@"P2DT3H".hours"#), num(3.0)); |
| 2442 | // unknown property on a temporal -> value-null (not an error). |
| 2443 | assert_eq!(ev(r#"@"2017-08-03".nonsense"#), Value::Null); |
| 2444 | } |
| 2445 | |
| 2446 | #[test] |
| 2447 | fn parse_error_is_reported() { |
| 2448 | assert!(matches!( |
| 2449 | evaluate("1 +", &Context::empty()), |
| 2450 | Err(FeelError::Parse(_)) |
| 2451 | )); |
| 2452 | assert!(matches!( |
| 2453 | evaluate("if x then", &Context::empty()), |
| 2454 | Err(FeelError::Parse(_)) |
| 2455 | )); |
| 2456 | } |
| 2457 | |
| 2458 | #[test] |
| 2459 | fn builtin_functions() { |
| 2460 | let s = |v: &str| Value::String(v.to_string()); |
| 2461 | |
| 2462 | // --- numeric --- (spec §10.3.4.5) |
| 2463 | assert_eq!(ev("abs(-10)"), num(10.0)); |
| 2464 | assert_eq!(ev("abs(10)"), num(10.0)); |
| 2465 | assert_eq!(ev("modulo(12, 5)"), num(2.0)); |
| 2466 | assert_eq!(ev("modulo(-12, 5)"), num(3.0)); // result follows divisor's sign |
| 2467 | assert_eq!(ev("modulo(12, -5)"), num(-3.0)); |
| 2468 | assert_eq!(ev("floor(1.5)"), num(1.0)); |
| 2469 | assert_eq!(ev("floor(-1.56, 1)"), num(-1.6)); |
| 2470 | assert_eq!(ev("ceiling(1.5)"), num(2.0)); |
| 2471 | assert_eq!(ev("ceiling(-1.56, 1)"), num(-1.5)); |
| 2472 | assert_eq!(ev("decimal(1.5, 0)"), num(2.0)); // round half to even |
| 2473 | assert_eq!(ev("decimal(2.5, 0)"), num(2.0)); // round half to even |
| 2474 | assert_eq!(ev("modulo(12, 0)"), Value::Null); // divide by zero -> null |
| 2475 | assert_eq!(ev("abs(true)"), Value::Null); // wrong type -> null |
| 2476 | assert_eq!(ev("sqrt(16)"), num(4.0)); |
| 2477 | assert_eq!(ev("sqrt(-1)"), Value::Null); // negative -> domain error -> null |
| 2478 | assert_eq!(ev("exp(0)"), num(1.0)); |
| 2479 | assert_eq!(ev("log(1)"), num(0.0)); |
| 2480 | assert_eq!(ev("log(0)"), Value::Null); // non-positive -> domain error -> null |
| 2481 | assert_eq!(ev("even(2)"), b(true)); |
| 2482 | assert_eq!(ev("even(3)"), b(false)); |
| 2483 | assert_eq!(ev("even(2.5)"), Value::Null); // non-integer -> domain error -> null |
| 2484 | assert_eq!(ev("odd(3)"), b(true)); |
| 2485 | assert_eq!(ev("odd(2)"), b(false)); |
| 2486 | |
| 2487 | // --- list --- (spec §10.3.4.4) |
| 2488 | assert_eq!(ev("count([1, 2, 3])"), num(3.0)); |
| 2489 | assert_eq!(ev("count([])"), num(0.0)); |
| 2490 | assert_eq!(ev("count([1, [2, 3]])"), num(2.0)); // counts structural elements |
| 2491 | assert_eq!(ev("min([1, 2, 3])"), num(1.0)); |
| 2492 | assert_eq!(ev("max(1, 2, 3)"), num(3.0)); // varargs form |
| 2493 | assert_eq!(ev("min(1)"), num(1.0)); |
| 2494 | assert_eq!(ev("min([])"), Value::Null); // empty -> null |
| 2495 | assert_eq!(ev("sum([1, 2, 3])"), num(6.0)); |
| 2496 | assert_eq!(ev("sum(1, 2, 3)"), num(6.0)); |
| 2497 | assert_eq!(ev("sum([])"), Value::Null); |
| 2498 | assert_eq!(ev("mean([1, 2, 3])"), num(2.0)); |
| 2499 | assert_eq!(ev("product([2, 3, 4])"), num(24.0)); |
| 2500 | assert_eq!(ev("median(8, 2, 5, 3, 4)"), num(4.0)); |
| 2501 | assert_eq!(ev("median([6, 1, 2, 3])"), num(2.5)); // even count -> avg of middle two |
| 2502 | assert_eq!(ev("mode([6, 1, 9, 6, 1])"), list(vec![num(1.0), num(6.0)])); |
| 2503 | assert_eq!(ev("mode([])"), list(vec![])); // mode of empty list is [] |
| 2504 | assert_eq!(ev("all([false, null, true])"), b(false)); // a false dominates |
| 2505 | assert_eq!(ev("all([true, true])"), b(true)); |
| 2506 | assert_eq!(ev("all([])"), b(true)); |
| 2507 | assert_eq!(ev("any([false, null, true])"), b(true)); // a true dominates |
| 2508 | assert_eq!(ev("any([])"), b(false)); |
| 2509 | assert_eq!( |
| 2510 | ev("append([1], 2, 3)"), |
| 2511 | list(vec![num(1.0), num(2.0), num(3.0)]) |
| 2512 | ); |
| 2513 | assert_eq!( |
| 2514 | ev("concatenate([1, 2], [3])"), |
| 2515 | list(vec![num(1.0), num(2.0), num(3.0)]) |
| 2516 | ); |
| 2517 | assert_eq!( |
| 2518 | ev("union([1, 2], [2, 3])"), |
| 2519 | list(vec![num(1.0), num(2.0), num(3.0)]) |
| 2520 | ); |
| 2521 | assert_eq!(ev("remove([1, 2, 3], 2)"), list(vec![num(1.0), num(3.0)])); |
| 2522 | assert_eq!( |
| 2523 | ev("reverse([1, 2, 3])"), |
| 2524 | list(vec![num(3.0), num(2.0), num(1.0)]) |
| 2525 | ); |
| 2526 | assert_eq!( |
| 2527 | ev("flatten([[1, 2], [[3]], 4])"), |
| 2528 | list(vec![num(1.0), num(2.0), num(3.0), num(4.0)]) |
| 2529 | ); |
| 2530 | assert_eq!( |
| 2531 | ev("sublist([4, 5, 6], 1, 2)"), |
| 2532 | list(vec![num(4.0), num(5.0)]) |
| 2533 | ); |
| 2534 | |
| 2535 | // --- string --- (spec §10.3.4.1, §10.3.4.3) |
| 2536 | assert_eq!(ev(r#"substring("foobar", 3)"#), s("obar")); |
| 2537 | assert_eq!(ev(r#"substring("foobar", 3, 3)"#), s("oba")); |
| 2538 | assert_eq!(ev(r#"substring("foobar", -2, 1)"#), s("a")); // negative from end |
| 2539 | assert_eq!(ev(r#"contains("foobar", "of")"#), b(false)); |
| 2540 | assert_eq!(ev(r#"contains("foobar", "oob")"#), b(true)); |
| 2541 | assert_eq!(ev("string(1.1)"), s("1.1")); |
| 2542 | assert_eq!(ev("string(null)"), Value::Null); |
| 2543 | assert_eq!(ev(r#"number("1.1")"#), num(1.1)); |
| 2544 | assert_eq!(ev(r#"number("1,000.0", ",", ".")"#), num(1000.0)); |
| 2545 | |
| 2546 | // --- temporal clock builtins return temporal values (ADR-18) --- |
| 2547 | assert!(matches!(ev("now()"), Value::DateTime(_))); |
| 2548 | assert!(matches!(ev("today()"), Value::Date(_))); |
| 2549 | assert_eq!(ev("now(1)"), Value::Null); // wrong arity -> null |
| 2550 | } |
| 2551 | |
| 2552 | #[test] |
| 2553 | fn temporal_constructors_and_component_functions() { |
| 2554 | let iso = |src: &str| ev(&format!("string({src})")); |
| 2555 | let s = |v: &str| Value::String(v.to_string()); |
| 2556 | |
| 2557 | // date(...) |
| 2558 | assert_eq!(iso("date(2017, 8, 3)"), s("2017-08-03")); |
| 2559 | assert_eq!(iso(r#"date("2017-08-03")"#), s("2017-08-03")); |
| 2560 | assert_eq!(iso(r#"date(@"2017-08-03T10:00:00")"#), s("2017-08-03")); // from datetime |
| 2561 | assert_eq!(ev("date(2017, 13, 1)"), Value::Null); // out of range -> null |
| 2562 | assert_eq!(ev("date(2017, null, 1)"), Value::Null); // null component -> null |
| 2563 | assert_eq!(ev("date(null)"), Value::Null); |
| 2564 | |
| 2565 | // time(...) |
| 2566 | assert_eq!(iso("time(11, 59, 0)"), s("11:59:00")); |
| 2567 | assert_eq!(iso(r#"time("10:30:05")"#), s("10:30:05")); |
| 2568 | assert_eq!( |
| 2569 | iso(r#"time(11, 59, 0, duration("PT2H"))"#), |
| 2570 | s("11:59:00+02:00") |
| 2571 | ); |
| 2572 | |
| 2573 | // date and time(...) |
| 2574 | assert_eq!( |
| 2575 | iso(r#"date and time("2017-01-01T10:00:00")"#), |
| 2576 | s("2017-01-01T10:00:00") |
| 2577 | ); |
| 2578 | assert_eq!( |
| 2579 | iso(r#"date and time(@"2017-01-01", @"10:00:00")"#), |
| 2580 | s("2017-01-01T10:00:00") |
| 2581 | ); |
| 2582 | |
| 2583 | // duration(...) and years and months duration(...) |
| 2584 | assert_eq!(iso(r#"duration("P1Y2M")"#), s("P1Y2M")); |
| 2585 | assert_eq!(iso(r#"duration("P2DT3H")"#), s("P2DT3H")); |
| 2586 | assert_eq!(ev(r#"duration("1D")"#), Value::Null); // missing P -> null |
| 2587 | assert_eq!( |
| 2588 | iso(r#"years and months duration(@"2011-12-22", @"2013-08-24")"#), |
| 2589 | s("P1Y8M") |
| 2590 | ); |
| 2591 | assert_eq!( |
| 2592 | iso(r#"years and months duration(@"2013-08-24", @"2011-12-22")"#), |
| 2593 | s("-P1Y8M") |
| 2594 | ); |
| 2595 | |
| 2596 | // component functions |
| 2597 | assert_eq!(ev(r#"day of week(@"2021-01-11")"#), s("Monday")); |
| 2598 | assert_eq!(ev(r#"month of year(@"2021-04-01")"#), s("April")); |
| 2599 | assert_eq!(ev(r#"day of year(@"1970-01-01")"#), num(1.0)); |
| 2600 | assert_eq!(ev(r#"week of year(@"1970-01-01")"#), num(1.0)); |
| 2601 | assert_eq!(ev(r#"day of week(null)"#), Value::Null); |
| 2602 | |
| 2603 | // abs of a duration (ADR-18; ADR-15 deferred it) |
| 2604 | assert_eq!(iso(r#"abs(@"-P1Y")"#), s("P1Y")); |
| 2605 | assert_eq!(iso(r#"abs(duration("-PT2H"))"#), s("PT2H")); |
| 2606 | } |
| 2607 | |
| 2608 | #[test] |
| 2609 | fn now_today_use_injected_clock() { |
| 2610 | // `now()`/`today()` read the injected instant, so they are deterministic |
| 2611 | // and (in feel-pg) can be pinned to the transaction start (ADR-18). |
| 2612 | let z = jiff::civil::date(2024, 3, 10) |
| 2613 | .at(12, 0, 0, 0) |
| 2614 | .to_zoned(jiff::tz::TimeZone::get("America/New_York").unwrap()) |
| 2615 | .unwrap(); |
| 2616 | let env = EvalEnv::new(®ex_provider::DEFAULT, z); |
| 2617 | let eval = |src: &str| { |
| 2618 | compile(src) |
| 2619 | .unwrap() |
| 2620 | .evaluate_with_env(&Context::empty(), &env) |
| 2621 | .unwrap() |
| 2622 | .into_lenient() |
| 2623 | }; |
| 2624 | assert_eq!( |
| 2625 | eval("string(now())"), |
| 2626 | Value::String("2024-03-10T12:00:00@America/New_York".into()) |
| 2627 | ); |
| 2628 | assert_eq!(eval("string(today())"), Value::String("2024-03-10".into())); |
| 2629 | } |
| 2630 | |
| 2631 | #[test] |
| 2632 | fn multi_word_builtin_functions() { |
| 2633 | use std::collections::BTreeMap; |
| 2634 | let s = |v: &str| Value::String(v.to_string()); |
| 2635 | let ctx_val = |pairs: &[(&str, Value)]| { |
| 2636 | Value::Context( |
| 2637 | pairs |
| 2638 | .iter() |
| 2639 | .map(|(k, v)| (k.to_string(), v.clone())) |
| 2640 | .collect::<BTreeMap<_, _>>(), |
| 2641 | ) |
| 2642 | }; |
| 2643 | |
| 2644 | // --- string (multi-word) --- (spec §10.3.4.1) |
| 2645 | assert_eq!(ev(r#"string length("abc")"#), num(3.0)); |
| 2646 | assert_eq!(ev(r#"string length("aaaaa dddd ")"#), num(11.0)); // trailing space counts |
| 2647 | assert_eq!(ev(r#"upper case("aBc")"#), s("ABC")); |
| 2648 | assert_eq!(ev(r#"lower case("aBc4")"#), s("abc4")); |
| 2649 | assert_eq!(ev(r#"substring before("foobar", "bar")"#), s("foo")); |
| 2650 | assert_eq!(ev(r#"substring before("abc", "a")"#), s("")); // match at start |
| 2651 | assert_eq!(ev(r#"substring before("foobar", "x")"#), s("")); // not found |
| 2652 | assert_eq!(ev(r#"substring after("foobar", "ob")"#), s("ar")); |
| 2653 | assert_eq!(ev(r#"substring after("abc", "")"#), s("abc")); // empty match |
| 2654 | assert_eq!(ev(r#"starts with("foobar", "foo")"#), b(true)); |
| 2655 | assert_eq!(ev(r#"starts with("foobar", "x")"#), b(false)); |
| 2656 | assert_eq!(ev(r#"ends with("foobar", "bar")"#), b(true)); |
| 2657 | assert_eq!(ev(r#"string join(["a","b","c"])"#), s("abc")); |
| 2658 | assert_eq!( |
| 2659 | ev(r#"string join(["a","b","c"], " and ")"#), |
| 2660 | s("a and b and c") |
| 2661 | ); |
| 2662 | assert_eq!(ev(r#"string join(["a","b","c"], null)"#), s("abc")); // null delim = "" |
| 2663 | assert_eq!(ev(r#"string join(["a",null,"c"], "X")"#), s("aXc")); // null items skipped |
| 2664 | assert_eq!(ev("string join([])"), s("")); // empty list -> empty string |
| 2665 | assert_eq!(ev(r#"string join("a", "X")"#), s("a")); // scalar -> one-element list |
| 2666 | assert_eq!(ev("string join()"), Value::Null); // wrong arity -> null |
| 2667 | assert_eq!(ev(r#"string join([1,2,3], "X")"#), Value::Null); // non-string items -> null |
| 2668 | |
| 2669 | // --- list (multi-word) --- (spec §10.3.4.4) |
| 2670 | assert_eq!(ev("list contains([1,2,3], 2)"), b(true)); |
| 2671 | assert_eq!(ev("list contains([1,2,3], 9)"), b(false)); |
| 2672 | assert_eq!(ev("list contains([[1,2],[3]], [3])"), b(true)); // structural element |
| 2673 | assert_eq!(ev("index of([1,2,3,2], 2)"), list(vec![num(2.0), num(4.0)])); |
| 2674 | assert_eq!(ev("index of([1,2,3], 9)"), list(vec![])); |
| 2675 | assert_eq!( |
| 2676 | ev("distinct values([1,2,3,2,1])"), |
| 2677 | list(vec![num(1.0), num(2.0), num(3.0)]) |
| 2678 | ); |
| 2679 | assert_eq!( |
| 2680 | ev("insert before([1,2,3], 1, 4)"), |
| 2681 | list(vec![num(4.0), num(1.0), num(2.0), num(3.0)]) |
| 2682 | ); |
| 2683 | assert_eq!( |
| 2684 | ev("insert before([1,2,3], 3, 4)"), |
| 2685 | list(vec![num(1.0), num(2.0), num(4.0), num(3.0)]) |
| 2686 | ); |
| 2687 | assert_eq!( |
| 2688 | ev("list replace([1,2,3], 2, 4)"), |
| 2689 | list(vec![num(1.0), num(4.0), num(3.0)]) |
| 2690 | ); |
| 2691 | assert_eq!( |
| 2692 | ev("list replace([1,2,3], -1, 4)"), |
| 2693 | list(vec![num(1.0), num(2.0), num(4.0)]) |
| 2694 | ); |
| 2695 | assert_eq!(ev("list replace([1,2,3], 0, 4)"), Value::Null); // position 0 invalid |
| 2696 | assert_eq!( |
| 2697 | ev("list replace([1,2,3], 2.5, 4)"), // position truncates toward zero |
| 2698 | list(vec![num(1.0), num(4.0), num(3.0)]) |
| 2699 | ); |
| 2700 | |
| 2701 | // --- context (multi-word) --- (spec §10.3.4.6) |
| 2702 | assert_eq!(ev(r#"get value({a: "foo"}, "a")"#), s("foo")); |
| 2703 | assert_eq!(ev(r#"get value({a: "foo"}, "z")"#), Value::Null); // absent key |
| 2704 | assert_eq!(ev(r#"get value({a: null}, "a")"#), Value::Null); // present null value |
| 2705 | assert_eq!(ev(r#"get value("foo", "a")"#), Value::Null); // not a context -> null |
| 2706 | assert_eq!( |
| 2707 | ev(r#"get entries({a: "foo", b: "bar"})"#), |
| 2708 | list(vec![ |
| 2709 | ctx_val(&[("key", s("a")), ("value", s("foo"))]), |
| 2710 | ctx_val(&[("key", s("b")), ("value", s("bar"))]), |
| 2711 | ]) |
| 2712 | ); |
| 2713 | assert_eq!(ev("get entries({})"), list(vec![])); |
| 2714 | |
| 2715 | // --- keyword-phrase temporal builtin now evaluates (ADR-18) --- |
| 2716 | assert_eq!( |
| 2717 | ev(r#"string(date and time("2018-12-08"))"#), |
| 2718 | s("2018-12-08T00:00:00") |
| 2719 | ); |
| 2720 | } |
| 2721 | |
| 2722 | #[test] |
| 2723 | fn round_builtin_functions() { |
| 2724 | // round up/down/half up/half down(n, scale) (DMN-TCK 1141–1144). Numbers |
| 2725 | // are f64 (ADR-2), so the modes use native f64 rounding. |
| 2726 | assert_eq!(ev("round up(5.5, 0)"), num(6.0)); // away from zero |
| 2727 | assert_eq!(ev("round up(-5.5, 0)"), num(-6.0)); |
| 2728 | assert_eq!(ev("round up(1.121, 2)"), num(1.13)); |
| 2729 | assert_eq!(ev("round down(5.5, 0)"), num(5.0)); // toward zero |
| 2730 | assert_eq!(ev("round down(-5.5, 0)"), num(-5.0)); |
| 2731 | assert_eq!(ev("round half up(2.5, 0)"), num(3.0)); // ties away from zero |
| 2732 | assert_eq!(ev("round half up(-2.5, 0)"), num(-3.0)); |
| 2733 | assert_eq!(ev("round half down(2.5, 0)"), num(2.0)); // ties toward zero |
| 2734 | assert_eq!(ev("round half down(-2.5, 0)"), num(-2.0)); |
| 2735 | assert_eq!(ev("round up(null, 0)"), Value::Null); // null arg -> null |
| 2736 | assert_eq!(ev("round up(5.5)"), Value::Null); // scale required -> arity null |
| 2737 | assert_eq!(ev("round up(5.5, 6176)"), num(5.5)); // scale beyond f64 range: no effect |
| 2738 | assert_eq!(ev("round up(5.5, (6176 + 1))"), Value::Null); // out of decimal128 range -> null |
| 2739 | } |
| 2740 | |
| 2741 | #[test] |
| 2742 | fn context_builtin_functions() { |
| 2743 | use std::collections::BTreeMap; |
| 2744 | let ctx_val = |pairs: &[(&str, Value)]| { |
| 2745 | Value::Context( |
| 2746 | pairs |
| 2747 | .iter() |
| 2748 | .map(|(k, v)| (k.to_string(), v.clone())) |
| 2749 | .collect::<BTreeMap<_, _>>(), |
| 2750 | ) |
| 2751 | }; |
| 2752 | |
| 2753 | // context(entries) (DMN-TCK 1145) |
| 2754 | assert_eq!( |
| 2755 | ev(r#"context([{key:"a", value:1}, {key:"b", value:2}])"#), |
| 2756 | ctx_val(&[("a", num(1.0)), ("b", num(2.0))]) |
| 2757 | ); |
| 2758 | assert_eq!( |
| 2759 | ev(r#"context({key:"a", value:1})"#), |
| 2760 | ctx_val(&[("a", num(1.0))]) |
| 2761 | ); // single coerced |
| 2762 | assert_eq!( |
| 2763 | ev(r#"context([{key:"a", value:1}, {key:"a", value:2}])"#), |
| 2764 | Value::Null |
| 2765 | ); // duplicate key |
| 2766 | assert_eq!(ev(r#"context({key:"a"})"#), Value::Null); // missing value |
| 2767 | |
| 2768 | // context put(context, key, value) (DMN-TCK 1146) |
| 2769 | assert_eq!( |
| 2770 | ev(r#"context put({}, "a", 1)"#), |
| 2771 | ctx_val(&[("a", num(1.0))]) |
| 2772 | ); |
| 2773 | assert_eq!( |
| 2774 | ev(r#"context put({"a": 1}, "a", 2)"#), |
| 2775 | ctx_val(&[("a", num(2.0))]) |
| 2776 | ); // overwrite |
| 2777 | assert_eq!( |
| 2778 | ev(r#"context put({x:1, y: {a: 0}}, ["y", "a"], 2)"#), // nested path |
| 2779 | ctx_val(&[("x", num(1.0)), ("y", ctx_val(&[("a", num(2.0))]))]) |
| 2780 | ); |
| 2781 | assert_eq!( |
| 2782 | ev(r#"context put({x:1, y: {a: 0}}, ["y", "a", "b"], 2)"#), |
| 2783 | Value::Null |
| 2784 | ); // descend into non-context |
| 2785 | assert_eq!(ev(r#"context put(null, "a", 1)"#), Value::Null); |
| 2786 | |
| 2787 | // context merge(contexts) (DMN-TCK 1147) |
| 2788 | assert_eq!( |
| 2789 | ev(r#"context merge([{a: 1}, {b: 2}])"#), |
| 2790 | ctx_val(&[("a", num(1.0)), ("b", num(2.0))]) |
| 2791 | ); |
| 2792 | assert_eq!( |
| 2793 | ev(r#"context merge([{a: 1}, {a: 2}])"#), |
| 2794 | ctx_val(&[("a", num(2.0))]) |
| 2795 | ); // later wins |
| 2796 | assert_eq!(ev(r#"context merge({a: 1})"#), ctx_val(&[("a", num(1.0))])); // single coerced |
| 2797 | assert_eq!(ev(r#"context merge([{a: 1}, 2])"#), Value::Null); // non-context element |
| 2798 | } |
| 2799 | |
| 2800 | // The regex builtins are dialect-dependent (ADR-16): under the default |
| 2801 | // `rust-regex` provider they keep the Rust-dialect results recorded in |
| 2802 | // ADR-15; under `--no-default-features` (no provider) they evaluate to null. |
| 2803 | #[cfg(feature = "rust-regex")] |
| 2804 | #[test] |
| 2805 | fn builtin_regex_functions() { |
| 2806 | let s = |v: &str| Value::String(v.to_string()); |
| 2807 | assert_eq!(ev(r#"replace("banana", "a", "o")"#), s("bonono")); |
| 2808 | assert_eq!(ev(r#"matches("foobar", "^fo*b")"#), b(true)); |
| 2809 | assert_eq!( |
| 2810 | ev(r#"split("a;b;c;;", ";")"#), |
| 2811 | list(vec![s("a"), s("b"), s("c"), s(""), s("")]) |
| 2812 | ); |
| 2813 | } |
| 2814 | |
| 2815 | #[cfg(not(feature = "rust-regex"))] |
| 2816 | #[test] |
| 2817 | fn regex_builtins_are_error_null_without_a_provider() { |
| 2818 | // No host engine is injected on the default `evaluate` path, so the three |
| 2819 | // regex builtins are an error-null ("unsupported in this build") — raw, |
| 2820 | // not collapsed — so the strict boundary surfaces it (ADR-14/ADR-16). |
| 2821 | let raw = |
| 2822 | |src: &str| evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}`: {e}")); |
| 2823 | assert_eq!(raw(r#"matches("foobar", "^fo*b")"#), Value::Error); |
| 2824 | assert_eq!(raw(r#"replace("banana", "a", "o")"#), Value::Error); |
| 2825 | assert_eq!(raw(r#"split("a;b;c", ";")"#), Value::Error); |
| 2826 | // Non-regex builtins are unaffected. |
| 2827 | assert_eq!(raw("sum([1, 2, 3])"), num(6.0)); |
| 2828 | } |
| 2829 | |
| 2830 | /// Named-argument built-in calls (FEEL spec §10.3.2.13.5). |
| 2831 | /// |
| 2832 | /// Each test cites the TCK fixture or spec table section that motivates it. |
| 2833 | #[test] |
| 2834 | fn named_args_builtin_functions() { |
| 2835 | let s = |v: &str| Value::String(v.to_string()); |
| 2836 | |
| 2837 | // spec §10.3.4.3 Table 75: `substring(string, start position, length?)` |
| 2838 | // Named call must equal the positional call (TCK 0008-feel-builtins / substring). |
| 2839 | assert_eq!( |
| 2840 | ev(r#"substring(string: "foobar", start position: 3)"#), |
| 2841 | s("obar") |
| 2842 | ); |
| 2843 | assert_eq!( |
| 2844 | ev(r#"substring("foobar", 3)"#), |
| 2845 | s("obar") |
| 2846 | ); |
| 2847 | |
| 2848 | // spec §10.3.4.3: named arguments are order-independent. |
| 2849 | assert_eq!( |
| 2850 | ev(r#"substring(start position: 3, string: "foobar")"#), |
| 2851 | s("obar") |
| 2852 | ); |
| 2853 | |
| 2854 | // spec §10.3.4.3: omitting the optional `length` named arg still works. |
| 2855 | assert_eq!( |
| 2856 | ev(r#"substring(string: "foobar", start position: 3)"#), |
| 2857 | ev(r#"substring("foobar", 3)"#) |
| 2858 | ); |
| 2859 | |
| 2860 | // spec §10.3.4.3: supplying the optional `length` by name. |
| 2861 | assert_eq!( |
| 2862 | ev(r#"substring(string: "foobar", start position: 3, length: 3)"#), |
| 2863 | s("oba") |
| 2864 | ); |
| 2865 | |
| 2866 | // spec §10.3.4.3: `contains(string, match)`. |
| 2867 | assert_eq!( |
| 2868 | ev(r#"contains(string: "foobar", match: "oob")"#), |
| 2869 | b(true) |
| 2870 | ); |
| 2871 | |
| 2872 | // spec §10.3.4.3: `string length(string)`. |
| 2873 | assert_eq!(ev(r#"string length(string: "abc")"#), num(3.0)); |
| 2874 | |
| 2875 | // spec §10.3.4.3: `upper case(string)` / `lower case(string)`. |
| 2876 | assert_eq!(ev(r#"upper case(string: "aBc")"#), s("ABC")); |
| 2877 | assert_eq!(ev(r#"lower case(string: "aBc4")"#), s("abc4")); |
| 2878 | |
| 2879 | // spec §10.3.4.3: `starts with(string, match)`. |
| 2880 | assert_eq!(ev(r#"starts with(string: "foobar", match: "foo")"#), b(true)); |
| 2881 | |
| 2882 | // spec §10.3.4.3: `ends with(string, match)`. |
| 2883 | assert_eq!(ev(r#"ends with(string: "foobar", match: "bar")"#), b(true)); |
| 2884 | |
| 2885 | // spec §10.3.4.3: `substring before(string, match)` / `substring after(string, match)`. |
| 2886 | assert_eq!( |
| 2887 | ev(r#"substring before(string: "foobar", match: "bar")"#), |
| 2888 | s("foo") |
| 2889 | ); |
| 2890 | assert_eq!( |
| 2891 | ev(r#"substring after(string: "foobar", match: "ob")"#), |
| 2892 | s("ar") |
| 2893 | ); |
| 2894 | |
| 2895 | // spec §10.3.4.4: `list contains(list, element)`. |
| 2896 | assert_eq!(ev("list contains(list: [1,2,3], element: 2)"), b(true)); |
| 2897 | |
| 2898 | // spec §10.3.4.4: `count(list)`. |
| 2899 | assert_eq!(ev("count(list: [1,2,3])"), num(3.0)); |
| 2900 | |
| 2901 | // spec §10.3.4.4: `sublist(list, start position, length?)`. |
| 2902 | assert_eq!( |
| 2903 | ev("sublist(list: [4,5,6], start position: 1, length: 2)"), |
| 2904 | list(vec![num(4.0), num(5.0)]) |
| 2905 | ); |
| 2906 | |
| 2907 | // spec §10.3.4.5: `decimal(n, scale)`. |
| 2908 | assert_eq!(ev("decimal(n: 1.5, scale: 0)"), num(2.0)); |
| 2909 | |
| 2910 | // spec §10.3.4.5: `abs(n)`. |
| 2911 | assert_eq!(ev("abs(n: -10)"), num(10.0)); |
| 2912 | |
| 2913 | // spec §10.3.4.5: `modulo(dividend, divisor)`. |
| 2914 | assert_eq!(ev("modulo(dividend: 12, divisor: 5)"), num(2.0)); |
| 2915 | |
| 2916 | // spec §10.3.4.10: `get value(m, key)`. |
| 2917 | assert_eq!(ev(r#"get value(m: {a: 1}, key: "a")"#), num(1.0)); |
| 2918 | |
| 2919 | // spec §10.3.4.1: `string(from)`. |
| 2920 | assert_eq!(ev("string(from: 1.1)"), s("1.1")); |
| 2921 | |
| 2922 | // Unknown parameter name -> error-null (spec §10.3.2.13.5: no match -> null). |
| 2923 | // ev() uses into_lenient(), so error-null collapses to Value::Null. |
| 2924 | assert_eq!( |
| 2925 | ev(r#"substring(string: "foobar", start: 3)"#), |
| 2926 | Value::Null |
| 2927 | ); |
| 2928 | |
| 2929 | // A variadic-only built-in called with named args -> null (no table entry). |
| 2930 | // `sum` accepts either a list or N scalars; it has no named-parameter form. |
| 2931 | assert_eq!(ev("sum(n: 1)"), Value::Null); |
| 2932 | } |
| 2933 | |
| 2934 | // --- `instance of` type predicate (DMN §10.3.2.9, ADR-26) ---------------- // |
| 2935 | |
| 2936 | #[test] |
| 2937 | fn instance_of_primitives_and_null() { |
| 2938 | // spec Table 62. |
| 2939 | assert_eq!(ev(r#""abc" instance of string"#), b(true)); |
| 2940 | assert_eq!(ev("123 instance of string"), b(false)); |
| 2941 | // A bare `list` requires parameters, so it is unmappable -> null (spec example). |
| 2942 | assert_eq!(ev("123 instance of list"), Value::Null); |
| 2943 | |
| 2944 | // Primitive cross-checks. |
| 2945 | assert_eq!(ev("123.01 instance of number"), b(true)); |
| 2946 | assert_eq!(ev("true instance of boolean"), b(true)); |
| 2947 | assert_eq!(ev("true instance of number"), b(false)); |
| 2948 | assert_eq!(ev("123 instance of Any"), b(true)); |
| 2949 | |
| 2950 | // Top-level null rule: null is an instance only of `Null`. |
| 2951 | assert_eq!(ev("null instance of Null"), b(true)); |
| 2952 | assert_eq!(ev("null instance of string"), b(false)); |
| 2953 | assert_eq!(ev("null instance of Any"), b(false)); |
| 2954 | |
| 2955 | // An unknown / item-definition type name is unmappable -> null. |
| 2956 | assert_eq!(ev("256 instance of t255"), Value::Null); |
| 2957 | |
| 2958 | // `and` after a type is logical-and, not part of the type name. |
| 2959 | assert_eq!(ev("1 instance of number and 2 instance of number"), b(true)); |
| 2960 | assert_eq!(ev("1 instance of string and 2 instance of number"), b(false)); |
| 2961 | } |
| 2962 | |
| 2963 | #[test] |
| 2964 | fn instance_of_temporal() { |
| 2965 | assert_eq!(ev(r#"date("2018-12-08") instance of date"#), b(true)); |
| 2966 | assert_eq!(ev(r#"date("2018-12-08") instance of date and time"#), b(false)); |
| 2967 | assert_eq!(ev(r#"time("10:30:00") instance of time"#), b(true)); |
| 2968 | // `date and time` works as both a constructor head and a type name. |
| 2969 | assert_eq!( |
| 2970 | ev(r#"date and time("2018-12-08T10:30:00") instance of date and time"#), |
| 2971 | b(true) |
| 2972 | ); |
| 2973 | // The two duration kinds are distinguished. |
| 2974 | assert_eq!(ev(r#"duration("P1Y") instance of years and months duration"#), b(true)); |
| 2975 | assert_eq!(ev(r#"duration("P1Y") instance of days and time duration"#), b(false)); |
| 2976 | assert_eq!(ev(r#"duration("P1D") instance of days and time duration"#), b(true)); |
| 2977 | } |
| 2978 | |
| 2979 | #[test] |
| 2980 | fn instance_of_generic_list_and_context() { |
| 2981 | // list<T>: a list whose every element conforms to T. |
| 2982 | assert_eq!(ev("[1, 2, 3] instance of list<Any>"), b(true)); |
| 2983 | assert_eq!(ev("[1, 2, 3] instance of list<number>"), b(true)); |
| 2984 | assert_eq!(ev(r#"[1, "a"] instance of list<number>"#), b(false)); |
| 2985 | assert_eq!(ev("[1] instance of number"), b(false)); // a list is not a number |
| 2986 | |
| 2987 | // context<…>: the value must carry (at least) every target key, each conforming. |
| 2988 | assert_eq!(ev(r#"{a: "foo"} instance of context<a: string>"#), b(true)); |
| 2989 | assert_eq!(ev(r#"{a: "123", b: 123} instance of context<a: string>"#), b(true)); // extra key ok |
| 2990 | assert_eq!(ev(r#"{a: "123"} instance of context<a: number>"#), b(false)); |
| 2991 | // A nested null field conforms (Null <: T), unlike a top-level null. |
| 2992 | assert_eq!(ev("{a: null} instance of context<a: string>"), b(true)); |
| 2993 | // Nested context types. |
| 2994 | assert_eq!(ev("{a: {b: 123}} instance of context<a: context<b: number>>"), b(true)); |
| 2995 | assert_eq!(ev("{a: {b: 123}} instance of context<a: context<b: string>>"), b(false)); |
| 2996 | // A list of contexts. |
| 2997 | assert_eq!( |
| 2998 | ev(r#"[{a: "a", b: "b"}] instance of list<context<a: string, b: string>>"#), |
| 2999 | b(true) |
| 3000 | ); |
| 3001 | assert_eq!( |
| 3002 | ev(r#"[{a: "a"}] instance of list<context<a: string, b: string>>"#), |
| 3003 | b(false) |
| 3004 | ); |
| 3005 | } |
| 3006 | |
| 3007 | #[test] |
| 3008 | fn instance_of_functions() { |
| 3009 | assert_eq!(ev(r#"(function() "foo") instance of function<> -> Any"#), b(true)); |
| 3010 | assert_eq!(ev(r#"(function() "foo") instance of Any"#), b(true)); |
| 3011 | assert_eq!(ev(r#"(function() "foo") instance of number"#), b(false)); |
| 3012 | // Untyped closures map to (Any, …) -> Any, so only the arity is checked. |
| 3013 | assert_eq!(ev("(function(x) x) instance of function<Any> -> Any"), b(true)); |
| 3014 | assert_eq!(ev("(function(x) x) instance of function<> -> Any"), b(false)); |
| 3015 | } |
| 3016 | } |
| 3017 | |
| 3018 | /// Tests for the lazy [`Value::Foreign`] seam (ADR-21). feel-core never constructs |
| 3019 | /// a `Foreign`, so these drive a *test-only* [`ForeignObject`] to prove the |
| 3020 | /// force-on-consume / lazy-on-path contract from inside the core. |
| 3021 | #[cfg(test)] |
| 3022 | mod foreign_tests { |
| 3023 | use super::*; |
| 3024 | use crate::foreign::{Foreign, ForeignObject}; |
| 3025 | use std::collections::BTreeMap; |
| 3026 | use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; |
| 3027 | use std::sync::Arc; |
| 3028 | |
| 3029 | /// A foreign object backed by a fixed map, counting `get`/`force` calls so the |
| 3030 | /// tests can assert *when* the host is consulted (path = `get`, consume = |
| 3031 | /// `force`). |
| 3032 | #[derive(Debug)] |
| 3033 | struct TestObj { |
| 3034 | data: BTreeMap<String, Value>, |
| 3035 | gets: Arc<AtomicUsize>, |
| 3036 | forces: Arc<AtomicUsize>, |
| 3037 | } |
| 3038 | |
| 3039 | impl ForeignObject for TestObj { |
| 3040 | fn get(&self, key: &str) -> Value { |
| 3041 | self.gets.fetch_add(1, AtomicOrdering::SeqCst); |
| 3042 | self.data.get(key).cloned().unwrap_or(Value::Null) |
| 3043 | } |
| 3044 | fn force(&self) -> Value { |
| 3045 | self.forces.fetch_add(1, AtomicOrdering::SeqCst); |
| 3046 | Value::Context(self.data.clone()) |
| 3047 | } |
| 3048 | fn as_any(&self) -> &dyn std::any::Any { |
| 3049 | self |
| 3050 | } |
| 3051 | } |
| 3052 | |
| 3053 | fn obj(pairs: &[(&str, Value)], gets: &Arc<AtomicUsize>, forces: &Arc<AtomicUsize>) -> Value { |
| 3054 | let data = pairs |
| 3055 | .iter() |
| 3056 | .map(|(k, v)| (k.to_string(), v.clone())) |
| 3057 | .collect(); |
| 3058 | Value::Foreign(Foreign(Arc::new(TestObj { |
| 3059 | data, |
| 3060 | gets: gets.clone(), |
| 3061 | forces: forces.clone(), |
| 3062 | }))) |
| 3063 | } |
| 3064 | |
| 3065 | fn run(src: &str, ctx: &Context) -> Value { |
| 3066 | evaluate(src, ctx).unwrap().into_lenient() |
| 3067 | } |
| 3068 | |
| 3069 | #[test] |
| 3070 | fn path_access_is_lazy_and_calls_get_not_force() { |
| 3071 | let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); |
| 3072 | // order -> { customer -> { name: "Ada" } }, all lazy. |
| 3073 | let customer = obj(&[("name", Value::String("Ada".into()))], &gets, &forces); |
| 3074 | let order = obj(&[("customer", customer)], &gets, &forces); |
| 3075 | let mut ctx = Context::empty(); |
| 3076 | ctx.insert("order", order); |
| 3077 | |
| 3078 | assert_eq!( |
| 3079 | run("order.customer.name", &ctx), |
| 3080 | Value::String("Ada".into()) |
| 3081 | ); |
| 3082 | // Two dots -> two `get`s; the dot never forces. |
| 3083 | assert_eq!(gets.load(AtomicOrdering::SeqCst), 2); |
| 3084 | assert_eq!(forces.load(AtomicOrdering::SeqCst), 0); |
| 3085 | // A missing member is a value-null, like a missing context key. |
| 3086 | assert_eq!(run("order.customer.missing", &ctx), Value::Null); |
| 3087 | } |
| 3088 | |
| 3089 | #[test] |
| 3090 | fn non_path_use_forces() { |
| 3091 | let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); |
| 3092 | let o = obj(&[("a", Value::Number(1.0))], &gets, &forces); |
| 3093 | let mut ctx = Context::empty(); |
| 3094 | ctx.insert("o", o); |
| 3095 | |
| 3096 | // Equality consumes the value -> the operand is forced to a context. |
| 3097 | assert_eq!(run("o = {a: 1}", &ctx), Value::Boolean(true)); |
| 3098 | assert!(forces.load(AtomicOrdering::SeqCst) >= 1); |
| 3099 | } |
| 3100 | |
| 3101 | #[test] |
| 3102 | fn forced_is_identity_on_non_foreign() { |
| 3103 | assert_eq!(Value::Number(2.0).forced(), Value::Number(2.0)); |
| 3104 | assert_eq!(Value::Null.forced(), Value::Null); |
| 3105 | assert_eq!( |
| 3106 | Value::String("x".into()).forced(), |
| 3107 | Value::String("x".into()) |
| 3108 | ); |
| 3109 | } |
| 3110 | |
| 3111 | /// An unbounded (cycle-equivalent) lazy graph: every key but `value` yields |
| 3112 | /// another node. A *finite* expression terminates because it can only navigate |
| 3113 | /// a finite path — no engine cycle guard is needed (ADR-21). |
| 3114 | #[derive(Debug)] |
| 3115 | struct Infinite; |
| 3116 | impl ForeignObject for Infinite { |
| 3117 | fn get(&self, key: &str) -> Value { |
| 3118 | if key == "value" { |
| 3119 | Value::Number(42.0) |
| 3120 | } else { |
| 3121 | Value::Foreign(Foreign(Arc::new(Infinite))) |
| 3122 | } |
| 3123 | } |
| 3124 | fn force(&self) -> Value { |
| 3125 | Value::Context(BTreeMap::new()) |
| 3126 | } |
| 3127 | fn as_any(&self) -> &dyn std::any::Any { |
| 3128 | self |
| 3129 | } |
| 3130 | } |
| 3131 | |
| 3132 | #[test] |
| 3133 | fn unbounded_graph_terminates_along_a_finite_path() { |
| 3134 | let mut ctx = Context::empty(); |
| 3135 | ctx.insert("o", Value::Foreign(Foreign(Arc::new(Infinite)))); |
| 3136 | assert_eq!(run("o.self.self.self.value", &ctx), Value::Number(42.0)); |
| 3137 | assert_eq!(run("o.a.b.c.d.e.f.value", &ctx), Value::Number(42.0)); |
| 3138 | } |
| 3139 | |
| 3140 | #[test] |
| 3141 | fn value_size_did_not_grow() { |
| 3142 | // `Value`'s size is set by its largest variant — the temporal `DateTime` |
| 3143 | // payload (32 bytes), giving 40 with the discriminant. The new `Foreign` |
| 3144 | // variant is a 16-byte fat pointer, well under that, so `Value` does not |
| 3145 | // grow: the zero-cost-for-Rust guarantee (ADR-21). Pin both so a regression |
| 3146 | // (an accidental inline payload, or `Foreign` becoming the determining |
| 3147 | // variant) is caught. |
| 3148 | assert_eq!(std::mem::size_of::<Foreign>(), 16); |
| 3149 | assert_eq!(std::mem::size_of::<Value>(), 40); |
| 3150 | } |
| 3151 | |
| 3152 | // ---- descendant expression `e ... name` (DMN §10.3.2.7, grammar rule 68) ---- |
| 3153 | |
| 3154 | #[test] |
| 3155 | fn descendant_spec_example() { |
| 3156 | // The spec's canonical example (§10.3.2.7): collect every `b` nested anywhere, |
| 3157 | // pre-order. `{a:{b:{b:1}}} ... b` -> [{b:1}, 1]. |
| 3158 | let ctx = Context::empty(); |
| 3159 | assert_eq!( |
| 3160 | run("{a: {b: {b: 1}}} ... b", &ctx), |
| 3161 | Value::List(vec![ |
| 3162 | Value::Context(BTreeMap::from([("b".to_string(), Value::Number(1.0))])), |
| 3163 | Value::Number(1.0), |
| 3164 | ]) |
| 3165 | ); |
| 3166 | } |
| 3167 | |
| 3168 | #[test] |
| 3169 | fn descendant_collects_across_a_list_of_contexts() { |
| 3170 | let ctx = Context::empty(); |
| 3171 | assert_eq!( |
| 3172 | run("[{x:1},{x:2}] ... x", &ctx), |
| 3173 | Value::List(vec![Value::Number(1.0), Value::Number(2.0)]) |
| 3174 | ); |
| 3175 | } |
| 3176 | |
| 3177 | #[test] |
| 3178 | fn descendant_no_match_is_empty_list() { |
| 3179 | // A search that finds nothing still yields a (flat) list, not null. |
| 3180 | let ctx = Context::empty(); |
| 3181 | assert_eq!(run("{a:1} ... z", &ctx), Value::List(vec![])); |
| 3182 | } |
| 3183 | |
| 3184 | #[test] |
| 3185 | fn descendant_on_null_and_scalar() { |
| 3186 | let ctx = Context::empty(); |
| 3187 | // null propagates. |
| 3188 | assert_eq!(run("null ... x", &ctx), Value::Null); |
| 3189 | // A non-navigable scalar: applicability "type e is a context" fails -> null |
| 3190 | // (mirrors `.` on a non-context). |
| 3191 | assert_eq!(run("5 ... x", &ctx), Value::Null); |
| 3192 | } |
| 3193 | |
| 3194 | #[test] |
| 3195 | fn descendant_descends_into_foreign() { |
| 3196 | // order -> { customer -> { name: "Ada" } }, all lazy Foreigns. |
| 3197 | let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); |
| 3198 | let customer = obj(&[("name", Value::String("Ada".into()))], &gets, &forces); |
| 3199 | let order = obj(&[("customer", customer)], &gets, &forces); |
| 3200 | let mut ctx = Context::empty(); |
| 3201 | ctx.insert("order", order); |
| 3202 | // Descendant forces its way down the lazy graph and collects `name`. |
| 3203 | assert_eq!( |
| 3204 | run("order ... name", &ctx), |
| 3205 | Value::List(vec![Value::String("Ada".into())]) |
| 3206 | ); |
| 3207 | } |
| 3208 | |
| 3209 | /// A cyclic foreign graph that mimics a host (feel-py) wrapping the *same* |
| 3210 | /// object with a *fresh* `Arc` on every access: `force`/`get("next")` mint a new |
| 3211 | /// `Arc<Cycle>` carrying the same `id`, so the Rust allocation address differs |
| 3212 | /// every time. Only the `identity()` override (the stable `id`) lets the |
| 3213 | /// descendant guard break the cycle — exactly the feel-py/lua/wasm scenario. |
| 3214 | #[derive(Debug)] |
| 3215 | struct Cycle { |
| 3216 | id: usize, |
| 3217 | value: f64, |
| 3218 | } |
| 3219 | impl ForeignObject for Cycle { |
| 3220 | fn get(&self, key: &str) -> Value { |
| 3221 | match key { |
| 3222 | "value" => Value::Number(self.value), |
| 3223 | "next" => Value::Foreign(Foreign(Arc::new(Cycle { |
| 3224 | id: self.id, |
| 3225 | value: self.value, |
| 3226 | }))), |
| 3227 | _ => Value::Null, |
| 3228 | } |
| 3229 | } |
| 3230 | fn force(&self) -> Value { |
| 3231 | let mut map = BTreeMap::new(); |
| 3232 | map.insert("value".to_string(), Value::Number(self.value)); |
| 3233 | map.insert( |
| 3234 | "next".to_string(), |
| 3235 | Value::Foreign(Foreign(Arc::new(Cycle { |
| 3236 | id: self.id, |
| 3237 | value: self.value, |
| 3238 | }))), |
| 3239 | ); |
| 3240 | Value::Context(map) |
| 3241 | } |
| 3242 | fn as_any(&self) -> &dyn std::any::Any { |
| 3243 | self |
| 3244 | } |
| 3245 | fn identity(&self) -> usize { |
| 3246 | self.id |
| 3247 | } |
| 3248 | } |
| 3249 | |
| 3250 | #[test] |
| 3251 | fn descendant_terminates_on_a_cyclic_foreign_with_fresh_arcs() { |
| 3252 | // Without the identity() override this would loop forever; with it, the |
| 3253 | // back-edge into the same `id` is skipped after the first descent. |
| 3254 | let mut ctx = Context::empty(); |
| 3255 | ctx.insert( |
| 3256 | "c", |
| 3257 | Value::Foreign(Foreign(Arc::new(Cycle { id: 7, value: 42.0 }))), |
| 3258 | ); |
| 3259 | // value=42 at the top, then once more at the (single) re-entered node before |
| 3260 | // the back-edge is cut -> [42, 42]. |
| 3261 | assert_eq!( |
| 3262 | run("c ... value", &ctx), |
| 3263 | Value::List(vec![Value::Number(42.0), Value::Number(42.0)]) |
| 3264 | ); |
| 3265 | } |
| 3266 | |
| 3267 | /// A self-referential cycle via a *single shared* `Arc` (the allocation address |
| 3268 | /// is reused), so the DEFAULT `identity()` (allocation address) suffices — this |
| 3269 | /// exercises the default code path rather than an override. |
| 3270 | #[derive(Debug)] |
| 3271 | struct SharedCycle { |
| 3272 | next: std::sync::OnceLock<Value>, |
| 3273 | value: f64, |
| 3274 | } |
| 3275 | impl ForeignObject for SharedCycle { |
| 3276 | fn get(&self, key: &str) -> Value { |
| 3277 | match key { |
| 3278 | "value" => Value::Number(self.value), |
| 3279 | "next" => self.next.get().cloned().unwrap_or(Value::Null), |
| 3280 | _ => Value::Null, |
| 3281 | } |
| 3282 | } |
| 3283 | fn force(&self) -> Value { |
| 3284 | let mut map = BTreeMap::new(); |
| 3285 | map.insert("value".to_string(), Value::Number(self.value)); |
| 3286 | map.insert( |
| 3287 | "next".to_string(), |
| 3288 | self.next.get().cloned().unwrap_or(Value::Null), |
| 3289 | ); |
| 3290 | Value::Context(map) |
| 3291 | } |
| 3292 | fn as_any(&self) -> &dyn std::any::Any { |
| 3293 | self |
| 3294 | } |
| 3295 | } |
| 3296 | |
| 3297 | #[test] |
| 3298 | fn descendant_terminates_on_a_cyclic_foreign_with_a_shared_arc() { |
| 3299 | let arc = Arc::new(SharedCycle { |
| 3300 | next: std::sync::OnceLock::new(), |
| 3301 | value: 9.0, |
| 3302 | }); |
| 3303 | // Wire the self-reference after the Arc exists (same allocation reused). |
| 3304 | arc.next |
| 3305 | .set(Value::Foreign(Foreign(arc.clone()))) |
| 3306 | .unwrap(); |
| 3307 | let mut ctx = Context::empty(); |
| 3308 | ctx.insert("c", Value::Foreign(Foreign(arc))); |
| 3309 | assert_eq!( |
| 3310 | run("c ... value", &ctx), |
| 3311 | Value::List(vec![Value::Number(9.0), Value::Number(9.0)]) |
| 3312 | ); |
| 3313 | } |
| 3314 | |
| 3315 | #[test] |
| 3316 | fn descendant_dedups_a_shared_acyclic_foreign_dag() { |
| 3317 | // Pure-FEEL contrast first: two DISTINCT value contexts (owned, never |
| 3318 | // Foreign) -> both traversed -> multiset [1, 1]. The spec domain is exact. |
| 3319 | let ctx = Context::empty(); |
| 3320 | assert_eq!( |
| 3321 | run("{x:{v:1}, y:{v:1}} ... v", &ctx), |
| 3322 | Value::List(vec![Value::Number(1.0), Value::Number(1.0)]) |
| 3323 | ); |
| 3324 | |
| 3325 | // Same shape but the inner object is ONE shared host object (a diamond/DAG, |
| 3326 | // not a cycle): both `x` and `y` reference the same `a` (same Foreign |
| 3327 | // identity). The GLOBAL visited-set collects `v` once, not once per path — |
| 3328 | // the intentional DAG de-dup (ADR-46). Host object graphs are out of DMN |
| 3329 | // spec; the global set is chosen over a path-scoped set to avoid exponential |
| 3330 | // blowup on diamond-heavy DAGs, accepting per-path multiset semantics for |
| 3331 | // shared host data. |
| 3332 | let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); |
| 3333 | let a = obj(&[("v", Value::Number(1.0))], &gets, &forces); |
| 3334 | let g = obj(&[("x", a.clone()), ("y", a.clone())], &gets, &forces); |
| 3335 | let mut ctx = Context::empty(); |
| 3336 | ctx.insert("g", g); |
| 3337 | assert_eq!( |
| 3338 | run("g ... v", &ctx), |
| 3339 | Value::List(vec![Value::Number(1.0)]) |
| 3340 | ); |
| 3341 | } |
| 3342 | } |
| 3343 | |
| 3344 | /// User-defined functions: native FEEL closures and host callables (ADR-23). |
| 3345 | /// |
| 3346 | /// The DMN-TCK has dedicated cases (compliance-level-3 `0030`/`0031`), but those |
| 3347 | /// decisions are *boxed* (a `<context>`/`<functionDefinition>`), not single literal |
| 3348 | /// expressions, and use named-argument and library-import forms outside this slice, |
| 3349 | /// so `tools/ingest_tck.py` cannot ingest them. The closure tests below therefore |
| 3350 | /// reconstruct the TCK 0030 semantics as self-contained FEEL expressions; each |
| 3351 | /// carries a `mirrors DMN-TCK …` note so this stays easy to refresh against the |
| 3352 | /// source. Source: https://github.com/dmn-tck/tck — TestCases/compliance-level-3/0030-user-defined-functions |
| 3353 | #[cfg(test)] |
| 3354 | mod function_tests { |
| 3355 | use super::*; |
| 3356 | use crate::function::{Args, ForeignFunction, Func}; |
| 3357 | use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; |
| 3358 | use std::sync::Arc; |
| 3359 | |
| 3360 | /// Evaluate against an empty context, collapsing error provenance (lenient view). |
| 3361 | fn ev(src: &str) -> Value { |
| 3362 | evaluate(src, &Context::empty()) |
| 3363 | .unwrap_or_else(|e| panic!("`{src}` failed: {e}")) |
| 3364 | .into_lenient() |
| 3365 | } |
| 3366 | |
| 3367 | // --- native FEEL closures (`function(…)` literals) ------------------------ // |
| 3368 | |
| 3369 | #[test] |
| 3370 | fn closure_literal_and_positional_invocation() { |
| 3371 | // A function bound in a context entry, then invoked by name — the self- |
| 3372 | // contained shape of a TCK boxed-context function invocation. |
| 3373 | assert_eq!( |
| 3374 | ev("{f: function(a, b) a + b, r: f(1, 2)}.r"), |
| 3375 | Value::Number(3.0) |
| 3376 | ); |
| 3377 | // mirrors DMN-TCK 0030 testCase 001 "simple function invocation": |
| 3378 | // f("feel","#") + f("feel","#") == "feel#" + "feel#" == "feel#feel#". |
| 3379 | assert_eq!( |
| 3380 | ev(r##"{f: function(a, b) a + b, r: f("feel", "#") + f("feel", "#")}.r"##), |
| 3381 | Value::String("feel#feel#".into()) |
| 3382 | ); |
| 3383 | // a zero-parameter function. |
| 3384 | assert_eq!(ev("{f: function() 42, r: f()}.r"), Value::Number(42.0)); |
| 3385 | } |
| 3386 | |
| 3387 | #[test] |
| 3388 | fn named_and_mixed_invocation() { |
| 3389 | // mirrors DMN-TCK 0030 testCase 001 "named function invocation": the names |
| 3390 | // are bound by position-independent name, here swapped, giving "#feel#feel". |
| 3391 | assert_eq!( |
| 3392 | ev(r##"{f: function(a, b) a + b, r: f(b: "feel", a: "#") + f(b: "feel", a: "#")}.r"##), |
| 3393 | Value::String("#feel#feel".into()) |
| 3394 | ); |
| 3395 | // named arguments, order reversed: a - b with a=7, b=2 -> 5. |
| 3396 | assert_eq!( |
| 3397 | ev("{f: function(a, b) a - b, r: f(b: 2, a: 7)}.r"), |
| 3398 | Value::Number(5.0) |
| 3399 | ); |
| 3400 | // mixed positional + named (ADR-23 superset of FEEL spec rule 39): 7 - 2 = 5. |
| 3401 | assert_eq!( |
| 3402 | ev("{f: function(a, b) a - b, r: f(7, b: 2)}.r"), |
| 3403 | Value::Number(5.0) |
| 3404 | ); |
| 3405 | } |
| 3406 | |
| 3407 | #[test] |
| 3408 | fn lexical_capture() { |
| 3409 | // The body sees `x` from the scope the function was defined in (a closure). |
| 3410 | assert_eq!( |
| 3411 | ev("{x: 10, f: function(a) a + x, r: f(5)}.r"), |
| 3412 | Value::Number(15.0) |
| 3413 | ); |
| 3414 | } |
| 3415 | |
| 3416 | #[test] |
| 3417 | fn arity_is_lenient() { |
| 3418 | // Under-supplied positional: the unused param is value-null, so f(7)=7. |
| 3419 | assert_eq!(ev("{f: function(a, b) a, r: f(7)}.r"), Value::Number(7.0)); |
| 3420 | // An unsupplied param read in the body is null -> a + null -> null. |
| 3421 | assert_eq!(ev("{f: function(a, b) a + b, r: f(7)}.r"), Value::Null); |
| 3422 | // Non-conformance is an error-null (-> null lenient): too many positional, |
| 3423 | assert_eq!(ev("{f: function(a) a, r: f(1, 2)}.r"), Value::Null); |
| 3424 | // an unknown named parameter, |
| 3425 | assert_eq!(ev("{f: function(a) a, r: f(z: 1)}.r"), Value::Null); |
| 3426 | // and a parameter supplied both positionally and by name. |
| 3427 | assert_eq!(ev("{f: function(a, b) a, r: f(1, a: 2)}.r"), Value::Null); |
| 3428 | } |
| 3429 | |
| 3430 | #[test] |
| 3431 | fn function_equality_is_identity() { |
| 3432 | // The same binding referenced twice is the same value -> equal. |
| 3433 | assert_eq!(ev("{f: function(a) a, r: f = f}.r"), Value::Boolean(true)); |
| 3434 | // Two distinct function literals are incomparable -> error-null (-> null). |
| 3435 | assert_eq!( |
| 3436 | ev("{f: function(a) a, g: function(a) a, r: f = g}.r"), |
| 3437 | Value::Null |
| 3438 | ); |
| 3439 | } |
| 3440 | |
| 3441 | #[test] |
| 3442 | fn recursion_guard_returns_null_not_overflow() { |
| 3443 | // A self-applying function recurses unboundedly; the call-depth cap turns |
| 3444 | // that into an error-null (-> null) instead of a stack overflow (ADR-23). |
| 3445 | assert_eq!( |
| 3446 | ev("{apply: function(g, n) g(g, n), r: apply(apply, 1)}.r"), |
| 3447 | Value::Null |
| 3448 | ); |
| 3449 | } |
| 3450 | |
| 3451 | // --- typed formal parameters (FEEL rule 56, ADR-35) ---------------------- // |
| 3452 | |
| 3453 | #[test] |
| 3454 | fn typed_formal_params_parse_and_eval() { |
| 3455 | // A typed param `a: number` is semantically identical to bare `a` — the type |
| 3456 | // annotation is parsed and discarded in this slice (ADR-35). |
| 3457 | assert_eq!( |
| 3458 | ev("{f: function (a: number) 1 + a, r: f(2)}.r"), |
| 3459 | Value::Number(3.0) |
| 3460 | ); |
| 3461 | // Multiple typed params. |
| 3462 | assert_eq!( |
| 3463 | ev("{f: function (a: number, b: number) a * b, r: f(3, 4)}.r"), |
| 3464 | Value::Number(12.0) |
| 3465 | ); |
| 3466 | // Mixed typed and bare params — the parser accepts both in the same list. |
| 3467 | assert_eq!( |
| 3468 | ev("{f: function (a: number, b) a + b, r: f(10, 5)}.r"), |
| 3469 | Value::Number(15.0) |
| 3470 | ); |
| 3471 | // A typed param with a generic type `function<number> -> number` (rule 56). |
| 3472 | assert_eq!( |
| 3473 | ev("{bkm: function (fn1: function<number> -> number) fn1(3), r: bkm(function (x: number) x + 1)}.r"), |
| 3474 | Value::Number(4.0) |
| 3475 | ); |
| 3476 | } |
| 3477 | |
| 3478 | #[test] |
| 3479 | fn typed_params_closure_and_currying() { |
| 3480 | // Typed params work with closures (closed-over var `base`). |
| 3481 | assert_eq!( |
| 3482 | ev("{base: 10, f: function (a: number) a * base, r: f(5)}.r"), |
| 3483 | Value::Number(50.0) |
| 3484 | ); |
| 3485 | // Curried closures: outer typed param `a` captured in inner lambda. |
| 3486 | assert_eq!( |
| 3487 | ev("{outer: function (a: number) function (b: number) a * b, step1: outer(3), r: step1(4)}.r"), |
| 3488 | Value::Number(12.0) |
| 3489 | ); |
| 3490 | // Three-level currying. |
| 3491 | assert_eq!( |
| 3492 | ev("{f: function (a: number) function (b: number) function (c: number) a + b + c, s1: f(1), s2: s1(2), r: s2(3)}.r"), |
| 3493 | Value::Number(6.0) |
| 3494 | ); |
| 3495 | } |
| 3496 | |
| 3497 | // --- first-class built-in function values (ADR-36) ----------------------- // |
| 3498 | |
| 3499 | #[test] |
| 3500 | fn builtin_as_first_class_value() { |
| 3501 | // A bare built-in name evaluates to a Function value when used as a value. |
| 3502 | assert!(matches!(ev("abs"), Value::Function(_))); |
| 3503 | assert!(matches!(ev("sqrt"), Value::Function(_))); |
| 3504 | // A context binding shadows the built-in (binding takes precedence). |
| 3505 | assert_eq!(ev("{abs: 42, r: abs}.r"), Value::Number(42.0)); |
| 3506 | } |
| 3507 | |
| 3508 | #[test] |
| 3509 | fn builtin_passed_as_argument_and_invoked() { |
| 3510 | // A built-in can be passed as a lambda argument and invoked via the param. |
| 3511 | assert_eq!( |
| 3512 | ev("{bkm: function (fn1, fn2) fn1(-5) * fn2(25), r: bkm(abs, sqrt)}.r"), |
| 3513 | Value::Number(25.0) |
| 3514 | ); |
| 3515 | // A built-in with wrong arity -> error-null -> null (lenient). |
| 3516 | assert_eq!( |
| 3517 | ev("{bkm: function (fn1) fn1(10, 2), r: bkm(sqrt)}.r"), |
| 3518 | Value::Null |
| 3519 | ); |
| 3520 | } |
| 3521 | |
| 3522 | // --- higher-order built-ins: sort + matching list replace (ADR-37) -------- // |
| 3523 | |
| 3524 | fn num(v: f64) -> Value { |
| 3525 | Value::Number(v) |
| 3526 | } |
| 3527 | fn str_val(v: &str) -> Value { |
| 3528 | Value::String(v.into()) |
| 3529 | } |
| 3530 | |
| 3531 | #[test] |
| 3532 | fn sort_ascending_descending() { |
| 3533 | // Numeric ascending. |
| 3534 | assert_eq!( |
| 3535 | ev("sort([3,1,4,5,2], function(x,y) x<y)"), |
| 3536 | Value::List(vec![num(1.0), num(2.0), num(3.0), num(4.0), num(5.0)]) |
| 3537 | ); |
| 3538 | // Numeric descending (0013-sort sort1: sort(listA, function(x,y) x>y)). |
| 3539 | assert_eq!( |
| 3540 | ev("sort([3,1,5,4], function(x,y) x>y)"), |
| 3541 | Value::List(vec![num(5.0), num(4.0), num(3.0), num(1.0)]) |
| 3542 | ); |
| 3543 | // String ascending (basic latin). |
| 3544 | assert_eq!( |
| 3545 | ev(r#"sort(["c","a","b"], function(x,y) x<y)"#), |
| 3546 | Value::List(vec![str_val("a"), str_val("b"), str_val("c")]) |
| 3547 | ); |
| 3548 | // Empty list. |
| 3549 | assert_eq!(ev("sort([], function(x,y) x<y)"), Value::List(vec![])); |
| 3550 | // Single-element list. |
| 3551 | assert_eq!( |
| 3552 | ev("sort([42], function(x,y) x<y)"), |
| 3553 | Value::List(vec![num(42.0)]) |
| 3554 | ); |
| 3555 | } |
| 3556 | |
| 3557 | #[test] |
| 3558 | fn sort_by_context_field() { |
| 3559 | // Sort contexts by a numeric field — mirrors 0013-sort sort2. |
| 3560 | assert_eq!( |
| 3561 | ev("{t: sort([{v:3},{v:1},{v:2}], function(x,y) x.v < y.v), r: t[1].v}.r"), |
| 3562 | num(1.0) |
| 3563 | ); |
| 3564 | } |
| 3565 | |
| 3566 | #[test] |
| 3567 | fn sort_stable() { |
| 3568 | // Elements comparing equal (precedes returns false both ways) must stay in |
| 3569 | // their original relative order (stable sort). |
| 3570 | assert_eq!( |
| 3571 | ev("sort([1,1,2], function(x,y) x<y)"), |
| 3572 | Value::List(vec![num(1.0), num(1.0), num(2.0)]) |
| 3573 | ); |
| 3574 | } |
| 3575 | |
| 3576 | #[test] |
| 3577 | fn sort_named_args() { |
| 3578 | // Named-argument form: sort(list: …, precedes: …). |
| 3579 | assert_eq!( |
| 3580 | ev("sort(list: [3,1,2], precedes: function(x,y) x<y)"), |
| 3581 | Value::List(vec![num(1.0), num(2.0), num(3.0)]) |
| 3582 | ); |
| 3583 | } |
| 3584 | |
| 3585 | #[test] |
| 3586 | fn sort_as_first_class_builtin() { |
| 3587 | // `sort` can be referenced as a first-class value and passed around. |
| 3588 | assert!(matches!(ev("sort"), Value::Function(_))); |
| 3589 | } |
| 3590 | |
| 3591 | #[test] |
| 3592 | fn sort_error_cases() { |
| 3593 | // Null list -> null (value-null from sort_fn). |
| 3594 | assert_eq!(ev("sort(null, function(x,y) x<y)"), Value::Null); |
| 3595 | // Non-list first arg -> error-null -> null (lenient). |
| 3596 | assert_eq!(ev("sort(1, function(x,y) x<y)"), Value::Null); |
| 3597 | // Non-function second arg -> error-null -> null. |
| 3598 | assert_eq!(ev("sort([1,2], 3)"), Value::Null); |
| 3599 | // Closure with wrong arity (1 param instead of 2) -> error-null -> null. |
| 3600 | assert_eq!(ev("sort([1,2], function(x) x)"), Value::Null); |
| 3601 | // Comparator returning non-boolean -> error-null -> null. |
| 3602 | assert_eq!(ev("sort([1,2], function(x,y) null)"), Value::Null); |
| 3603 | } |
| 3604 | |
| 3605 | #[test] |
| 3606 | fn sort_higher_order_closure_over_input() { |
| 3607 | // 0092-017: comparator closes over an input value. |
| 3608 | assert_eq!( |
| 3609 | ev(r#"{input_017_1: "a", bkm: function (fn1) sort(["a","z","a","z"], fn1), r: bkm(function (a: string, b: string) if a = input_017_1 then true else false)}.r"#), |
| 3610 | Value::List(vec![str_val("a"), str_val("a"), str_val("z"), str_val("z")]) |
| 3611 | ); |
| 3612 | // 0092-018: BKM passed as the comparator. |
| 3613 | assert_eq!( |
| 3614 | ev(r#"{bkm_018: function (p1, p2) if p1 = "a" then true else false, r: sort(["a","z","a","z"], bkm_018)}.r"#), |
| 3615 | Value::List(vec![str_val("a"), str_val("a"), str_val("z"), str_val("z")]) |
| 3616 | ); |
| 3617 | } |
| 3618 | |
| 3619 | #[test] |
| 3620 | fn list_replace_matching_form() { |
| 3621 | // Replace items where match(item, newItem) returns true. |
| 3622 | assert_eq!( |
| 3623 | ev("list replace([2,4,7,8], function(item,newItem) item<newItem, 5)"), |
| 3624 | Value::List(vec![num(5.0), num(5.0), num(7.0), num(8.0)]) |
| 3625 | ); |
| 3626 | // All items match. |
| 3627 | assert_eq!( |
| 3628 | ev("list replace([1,2,3], function(item,newItem) true, 5)"), |
| 3629 | Value::List(vec![num(5.0), num(5.0), num(5.0)]) |
| 3630 | ); |
| 3631 | // No items match. |
| 3632 | assert_eq!( |
| 3633 | ev("list replace([1,2,3], function(item,newItem) false, 5)"), |
| 3634 | Value::List(vec![num(1.0), num(2.0), num(3.0)]) |
| 3635 | ); |
| 3636 | } |
| 3637 | |
| 3638 | #[test] |
| 3639 | fn list_replace_matching_named_args() { |
| 3640 | // Named `match:` overload (1155 test 117). |
| 3641 | assert_eq!( |
| 3642 | ev("list replace(match: function(item, newItem) item = 2, newItem: 4, list: [1,2,3])"), |
| 3643 | Value::List(vec![num(1.0), num(4.0), num(3.0)]) |
| 3644 | ); |
| 3645 | } |
| 3646 | |
| 3647 | #[test] |
| 3648 | fn list_replace_matching_error_cases() { |
| 3649 | // Comparator returning a non-boolean value -> error-null -> null (1155 test 165). |
| 3650 | assert_eq!( |
| 3651 | ev("list replace([2,4], function(item,newItem) item, 5)"), |
| 3652 | Value::Null |
| 3653 | ); |
| 3654 | // Closure with 3 params instead of 2 -> error-null -> null (1155 test 149). |
| 3655 | assert_eq!( |
| 3656 | ev("list replace([2,4], function(item,newItem,extra) item=2, 5)"), |
| 3657 | Value::Null |
| 3658 | ); |
| 3659 | // Closure with 1 param instead of 2 -> error-null -> null (1155 test 157). |
| 3660 | assert_eq!( |
| 3661 | ev("list replace([2,4], function(item) item=2, 5)"), |
| 3662 | Value::Null |
| 3663 | ); |
| 3664 | } |
| 3665 | |
| 3666 | // --- value-invocation of a non-function → null (ADR-38, 1131) ----------- // |
| 3667 | |
| 3668 | #[test] |
| 3669 | fn invoke_non_function_yields_null() { |
| 3670 | // unknown name → error-null (FnCall path, unchanged) |
| 3671 | assert_eq!(ev("non_existing_function()"), Value::Null); |
| 3672 | // null, string, number, boolean, date — all non-functions → null |
| 3673 | assert_eq!(ev("null()"), Value::Null); |
| 3674 | assert_eq!(ev("\"some_func\"()"), Value::Null); |
| 3675 | assert_eq!(ev("\"abs\"(-1)"), Value::Null); |
| 3676 | assert_eq!(ev("123()"), Value::Null); |
| 3677 | assert_eq!(ev("true()"), Value::Null); |
| 3678 | assert_eq!(ev("false()"), Value::Null); |
| 3679 | assert_eq!(ev("@\"2023-11-11\"()"), Value::Null); |
| 3680 | // Named calls to built-ins must be unaffected (FnCall path still works). |
| 3681 | assert_eq!(ev("abs(-1)"), Value::Number(1.0)); |
| 3682 | assert_eq!(ev("abs(n: -2)"), Value::Number(2.0)); |
| 3683 | } |
| 3684 | |
| 3685 | // --- host callables (ForeignFunction) ------------------------------------ // |
| 3686 | |
| 3687 | /// A host function that sums all of its numeric arguments (positional + named), |
| 3688 | /// so the tests can exercise both argument forms crossing the seam. |
| 3689 | #[derive(Debug)] |
| 3690 | struct SumFn; |
| 3691 | impl ForeignFunction for SumFn { |
| 3692 | fn call(&self, args: Args) -> Value { |
| 3693 | let mut total = 0.0; |
| 3694 | for v in args.positional { |
| 3695 | if let Value::Number(n) = v.forced() { |
| 3696 | total += n; |
| 3697 | } |
| 3698 | } |
| 3699 | for (_, v) in args.named { |
| 3700 | if let Value::Number(n) = v.forced() { |
| 3701 | total += n; |
| 3702 | } |
| 3703 | } |
| 3704 | Value::Number(total) |
| 3705 | } |
| 3706 | fn as_any(&self) -> &dyn std::any::Any { |
| 3707 | self |
| 3708 | } |
| 3709 | } |
| 3710 | |
| 3711 | fn host_fn(f: impl ForeignFunction + 'static) -> Value { |
| 3712 | Value::Function(Arc::new(Func::Foreign(Arc::new(f)))) |
| 3713 | } |
| 3714 | |
| 3715 | #[test] |
| 3716 | fn host_function_as_context_value() { |
| 3717 | let mut ctx = Context::empty(); |
| 3718 | ctx.insert("add", host_fn(SumFn)); |
| 3719 | let run = |src: &str| evaluate(src, &ctx).unwrap().into_lenient(); |
| 3720 | assert_eq!(run("add(2, 3)"), Value::Number(5.0)); |
| 3721 | // Named args reach the host too (here name-agnostic, summed). |
| 3722 | assert_eq!(run("add(x: 2, y: 3)"), Value::Number(5.0)); |
| 3723 | // Mixed positional + named. |
| 3724 | assert_eq!(run("add(2, y: 3)"), Value::Number(5.0)); |
| 3725 | } |
| 3726 | |
| 3727 | /// A host registry exposing `add` as an ambient function (the second injection |
| 3728 | /// path beside a context binding; ADR-23). |
| 3729 | struct Registry; |
| 3730 | impl FunctionRegistry for Registry { |
| 3731 | fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> { |
| 3732 | (name == "add").then(|| Arc::new(SumFn) as Arc<dyn ForeignFunction>) |
| 3733 | } |
| 3734 | } |
| 3735 | |
| 3736 | #[test] |
| 3737 | fn host_function_via_registry() { |
| 3738 | let compiled = compile("add(2, 3, 4)").unwrap(); |
| 3739 | let env = |
| 3740 | EvalEnv::with_functions(&crate::regex_provider::DEFAULT, default_now(), &Registry); |
| 3741 | let r = compiled |
| 3742 | .evaluate_with_env(&Context::empty(), &env) |
| 3743 | .unwrap() |
| 3744 | .into_lenient(); |
| 3745 | assert_eq!(r, Value::Number(9.0)); |
| 3746 | } |
| 3747 | |
| 3748 | /// A counting foreign *object*, to prove a closure's arguments stay unforced so |
| 3749 | /// path access inside the body remains lazy (ADR-21). |
| 3750 | #[derive(Debug)] |
| 3751 | struct CountObj { |
| 3752 | gets: Arc<AtomicUsize>, |
| 3753 | forces: Arc<AtomicUsize>, |
| 3754 | } |
| 3755 | impl crate::foreign::ForeignObject for CountObj { |
| 3756 | fn get(&self, key: &str) -> Value { |
| 3757 | self.gets.fetch_add(1, AtomicOrdering::SeqCst); |
| 3758 | if key == "x" { |
| 3759 | Value::Number(99.0) |
| 3760 | } else { |
| 3761 | Value::Null |
| 3762 | } |
| 3763 | } |
| 3764 | fn force(&self) -> Value { |
| 3765 | self.forces.fetch_add(1, AtomicOrdering::SeqCst); |
| 3766 | Value::Null |
| 3767 | } |
| 3768 | fn as_any(&self) -> &dyn std::any::Any { |
| 3769 | self |
| 3770 | } |
| 3771 | } |
| 3772 | |
| 3773 | #[test] |
| 3774 | fn closure_arguments_stay_unforced() { |
| 3775 | let gets = Arc::new(AtomicUsize::new(0)); |
| 3776 | let forces = Arc::new(AtomicUsize::new(0)); |
| 3777 | let o = Value::Foreign(crate::foreign::Foreign(Arc::new(CountObj { |
| 3778 | gets: gets.clone(), |
| 3779 | forces: forces.clone(), |
| 3780 | }))); |
| 3781 | let mut ctx = Context::empty(); |
| 3782 | ctx.insert("o", o); |
| 3783 | // `f(o)` binds the foreign object to `p` unforced; the body navigates `p.x` |
| 3784 | // via a single `get`, never forcing the whole object. |
| 3785 | let r = evaluate("{f: function(p) p.x, r: f(o)}.r", &ctx) |
| 3786 | .unwrap() |
| 3787 | .into_lenient(); |
| 3788 | assert_eq!(r, Value::Number(99.0)); |
| 3789 | assert_eq!(gets.load(AtomicOrdering::SeqCst), 1); |
| 3790 | assert_eq!(forces.load(AtomicOrdering::SeqCst), 0); |
| 3791 | } |
| 3792 | } |