Public repository: timo / feel

Reader

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

Outline: 75 definitions
1
//! FEEL temporal types: `date`, `time`, `date and time`, and the two durations
2
//! (`years and months duration`, `days and time duration`). Backed by `jiff`
3
//! (ADR-18). This module is the single home for temporal parsing, canonical
4
//! ISO-8601 formatting, comparison/equality, arithmetic, and component access, so
5
//! `eval.rs`/`builtins.rs` stay thin and just delegate here.
6
//!
7
//! Representation choices:
8
//! - `date` is a `jiff::civil::Date`.
9
//! - `time`/`date and time` keep the *wall-clock* civil value plus an optional
10
//!   [`Zone`], rather than a `jiff::Zoned`, so the original offset/zone is
11
//!   preserved verbatim for round-trip output (`Z` vs `+00:00`, an IANA name).
12
//! - the two durations are distinct FEEL types: a years-months duration is an
13
//!   `i64` total of months; a days-time duration is a `jiff::SignedDuration`.
14
15
use std::cmp::Ordering;
16
use std::str::FromStr;
17
18
use jiff::civil::{self, Weekday};
19
use jiff::tz::{Offset, TimeZone};
20
use jiff::{SignedDuration, Span, Unit, Zoned};
21
22
use crate::ast::ArithOp;
23
use crate::Value;
24
25
/// The zone attached to a `time` / `date and time`. Kept faithful for output:
26
/// `Utc` renders as `Z`, `Offset` as `±HH:MM`, `Named` as `@Area/City`.
27
#[derive(Debug, Clone, PartialEq, Eq)]
28
pub enum Zone {
29
    /// `Z` — UTC written explicitly (distinct from a `+00:00` offset for output).
30
    Utc,
31
    /// A fixed offset from UTC, e.g. `+02:00`.
32
    Offset(Offset),
33
    /// A named IANA zone, e.g. `Europe/Paris` (stored by name; resolved on demand).
34
    Named(String),
35
}
36
37
/// A FEEL `time`: a civil time-of-day with an optional zone.
38
#[derive(Debug, Clone, PartialEq, Eq)]
39
pub struct Time {
40
    pub time: civil::Time,
41
    pub zone: Option<Zone>,
42
}
43
44
/// A FEEL `date and time`: a civil date-time with an optional zone.
45
#[derive(Debug, Clone, PartialEq, Eq)]
46
pub struct DateTime {
47
    pub dt: civil::DateTime,
48
    pub zone: Option<Zone>,
49
}
50
51
/// `true` if `v` is a `time` / `date and time` carrying a *named* IANA zone
52
/// (e.g. `@Europe/Berlin`) rather than a fixed offset or `Z`. A named zone's UTC
53
/// offset is resolved against the (updatable) IANA tzdb, so a deterministic /
54
/// IMMUTABLE evaluation surface bans it via [`crate::EvalEnv::vet_named_zone`]
55
/// (RD-10). Offsets and `Z` are tzdb-independent and always allowed.
56
pub(crate) fn has_named_zone(v: &Value) -> bool {
57
    matches!(
58
        v,
59
        Value::Time(Time {
60
            zone: Some(Zone::Named(_)),
61
            ..
62
        }) | Value::DateTime(DateTime {
63
            zone: Some(Zone::Named(_)),
64
            ..
65
        })
66
    )
67
}
68
69
// --------------------------------------------------------------------------- //
70
// Parsing — `@"…"` literals and the typed forms behind the constructors
71
// --------------------------------------------------------------------------- //
72
73
/// Parse the inner text of an `@"…"` literal. The lexical form selects the type:
74
/// a leading `P`/`-P` is a duration; otherwise a `T` marks a date-and-time, a `:`
75
/// (without `T`) a time, and anything else a date. A malformed literal is `None`
76
/// (the caller maps that to an error-null).
77
pub(crate) fn parse_at_literal(s: &str) -> Option<Value> {
78
    let t = s.trim();
79
    if t.starts_with('P') || t.starts_with("-P") {
80
        parse_duration(t)
81
    } else if t.contains('T') {
82
        parse_date_time(t).map(Value::DateTime)
83
    } else if t.contains(':') {
84
        parse_time(t).map(Value::Time)
85
    } else {
86
        parse_date(t).map(Value::Date)
87
    }
88
}
89
90
/// Parse a string for a typed temporal slot (used by constructors and the fixture
91
/// loop). `kind` is one of `date` / `time` / `date and time` / `duration`.
92
pub fn temporal_from_iso(kind: &str, text: &str) -> Option<Value> {
93
    let t = text.trim();
94
    match kind {
95
        "date" => parse_date(t).map(Value::Date),
96
        "time" => parse_time(t).map(Value::Time),
97
        "date and time" => parse_date_time(t).map(Value::DateTime),
98
        "duration" => parse_duration(t),
99
        _ => None,
100
    }
101
}
102
103
/// Parse a `date` in the strict FEEL/XSD lexical form: an optional leading `-`,
104
/// then **exactly** four year digits, `-`, two month digits, `-`, two day digits.
105
/// This rejects `998-12-31` (3-digit), `01211-12-31` (5-digit) and `+2012-12-02`
106
/// (leading `+`) the way the TCK requires; out-of-range years are `None` too.
107
pub(crate) fn parse_date(s: &str) -> Option<civil::Date> {
108
    let (neg, body) = match s.strip_prefix('-') {
109
        Some(b) => (true, b),
110
        None => (false, s),
111
    };
112
    let parts: Vec<&str> = body.split('-').collect();
113
    if parts.len() != 3 || parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 {
114
        return None;
115
    }
116
    if !parts.iter().all(|p| digits(p)) {
117
        return None;
118
    }
119
    let y: i16 = parts[0].parse().ok()?;
120
    let m: i8 = parts[1].parse().ok()?;
121
    let d: i8 = parts[2].parse().ok()?;
122
    civil::Date::new(if neg { -y } else { y }, m, d).ok()
123
}
124
125
pub(crate) fn parse_time(s: &str) -> Option<Time> {
126
    let (civil_part, zone) = split_zone(s)?;
127
    let time = parse_civil_time(civil_part)?;
128
    Some(Time { time, zone })
129
}
130
131
pub(crate) fn parse_date_time(s: &str) -> Option<DateTime> {
132
    let (civil_part, zone) = split_zone(s)?;
133
    // A date-only string is a date and time at midnight (per the TCK, e.g.
134
    // `date and time("2012-12-24") = 2012-12-24T00:00:00`).
135
    let dt = match civil_part.split_once('T') {
136
        // `24:00:00` is end-of-day = next-day midnight (XSD); jiff has no hour 24.
137
        Some((date_str, "24:00:00")) => parse_date(date_str)?.tomorrow().ok()?.to_datetime(civil::Time::MIN),
138
        Some((date_str, time_str)) => parse_date(date_str)?.to_datetime(parse_civil_time(time_str)?),
139
        None => parse_date(civil_part)?.to_datetime(civil::Time::MIN),
140
    };
141
    Some(DateTime { dt, zone })
142
}
143
144
/// Parse a civil time-of-day, rejecting a leap second (`:60`) which FEEL does not
145
/// have but jiff would accept.
146
fn parse_civil_time(s: &str) -> Option<civil::Time> {
147
    let sec_field = s.split(':').nth(2)?;
148
    let sec_int = sec_field.split('.').next()?;
149
    if sec_int.parse::<u32>().ok()? >= 60 {
150
        return None;
151
    }
152
    civil::Time::from_str(s).ok()
153
}
154
155
/// Split a trailing zone designator (`Z`, `±HH:MM[:SS]`, or `@Area/City`) off a
156
/// time / date-time string. Returns the civil remainder and the parsed zone, or
157
/// `None` for an invalid combination (a named zone *and* an explicit offset, or an
158
/// out-of-range offset). The leading sign of a negative year is never mistaken for
159
/// an offset (we only inspect the tail).
160
fn split_zone(s: &str) -> Option<(&str, Option<Zone>)> {
161
    let (rest, named) = match s.find('@') {
162
        Some(idx) => {
163
            let name = &s[idx + 1..];
164
            // Validate the zone name eagerly so a bad `@xyz/abc` is an error-null.
165
            TimeZone::get(name).ok()?;
166
            (&s[..idx], Some(Zone::Named(name.to_string())))
167
        }
168
        None => (s, None),
169
    };
170
    let (civil_part, off_zone) = if let Some(r) = rest.strip_suffix('Z') {
171
        (r, Some(Zone::Utc))
172
    } else if let Some((r, secs)) = split_offset_suffix(rest) {
173
        (r, Some(offset_to_zone(secs)?))
174
    } else {
175
        (rest, None)
176
    };
177
    // FEEL forbids combining an explicit offset with a named zone.
178
    if named.is_some() && off_zone.is_some() {
179
        return None;
180
    }
181
    Some((civil_part, named.or(off_zone)))
182
}
183
184
/// Detect a trailing `±HH:MM` or `±HH:MM:SS` offset. Returns the remainder and the
185
/// offset's total seconds, or `None` if the tail is not an offset.
186
fn split_offset_suffix(s: &str) -> Option<(&str, i32)> {
187
    // Try the longest form first (`±HH:MM:SS` = 9 chars), then `±HH:MM` (6).
188
    for len in [9usize, 6] {
189
        if s.len() <= len {
190
            continue;
191
        }
192
        let tail = &s[s.len() - len..];
193
        let sign = match tail.as_bytes()[0] {
194
            b'+' => 1,
195
            b'-' => -1,
196
            _ => continue,
197
        };
198
        let ok = match len {
199
            6 => &tail[3..4] == ":" && digits(&tail[1..3]) && digits(&tail[4..6]),
200
            9 => {
201
                &tail[3..4] == ":"
202
                    && &tail[6..7] == ":"
203
                    && digits(&tail[1..3])
204
                    && digits(&tail[4..6])
205
                    && digits(&tail[7..9])
206
            }
207
            _ => false,
208
        };
209
        if !ok {
210
            continue;
211
        }
212
        let h: i32 = tail[1..3].parse().ok()?;
213
        let m: i32 = tail[4..6].parse().ok()?;
214
        let sec: i32 = if len == 9 { tail[7..9].parse().ok()? } else { 0 };
215
        return Some((&s[..s.len() - len], sign * (h * 3600 + m * 60 + sec)));
216
    }
217
    None
218
}
219
220
/// Turn an offset's total seconds into a [`Zone`], applying FEEL's rules: a zero
221
/// offset (`+00:00`/`-00:00`) is written `Z`, and the magnitude must be within
222
/// ±14:00 (else `None` -> error-null).
223
fn offset_to_zone(total_secs: i32) -> Option<Zone> {
224
    if total_secs.abs() > 14 * 3600 {
225
        return None;
226
    }
227
    if total_secs == 0 {
228
        Some(Zone::Utc)
229
    } else {
230
        Some(Zone::Offset(Offset::from_seconds(total_secs).ok()?))
231
    }
232
}
233
234
fn digits(s: &str) -> bool {
235
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
236
}
237
238
/// `time(date)` yields midnight UTC (`00:00:00Z`) per the TCK.
239
pub(crate) fn midnight_utc_time() -> Time {
240
    Time { time: civil::Time::MIN, zone: Some(Zone::Utc) }
241
}
242
243
/// Parse an ISO-8601 duration, classifying it as years-months or days-time by its
244
/// lexical form: a `D`, `T` or `W` part makes it a days-time duration, otherwise
245
/// (only `Y`/`M`) a years-months duration. This keeps `P0M` (ym) distinct from
246
/// `PT0S`/`P0D` (dt). FEEL forbids mixing the two families.
247
pub(crate) fn parse_duration(s: &str) -> Option<Value> {
248
    let body = s.strip_prefix('-').unwrap_or(s).strip_prefix('P')?;
249
    let is_days_time = body.contains('T') || body.contains('D') || body.contains('W');
250
    let span = Span::from_str(s).ok()?;
251
    if is_days_time {
252
        // Reject a mixed duration (`P1Y1D`) — not a valid FEEL duration.
253
        if span.get_years() != 0 || span.get_months() != 0 {
254
            return None;
255
        }
256
        Some(Value::DaysTimeDuration(span_to_signed(&span)))
257
    } else {
258
        if span.get_weeks() != 0 || span.get_days() != 0 {
259
            return None;
260
        }
261
        let months = span.get_years() as i64 * 12 + span.get_months() as i64;
262
        Some(Value::YearsMonthsDuration(months))
263
    }
264
}
265
266
/// Convert a (days-time) [`Span`] to a [`SignedDuration`]. Days are taken as exactly
267
/// 24h (FEEL durations are absolute), so this does not need a relative date.
268
fn span_to_signed(span: &Span) -> SignedDuration {
269
    let secs = span.get_days() as i64 * 86_400
270
        + span.get_weeks() as i64 * 7 * 86_400
271
        + span.get_hours() as i64 * 3_600
272
        + span.get_minutes() as i64 * 60
273
        + span.get_seconds();
274
    let nanos = span.get_milliseconds() * 1_000_000
275
        + span.get_microseconds() * 1_000
276
        + span.get_nanoseconds();
277
    SignedDuration::new(secs, nanos as i32)
278
}
279
280
// --------------------------------------------------------------------------- //
281
// Canonical ISO-8601 / XSD formatting
282
// --------------------------------------------------------------------------- //
283
284
/// Canonical XSD/FEEL lexical form for a temporal value, or `None` if `v` is not
285
/// temporal. Used by the wrappers' boundary, the fixture loop, and `string(x)`.
286
pub fn to_iso(v: &Value) -> Option<String> {
287
    Some(match v {
288
        Value::Date(d) => fmt_date(*d),
289
        Value::Time(t) => format!("{}{}", fmt_time(t.time), fmt_zone(&t.zone)),
290
        Value::DateTime(dt) => format!(
291
            "{}T{}{}",
292
            fmt_date(dt.dt.date()),
293
            fmt_time(dt.dt.time()),
294
            fmt_zone(&dt.zone)
295
        ),
296
        Value::YearsMonthsDuration(months) => fmt_ym(*months),
297
        Value::DaysTimeDuration(d) => fmt_dt(*d),
298
        _ => return None,
299
    })
300
}
301
302
fn fmt_date(d: civil::Date) -> String {
303
    let (y, m, day) = (d.year(), d.month(), d.day());
304
    if y < 0 {
305
        format!("-{:04}-{:02}-{:02}", -y, m, day)
306
    } else {
307
        format!("{:04}-{:02}-{:02}", y, m, day)
308
    }
309
}
310
311
fn fmt_time(t: civil::Time) -> String {
312
    let mut s = format!("{:02}:{:02}:{:02}", t.hour(), t.minute(), t.second());
313
    let nanos = t.subsec_nanosecond();
314
    if nanos != 0 {
315
        // Trim trailing zeros from the 9-digit fractional part.
316
        let frac = format!("{nanos:09}");
317
        s.push('.');
318
        s.push_str(frac.trim_end_matches('0'));
319
    }
320
    s
321
}
322
323
fn fmt_zone(zone: &Option<Zone>) -> String {
324
    match zone {
325
        None => String::new(),
326
        Some(Zone::Utc) => "Z".to_string(),
327
        Some(Zone::Offset(o)) => fmt_offset(*o),
328
        Some(Zone::Named(name)) => format!("@{name}"),
329
    }
330
}
331
332
fn fmt_offset(o: Offset) -> String {
333
    let total = o.seconds();
334
    let sign = if total < 0 { '-' } else { '+' };
335
    let abs = total.abs();
336
    let (h, m, s) = (abs / 3600, (abs % 3600) / 60, abs % 60);
337
    if s == 0 {
338
        format!("{sign}{h:02}:{m:02}")
339
    } else {
340
        format!("{sign}{h:02}:{m:02}:{s:02}")
341
    }
342
}
343
344
fn fmt_ym(months: i64) -> String {
345
    if months == 0 {
346
        return "P0M".to_string();
347
    }
348
    let mut s = String::from(if months < 0 { "-P" } else { "P" });
349
    let abs = months.unsigned_abs();
350
    let (y, m) = (abs / 12, abs % 12);
351
    if y > 0 {
352
        s.push_str(&format!("{y}Y"));
353
    }
354
    if m > 0 {
355
        s.push_str(&format!("{m}M"));
356
    }
357
    s
358
}
359
360
fn fmt_dt(d: SignedDuration) -> String {
361
    let neg = d.is_negative();
362
    let mut s = String::from(if neg { "-P" } else { "P" });
363
    let total_secs = d.as_secs().unsigned_abs();
364
    let nanos = d.subsec_nanos().unsigned_abs();
365
    let days = total_secs / 86_400;
366
    let hours = (total_secs % 86_400) / 3_600;
367
    let mins = (total_secs % 3_600) / 60;
368
    let secs = total_secs % 60;
369
    if days > 0 {
370
        s.push_str(&format!("{days}D"));
371
    }
372
    let has_time = hours > 0 || mins > 0 || secs > 0 || nanos > 0;
373
    if has_time || days == 0 {
374
        s.push('T');
375
        if hours > 0 {
376
            s.push_str(&format!("{hours}H"));
377
        }
378
        if mins > 0 {
379
            s.push_str(&format!("{mins}M"));
380
        }
381
        if secs > 0 || nanos > 0 || (hours == 0 && mins == 0) {
382
            if nanos > 0 {
383
                let frac = format!("{nanos:09}");
384
                s.push_str(&format!("{secs}.{}S", frac.trim_end_matches('0')));
385
            } else {
386
                s.push_str(&format!("{secs}S"));
387
            }
388
        }
389
    }
390
    s
391
}
392
393
// --------------------------------------------------------------------------- //
394
// Comparison & equality (within a single temporal type)
395
// --------------------------------------------------------------------------- //
396
397
/// True if `v` is any temporal value.
398
pub(crate) fn is_temporal(v: &Value) -> bool {
399
    matches!(
400
        v,
401
        Value::Date(_)
402
            | Value::Time(_)
403
            | Value::DateTime(_)
404
            | Value::YearsMonthsDuration(_)
405
            | Value::DaysTimeDuration(_)
406
    )
407
}
408
409
/// Order two temporal values. `None` for cross-type pairs (e.g. date vs duration,
410
/// or a ym- vs dt-duration) — a type mismatch, which the caller maps to an
411
/// error-null. Zoned date-times/times are compared by their instant.
412
pub(crate) fn compare(a: &Value, b: &Value) -> Option<Ordering> {
413
    match (a, b) {
414
        (Value::Date(x), Value::Date(y)) => Some(x.cmp(y)),
415
        (Value::Time(x), Value::Time(y)) => Some(time_instant(x).cmp(&time_instant(y))),
416
        (Value::DateTime(x), Value::DateTime(y)) => {
417
            Some(datetime_instant(x).cmp(&datetime_instant(y)))
418
        }
419
        (Value::YearsMonthsDuration(x), Value::YearsMonthsDuration(y)) => Some(x.cmp(y)),
420
        (Value::DaysTimeDuration(x), Value::DaysTimeDuration(y)) => Some(x.cmp(y)),
421
        _ => None,
422
    }
423
}
424
425
/// Temporal equality, three-valued in spirit: `Some(bool)` for same-type pairs,
426
/// `None` for cross temporal types (-> error-null at the call site).
427
pub(crate) fn equal(a: &Value, b: &Value) -> Option<bool> {
428
    compare(a, b).map(|o| o == Ordering::Equal)
429
}
430
431
/// Seconds-since-midnight (UTC-adjusted by any offset) for ordering times. A
432
/// named zone with no fixed offset falls back to the civil time-of-day.
433
fn time_instant(t: &Time) -> i64 {
434
    let civil = t.time.hour() as i64 * 3600
435
        + t.time.minute() as i64 * 60
436
        + t.time.second() as i64;
437
    let nanos = t.time.subsec_nanosecond() as i64;
438
    let off = match &t.zone {
439
        Some(Zone::Utc) => 0,
440
        Some(Zone::Offset(o)) => o.seconds() as i64,
441
        _ => 0,
442
    };
443
    (civil - off) * 1_000_000_000 + nanos
444
}
445
446
/// Nanoseconds since the civil epoch (UTC-adjusted by any offset) for ordering
447
/// date-times. A named zone is resolved to its offset at that instant.
448
fn datetime_instant(d: &DateTime) -> i128 {
449
    let base = civil_to_nanos(d.dt);
450
    let off_secs = match &d.zone {
451
        Some(Zone::Utc) => 0,
452
        Some(Zone::Offset(o)) => o.seconds() as i64,
453
        Some(Zone::Named(name)) => TimeZone::get(name)
454
            .ok()
455
            .and_then(|tz| d.dt.to_zoned(tz).ok())
456
            .map(|z| z.offset().seconds() as i64)
457
            .unwrap_or(0),
458
        None => 0,
459
    };
460
    base - off_secs as i128 * 1_000_000_000
461
}
462
463
fn civil_to_nanos(dt: civil::DateTime) -> i128 {
464
    // Relative to a fixed civil epoch; only used for *relative* ordering, so the
465
    // exact epoch is irrelevant as long as it is monotonic. Use jiff's timestamp
466
    // in UTC for a correct day-count across months/years.
467
    let z = dt.to_zoned(TimeZone::UTC).expect("UTC is always valid");
468
    z.timestamp().as_nanosecond()
469
}
470
471
// --------------------------------------------------------------------------- //
472
// Arithmetic (the FEEL temporal arithmetic table) and negation
473
// --------------------------------------------------------------------------- //
474
475
/// FEEL temporal arithmetic. `None` for any operand combination that is not a
476
/// defined temporal operation (the caller maps that to an error-null). Numbers
477
/// times/over durations are handled here too (the numeric-only path is upstream).
478
pub(crate) fn arith(op: ArithOp, a: &Value, b: &Value) -> Option<Value> {
479
    match op {
480
        ArithOp::Add => add(a, b),
481
        ArithOp::Sub => sub(a, b),
482
        ArithOp::Mul => mul(a, b),
483
        ArithOp::Div => div(a, b),
484
        ArithOp::Pow => None,
485
    }
486
}
487
488
/// Negate a duration (`-P1Y`, `-PT1H`). `None` for any non-duration.
489
pub(crate) fn negate(v: &Value) -> Option<Value> {
490
    match v {
491
        Value::YearsMonthsDuration(m) => Some(Value::YearsMonthsDuration(-m)),
492
        Value::DaysTimeDuration(d) => Some(Value::DaysTimeDuration(-*d)),
493
        _ => None,
494
    }
495
}
496
497
fn add(a: &Value, b: &Value) -> Option<Value> {
498
    use Value::*;
499
    match (a, b) {
500
        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => Some(YearsMonthsDuration(x + y)),
501
        (DaysTimeDuration(x), DaysTimeDuration(y)) => x.checked_add(*y).map(DaysTimeDuration),
502
        (Date(d), YearsMonthsDuration(m)) | (YearsMonthsDuration(m), Date(d)) => {
503
            add_months_date(*d, *m).map(Date)
504
        }
505
        (Date(d), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), Date(d)) => {
506
            // date + days-time duration -> date (the date part of midnight + dur).
507
            date_plus_dtd(*d, *dur).map(Date)
508
        }
509
        (DateTime(dt), YearsMonthsDuration(m)) | (YearsMonthsDuration(m), DateTime(dt)) => {
510
            add_months_dt(dt, *m).map(DateTime)
511
        }
512
        (DateTime(dt), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), DateTime(dt)) => {
513
            dt_plus_dtd(dt, *dur).map(DateTime)
514
        }
515
        (Time(t), DaysTimeDuration(dur)) | (DaysTimeDuration(dur), Time(t)) => {
516
            Some(Time(time_plus_dtd(t, *dur)))
517
        }
518
        _ => None,
519
    }
520
}
521
522
fn sub(a: &Value, b: &Value) -> Option<Value> {
523
    use Value::*;
524
    match (a, b) {
525
        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => Some(YearsMonthsDuration(x - y)),
526
        (DaysTimeDuration(x), DaysTimeDuration(y)) => x.checked_sub(*y).map(DaysTimeDuration),
527
        // point − point -> days-time duration. A date or a zoned date-time is an
528
        // *instant* (a date is midnight UTC); a zoneless date-time is *floating*.
529
        // Subtracting mixes only within the same kind — instant−instant uses the
530
        // global timeline, floating−floating the naive wall clock; a mixed pair is
531
        // a type error (-> None -> error-null).
532
        (Date(_) | DateTime(_), Date(_) | DateTime(_)) => {
533
            diff_temporal(a, b).map(DaysTimeDuration)
534
        }
535
        (Time(x), Time(y)) => {
536
            Some(DaysTimeDuration(SignedDuration::from_nanos(time_instant(x) - time_instant(y))))
537
        }
538
        (Date(d), YearsMonthsDuration(m)) => add_months_date(*d, -m).map(Date),
539
        (Date(d), DaysTimeDuration(dur)) => date_plus_dtd(*d, -*dur).map(Date),
540
        (DateTime(dt), YearsMonthsDuration(m)) => add_months_dt(dt, -m).map(DateTime),
541
        (DateTime(dt), DaysTimeDuration(dur)) => dt_plus_dtd(dt, -*dur).map(DateTime),
542
        (Time(t), DaysTimeDuration(dur)) => Some(Time(time_plus_dtd(t, -*dur))),
543
        _ => None,
544
    }
545
}
546
547
/// True if a date/date-time value sits on the global timeline (an *instant*): a
548
/// date (midnight UTC) or a zoned date-time. A zoneless date-time is *floating*.
549
fn is_instant(v: &Value) -> bool {
550
    match v {
551
        Value::Date(_) => true,
552
        Value::DateTime(dt) => dt.zone.is_some(),
553
        _ => false,
554
    }
555
}
556
557
/// Nanoseconds for a date/date-time: the real UTC instant for an instant value
558
/// (date = midnight UTC, zoned date-time resolved by its zone), or the naive civil
559
/// nanoseconds for a floating date-time.
560
fn point_nanos(v: &Value) -> i128 {
561
    match v {
562
        Value::Date(d) => date_nanos(*d),
563
        Value::DateTime(dt) => datetime_instant(dt),
564
        _ => 0,
565
    }
566
}
567
568
/// Difference between two date/date-time points, or `None` if one is an instant
569
/// and the other floating (an undefined mix in FEEL).
570
fn diff_temporal(a: &Value, b: &Value) -> Option<SignedDuration> {
571
    if is_instant(a) != is_instant(b) {
572
        return None;
573
    }
574
    nanos_to_signed(point_nanos(a) - point_nanos(b))
575
}
576
577
fn mul(a: &Value, b: &Value) -> Option<Value> {
578
    use Value::*;
579
    let (dur, n) = match (a, b) {
580
        (d, Number(n)) if is_duration(d) => (d, *n),
581
        (Number(n), d) if is_duration(d) => (d, *n),
582
        _ => return None,
583
    };
584
    scale_duration(dur, n)
585
}
586
587
fn div(a: &Value, b: &Value) -> Option<Value> {
588
    use Value::*;
589
    match (a, b) {
590
        (d, Number(n)) if is_duration(d) => {
591
            if *n == 0.0 {
592
                None
593
            } else {
594
                scale_duration(d, 1.0 / n)
595
            }
596
        }
597
        (YearsMonthsDuration(x), YearsMonthsDuration(y)) => {
598
            if *y == 0 {
599
                None
600
            } else {
601
                Some(Number(*x as f64 / *y as f64))
602
            }
603
        }
604
        (DaysTimeDuration(x), DaysTimeDuration(y)) => {
605
            let yn = signed_nanos(*y);
606
            if yn == 0 {
607
                None
608
            } else {
609
                Some(Number(signed_nanos(*x) as f64 / yn as f64))
610
            }
611
        }
612
        _ => None,
613
    }
614
}
615
616
fn is_duration(v: &Value) -> bool {
617
    matches!(v, Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_))
618
}
619
620
/// Scale a duration by an f64 factor (ADR-2: f64 is the accepted numeric model).
621
/// Years-months rounds to whole months; days-time scales its nanoseconds.
622
fn scale_duration(dur: &Value, factor: f64) -> Option<Value> {
623
    match dur {
624
        Value::YearsMonthsDuration(m) => {
625
            // Truncate toward zero (the TCK: `P1Y11M * -2.5 = -P4Y9M`, i.e.
626
            // 23 × −2.5 = −57.5 → −57 months).
627
            let scaled = (*m as f64 * factor).trunc();
628
            if scaled.is_finite() {
629
                Some(Value::YearsMonthsDuration(scaled as i64))
630
            } else {
631
                None
632
            }
633
        }
634
        Value::DaysTimeDuration(d) => {
635
            let scaled = signed_nanos(*d) as f64 * factor;
636
            if scaled.is_finite() {
637
                nanos_to_signed(scaled as i128).map(Value::DaysTimeDuration)
638
            } else {
639
                None
640
            }
641
        }
642
        _ => None,
643
    }
644
}
645
646
fn add_months_date(d: civil::Date, months: i64) -> Option<civil::Date> {
647
    d.checked_add(Span::new().months(months)).ok()
648
}
649
650
fn add_months_dt(dt: &DateTime, months: i64) -> Option<DateTime> {
651
    let new = dt.dt.checked_add(Span::new().months(months)).ok()?;
652
    Some(DateTime { dt: new, zone: dt.zone.clone() })
653
}
654
655
fn date_plus_dtd(d: civil::Date, dur: SignedDuration) -> Option<civil::Date> {
656
    Some(d.to_datetime(civil::Time::MIN).checked_add(dur).ok()?.date())
657
}
658
659
fn dt_plus_dtd(dt: &DateTime, dur: SignedDuration) -> Option<DateTime> {
660
    let new = dt.dt.checked_add(dur).ok()?;
661
    Some(DateTime { dt: new, zone: dt.zone.clone() })
662
}
663
664
fn time_plus_dtd(t: &Time, dur: SignedDuration) -> Time {
665
    Time { time: t.time.wrapping_add(dur), zone: t.zone.clone() }
666
}
667
668
/// Nanoseconds of a (zoneless) date taken at midnight, for date subtraction.
669
fn date_nanos(d: civil::Date) -> i128 {
670
    civil_to_nanos(d.to_datetime(civil::Time::MIN))
671
}
672
673
fn signed_nanos(d: SignedDuration) -> i128 {
674
    d.as_nanos()
675
}
676
677
fn nanos_to_signed(n: i128) -> Option<SignedDuration> {
678
    let secs = i64::try_from(n.div_euclid(1_000_000_000)).ok()?;
679
    let nanos = n.rem_euclid(1_000_000_000) as i32;
680
    Some(SignedDuration::new(secs, nanos))
681
}
682
683
// --------------------------------------------------------------------------- //
684
// Component / property access (`date.year`, `time.hour`, `dur.seconds`, …)
685
// --------------------------------------------------------------------------- //
686
687
/// Read a FEEL property of a temporal value. An unknown or absent property is a
688
/// value-null (`Value::Null`); the caller only routes here for temporal targets.
689
pub(crate) fn get_property(v: &Value, name: &str) -> Value {
690
    match v {
691
        Value::Date(d) => date_property(*d, name),
692
        Value::DateTime(dt) => datetime_property(dt, name),
693
        Value::Time(t) => time_property(t, name),
694
        Value::YearsMonthsDuration(m) => ym_property(*m, name),
695
        Value::DaysTimeDuration(d) => dt_property(*d, name),
696
        _ => Value::Null,
697
    }
698
}
699
700
fn num(n: impl Into<f64>) -> Value {
701
    Value::Number(n.into())
702
}
703
704
fn weekday_number(wd: Weekday) -> f64 {
705
    // FEEL weekday: Monday = 1 … Sunday = 7.
706
    match wd {
707
        Weekday::Monday => 1.0,
708
        Weekday::Tuesday => 2.0,
709
        Weekday::Wednesday => 3.0,
710
        Weekday::Thursday => 4.0,
711
        Weekday::Friday => 5.0,
712
        Weekday::Saturday => 6.0,
713
        Weekday::Sunday => 7.0,
714
    }
715
}
716
717
fn date_property(d: civil::Date, name: &str) -> Value {
718
    match name {
719
        "year" => num(d.year()),
720
        "month" => num(d.month()),
721
        "day" => num(d.day()),
722
        "weekday" => num(weekday_number(d.weekday())),
723
        _ => Value::Null,
724
    }
725
}
726
727
fn time_property(t: &Time, name: &str) -> Value {
728
    match name {
729
        "hour" => num(t.time.hour()),
730
        "minute" => num(t.time.minute()),
731
        "second" => num(second_with_fraction(t.time)),
732
        "time offset" => offset_duration(&t.zone),
733
        "timezone" => zone_name(&t.zone),
734
        _ => Value::Null,
735
    }
736
}
737
738
fn datetime_property(dt: &DateTime, name: &str) -> Value {
739
    match name {
740
        "year" => num(dt.dt.year()),
741
        "month" => num(dt.dt.month()),
742
        "day" => num(dt.dt.day()),
743
        "weekday" => num(weekday_number(dt.dt.weekday())),
744
        "hour" => num(dt.dt.hour()),
745
        "minute" => num(dt.dt.minute()),
746
        "second" => num(second_with_fraction(dt.dt.time())),
747
        "time offset" => offset_duration(&dt.zone),
748
        "timezone" => zone_name(&dt.zone),
749
        _ => Value::Null,
750
    }
751
}
752
753
fn ym_property(months: i64, name: &str) -> Value {
754
    match name {
755
        "years" => num((months / 12) as f64),
756
        "months" => num((months % 12) as f64),
757
        _ => Value::Null,
758
    }
759
}
760
761
fn dt_property(d: SignedDuration, name: &str) -> Value {
762
    let total = d.as_secs();
763
    let nanos = d.subsec_nanos();
764
    match name {
765
        "days" => num((total / 86_400) as f64),
766
        "hours" => num(((total % 86_400) / 3_600) as f64),
767
        "minutes" => num(((total % 3_600) / 60) as f64),
768
        "seconds" => num((total % 60) as f64 + nanos as f64 / 1e9),
769
        _ => Value::Null,
770
    }
771
}
772
773
fn second_with_fraction(t: civil::Time) -> f64 {
774
    t.second() as f64 + t.subsec_nanosecond() as f64 / 1e9
775
}
776
777
/// The `.time offset` property: a days-and-time duration equal to the zone offset,
778
/// or null when the value has no zone.
779
fn offset_duration(zone: &Option<Zone>) -> Value {
780
    match zone {
781
        Some(Zone::Utc) => Value::DaysTimeDuration(SignedDuration::ZERO),
782
        Some(Zone::Offset(o)) => {
783
            Value::DaysTimeDuration(SignedDuration::from_secs(o.seconds() as i64))
784
        }
785
        Some(Zone::Named(name)) => TimeZone::get(name)
786
            .ok()
787
            .map(|tz| tz.to_offset(jiff::Timestamp::UNIX_EPOCH).seconds())
788
            .map(|s| Value::DaysTimeDuration(SignedDuration::from_secs(s as i64)))
789
            .unwrap_or(Value::Null),
790
        None => Value::Null,
791
    }
792
}
793
794
/// The `.timezone` property: the IANA name for a named zone, else null.
795
fn zone_name(zone: &Option<Zone>) -> Value {
796
    match zone {
797
        Some(Zone::Named(name)) => Value::String(name.clone()),
798
        _ => Value::Null,
799
    }
800
}
801
802
// --------------------------------------------------------------------------- //
803
// Clock — `now()` / `today()` from an injected instant (ADR-18)
804
// --------------------------------------------------------------------------- //
805
806
/// `now()` as a FEEL `date and time`, taken from the injected evaluation instant.
807
pub(crate) fn now_value(z: &Zoned) -> Value {
808
    Value::DateTime(DateTime { dt: z.datetime(), zone: zone_from_zoned(z) })
809
}
810
811
/// `today()` as a FEEL `date`, taken from the injected evaluation instant.
812
pub(crate) fn today_value(z: &Zoned) -> Value {
813
    Value::Date(z.date())
814
}
815
816
/// The [`Zone`] of an injected instant: its IANA name if it has one, else its
817
/// fixed offset.
818
fn zone_from_zoned(z: &Zoned) -> Option<Zone> {
819
    match z.time_zone().iana_name() {
820
        Some(name) => Some(Zone::Named(name.to_string())),
821
        None => Some(Zone::Offset(z.offset())),
822
    }
823
}
824
825
// --------------------------------------------------------------------------- //
826
// Constructors & component helpers (used by the builtins; ADR-18)
827
// --------------------------------------------------------------------------- //
828
829
/// Build a `date` from integer components, or `None` if out of range.
830
pub(crate) fn make_date(y: i64, m: i64, d: i64) -> Option<civil::Date> {
831
    civil::Date::new(i16::try_from(y).ok()?, i8::try_from(m).ok()?, i8::try_from(d).ok()?).ok()
832
}
833
834
/// Build a `time` from integer components (+ optional zone), or `None` if out of
835
/// range.
836
pub(crate) fn make_time(h: i64, m: i64, s: i64, nanos: i64, zone: Option<Zone>) -> Option<Time> {
837
    let time = civil::Time::new(
838
        i8::try_from(h).ok()?,
839
        i8::try_from(m).ok()?,
840
        i8::try_from(s).ok()?,
841
        i32::try_from(nanos).ok()?,
842
    )
843
    .ok()?;
844
    Some(Time { time, zone })
845
}
846
847
/// Combine a `date` and a `time` (carrying the time's zone) into a `date and time`.
848
pub(crate) fn combine_date_time(date: civil::Date, t: &Time) -> DateTime {
849
    DateTime { dt: date.to_datetime(t.time), zone: t.zone.clone() }
850
}
851
852
/// Turn a days-and-time duration into a zone (the `time(h,m,s,off)` fourth
853
/// argument): a fixed offset, or `Z` for a zero offset; `None` if it is not a
854
/// whole-second offset within ±14:00.
855
pub(crate) fn offset_zone_from_dtd(d: SignedDuration) -> Option<Zone> {
856
    if d.subsec_nanos() != 0 {
857
        return None;
858
    }
859
    offset_to_zone(i32::try_from(d.as_secs()).ok()?)
860
}
861
862
/// The `date` part of a date or date-and-time value (else `None`).
863
pub(crate) fn date_of(v: &Value) -> Option<civil::Date> {
864
    match v {
865
        Value::Date(d) => Some(*d),
866
        Value::DateTime(dt) => Some(dt.dt.date()),
867
        _ => None,
868
    }
869
}
870
871
/// The `time` part of a time or date-and-time value (else `None`).
872
pub(crate) fn time_of(v: &Value) -> Option<Time> {
873
    match v {
874
        Value::Time(t) => Some(t.clone()),
875
        Value::DateTime(dt) => Some(Time { time: dt.dt.time(), zone: dt.zone.clone() }),
876
        _ => None,
877
    }
878
}
879
880
/// Whole months between two dates (the `years and months duration(from, to)`
881
/// builtin) — leftover days are dropped, and the result is signed by direction.
882
pub(crate) fn ym_between(a: civil::Date, b: civil::Date) -> Option<i64> {
883
    let span = a.until((Unit::Month, b)).ok()?;
884
    Some(span.get_years() as i64 * 12 + span.get_months() as i64)
885
}
886
887
const MONTH_NAMES: [&str; 12] = [
888
    "January", "February", "March", "April", "May", "June", "July", "August",
889
    "September", "October", "November", "December",
890
];
891
892
pub(crate) fn day_of_week_name(d: civil::Date) -> &'static str {
893
    match d.weekday() {
894
        Weekday::Monday => "Monday",
895
        Weekday::Tuesday => "Tuesday",
896
        Weekday::Wednesday => "Wednesday",
897
        Weekday::Thursday => "Thursday",
898
        Weekday::Friday => "Friday",
899
        Weekday::Saturday => "Saturday",
900
        Weekday::Sunday => "Sunday",
901
    }
902
}
903
904
pub(crate) fn month_of_year_name(d: civil::Date) -> &'static str {
905
    MONTH_NAMES[(d.month() - 1) as usize]
906
}
907
908
pub(crate) fn day_of_year_num(d: civil::Date) -> i64 {
909
    d.day_of_year() as i64
910
}
911
912
pub(crate) fn week_of_year_num(d: civil::Date) -> i64 {
913
    d.iso_week_date().week() as i64
914
}
915
916
/// `abs` of a duration (ADR-15 deferred this; ADR-18 enables it).
917
pub(crate) fn abs(v: &Value) -> Option<Value> {
918
    match v {
919
        Value::YearsMonthsDuration(m) => Some(Value::YearsMonthsDuration(m.abs())),
920
        Value::DaysTimeDuration(d) => Some(Value::DaysTimeDuration(d.abs())),
921
        _ => None,
922
    }
923
}