Public repository: timo / feel

Reader

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

feat(core): temporal constructor & component built-in functions (ADR-18)

public

feat(core): temporal constructor & component built-in functions (ADR-18)

Implement the remaining temporal builtins:
- constructors: date / time / date and time / duration /
  years and months duration, with their arity overloads (string,
  components, from-temporal, date+time, two-dates)
- components: day of week / month of year (names), day of year /
  week of year (numbers)
- extend abs() to durations (ADR-15 had deferred this)

Null arguments propagate to a value-null (the TCK expects nil, e.g.
date(2017, null, 1) = null); wrong types / out-of-range components are
error-nulls. Update the two ADR-17 placeholder tests now that
`date and time(...)` actually evaluates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changeset2c1d27ba863e4841fccbdac77364e1543b253189
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents49b54c2fdc40
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/builtins.rs +173 −3

@@ -112,7 +112,18 @@
112112
         "now" => nullary(args, || crate::temporal::now_value(&env.now)),
113113
         "today" => nullary(args, || crate::temporal::today_value(&env.now)),
114114
 
115
-        // Unknown / unimplemented (temporal constructors, user-defined) call.
115
+        // --- temporal constructors & component functions (ADR-18) ---
116
+        "date" => date_fn(args),
117
+        "time" => time_fn(args),
118
+        "date and time" => date_and_time_fn(args),
119
+        "duration" => duration_fn(args),
120
+        "years and months duration" => years_and_months_duration_fn(args),
121
+        "day of week" => component_str_fn(args, crate::temporal::day_of_week_name),
122
+        "month of year" => component_str_fn(args, crate::temporal::month_of_year_name),
123
+        "day of year" => component_num_fn(args, crate::temporal::day_of_year_num),
124
+        "week of year" => component_num_fn(args, crate::temporal::week_of_year_num),
125
+
126
+        // Unknown / unimplemented (user-defined) call.
116127
         _ => Value::Error,
117128
     }
118129
 }
@@ -124,6 +135,161 @@
124135
         f()
125136
     } else {
126137
         Value::Error
138
+    }
139
+}
140
+
141
+// --------------------------------------------------------------------------- //
142
+// Temporal constructors & component functions (ADR-18)
143
+// --------------------------------------------------------------------------- //
144
+//
145
+// Null-propagation rule: a `null` argument yields a value-null (the TCK expects a
146
+// nil result, e.g. `date(2017, null, 1) = null`); a wrong type or out-of-range
147
+// component is an error-null. Both collapse to `null` at the lenient boundary.
148
+
149
+/// An integer component argument: a number with no fractional part, a (value-)null,
150
+/// or a wrong type.
151
+enum IntArg {
152
+    Int(i64),
153
+    Null,
154
+    Err,
155
+}
156
+
157
+fn int_arg(v: &Value) -> IntArg {
158
+    match v {
159
+        Value::Number(n) if n.fract() == 0.0 => IntArg::Int(*n as i64),
160
+        Value::Null => IntArg::Null,
161
+        _ => IntArg::Err,
162
+    }
163
+}
164
+
165
+/// A seconds component: an integer-or-fractional number (split into whole seconds
166
+/// and nanoseconds), a null, or a wrong type.
167
+enum SecArg {
168
+    Sec(i64, i64),
169
+    Null,
170
+    Err,
171
+}
172
+
173
+fn sec_arg(v: &Value) -> SecArg {
174
+    match v {
175
+        Value::Number(n) => {
176
+            let whole = n.trunc() as i64;
177
+            let nanos = ((n - n.trunc()) * 1e9).round() as i64;
178
+            SecArg::Sec(whole, nanos)
179
+        }
180
+        Value::Null => SecArg::Null,
181
+        _ => SecArg::Err,
182
+    }
183
+}
184
+
185
+fn date_fn(args: Vec<Value>) -> Value {
186
+    match args.as_slice() {
187
+        [Value::Null] => Value::Null,
188
+        [Value::String(s)] => crate::temporal::parse_date(s).map(Value::Date).unwrap_or(Value::Error),
189
+        [Value::Date(d)] => Value::Date(*d),
190
+        [Value::DateTime(dt)] => Value::Date(dt.dt.date()),
191
+        [y, m, d] => match (int_arg(y), int_arg(m), int_arg(d)) {
192
+            (IntArg::Null, _, _) | (_, IntArg::Null, _) | (_, _, IntArg::Null) => Value::Null,
193
+            (IntArg::Int(y), IntArg::Int(m), IntArg::Int(d)) => {
194
+                crate::temporal::make_date(y, m, d).map(Value::Date).unwrap_or(Value::Error)
195
+            }
196
+            _ => Value::Error,
197
+        },
198
+        _ => Value::Error,
199
+    }
200
+}
201
+
202
+fn time_fn(args: Vec<Value>) -> Value {
203
+    match args.as_slice() {
204
+        [Value::Null] => Value::Null,
205
+        [Value::String(s)] => crate::temporal::parse_time(s).map(Value::Time).unwrap_or(Value::Error),
206
+        [Value::Time(t)] => Value::Time(t.clone()),
207
+        [v @ Value::DateTime(_)] => {
208
+            crate::temporal::time_of(v).map(Value::Time).unwrap_or(Value::Error)
209
+        }
210
+        [h, m, s] => time_components(h, m, s, None),
211
+        [h, m, s, off] => match off {
212
+            Value::Null => Value::Null,
213
+            Value::DaysTimeDuration(d) => match crate::temporal::offset_zone_from_dtd(*d) {
214
+                Some(zone) => time_components(h, m, s, Some(zone)),
215
+                None => Value::Error,
216
+            },
217
+            _ => Value::Error,
218
+        },
219
+        _ => Value::Error,
220
+    }
221
+}
222
+
223
+fn time_components(h: &Value, m: &Value, s: &Value, zone: Option<crate::temporal::Zone>) -> Value {
224
+    match (int_arg(h), int_arg(m), sec_arg(s)) {
225
+        (IntArg::Null, _, _) | (_, IntArg::Null, _) | (_, _, SecArg::Null) => Value::Null,
226
+        (IntArg::Int(h), IntArg::Int(m), SecArg::Sec(s, nanos)) => {
227
+            crate::temporal::make_time(h, m, s, nanos, zone).map(Value::Time).unwrap_or(Value::Error)
228
+        }
229
+        _ => Value::Error,
230
+    }
231
+}
232
+
233
+fn date_and_time_fn(args: Vec<Value>) -> Value {
234
+    match args.as_slice() {
235
+        [Value::Null] => Value::Null,
236
+        [Value::String(s)] => {
237
+            crate::temporal::parse_date_time(s).map(Value::DateTime).unwrap_or(Value::Error)
238
+        }
239
+        [v @ Value::DateTime(_)] => v.clone(),
240
+        [a, b] => match (a, b) {
241
+            (Value::Null, _) | (_, Value::Null) => Value::Null,
242
+            (Value::Date(d), Value::Time(t)) => {
243
+                Value::DateTime(crate::temporal::combine_date_time(*d, t))
244
+            }
245
+            _ => Value::Error,
246
+        },
247
+        _ => Value::Error,
248
+    }
249
+}
250
+
251
+fn duration_fn(args: Vec<Value>) -> Value {
252
+    match args.as_slice() {
253
+        [Value::Null] => Value::Null,
254
+        [Value::String(s)] => crate::temporal::parse_duration(s).unwrap_or(Value::Error),
255
+        _ => Value::Error,
256
+    }
257
+}
258
+
259
+fn years_and_months_duration_fn(args: Vec<Value>) -> Value {
260
+    match args.as_slice() {
261
+        [a, b] => match (a, b) {
262
+            (Value::Null, _) | (_, Value::Null) => Value::Null,
263
+            _ => match (crate::temporal::date_of(a), crate::temporal::date_of(b)) {
264
+                (Some(x), Some(y)) => crate::temporal::ym_between(x, y)
265
+                    .map(Value::YearsMonthsDuration)
266
+                    .unwrap_or(Value::Error),
267
+                _ => Value::Error,
268
+            },
269
+        },
270
+        _ => Value::Error,
271
+    }
272
+}
273
+
274
+/// `day of week` / `month of year`: a string name from a date/date-and-time.
275
+fn component_str_fn(args: Vec<Value>, f: fn(jiff::civil::Date) -> &'static str) -> Value {
276
+    match args.as_slice() {
277
+        [Value::Null] => Value::Null,
278
+        [v] => crate::temporal::date_of(v)
279
+            .map(|d| Value::String(f(d).to_string()))
280
+            .unwrap_or(Value::Error),
281
+        _ => Value::Error,
282
+    }
283
+}
284
+
285
+/// `day of year` / `week of year`: a number from a date/date-and-time.
286
+fn component_num_fn(args: Vec<Value>, f: fn(jiff::civil::Date) -> i64) -> Value {
287
+    match args.as_slice() {
288
+        [Value::Null] => Value::Null,
289
+        [v] => crate::temporal::date_of(v)
290
+            .map(|d| Value::Number(f(d) as f64))
291
+            .unwrap_or(Value::Error),
292
+        _ => Value::Error,
127293
     }
128294
 }
129295
 
@@ -1002,8 +1168,12 @@
10021168
 fn abs_fn(args: Vec<Value>) -> Value {
10031169
     match args.as_slice() {
10041170
         [Value::Number(n)] => Value::Number(n.abs()),
1005
-        [Value::Null] => Value::Null,
1006
-        _ => Value::Error, // durations are temporal -> out of scope (ADR-15)
1171
+        // `abs` of a duration (ADR-18; ADR-15 had deferred this).
1172
+        [v @ (Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_))] => {
1173
+            crate::temporal::abs(v).unwrap_or(Value::Error)
1174
+        }
1175
+        [Value::Null] => Value::Null,
1176
+        _ => Value::Error,
10071177
     }
10081178
 }
10091179
 

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

@@ -544,13 +544,13 @@
544544
     #[test]
545545
     fn keyword_phrase_builtin_parses_in_call_position() {
546546
         // A keyword-containing builtin name (`date and time`) is recognised as one
547
-        // call head in call position — raw error-null until temporal types land,
548
-        // NOT `date and (time(...))` (ADR-17). Out of call position it stays the
547
+        // call head in call position and now evaluates (ADR-18), NOT as
548
+        // `date and (time(...))` (ADR-17). Out of call position it stays the
549549
         // boolean `and` (back-compat), so `date`/`time` unbound -> a value-null.
550
-        let raw = |src: &str| {
551
-            evaluate(src, &Context::empty()).unwrap_or_else(|e| panic!("`{src}` failed: {e}"))
552
-        };
553
-        assert_eq!(raw(r#"date and time("2018-12-08")"#), Value::Error);
550
+        assert_eq!(
551
+            ev(r#"string(date and time("2018-12-08"))"#),
552
+            Value::String("2018-12-08T00:00:00".into())
553
+        );
554554
         assert_eq!(ev("date and time"), Value::Null);
555555
     }
556556
 
@@ -731,6 +731,47 @@
731731
     }
732732
 
733733
     #[test]
734
+    fn temporal_constructors_and_component_functions() {
735
+        let iso = |src: &str| ev(&format!("string({src})"));
736
+        let s = |v: &str| Value::String(v.to_string());
737
+
738
+        // date(...)
739
+        assert_eq!(iso("date(2017, 8, 3)"), s("2017-08-03"));
740
+        assert_eq!(iso(r#"date("2017-08-03")"#), s("2017-08-03"));
741
+        assert_eq!(iso(r#"date(@"2017-08-03T10:00:00")"#), s("2017-08-03")); // from datetime
742
+        assert_eq!(ev("date(2017, 13, 1)"), Value::Null); // out of range -> null
743
+        assert_eq!(ev("date(2017, null, 1)"), Value::Null); // null component -> null
744
+        assert_eq!(ev("date(null)"), Value::Null);
745
+
746
+        // time(...)
747
+        assert_eq!(iso("time(11, 59, 0)"), s("11:59:00"));
748
+        assert_eq!(iso(r#"time("10:30:05")"#), s("10:30:05"));
749
+        assert_eq!(iso(r#"time(11, 59, 0, duration("PT2H"))"#), s("11:59:00+02:00"));
750
+
751
+        // date and time(...)
752
+        assert_eq!(iso(r#"date and time("2017-01-01T10:00:00")"#), s("2017-01-01T10:00:00"));
753
+        assert_eq!(iso(r#"date and time(@"2017-01-01", @"10:00:00")"#), s("2017-01-01T10:00:00"));
754
+
755
+        // duration(...) and years and months duration(...)
756
+        assert_eq!(iso(r#"duration("P1Y2M")"#), s("P1Y2M"));
757
+        assert_eq!(iso(r#"duration("P2DT3H")"#), s("P2DT3H"));
758
+        assert_eq!(ev(r#"duration("1D")"#), Value::Null); // missing P -> null
759
+        assert_eq!(iso(r#"years and months duration(@"2011-12-22", @"2013-08-24")"#), s("P1Y8M"));
760
+        assert_eq!(iso(r#"years and months duration(@"2013-08-24", @"2011-12-22")"#), s("-P1Y8M"));
761
+
762
+        // component functions
763
+        assert_eq!(ev(r#"day of week(@"2021-01-11")"#), s("Monday"));
764
+        assert_eq!(ev(r#"month of year(@"2021-04-01")"#), s("April"));
765
+        assert_eq!(ev(r#"day of year(@"1970-01-01")"#), num(1.0));
766
+        assert_eq!(ev(r#"week of year(@"1970-01-01")"#), num(1.0));
767
+        assert_eq!(ev(r#"day of week(null)"#), Value::Null);
768
+
769
+        // abs of a duration (ADR-18; ADR-15 deferred it)
770
+        assert_eq!(iso(r#"abs(@"-P1Y")"#), s("P1Y"));
771
+        assert_eq!(iso(r#"abs(duration("-PT2H"))"#), s("PT2H"));
772
+    }
773
+
774
+    #[test]
734775
     fn now_today_use_injected_clock() {
735776
         // `now()`/`today()` read the injected instant, so they are deterministic
736777
         // and (in feel-pg) can be pinned to the transaction start (ADR-18).
@@ -828,8 +869,8 @@
828869
         );
829870
         assert_eq!(ev("get entries({})"), list(vec![]));
830871
 
831
-        // --- keyword-phrase temporal builtin: parses, still error-null (lenient) ---
832
-        assert_eq!(ev(r#"date and time("2018-12-08")"#), Value::Null);
872
+        // --- keyword-phrase temporal builtin now evaluates (ADR-18) ---
873
+        assert_eq!(ev(r#"string(date and time("2018-12-08"))"#), s("2018-12-08T00:00:00"));
833874
     }
834875
 
835876
     // The regex builtins are dialect-dependent (ADR-16): under the default

modified crates/feel-core/src/temporal.rs +102 −2

@@ -17,7 +17,7 @@
1717
 
1818
 use jiff::civil::{self, Weekday};
1919
 use jiff::tz::{Offset, TimeZone};
20
-use jiff::{SignedDuration, Span, Zoned};
20
+use jiff::{SignedDuration, Span, Unit, Zoned};
2121
 
2222
 use crate::ast::ArithOp;
2323
 use crate::Value;
@@ -188,7 +188,7 @@
188188
 /// lexical form: a `D`, `T` or `W` part makes it a days-time duration, otherwise
189189
 /// (only `Y`/`M`) a years-months duration. This keeps `P0M` (ym) distinct from
190190
 /// `PT0S`/`P0D` (dt). FEEL forbids mixing the two families.
191
-fn parse_duration(s: &str) -> Option<Value> {
191
+pub(crate) fn parse_duration(s: &str) -> Option<Value> {
192192
     let body = s.strip_prefix('-').unwrap_or(s).strip_prefix('P')?;
193193
     let is_days_time = body.contains('T') || body.contains('D') || body.contains('W');
194194
     let span = Span::from_str(s).ok()?;
@@ -731,3 +731,103 @@
731731
         None => Some(Zone::Offset(z.offset())),
732732
     }
733733
 }
734
+
735
+// --------------------------------------------------------------------------- //
736
+// Constructors & component helpers (used by the builtins; ADR-18)
737
+// --------------------------------------------------------------------------- //
738
+
739
+/// Build a `date` from integer components, or `None` if out of range.
740
+pub(crate) fn make_date(y: i64, m: i64, d: i64) -> Option<civil::Date> {
741
+    civil::Date::new(i16::try_from(y).ok()?, i8::try_from(m).ok()?, i8::try_from(d).ok()?).ok()
742
+}
743
+
744
+/// Build a `time` from integer components (+ optional zone), or `None` if out of
745
+/// range.
746
+pub(crate) fn make_time(h: i64, m: i64, s: i64, nanos: i64, zone: Option<Zone>) -> Option<Time> {
747
+    let time = civil::Time::new(
748
+        i8::try_from(h).ok()?,
749
+        i8::try_from(m).ok()?,
750
+        i8::try_from(s).ok()?,
751
+        i32::try_from(nanos).ok()?,
752
+    )
753
+    .ok()?;
754
+    Some(Time { time, zone })
755
+}
756
+
757
+/// Combine a `date` and a `time` (carrying the time's zone) into a `date and time`.
758
+pub(crate) fn combine_date_time(date: civil::Date, t: &Time) -> DateTime {
759
+    DateTime { dt: date.to_datetime(t.time), zone: t.zone.clone() }
760
+}
761
+
762
+/// Turn a days-and-time duration into a fixed-offset [`Zone`] (the `time(h,m,s,off)`
763
+/// fourth argument), or `None` if it is not a whole-second offset in range.
764
+pub(crate) fn offset_zone_from_dtd(d: SignedDuration) -> Option<Zone> {
765
+    if d.subsec_nanos() != 0 {
766
+        return None;
767
+    }
768
+    let secs = i32::try_from(d.as_secs()).ok()?;
769
+    Some(Zone::Offset(Offset::from_seconds(secs).ok()?))
770
+}
771
+
772
+/// The `date` part of a date or date-and-time value (else `None`).
773
+pub(crate) fn date_of(v: &Value) -> Option<civil::Date> {
774
+    match v {
775
+        Value::Date(d) => Some(*d),
776
+        Value::DateTime(dt) => Some(dt.dt.date()),
777
+        _ => None,
778
+    }
779
+}
780
+
781
+/// The `time` part of a time or date-and-time value (else `None`).
782
+pub(crate) fn time_of(v: &Value) -> Option<Time> {
783
+    match v {
784
+        Value::Time(t) => Some(t.clone()),
785
+        Value::DateTime(dt) => Some(Time { time: dt.dt.time(), zone: dt.zone.clone() }),
786
+        _ => None,
787
+    }
788
+}
789
+
790
+/// Whole months between two dates (the `years and months duration(from, to)`
791
+/// builtin) — leftover days are dropped, and the result is signed by direction.
792
+pub(crate) fn ym_between(a: civil::Date, b: civil::Date) -> Option<i64> {
793
+    let span = a.until((Unit::Month, b)).ok()?;
794
+    Some(span.get_years() as i64 * 12 + span.get_months() as i64)
795
+}
796
+
797
+const MONTH_NAMES: [&str; 12] = [
798
+    "January", "February", "March", "April", "May", "June", "July", "August",
799
+    "September", "October", "November", "December",
800
+];
801
+
802
+pub(crate) fn day_of_week_name(d: civil::Date) -> &'static str {
803
+    match d.weekday() {
804
+        Weekday::Monday => "Monday",
805
+        Weekday::Tuesday => "Tuesday",
806
+        Weekday::Wednesday => "Wednesday",
807
+        Weekday::Thursday => "Thursday",
808
+        Weekday::Friday => "Friday",
809
+        Weekday::Saturday => "Saturday",
810
+        Weekday::Sunday => "Sunday",
811
+    }
812
+}
813
+
814
+pub(crate) fn month_of_year_name(d: civil::Date) -> &'static str {
815
+    MONTH_NAMES[(d.month() - 1) as usize]
816
+}
817
+
818
+pub(crate) fn day_of_year_num(d: civil::Date) -> i64 {
819
+    d.day_of_year() as i64
820
+}
821
+
822
+pub(crate) fn week_of_year_num(d: civil::Date) -> i64 {
823
+    d.iso_week_date().week() as i64
824
+}
825
+
826
+/// `abs` of a duration (ADR-15 deferred this; ADR-18 enables it).
827
+pub(crate) fn abs(v: &Value) -> Option<Value> {
828
+    match v {
829
+        Value::YearsMonthsDuration(m) => Some(Value::YearsMonthsDuration(m.abs())),
830
+        Value::DaysTimeDuration(d) => Some(Value::DaysTimeDuration(d.abs())),
831
+        _ => None,
832
+    }
833
+}