feat(core): inject evaluation clock via EvalEnv; implement now()/today() (ADR-18)
public
feat(core): inject evaluation clock via EvalEnv; implement now()/today() (ADR-18) Generalize the regex-provider seam (ADR-16) into an `EvalEnv` carrying both the host regex provider and the instant `now()`/`today()` read. `CompiledExpr` gains `evaluate_with_env`; the existing `evaluate`/ `evaluate_with` build a default env from the wall clock. `now()` returns that instant as a date and time, `today()` its date. Reading an injected instant (instead of the wall clock) lets feel-pg pin it to the transaction start and makes the builtins deterministic in tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
| Changeset | 49b54c2fdc40862cd58cff0007cd97c9ae9f3bef |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 610385640ac0 |
| Children | |
| Pushlog | by timo via ssh |
modified crates/feel-core/src/builtins.rs +23 −5
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | |
| 26 | 26 | use crate::eval::{as_number, feel_order}; |
| 27 | 27 | use crate::regex_provider::{match_value, FeelRegex}; |
| 28 | -use crate::Value; | |
| 28 | +use crate::{EvalEnv, Value}; | |
| 29 | 29 | |
| 30 | 30 | /// Built-in function names that contain a *keyword* word-part, which Tier-1 |
| 31 | 31 | /// whitespace joining in the lexer cannot form (a keyword is a separate token |
| @@ -37,12 +37,14 @@ | ||
| 37 | 37 | pub(crate) const KEYWORD_PHRASE_BUILTINS: &[&str] = &["date and time", "years and months duration"]; |
| 38 | 38 | |
| 39 | 39 | /// Dispatch a single- or multi-word built-in call. Arguments are already |
| 40 | -/// evaluated. The `regex` provider is consulted only by `matches`/`replace`/`split`. | |
| 41 | -pub(crate) fn call(name: &str, args: Vec<Value>, regex: &dyn FeelRegex) -> Value { | |
| 40 | +/// evaluated. The `env` carries the regex provider (consulted only by | |
| 41 | +/// `matches`/`replace`/`split`) and the instant `now()`/`today()` read (ADR-18). | |
| 42 | +pub(crate) fn call(name: &str, args: Vec<Value>, env: &EvalEnv) -> Value { | |
| 42 | 43 | // A type error in any (top-level) argument propagates as an error-null. |
| 43 | 44 | if args.iter().any(|a| matches!(a, Value::Error)) { |
| 44 | 45 | return Value::Error; |
| 45 | 46 | } |
| 47 | + let regex = env.regex; | |
| 46 | 48 | match name { |
| 47 | 49 | // --- conversion --- |
| 48 | 50 | "string" => string_fn(args), |
| @@ -104,8 +106,24 @@ | ||
| 104 | 106 | "even" => even_odd_fn(args, true), |
| 105 | 107 | "odd" => even_odd_fn(args, false), |
| 106 | 108 | |
| 107 | - // Unknown / unimplemented (multi-word, temporal, user-defined) call. | |
| 108 | - _ => Value::Error, | |
| 109 | + // --- temporal clock (ADR-18) — read the injected instant, not the wall | |
| 110 | + // clock, so feel-pg can pin it to the transaction start and tests are | |
| 111 | + // deterministic. --- | |
| 112 | + "now" => nullary(args, || crate::temporal::now_value(&env.now)), | |
| 113 | + "today" => nullary(args, || crate::temporal::today_value(&env.now)), | |
| 114 | + | |
| 115 | + // Unknown / unimplemented (temporal constructors, user-defined) call. | |
| 116 | + _ => Value::Error, | |
| 117 | + } | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// A nullary builtin: produce the value when called with no arguments, else an | |
| 121 | +/// arity error-null. | |
| 122 | +fn nullary(args: Vec<Value>, f: impl FnOnce() -> Value) -> Value { | |
| 123 | + if args.is_empty() { | |
| 124 | + f() | |
| 125 | + } else { | |
| 126 | + Value::Error | |
| 109 | 127 | } |
| 110 | 128 | } |
| 111 | 129 | |
modified crates/feel-core/src/eval.rs +8 −8
| @@ -11,17 +11,17 @@ | ||
| 11 | 11 | use std::collections::BTreeMap; |
| 12 | 12 | |
| 13 | 13 | use crate::ast::{ArithOp, CmpOp, Expr, Interval, IterSource, Quantifier}; |
| 14 | -use crate::regex_provider::FeelRegex; | |
| 15 | -use crate::{temporal, Context, FeelError, Value}; | |
| 14 | +use crate::{temporal, Context, EvalEnv, FeelError, Value}; | |
| 16 | 15 | |
| 17 | 16 | type EvalResult = Result<Value, FeelError>; |
| 18 | 17 | |
| 19 | -/// A tree-walking evaluator carrying the host regex provider (ADR-16). The | |
| 20 | -/// provider is held by reference and only consulted by the three regex builtins; | |
| 21 | -/// it is **not** part of [`Context`] (which is cloned per loop iteration and | |
| 22 | -/// compared with `PartialEq`), so threading it here keeps those cheap. | |
| 18 | +/// A tree-walking evaluator carrying the evaluation environment (host regex | |
| 19 | +/// provider + `now()`/`today()` instant; ADR-16/ADR-18). The env is held by | |
| 20 | +/// reference and is **not** part of [`Context`] (which is cloned per loop | |
| 21 | +/// iteration and compared with `PartialEq`), so threading it here keeps those | |
| 22 | +/// cheap. | |
| 23 | 23 | pub(crate) struct Evaluator<'a> { |
| 24 | - pub(crate) regex: &'a dyn FeelRegex, | |
| 24 | + pub(crate) env: &'a EvalEnv<'a>, | |
| 25 | 25 | } |
| 26 | 26 | |
| 27 | 27 | impl Evaluator<'_> { |
| @@ -62,7 +62,7 @@ | ||
| 62 | 62 | for arg in args { |
| 63 | 63 | vals.push(self.eval(arg, ctx)?); |
| 64 | 64 | } |
| 65 | - Ok(crate::builtins::call(name, vals, self.regex)) | |
| 65 | + Ok(crate::builtins::call(name, vals, self.env)) | |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | 68 | // --- arithmetic --- |
modified crates/feel-core/src/lib.rs +72 −7
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | pub use regex_provider::FeelRegex; |
| 17 | 17 | pub use temporal::temporal_from_iso; |
| 18 | 18 | pub use value::Value; |
| 19 | +// `EvalEnv` is defined below; re-stated here for discoverability via the crate root. | |
| 19 | 20 | |
| 20 | 21 | /// The Rust `regex` engine as a [`FeelRegex`] provider (available when the |
| 21 | 22 | /// default `rust-regex` feature is on). Wrappers that bring their own host engine |
| @@ -94,23 +95,62 @@ | ||
| 94 | 95 | impl CompiledExpr { |
| 95 | 96 | /// Evaluate this already-parsed expression against a context, using the |
| 96 | 97 | /// default regex provider (`RustRegex` with the `rust-regex` feature on, |
| 97 | - /// otherwise a no-op provider whose regex builtins yield an error-null). | |
| 98 | + /// otherwise a no-op provider whose regex builtins yield an error-null) and | |
| 99 | + /// the wall-clock instant for `now()`/`today()`. | |
| 98 | 100 | pub fn evaluate(&self, context: &Context) -> Result<Value, FeelError> { |
| 99 | 101 | self.evaluate_with(context, ®ex_provider::DEFAULT) |
| 100 | 102 | } |
| 101 | 103 | |
| 102 | - /// Evaluate against a context using a caller-supplied [`FeelRegex`] provider. | |
| 104 | + /// Evaluate against a context using a caller-supplied [`FeelRegex`] provider, | |
| 105 | + /// with the wall-clock instant for `now()`/`today()`. | |
| 103 | 106 | /// |
| 104 | 107 | /// This is the seam for host-environment regex dialects (ADR-16): only the |
| 105 | 108 | /// `matches`/`replace`/`split` builtins consult `regex`; every other result |
| 106 | - /// is identical regardless of provider. | |
| 109 | + /// is identical regardless of provider. To also control the evaluation | |
| 110 | + /// instant (e.g. a transaction timestamp, or a fixed instant in tests) use | |
| 111 | + /// [`CompiledExpr::evaluate_with_env`]. | |
| 107 | 112 | pub fn evaluate_with( |
| 108 | 113 | &self, |
| 109 | 114 | context: &Context, |
| 110 | 115 | regex: &dyn FeelRegex, |
| 111 | 116 | ) -> Result<Value, FeelError> { |
| 112 | - eval::Evaluator { regex }.eval(&self.0, context) | |
| 113 | - } | |
| 117 | + self.evaluate_with_env(context, &EvalEnv::new(regex, default_now())) | |
| 118 | + } | |
| 119 | + | |
| 120 | + /// Evaluate against a context using a fully caller-supplied [`EvalEnv`] | |
| 121 | + /// (regex provider + the instant `now()`/`today()` read; ADR-18). The | |
| 122 | + /// wrappers inject their host's clock here (e.g. feel-pg's transaction start), | |
| 123 | + /// which also makes `now()`/`today()` deterministic in tests. | |
| 124 | + pub fn evaluate_with_env( | |
| 125 | + &self, | |
| 126 | + context: &Context, | |
| 127 | + env: &EvalEnv, | |
| 128 | + ) -> Result<Value, FeelError> { | |
| 129 | + eval::Evaluator { env }.eval(&self.0, context) | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// The evaluation environment threaded through the engine: the host regex | |
| 134 | +/// provider (ADR-16) plus the instant `now()`/`today()` read (ADR-18). Held by | |
| 135 | +/// reference during evaluation (never cloned per loop iteration), so building one | |
| 136 | +/// is cheap and the clock is fixed for the whole evaluation. | |
| 137 | +pub struct EvalEnv<'a> { | |
| 138 | + /// The host regex provider consulted by `matches`/`replace`/`split`. | |
| 139 | + pub regex: &'a dyn FeelRegex, | |
| 140 | + /// The instant `now()` returns (and whose date `today()` returns). | |
| 141 | + pub now: jiff::Zoned, | |
| 142 | +} | |
| 143 | + | |
| 144 | +impl<'a> EvalEnv<'a> { | |
| 145 | + /// Build an environment from a regex provider and an evaluation instant. | |
| 146 | + pub fn new(regex: &'a dyn FeelRegex, now: jiff::Zoned) -> Self { | |
| 147 | + Self { regex, now } | |
| 148 | + } | |
| 149 | +} | |
| 150 | + | |
| 151 | +/// The default evaluation instant: the system wall clock in the system zone. | |
| 152 | +fn default_now() -> jiff::Zoned { | |
| 153 | + jiff::Zoned::now() | |
| 114 | 154 | } |
| 115 | 155 | |
| 116 | 156 | /// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it. |
| @@ -684,8 +724,33 @@ | ||
| 684 | 724 | assert_eq!(ev(r#"number("1.1")"#), num(1.1)); |
| 685 | 725 | assert_eq!(ev(r#"number("1,000.0", ",", ".")"#), num(1000.0)); |
| 686 | 726 | |
| 687 | - // --- unknown / out-of-scope function -> null (error-null, lenient) --- | |
| 688 | - assert_eq!(ev("now()"), Value::Null); // temporal, not yet implemented | |
| 727 | + // --- temporal clock builtins return temporal values (ADR-18) --- | |
| 728 | + assert!(matches!(ev("now()"), Value::DateTime(_))); | |
| 729 | + assert!(matches!(ev("today()"), Value::Date(_))); | |
| 730 | + assert_eq!(ev("now(1)"), Value::Null); // wrong arity -> null | |
| 731 | + } | |
| 732 | + | |
| 733 | + #[test] | |
| 734 | + fn now_today_use_injected_clock() { | |
| 735 | + // `now()`/`today()` read the injected instant, so they are deterministic | |
| 736 | + // and (in feel-pg) can be pinned to the transaction start (ADR-18). | |
| 737 | + let z = jiff::civil::date(2024, 3, 10) | |
| 738 | + .at(12, 0, 0, 0) | |
| 739 | + .to_zoned(jiff::tz::TimeZone::get("America/New_York").unwrap()) | |
| 740 | + .unwrap(); | |
| 741 | + let env = EvalEnv::new(®ex_provider::DEFAULT, z); | |
| 742 | + let eval = |src: &str| { | |
| 743 | + compile(src) | |
| 744 | + .unwrap() | |
| 745 | + .evaluate_with_env(&Context::empty(), &env) | |
| 746 | + .unwrap() | |
| 747 | + .into_lenient() | |
| 748 | + }; | |
| 749 | + assert_eq!( | |
| 750 | + eval("string(now())"), | |
| 751 | + Value::String("2024-03-10T12:00:00@America/New_York".into()) | |
| 752 | + ); | |
| 753 | + assert_eq!(eval("string(today())"), Value::String("2024-03-10".into())); | |
| 689 | 754 | } |
| 690 | 755 | |
| 691 | 756 | #[test] |
modified crates/feel-core/src/temporal.rs +24 −1
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | use jiff::civil::{self, Weekday}; |
| 19 | 19 | use jiff::tz::{Offset, TimeZone}; |
| 20 | -use jiff::{SignedDuration, Span}; | |
| 20 | +use jiff::{SignedDuration, Span, Zoned}; | |
| 21 | 21 | |
| 22 | 22 | use crate::ast::ArithOp; |
| 23 | 23 | use crate::Value; |
| @@ -708,3 +708,26 @@ | ||
| 708 | 708 | _ => Value::Null, |
| 709 | 709 | } |
| 710 | 710 | } |
| 711 | + | |
| 712 | +// --------------------------------------------------------------------------- // | |
| 713 | +// Clock — `now()` / `today()` from an injected instant (ADR-18) | |
| 714 | +// --------------------------------------------------------------------------- // | |
| 715 | + | |
| 716 | +/// `now()` as a FEEL `date and time`, taken from the injected evaluation instant. | |
| 717 | +pub(crate) fn now_value(z: &Zoned) -> Value { | |
| 718 | + Value::DateTime(DateTime { dt: z.datetime(), zone: zone_from_zoned(z) }) | |
| 719 | +} | |
| 720 | + | |
| 721 | +/// `today()` as a FEEL `date`, taken from the injected evaluation instant. | |
| 722 | +pub(crate) fn today_value(z: &Zoned) -> Value { | |
| 723 | + Value::Date(z.date()) | |
| 724 | +} | |
| 725 | + | |
| 726 | +/// The [`Zone`] of an injected instant: its IANA name if it has one, else its | |
| 727 | +/// fixed offset. | |
| 728 | +fn zone_from_zoned(z: &Zoned) -> Option<Zone> { | |
| 729 | + match z.time_zone().iana_name() { | |
| 730 | + Some(name) => Some(Zone::Named(name.to_string())), | |
| 731 | + None => Some(Zone::Offset(z.offset())), | |
| 732 | + } | |
| 733 | +} | |