Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

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>
Changeset49b54c2fdc40862cd58cff0007cd97c9ae9f3bef
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents610385640ac0
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/builtins.rs +23 −5

@@ -25,7 +25,7 @@
2525
 
2626
 use crate::eval::{as_number, feel_order};
2727
 use crate::regex_provider::{match_value, FeelRegex};
28
-use crate::Value;
28
+use crate::{EvalEnv, Value};
2929
 
3030
 /// Built-in function names that contain a *keyword* word-part, which Tier-1
3131
 /// whitespace joining in the lexer cannot form (a keyword is a separate token
@@ -37,12 +37,14 @@
3737
 pub(crate) const KEYWORD_PHRASE_BUILTINS: &[&str] = &["date and time", "years and months duration"];
3838
 
3939
 /// 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 {
4243
     // A type error in any (top-level) argument propagates as an error-null.
4344
     if args.iter().any(|a| matches!(a, Value::Error)) {
4445
         return Value::Error;
4546
     }
47
+    let regex = env.regex;
4648
     match name {
4749
         // --- conversion ---
4850
         "string" => string_fn(args),
@@ -104,8 +106,24 @@
104106
         "even" => even_odd_fn(args, true),
105107
         "odd" => even_odd_fn(args, false),
106108
 
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
109127
     }
110128
 }
111129
 

modified crates/feel-core/src/eval.rs +8 −8

@@ -11,17 +11,17 @@
1111
 use std::collections::BTreeMap;
1212
 
1313
 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};
1615
 
1716
 type EvalResult = Result<Value, FeelError>;
1817
 
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.
2323
 pub(crate) struct Evaluator<'a> {
24
-    pub(crate) regex: &'a dyn FeelRegex,
24
+    pub(crate) env: &'a EvalEnv<'a>,
2525
 }
2626
 
2727
 impl Evaluator<'_> {
@@ -62,7 +62,7 @@
6262
                 for arg in args {
6363
                     vals.push(self.eval(arg, ctx)?);
6464
                 }
65
-                Ok(crate::builtins::call(name, vals, self.regex))
65
+                Ok(crate::builtins::call(name, vals, self.env))
6666
             }
6767
 
6868
             // --- arithmetic ---

modified crates/feel-core/src/lib.rs +72 −7

@@ -16,6 +16,7 @@
1616
 pub use regex_provider::FeelRegex;
1717
 pub use temporal::temporal_from_iso;
1818
 pub use value::Value;
19
+// `EvalEnv` is defined below; re-stated here for discoverability via the crate root.
1920
 
2021
 /// The Rust `regex` engine as a [`FeelRegex`] provider (available when the
2122
 /// default `rust-regex` feature is on). Wrappers that bring their own host engine
@@ -94,23 +95,62 @@
9495
 impl CompiledExpr {
9596
     /// Evaluate this already-parsed expression against a context, using the
9697
     /// 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()`.
98100
     pub fn evaluate(&self, context: &Context) -> Result<Value, FeelError> {
99101
         self.evaluate_with(context, &regex_provider::DEFAULT)
100102
     }
101103
 
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()`.
103106
     ///
104107
     /// This is the seam for host-environment regex dialects (ADR-16): only the
105108
     /// `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`].
107112
     pub fn evaluate_with(
108113
         &self,
109114
         context: &Context,
110115
         regex: &dyn FeelRegex,
111116
     ) -> 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()
114154
 }
115155
 
116156
 /// Parse a FEEL expression into a reusable [`CompiledExpr`] without evaluating it.
@@ -684,8 +724,33 @@
684724
         assert_eq!(ev(r#"number("1.1")"#), num(1.1));
685725
         assert_eq!(ev(r#"number("1,000.0", ",", ".")"#), num(1000.0));
686726
 
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(&regex_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()));
689754
     }
690755
 
691756
     #[test]

modified crates/feel-core/src/temporal.rs +24 −1

@@ -17,7 +17,7 @@
1717
 
1818
 use jiff::civil::{self, Weekday};
1919
 use jiff::tz::{Offset, TimeZone};
20
-use jiff::{SignedDuration, Span};
20
+use jiff::{SignedDuration, Span, Zoned};
2121
 
2222
 use crate::ast::ArithOp;
2323
 use crate::Value;
@@ -708,3 +708,26 @@
708708
         _ => Value::Null,
709709
     }
710710
 }
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
+}