Public repository: timo / feel

Reader

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

feat(core): temporal arithmetic, duration negation & component access (ADR-18)

public

feat(core): temporal arithmetic, duration negation & component access (ADR-18)

Implement the FEEL temporal arithmetic table in `temporal::arith`:
date/time/date-and-time ± duration, datetime − datetime → days-time
duration, duration ± duration (same family), duration × / number, and
duration / duration → number. `eval_arith` now tries the numeric path
first and falls back to the temporal table.

Also: unary `-` negates a duration, and `Expr::Path` reads temporal
components (`.year`, `.weekday`, `.time offset`, `.timezone`, `.years`,
`.seconds`, …) with an unknown property yielding a value-null.

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

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

@@ -48,6 +48,9 @@
4848
                 // A missing member is a value-null (like an unbound variable);
4949
                 // a path on a non-context is a type error -> error-null.
5050
                 Value::Context(map) => map.get(name).cloned().unwrap_or(Value::Null),
51
+                // Component access on a temporal value (`d.year`, `dur.seconds`);
52
+                // an unknown property is a value-null (ADR-18).
53
+                v if temporal::is_temporal(&v) => temporal::get_property(&v, name),
5154
                 Value::Error => Value::Error,
5255
                 _ => Value::Error,
5356
             }),
@@ -65,7 +68,9 @@
6568
             // --- arithmetic ---
6669
             Expr::Neg(e) => Ok(match self.eval(e, ctx)? {
6770
                 Value::Number(n) => Value::Number(-n),
68
-                _ => Value::Error, // negation of a non-number -> error-null
71
+                // Negating a duration flips its sign (ADR-18).
72
+                v if temporal::is_temporal(&v) => temporal::negate(&v).unwrap_or(Value::Error),
73
+                _ => Value::Error, // negation of a non-number/non-duration -> error-null
6974
             }),
7075
             Expr::Arith(op, l, r) => eval_arith(*op, self.eval(l, ctx)?, self.eval(r, ctx)?),
7176
 
@@ -141,29 +146,31 @@
141146
 // --------------------------------------------------------------------------- //
142147
 
143148
 fn eval_arith(op: ArithOp, lhs: Value, rhs: Value) -> EvalResult {
144
-    let (a, b) = match (as_number(&lhs), as_number(&rhs)) {
145
-        (Some(a), Some(b)) => (a, b),
146
-        _ => return Ok(Value::Error), // non-numeric operand -> error-null
147
-    };
148
-    let out = match op {
149
-        ArithOp::Add => a + b,
150
-        ArithOp::Sub => a - b,
151
-        ArithOp::Mul => a * b,
152
-        ArithOp::Div => {
153
-            if b == 0.0 {
154
-                return Ok(Value::Error); // division by zero -> error-null
155
-            }
156
-            a / b
157
-        }
158
-        ArithOp::Pow => a.powf(b),
159
-    };
160
-    // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) are a domain error;
161
-    // this also keeps every Number JSON-representable at the wrappers.
162
-    Ok(if out.is_finite() {
163
-        Value::Number(out)
164
-    } else {
165
-        Value::Error
166
-    })
149
+    // Numeric path: both operands are numbers.
150
+    if let (Some(a), Some(b)) = (as_number(&lhs), as_number(&rhs)) {
151
+        let out = match op {
152
+            ArithOp::Add => a + b,
153
+            ArithOp::Sub => a - b,
154
+            ArithOp::Mul => a * b,
155
+            ArithOp::Div => {
156
+                if b == 0.0 {
157
+                    return Ok(Value::Error); // division by zero -> error-null
158
+                }
159
+                a / b
160
+            }
161
+            ArithOp::Pow => a.powf(b),
162
+        };
163
+        // Non-finite results (overflow / NaN, e.g. (-8) ** 0.5) are a domain error;
164
+        // this also keeps every Number JSON-representable at the wrappers.
165
+        return Ok(if out.is_finite() {
166
+            Value::Number(out)
167
+        } else {
168
+            Value::Error
169
+        });
170
+    }
171
+    // Temporal path: date/time/duration arithmetic (ADR-18). Anything not defined
172
+    // (incl. a number mixed with a non-duration) is an error-null.
173
+    Ok(temporal::arith(op, &lhs, &rhs).unwrap_or(Value::Error))
167174
 }
168175
 
169176
 // --------------------------------------------------------------------------- //

modified crates/feel-core/src/lib.rs +51 −0

@@ -552,6 +552,57 @@
552552
         // cross temporal types are a type mismatch -> null (lenient).
553553
         assert_eq!(ev(r#"@"2017-01-01" = @"P1Y""#), Value::Null);
554554
         assert_eq!(ev(r#"@"P1Y" < @"PT1H""#), Value::Null);
555
+    }
556
+
557
+    #[test]
558
+    fn temporal_arithmetic_negation_and_properties() {
559
+        let iso = |src: &str| ev(&format!("string({src})"));
560
+        let s = |v: &str| Value::String(v.to_string());
561
+
562
+        // date/datetime + duration
563
+        assert_eq!(iso(r#"@"2017-01-01" + @"P1Y2M""#), s("2018-03-01")); // date + ymd -> date
564
+        assert_eq!(iso(r#"@"2017-01-01" + @"PT1H""#), s("2017-01-01T01:00:00")); // date + dtd -> datetime
565
+        assert_eq!(iso(r#"@"2017-01-01T10:00:00" + @"P1M""#), s("2017-02-01T10:00:00"));
566
+        assert_eq!(iso(r#"@"23:00:00" + @"PT2H""#), s("01:00:00")); // time wraps mod 24h
567
+
568
+        // duration ± duration (same family)
569
+        assert_eq!(iso(r#"@"P1Y" + @"P2M""#), s("P1Y2M"));
570
+        assert_eq!(iso(r#"@"PT1H" + @"PT30M""#), s("PT1H30M"));
571
+
572
+        // date/datetime − date/datetime -> days-and-time duration
573
+        assert_eq!(iso(r#"@"2017-01-10" - @"2017-01-01""#), s("P9D"));
574
+        assert_eq!(iso(r#"@"2017-01-01T12:00:00" - @"2017-01-01T10:00:00""#), s("PT2H"));
575
+
576
+        // duration * / number, and duration / duration -> number
577
+        assert_eq!(iso(r#"@"P1Y" * 2"#), s("P2Y"));
578
+        assert_eq!(iso(r#"@"PT1H" * 3"#), s("PT3H"));
579
+        assert_eq!(iso(r#"@"P2Y" / 2"#), s("P1Y"));
580
+        assert_eq!(ev(r#"@"PT2H" / @"PT1H""#), num(2.0));
581
+
582
+        // negation of a duration
583
+        assert_eq!(iso(r#"-@"P1Y""#), s("-P1Y"));
584
+
585
+        // invalid combinations -> null (lenient view of error-null)
586
+        assert_eq!(ev(r#"@"2017-01-01" + @"2017-01-02""#), Value::Null); // date + date
587
+        assert_eq!(ev(r#"@"P1Y" + @"PT1H""#), Value::Null); // mixed duration families
588
+
589
+        // property / component access
590
+        assert_eq!(ev(r#"@"2017-08-03".year"#), num(2017.0));
591
+        assert_eq!(ev(r#"@"2017-08-03".month"#), num(8.0));
592
+        assert_eq!(ev(r#"@"2017-08-03".day"#), num(3.0));
593
+        assert_eq!(ev(r#"@"2017-08-03".weekday"#), num(4.0)); // Thursday
594
+        assert_eq!(ev(r#"@"10:30:05".hour"#), num(10.0));
595
+        assert_eq!(ev(r#"@"10:30:05".minute"#), num(30.0));
596
+        assert_eq!(ev(r#"@"10:30:05".second"#), num(5.0));
597
+        assert_eq!(ev(r#"string(@"10:30:05+02:00".time offset)"#), s("PT2H"));
598
+        assert_eq!(ev(r#"@"10:30:05".timezone"#), Value::Null);
599
+        assert_eq!(ev(r#"@"2017-06-23T11:23:00@Europe/Paris".timezone"#), s("Europe/Paris"));
600
+        assert_eq!(ev(r#"@"P1Y2M".years"#), num(1.0));
601
+        assert_eq!(ev(r#"@"P1Y2M".months"#), num(2.0));
602
+        assert_eq!(ev(r#"@"P2DT3H".days"#), num(2.0));
603
+        assert_eq!(ev(r#"@"P2DT3H".hours"#), num(3.0));
604
+        // unknown property on a temporal -> value-null (not an error).
605
+        assert_eq!(ev(r#"@"2017-08-03".nonsense"#), Value::Null);
555606
     }
556607
 
557608
     #[test]

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

@@ -15,10 +15,11 @@
1515
 use std::cmp::Ordering;
1616
 use std::str::FromStr;
1717
 
18
-use jiff::civil;
18
+use jiff::civil::{self, Weekday};
1919
 use jiff::tz::{Offset, TimeZone};
2020
 use jiff::{SignedDuration, Span};
2121
 
22
+use crate::ast::ArithOp;
2223
 use crate::Value;
2324
 
2425
 /// The zone attached to a `time` / `date and time`. Kept faithful for output:
@@ -410,3 +411,300 @@
410411
     let z = dt.to_zoned(TimeZone::UTC).expect("UTC is always valid");
411412
     z.timestamp().as_nanosecond()
412413
 }
414
+
415
+// --------------------------------------------------------------------------- //
416
+// Arithmetic (the FEEL temporal arithmetic table) and negation
417
+// --------------------------------------------------------------------------- //
418
+
419
+/// FEEL temporal arithmetic. `None` for any operand combination that is not a
420
+/// defined temporal operation (the caller maps that to an error-null). Numbers
421
+/// times/over durations are handled here too (the numeric-only path is upstream).
422
+pub(crate) fn arith(op: ArithOp, a: &Value, b: &Value) -> Option<Value> {
423
+    match op {
424
+        ArithOp::Add => add(a, b),
425
+        ArithOp::Sub => sub(a, b),
426
+        ArithOp::Mul => mul(a, b),
427
+        ArithOp::Div => div(a, b),
428
+        ArithOp::Pow => None,
429
+    }
430
+}
431
+
432
+/// Negate a duration (`-P1Y`, `-PT1H`). `None` for any non-duration.
433
+pub(crate) fn negate(v: &Value) -> Option<Value> {
434
+    match v {
435
+        Value::YearsMonthsDuration(m) => Some(Value::YearsMonthsDuration(-m)),
436
+        Value::DaysTimeDuration(d) => Some(Value::DaysTimeDuration(-*d)),
437
+        _ => None,
438
+    }
439
+}
440
+
441
+fn add(a: &Value, b: &Value) -> Option<Value> {
442
+    use Value::*;
443
+    match (a, b) {
444
+        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => Some(YearsMonthsDuration(x + y)),
445
+        (DaysTimeDuration(x), DaysTimeDuration(y)) => x.checked_add(*y).map(DaysTimeDuration),
446
+        (Date(d), YearsMonthsDuration(m)) | (YearsMonthsDuration(m), Date(d)) => {
447
+            add_months_date(*d, *m).map(Date)
448
+        }
449
+        (Date(d), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), Date(d)) => {
450
+            date_plus_dtd(*d, *dur).map(DateTime)
451
+        }
452
+        (DateTime(dt), YearsMonthsDuration(m)) | (YearsMonthsDuration(m), DateTime(dt)) => {
453
+            add_months_dt(dt, *m).map(DateTime)
454
+        }
455
+        (DateTime(dt), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), DateTime(dt)) => {
456
+            dt_plus_dtd(dt, *dur).map(DateTime)
457
+        }
458
+        (Time(t), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), Time(t)) => {
459
+            Some(Time(time_plus_dtd(t, *dur)))
460
+        }
461
+        _ => None,
462
+    }
463
+}
464
+
465
+fn sub(a: &Value, b: &Value) -> Option<Value> {
466
+    use Value::*;
467
+    match (a, b) {
468
+        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => Some(YearsMonthsDuration(x - y)),
469
+        (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)
475
+        }
476
+        (Time(x), Time(y)) => {
477
+            Some(DaysTimeDuration(SignedDuration::from_nanos(time_instant(x) - time_instant(y))))
478
+        }
479
+        (Date(d), YearsMonthsDuration(m)) => add_months_date(*d, -m).map(Date),
480
+        (Date(d), DaysTimeDuration(dur)) => date_plus_dtd(*d, -*dur).map(DateTime),
481
+        (DateTime(dt), YearsMonthsDuration(m)) => add_months_dt(dt, -m).map(DateTime),
482
+        (DateTime(dt), DaysTimeDuration(dur)) => dt_plus_dtd(dt, -*dur).map(DateTime),
483
+        (Time(t), DaysTimeDuration(dur)) => Some(Time(time_plus_dtd(t, -*dur))),
484
+        _ => None,
485
+    }
486
+}
487
+
488
+fn mul(a: &Value, b: &Value) -> Option<Value> {
489
+    use Value::*;
490
+    let (dur, n) = match (a, b) {
491
+        (d, Number(n)) if is_duration(d) => (d, *n),
492
+        (Number(n), d) if is_duration(d) => (d, *n),
493
+        _ => return None,
494
+    };
495
+    scale_duration(dur, n)
496
+}
497
+
498
+fn div(a: &Value, b: &Value) -> Option<Value> {
499
+    use Value::*;
500
+    match (a, b) {
501
+        (d, Number(n)) if is_duration(d) => {
502
+            if *n == 0.0 {
503
+                None
504
+            } else {
505
+                scale_duration(d, 1.0 / n)
506
+            }
507
+        }
508
+        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => {
509
+            if *y == 0 {
510
+                None
511
+            } else {
512
+                Some(Number(*x as f64 / *y as f64))
513
+            }
514
+        }
515
+        (DaysTimeDuration(x), DaysTimeDuration(y)) => {
516
+            let yn = signed_nanos(*y);
517
+            if yn == 0 {
518
+                None
519
+            } else {
520
+                Some(Number(signed_nanos(*x) as f64 / yn as f64))
521
+            }
522
+        }
523
+        _ => None,
524
+    }
525
+}
526
+
527
+fn is_duration(v: &Value) -> bool {
528
+    matches!(v, Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_))
529
+}
530
+
531
+/// Scale a duration by an f64 factor (ADR-2: f64 is the accepted numeric model).
532
+/// Years-months rounds to whole months; days-time scales its nanoseconds.
533
+fn scale_duration(dur: &Value, factor: f64) -> Option<Value> {
534
+    match dur {
535
+        Value::YearsMonthsDuration(m) => {
536
+            let scaled = (*m as f64 * factor).round();
537
+            if scaled.is_finite() {
538
+                Some(Value::YearsMonthsDuration(scaled as i64))
539
+            } else {
540
+                None
541
+            }
542
+        }
543
+        Value::DaysTimeDuration(d) => {
544
+            let scaled = signed_nanos(*d) as f64 * factor;
545
+            if scaled.is_finite() {
546
+                nanos_to_signed(scaled as i128).map(Value::DaysTimeDuration)
547
+            } else {
548
+                None
549
+            }
550
+        }
551
+        _ => None,
552
+    }
553
+}
554
+
555
+fn add_months_date(d: civil::Date, months: i64) -> Option<civil::Date> {
556
+    d.checked_add(Span::new().months(months)).ok()
557
+}
558
+
559
+fn add_months_dt(dt: &DateTime, months: i64) -> Option<DateTime> {
560
+    let new = dt.dt.checked_add(Span::new().months(months)).ok()?;
561
+    Some(DateTime { dt: new, zone: dt.zone.clone() })
562
+}
563
+
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 })
567
+}
568
+
569
+fn dt_plus_dtd(dt: &DateTime, dur: SignedDuration) -> Option<DateTime> {
570
+    let new = dt.dt.checked_add(dur).ok()?;
571
+    Some(DateTime { dt: new, zone: dt.zone.clone() })
572
+}
573
+
574
+fn time_plus_dtd(t: &Time, dur: SignedDuration) -> Time {
575
+    Time { time: t.time.wrapping_add(dur), zone: t.zone.clone() }
576
+}
577
+
578
+/// Nanoseconds of a (zoneless) date taken at midnight, for date subtraction.
579
+fn date_nanos(d: civil::Date) -> i128 {
580
+    civil_to_nanos(d.to_datetime(civil::Time::MIN))
581
+}
582
+
583
+fn signed_nanos(d: SignedDuration) -> i128 {
584
+    d.as_nanos()
585
+}
586
+
587
+fn nanos_to_signed(n: i128) -> Option<SignedDuration> {
588
+    let secs = i64::try_from(n.div_euclid(1_000_000_000)).ok()?;
589
+    let nanos = n.rem_euclid(1_000_000_000) as i32;
590
+    Some(SignedDuration::new(secs, nanos))
591
+}
592
+
593
+// --------------------------------------------------------------------------- //
594
+// Component / property access (`date.year`, `time.hour`, `dur.seconds`, …)
595
+// --------------------------------------------------------------------------- //
596
+
597
+/// Read a FEEL property of a temporal value. An unknown or absent property is a
598
+/// value-null (`Value::Null`); the caller only routes here for temporal targets.
599
+pub(crate) fn get_property(v: &Value, name: &str) -> Value {
600
+    match v {
601
+        Value::Date(d) => date_property(*d, name),
602
+        Value::DateTime(dt) => datetime_property(dt, name),
603
+        Value::Time(t) => time_property(t, name),
604
+        Value::YearsMonthsDuration(m) => ym_property(*m, name),
605
+        Value::DaysTimeDuration(d) => dt_property(*d, name),
606
+        _ => Value::Null,
607
+    }
608
+}
609
+
610
+fn num(n: impl Into<f64>) -> Value {
611
+    Value::Number(n.into())
612
+}
613
+
614
+fn weekday_number(wd: Weekday) -> f64 {
615
+    // FEEL weekday: Monday = 1 … Sunday = 7.
616
+    match wd {
617
+        Weekday::Monday => 1.0,
618
+        Weekday::Tuesday => 2.0,
619
+        Weekday::Wednesday => 3.0,
620
+        Weekday::Thursday => 4.0,
621
+        Weekday::Friday => 5.0,
622
+        Weekday::Saturday => 6.0,
623
+        Weekday::Sunday => 7.0,
624
+    }
625
+}
626
+
627
+fn date_property(d: civil::Date, name: &str) -> Value {
628
+    match name {
629
+        "year" => num(d.year()),
630
+        "month" => num(d.month()),
631
+        "day" => num(d.day()),
632
+        "weekday" => num(weekday_number(d.weekday())),
633
+        _ => Value::Null,
634
+    }
635
+}
636
+
637
+fn time_property(t: &Time, name: &str) -> Value {
638
+    match name {
639
+        "hour" => num(t.time.hour()),
640
+        "minute" => num(t.time.minute()),
641
+        "second" => num(second_with_fraction(t.time)),
642
+        "time offset" => offset_duration(&t.zone),
643
+        "timezone" => zone_name(&t.zone),
644
+        _ => Value::Null,
645
+    }
646
+}
647
+
648
+fn datetime_property(dt: &DateTime, name: &str) -> Value {
649
+    match name {
650
+        "year" => num(dt.dt.year()),
651
+        "month" => num(dt.dt.month()),
652
+        "day" => num(dt.dt.day()),
653
+        "weekday" => num(weekday_number(dt.dt.weekday())),
654
+        "hour" => num(dt.dt.hour()),
655
+        "minute" => num(dt.dt.minute()),
656
+        "second" => num(second_with_fraction(dt.dt.time())),
657
+        "time offset" => offset_duration(&dt.zone),
658
+        "timezone" => zone_name(&dt.zone),
659
+        _ => Value::Null,
660
+    }
661
+}
662
+
663
+fn ym_property(months: i64, name: &str) -> Value {
664
+    match name {
665
+        "years" => num((months / 12) as f64),
666
+        "months" => num((months % 12) as f64),
667
+        _ => Value::Null,
668
+    }
669
+}
670
+
671
+fn dt_property(d: SignedDuration, name: &str) -> Value {
672
+    let total = d.as_secs();
673
+    let nanos = d.subsec_nanos();
674
+    match name {
675
+        "days" => num((total / 86_400) as f64),
676
+        "hours" => num(((total % 86_400) / 3_600) as f64),
677
+        "minutes" => num(((total % 3_600) / 60) as f64),
678
+        "seconds" => num((total % 60) as f64 + nanos as f64 / 1e9),
679
+        _ => Value::Null,
680
+    }
681
+}
682
+
683
+fn second_with_fraction(t: civil::Time) -> f64 {
684
+    t.second() as f64 + t.subsec_nanosecond() as f64 / 1e9
685
+}
686
+
687
+/// The `.time offset` property: a days-and-time duration equal to the zone offset,
688
+/// or null when the value has no zone.
689
+fn offset_duration(zone: &Option<Zone>) -> Value {
690
+    match zone {
691
+        Some(Zone::Utc) => Value::DaysTimeDuration(SignedDuration::ZERO),
692
+        Some(Zone::Offset(o)) => {
693
+            Value::DaysTimeDuration(SignedDuration::from_secs(o.seconds() as i64))
694
+        }
695
+        Some(Zone::Named(name)) => TimeZone::get(name)
696
+            .ok()
697
+            .map(|tz| tz.to_offset(jiff::Timestamp::UNIX_EPOCH).seconds())
698
+            .map(|s| Value::DaysTimeDuration(SignedDuration::from_secs(s as i64)))
699
+            .unwrap_or(Value::Null),
700
+        None => Value::Null,
701
+    }
702
+}
703
+
704
+/// The `.timezone` property: the IANA name for a named zone, else null.
705
+fn zone_name(zone: &Option<Zone>) -> Value {
706
+    match zone {
707
+        Some(Zone::Named(name)) => Value::String(name.clone()),
708
+        _ => Value::Null,
709
+    }
710
+}