Public repository: timo / feel

Reader

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

fix(core): align temporal semantics with the DMN-TCK

public

fix(core): align temporal semantics with the DMN-TCK

Refinements found by ingesting the temporal TCK dirs:
- string `+` concatenates (`"foo" + "bar" = "foobar"`)
- `date ± days-time-duration → date` (date part of midnight ± dur)
- date-time subtraction: a date or zoned date-time is an instant (date =
  midnight UTC), a zoneless date-time is floating; mixing instant and
  floating is a type error (null), matching the TCK
- strict 4-digit-year date strings (`998-…`, `01211-…`, `+2012-…` → null)
- a zero offset (`+00:00`/`-00:00`) canonicalises to `Z`; offsets are
  bounded to ±14:00; an explicit offset combined with a named zone, and a
  leap second (`:60`), are errors
- `24:00:00` rolls to next-day midnight; `time(date) = 00:00:00Z`;
  `time(h,m,s,null)` is a local time; `date and time(date-or-dt, time)`
- `ym-duration × number` truncates toward zero (`P1Y11M * -2.5 = -P4Y9M`)

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

modified crates/feel-core/src/builtins.rs +11 −4

@@ -207,9 +207,12 @@
207207
         [v @ Value::DateTime(_)] => {
208208
             crate::temporal::time_of(v).map(Value::Time).unwrap_or(Value::Error)
209209
         }
210
+        // `time(date)` yields midnight UTC (`00:00:00Z`) per the TCK.
211
+        [Value::Date(_)] => Value::Time(crate::temporal::midnight_utc_time()),
210212
         [h, m, s] => time_components(h, m, s, None),
211213
         [h, m, s, off] => match off {
212
-            Value::Null => Value::Null,
214
+            // A null offset means a local time (no zone), not a null result.
215
+            Value::Null => time_components(h, m, s, None),
213216
             Value::DaysTimeDuration(d) => match crate::temporal::offset_zone_from_dtd(*d) {
214217
                 Some(zone) => time_components(h, m, s, Some(zone)),
215218
                 None => Value::Error,
@@ -237,11 +240,15 @@
237240
             crate::temporal::parse_date_time(s).map(Value::DateTime).unwrap_or(Value::Error)
238241
         }
239242
         [v @ Value::DateTime(_)] => v.clone(),
243
+        // `date and time(date-or-datetime, time)`: take the date part of the first
244
+        // argument and the second's time (with its zone). The first argument's own
245
+        // zone, if any, is dropped.
240246
         [a, b] => match (a, b) {
241247
             (Value::Null, _) | (_, Value::Null) => Value::Null,
242
-            (Value::Date(d), Value::Time(t)) => {
243
-                Value::DateTime(crate::temporal::combine_date_time(*d, t))
244
-            }
248
+            (_, Value::Time(t)) => match crate::temporal::date_of(a) {
249
+                Some(d) => Value::DateTime(crate::temporal::combine_date_time(d, t)),
250
+                None => Value::Error,
251
+            },
245252
             _ => Value::Error,
246253
         },
247254
         _ => Value::Error,

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

@@ -167,6 +167,10 @@
167167
         } else {
168168
             Value::Error
169169
         });
170
+    }
171
+    // String concatenation: `"foo" + "bar" = "foobar"` (FEEL defines `+` on strings).
172
+    if let (ArithOp::Add, Value::String(a), Value::String(b)) = (op, &lhs, &rhs) {
173
+        return Ok(Value::String(format!("{a}{b}")));
170174
     }
171175
     // Temporal path: date/time/duration arithmetic (ADR-18). Anything not defined
172176
     // (incl. a number mixed with a non-duration) is an error-null.

modified crates/feel-core/src/lib.rs +2 −1

@@ -601,7 +601,8 @@
601601
 
602602
         // date/datetime + duration
603603
         assert_eq!(iso(r#"@"2017-01-01" + @"P1Y2M""#), s("2018-03-01")); // date + ymd -> date
604
-        assert_eq!(iso(r#"@"2017-01-01" + @"PT1H""#), s("2017-01-01T01:00:00")); // date + dtd -> datetime
604
+        assert_eq!(iso(r#"@"2017-01-01" + @"P1D""#), s("2017-01-02")); // date + dtd -> date
605
+        assert_eq!(iso(r#"@"2017-01-01" + @"PT36H""#), s("2017-01-02")); // dtd added, date part kept
605606
         assert_eq!(iso(r#"@"2017-01-01T10:00:00" + @"P1M""#), s("2017-02-01T10:00:00"));
606607
         assert_eq!(iso(r#"@"23:00:00" + @"PT2H""#), s("01:00:00")); // time wraps mod 24h
607608
 

modified crates/feel-core/src/temporal.rs +135 −63

@@ -82,76 +82,97 @@
8282
     }
8383
 }
8484
 
85
+/// Parse a `date` in the strict FEEL/XSD lexical form: an optional leading `-`,
86
+/// then **exactly** four year digits, `-`, two month digits, `-`, two day digits.
87
+/// This rejects `998-12-31` (3-digit), `01211-12-31` (5-digit) and `+2012-12-02`
88
+/// (leading `+`) the way the TCK requires; out-of-range years are `None` too.
8589
 pub(crate) fn parse_date(s: &str) -> Option<civil::Date> {
86
-    if let Ok(d) = civil::Date::from_str(s) {
87
-        return Some(d);
88
-    }
89
-    // jiff's strict ISO parser rejects the leading-minus (negative year) form, so
90
-    // peel the sign and reassemble (e.g. `-2017-01-01`).
91
-    let neg = s.starts_with('-');
92
-    let body = if neg { &s[1..] } else { s };
93
-    let mut parts = body.splitn(3, '-');
94
-    let y: i16 = parts.next()?.parse().ok()?;
95
-    let m: i8 = parts.next()?.parse().ok()?;
96
-    let d: i8 = parts.next()?.parse().ok()?;
97
-    if parts.next().is_some() {
90
+    let (neg, body) = match s.strip_prefix('-') {
91
+        Some(b) => (true, b),
92
+        None => (false, s),
93
+    };
94
+    let parts: Vec<&str> = body.split('-').collect();
95
+    if parts.len() != 3 || parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 {
9896
         return None;
9997
     }
98
+    if !parts.iter().all(|p| digits(p)) {
99
+        return None;
100
+    }
101
+    let y: i16 = parts[0].parse().ok()?;
102
+    let m: i8 = parts[1].parse().ok()?;
103
+    let d: i8 = parts[2].parse().ok()?;
100104
     civil::Date::new(if neg { -y } else { y }, m, d).ok()
101105
 }
102106
 
103107
 pub(crate) fn parse_time(s: &str) -> Option<Time> {
104108
     let (civil_part, zone) = split_zone(s)?;
105
-    let time = civil::Time::from_str(civil_part).ok()?;
109
+    let time = parse_civil_time(civil_part)?;
106110
     Some(Time { time, zone })
107111
 }
108112
 
109113
 pub(crate) fn parse_date_time(s: &str) -> Option<DateTime> {
110114
     let (civil_part, zone) = split_zone(s)?;
111
-    let dt = match civil::DateTime::from_str(civil_part) {
112
-        Ok(dt) => dt,
113
-        Err(_) => {
114
-            // Negative-year fallback: split on `T`, parse each half ourselves.
115
-            let (date_str, time_str) = civil_part.split_once('T')?;
116
-            let date = parse_date(date_str)?;
117
-            let time = civil::Time::from_str(time_str).ok()?;
118
-            date.to_datetime(time)
119
-        }
115
+    // A date-only string is a date and time at midnight (per the TCK, e.g.
116
+    // `date and time("2012-12-24") = 2012-12-24T00:00:00`).
117
+    let dt = match civil_part.split_once('T') {
118
+        // `24:00:00` is end-of-day = next-day midnight (XSD); jiff has no hour 24.
119
+        Some((date_str, "24:00:00")) => parse_date(date_str)?.tomorrow().ok()?.to_datetime(civil::Time::MIN),
120
+        Some((date_str, time_str)) => parse_date(date_str)?.to_datetime(parse_civil_time(time_str)?),
121
+        None => parse_date(civil_part)?.to_datetime(civil::Time::MIN),
120122
     };
121123
     Some(DateTime { dt, zone })
122124
 }
123125
 
126
+/// Parse a civil time-of-day, rejecting a leap second (`:60`) which FEEL does not
127
+/// have but jiff would accept.
128
+fn parse_civil_time(s: &str) -> Option<civil::Time> {
129
+    let sec_field = s.split(':').nth(2)?;
130
+    let sec_int = sec_field.split('.').next()?;
131
+    if sec_int.parse::<u32>().ok()? >= 60 {
132
+        return None;
133
+    }
134
+    civil::Time::from_str(s).ok()
135
+}
136
+
124137
 /// Split a trailing zone designator (`Z`, `±HH:MM[:SS]`, or `@Area/City`) off a
125
-/// time / date-time string. Returns the civil remainder and the parsed zone.
126
-/// The leading sign of a negative year is never mistaken for an offset (we only
127
-/// inspect the tail).
138
+/// time / date-time string. Returns the civil remainder and the parsed zone, or
139
+/// `None` for an invalid combination (a named zone *and* an explicit offset, or an
140
+/// out-of-range offset). The leading sign of a negative year is never mistaken for
141
+/// an offset (we only inspect the tail).
128142
 fn split_zone(s: &str) -> Option<(&str, Option<Zone>)> {
129
-    if let Some(idx) = s.find('@') {
130
-        let name = &s[idx + 1..];
131
-        // Validate the zone name eagerly so a bad `@xyz/abc` is an error-null.
132
-        TimeZone::get(name).ok()?;
133
-        return Some((&s[..idx], Some(Zone::Named(name.to_string()))));
134
-    }
135
-    if let Some(rest) = s.strip_suffix('Z') {
136
-        return Some((rest, Some(Zone::Utc)));
137
-    }
138
-    if let Some((rest, offset)) = split_offset_suffix(s) {
139
-        return Some((rest, Some(Zone::Offset(offset))));
140
-    }
141
-    Some((s, None))
142
-}
143
-
144
-/// Detect a trailing `±HH:MM` or `±HH:MM:SS` offset. Returns the remainder and
145
-/// the offset, or `None` if the tail is not an offset.
146
-fn split_offset_suffix(s: &str) -> Option<(&str, Offset)> {
143
+    let (rest, named) = match s.find('@') {
144
+        Some(idx) => {
145
+            let name = &s[idx + 1..];
146
+            // Validate the zone name eagerly so a bad `@xyz/abc` is an error-null.
147
+            TimeZone::get(name).ok()?;
148
+            (&s[..idx], Some(Zone::Named(name.to_string())))
149
+        }
150
+        None => (s, None),
151
+    };
152
+    let (civil_part, off_zone) = if let Some(r) = rest.strip_suffix('Z') {
153
+        (r, Some(Zone::Utc))
154
+    } else if let Some((r, secs)) = split_offset_suffix(rest) {
155
+        (r, Some(offset_to_zone(secs)?))
156
+    } else {
157
+        (rest, None)
158
+    };
159
+    // FEEL forbids combining an explicit offset with a named zone.
160
+    if named.is_some() && off_zone.is_some() {
161
+        return None;
162
+    }
163
+    Some((civil_part, named.or(off_zone)))
164
+}
165
+
166
+/// Detect a trailing `±HH:MM` or `±HH:MM:SS` offset. Returns the remainder and the
167
+/// offset's total seconds, or `None` if the tail is not an offset.
168
+fn split_offset_suffix(s: &str) -> Option<(&str, i32)> {
147169
     // Try the longest form first (`±HH:MM:SS` = 9 chars), then `±HH:MM` (6).
148170
     for len in [9usize, 6] {
149171
         if s.len() <= len {
150172
             continue;
151173
         }
152174
         let tail = &s[s.len() - len..];
153
-        let bytes = tail.as_bytes();
154
-        let sign = match bytes[0] {
175
+        let sign = match tail.as_bytes()[0] {
155176
             b'+' => 1,
156177
             b'-' => -1,
157178
             _ => continue,
@@ -173,15 +194,32 @@
173194
         let h: i32 = tail[1..3].parse().ok()?;
174195
         let m: i32 = tail[4..6].parse().ok()?;
175196
         let sec: i32 = if len == 9 { tail[7..9].parse().ok()? } else { 0 };
176
-        let total = sign * (h * 3600 + m * 60 + sec);
177
-        let offset = Offset::from_seconds(total).ok()?;
178
-        return Some((&s[..s.len() - len], offset));
197
+        return Some((&s[..s.len() - len], sign * (h * 3600 + m * 60 + sec)));
179198
     }
180199
     None
200
+}
201
+
202
+/// Turn an offset's total seconds into a [`Zone`], applying FEEL's rules: a zero
203
+/// offset (`+00:00`/`-00:00`) is written `Z`, and the magnitude must be within
204
+/// ±14:00 (else `None` -> error-null).
205
+fn offset_to_zone(total_secs: i32) -> Option<Zone> {
206
+    if total_secs.abs() > 14 * 3600 {
207
+        return None;
208
+    }
209
+    if total_secs == 0 {
210
+        Some(Zone::Utc)
211
+    } else {
212
+        Some(Zone::Offset(Offset::from_seconds(total_secs).ok()?))
213
+    }
181214
 }
182215
 
183216
 fn digits(s: &str) -> bool {
184217
     !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
218
+}
219
+
220
+/// `time(date)` yields midnight UTC (`00:00:00Z`) per the TCK.
221
+pub(crate) fn midnight_utc_time() -> Time {
222
+    Time { time: civil::Time::MIN, zone: Some(Zone::Utc) }
185223
 }
186224
 
187225
 /// Parse an ISO-8601 duration, classifying it as years-months or days-time by its
@@ -447,7 +485,8 @@
447485
             add_months_date(*d, *m).map(Date)
448486
         }
449487
         (Date(d), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), Date(d)) => {
450
-            date_plus_dtd(*d, *dur).map(DateTime)
488
+            // date + days-time duration -> date (the date part of midnight + dur).
489
+            date_plus_dtd(*d, *dur).map(Date)
451490
         }
452491
         (DateTime(dt), YearsMonthsDuration(m)) | (YearsMonthsDuration(m), DateTime(dt)) => {
453492
             add_months_dt(dt, *m).map(DateTime)
@@ -467,22 +506,54 @@
467506
     match (a, b) {
468507
         (YearsMonthsDuration(x), YearsMonthsDuration(y)) => Some(YearsMonthsDuration(x - y)),
469508
         (DaysTimeDuration(x), DaysTimeDuration(y)) => x.checked_sub(*y).map(DaysTimeDuration),
470
-        (Date(x), Date(y)) => {
471
-            nanos_to_signed(date_nanos(*x) - date_nanos(*y)).map(DaysTimeDuration)
472
-        }
473
-        (DateTime(x), DateTime(y)) => {
474
-            nanos_to_signed(datetime_instant(x) - datetime_instant(y)).map(DaysTimeDuration)
509
+        // point − point -> days-time duration. A date or a zoned date-time is an
510
+        // *instant* (a date is midnight UTC); a zoneless date-time is *floating*.
511
+        // Subtracting mixes only within the same kind — instant−instant uses the
512
+        // global timeline, floating−floating the naive wall clock; a mixed pair is
513
+        // a type error (-> None -> error-null).
514
+        (Date(_) | DateTime(_), Date(_) | DateTime(_)) => {
515
+            diff_temporal(a, b).map(DaysTimeDuration)
475516
         }
476517
         (Time(x), Time(y)) => {
477518
             Some(DaysTimeDuration(SignedDuration::from_nanos(time_instant(x) - time_instant(y))))
478519
         }
479520
         (Date(d), YearsMonthsDuration(m)) => add_months_date(*d, -m).map(Date),
480
-        (Date(d), DaysTimeDuration(dur)) => date_plus_dtd(*d, -*dur).map(DateTime),
521
+        (Date(d), DaysTimeDuration(dur)) => date_plus_dtd(*d, -*dur).map(Date),
481522
         (DateTime(dt), YearsMonthsDuration(m)) => add_months_dt(dt, -m).map(DateTime),
482523
         (DateTime(dt), DaysTimeDuration(dur)) => dt_plus_dtd(dt, -*dur).map(DateTime),
483524
         (Time(t), DaysTimeDuration(dur)) => Some(Time(time_plus_dtd(t, -*dur))),
484525
         _ => None,
485526
     }
527
+}
528
+
529
+/// True if a date/date-time value sits on the global timeline (an *instant*): a
530
+/// date (midnight UTC) or a zoned date-time. A zoneless date-time is *floating*.
531
+fn is_instant(v: &Value) -> bool {
532
+    match v {
533
+        Value::Date(_) => true,
534
+        Value::DateTime(dt) => dt.zone.is_some(),
535
+        _ => false,
536
+    }
537
+}
538
+
539
+/// Nanoseconds for a date/date-time: the real UTC instant for an instant value
540
+/// (date = midnight UTC, zoned date-time resolved by its zone), or the naive civil
541
+/// nanoseconds for a floating date-time.
542
+fn point_nanos(v: &Value) -> i128 {
543
+    match v {
544
+        Value::Date(d) => date_nanos(*d),
545
+        Value::DateTime(dt) => datetime_instant(dt),
546
+        _ => 0,
547
+    }
548
+}
549
+
550
+/// Difference between two date/date-time points, or `None` if one is an instant
551
+/// and the other floating (an undefined mix in FEEL).
552
+fn diff_temporal(a: &Value, b: &Value) -> Option<SignedDuration> {
553
+    if is_instant(a) != is_instant(b) {
554
+        return None;
555
+    }
556
+    nanos_to_signed(point_nanos(a) - point_nanos(b))
486557
 }
487558
 
488559
 fn mul(a: &Value, b: &Value) -> Option<Value> {
@@ -533,7 +604,9 @@
533604
 fn scale_duration(dur: &Value, factor: f64) -> Option<Value> {
534605
     match dur {
535606
         Value::YearsMonthsDuration(m) => {
536
-            let scaled = (*m as f64 * factor).round();
607
+            // Truncate toward zero (the TCK: `P1Y11M * -2.5 = -P4Y9M`, i.e.
608
+            // 23 × −2.5 = −57.5 → −57 months).
609
+            let scaled = (*m as f64 * factor).trunc();
537610
             if scaled.is_finite() {
538611
                 Some(Value::YearsMonthsDuration(scaled as i64))
539612
             } else {
@@ -561,9 +634,8 @@
561634
     Some(DateTime { dt: new, zone: dt.zone.clone() })
562635
 }
563636
 
564
-fn date_plus_dtd(d: civil::Date, dur: SignedDuration) -> Option<DateTime> {
565
-    let dt = d.to_datetime(civil::Time::MIN).checked_add(dur).ok()?;
566
-    Some(DateTime { dt, zone: None })
637
+fn date_plus_dtd(d: civil::Date, dur: SignedDuration) -> Option<civil::Date> {
638
+    Some(d.to_datetime(civil::Time::MIN).checked_add(dur).ok()?.date())
567639
 }
568640
 
569641
 fn dt_plus_dtd(dt: &DateTime, dur: SignedDuration) -> Option<DateTime> {
@@ -759,14 +831,14 @@
759831
     DateTime { dt: date.to_datetime(t.time), zone: t.zone.clone() }
760832
 }
761833
 
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.
834
+/// Turn a days-and-time duration into a zone (the `time(h,m,s,off)` fourth
835
+/// argument): a fixed offset, or `Z` for a zero offset; `None` if it is not a
836
+/// whole-second offset within ±14:00.
764837
 pub(crate) fn offset_zone_from_dtd(d: SignedDuration) -> Option<Zone> {
765838
     if d.subsec_nanos() != 0 {
766839
         return None;
767840
     }
768
-    let secs = i32::try_from(d.as_secs()).ok()?;
769
-    Some(Zone::Offset(Offset::from_seconds(secs).ok()?))
841
+    offset_to_zone(i32::try_from(d.as_secs()).ok()?)
770842
 }
771843
 
772844
 /// The `date` part of a date or date-and-time value (else `None`).