Skip to main content

relate_core/temporal/
parse.rs

1//! Parsing of temporal values: ISO-8601 forms, CIP-228 patterns, and durations.
2
3use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
4
5use crate::{Error, Result, Value};
6
7use super::clock::ClockKind;
8use super::construct::date_from_week;
9use super::duration::parse_duration_iso;
10use super::duration_pattern::parse_duration_pattern;
11use super::pattern::{invalid_value, parse_instant_pattern};
12use super::zone::{
13    parse_offset, resolve_wall_forward, sub_offset, zone_kind, zone_offset_mismatch, OverlapPolicy,
14    ZoneSpec,
15};
16use super::{range_err, weekday_from_i, Temporal};
17
18pub fn parse_iso(kind: &str, s: &str) -> Result<Temporal> {
19    match kind {
20        "date" => parse_date_str(s),
21        // One arm and one parser per time kind: a `localtime` literal never
22        // carries an offset, and its parser says so (`cannot parse time`),
23        // rather than the kind falling out of a shared guard into the
24        // "unknown temporal kind" arm.
25        "localtime" => parse_naive_time(s).map(Temporal::LocalTime),
26        "time" => parse_time_str(s),
27        "localdatetime" => parse_localdatetime_str(s),
28        "datetime" => parse_zoned_dt(s),
29        "duration" => parse_duration_iso(s),
30        _ => Err(Error::ty(format!("unknown temporal kind {kind}"))),
31    }
32}
33
34/// Whether a time literal carries an offset marker: a `+`/`Z` suffix, or a
35/// `-` past the first byte (a `-` in the first position is a sign the time
36/// grammar never has, so it is left to the parser's own rejection).
37fn time_has_offset(s: &str) -> bool {
38    s.contains('+') || s.contains('Z') || s.get(1..).unwrap_or("").contains('-')
39}
40
41/// A `time` literal: the zone-less spelling builds the offset-zero wall
42/// clock, a carrying one goes through [`parse_zoned_time`]. A `time` literal
43/// has no date, so a bracketed zone name is not assignable to it; the
44/// reference engine rejects the literal rather than dropping the zone.
45fn parse_time_str(s: &str) -> Result<Temporal> {
46    if s.contains('[') {
47        return Err(Error::argument_error(
48            "Using a named time zone is not valid for a time without a date.",
49        ));
50    }
51    if time_has_offset(s) {
52        return parse_zoned_time(s);
53    }
54    parse_naive_time(s).map(|time| Temporal::Time { time, offset: 0 })
55}
56
57pub fn parse_pattern(kind: &str, value: &str, pattern: &str) -> Result<Temporal> {
58    if value.is_empty() || pattern.is_empty() {
59        return Err(invalid_value("empty temporal value or pattern"));
60    }
61    if kind == "duration" {
62        return parse_duration_pattern(value, pattern);
63    }
64    let kind = ClockKind::from_name(kind)
65        .ok_or_else(|| invalid_value(format!("unknown temporal kind {kind}")))?;
66    parse_instant_pattern(kind, value, pattern)
67}
68
69fn parse_civil_ymd(s: &str) -> Option<(i64, u32, u32)> {
70    let t = s.trim();
71    let (sign, rest) = if let Some(rest) = t.strip_prefix('+') {
72        (1i64, rest)
73    } else if let Some(rest) = t.strip_prefix('-') {
74        if rest.as_bytes().first().is_some_and(u8::is_ascii_digit) {
75            (-1i64, rest)
76        } else {
77            (1i64, t)
78        }
79    } else {
80        (1i64, t)
81    };
82    let mut parts = rest.split('-');
83    let year = parts.next()?.parse::<i64>().ok()? * sign;
84    let month = parts.next()?.parse().ok()?;
85    let day = parts.next()?.parse().ok()?;
86    Some((year, month, day))
87}
88
89fn parse_date_str(s: &str) -> Result<Temporal> {
90    if let Some((year, month, day)) = parse_civil_ymd(s) {
91        // One calendar check per branch: inside chrono's range
92        // `NaiveDate::from_ymd_opt` is the calendar, and outside it
93        // `is_civil_date` is (the check chrono cannot make for an i64 year).
94        // The split only chooses the representation.
95        if (i64::from(NaiveDate::MIN.year())..=i64::from(NaiveDate::MAX.year())).contains(&year) {
96            let date =
97                NaiveDate::from_ymd_opt(i32::try_from(year).map_err(|_| range_err())?, month, day)
98                    .ok_or_else(|| Error::ty(format!("invalid date '{s}'")))?;
99            return Ok(Temporal::Date(date));
100        }
101        if !is_civil_date(year, month, day) {
102            return Err(Error::ty(format!("invalid date '{s}'")));
103        }
104        return Ok(Temporal::CivilDate { year, month, day });
105    }
106    let t = s.trim().trim_start_matches('+');
107    parse_date_flexible(t)
108        .map(Temporal::Date)
109        .ok_or_else(|| Error::ty(format!("cannot parse date '{s}'")))
110}
111
112/// Whether `(year, month, day)` names a proleptic-Gregorian calendar date
113/// for any `i64` year — the check chrono cannot make outside its own range.
114fn is_civil_date(year: i64, month: u32, day: u32) -> bool {
115    days_in_month(year, month).is_some_and(|length| (1..=length).contains(&day))
116}
117
118/// The proleptic-Gregorian length of `month` in `year`, or `None` when
119/// `month` is not a month: February follows the 4/100/400 leap rule.
120/// Divisibility tests read the same for negative years, so the calendar
121/// stays proleptic on both sides of year zero.
122fn days_in_month(year: i64, month: u32) -> Option<u32> {
123    Some(match month {
124        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
125        4 | 6 | 9 | 11 => 30,
126        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
127        2 => 28,
128        _ => return None,
129    })
130}
131
132/// `date(s)` for the exact padded-ISO calendar form `YYYY-MM-DD` —
133/// ASCII digits in the year, month and day slots, dashes in the fixed
134/// separators — as [`parse_date_str`] builds it, without the
135/// split-and-parse walk. `None` for any other shape or for an impossible
136/// calendar date: the caller then constructs through the general policy
137/// (and reports its typed error). The per-row scan path reads stored
138/// padded-ISO birthdays this way; the mirrored reading is pinned by a
139/// differential test against `parse_date_str`.
140pub fn padded_iso_date_value(s: &str) -> Option<Value> {
141    let b = s.as_bytes();
142    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
143        return None;
144    }
145    let digits = |slot: &[u8]| slot.iter().all(u8::is_ascii_digit);
146    if !(digits(&b[..4]) && digits(&b[5..7]) && digits(&b[8..])) {
147        return None;
148    }
149    let year: i32 = s[..4].parse().ok()?;
150    let month: u32 = s[5..7].parse().ok()?;
151    let day: u32 = s[8..].parse().ok()?;
152    NaiveDate::from_ymd_opt(year, month, day).map(|d| Value::Temporal(Temporal::Date(d)))
153}
154
155fn parse_date_flexible(s: &str) -> Option<NaiveDate> {
156    let t = s.trim().trim_start_matches('+');
157    if let Ok(d) = NaiveDate::parse_from_str(t, "%Y-%m-%d") {
158        return Some(d);
159    }
160    if let Ok(d) = NaiveDate::parse_from_str(t, "%Y%m%d") {
161        return Some(d);
162    }
163    if t.len() == 7 && t.as_bytes().get(4) == Some(&b'-') {
164        if let (Ok(y), Ok(m)) = (t[..4].parse::<i32>(), t[5..].parse::<u32>()) {
165            return NaiveDate::from_ymd_opt(y, m, 1);
166        }
167    }
168    if t.len() == 6 && t.chars().all(|c| c.is_ascii_digit()) {
169        if let Ok(d) = NaiveDate::parse_from_str(&format!("{t}01"), "%Y%m%d") {
170            return Some(d);
171        }
172    }
173    if t.len() == 4 && t.chars().all(|c| c.is_ascii_digit()) {
174        return NaiveDate::from_ymd_opt(t.parse().ok()?, 1, 1);
175    }
176    if let Some(d) = parse_week_date(t) {
177        return Some(d);
178    }
179    parse_ordinal_date(t)
180}
181
182fn parse_week_date(s: &str) -> Option<NaiveDate> {
183    let compact = s.contains('W') && !s.contains('-');
184    let rest = s.split_once('W')?.1;
185    let year: i32 = s.split(['W', '-']).next()?.parse().ok()?;
186    if compact {
187        if rest.len() >= 3 {
188            let week: u32 = rest.get(..2)?.parse().ok()?;
189            let dow = rest.get(2..)?.parse::<u32>().unwrap_or(1);
190            return date_from_week(year, week, weekday_from_i(i64::from(dow))).ok();
191        }
192        let week: u32 = rest.parse().ok()?;
193        return date_from_week(year, week, Weekday::Mon).ok();
194    }
195    let parts: Vec<&str> = rest.split('-').collect();
196    let week: u32 = parts.first()?.parse().ok()?;
197    let dow = parts
198        .get(1)
199        .and_then(|p| p.parse::<i64>().ok())
200        .unwrap_or(1);
201    date_from_week(year, week, weekday_from_i(dow)).ok()
202}
203
204fn parse_ordinal_date(s: &str) -> Option<NaiveDate> {
205    if let Some((y, d)) = s.split_once('-') {
206        if y.len() == 4 && d.len() == 3 && d.chars().all(|c| c.is_ascii_digit()) {
207            return NaiveDate::from_yo_opt(y.parse().ok()?, d.parse().ok()?);
208        }
209    }
210    if s.len() == 7 && s.chars().all(|c| c.is_ascii_digit()) {
211        return NaiveDate::from_yo_opt(s[..4].parse().ok()?, s[4..].parse().ok()?);
212    }
213    None
214}
215
216fn parse_localdatetime_str(s: &str) -> Result<Temporal> {
217    let (body, _) = split_offset(s);
218    if let Ok(dt) = parse_naive_dt(body) {
219        return Ok(Temporal::LocalDateTime(dt));
220    }
221    let (date_s, time_s) = match body.split_once('T') {
222        Some((d, t)) => (d, Some(t)),
223        None => (body, None),
224    };
225    if let Temporal::CivilDate { year, month, day } = parse_date_str(date_s)? {
226        let time = match time_s {
227            Some(t) if !t.is_empty() => parse_naive_time(t).unwrap_or(NaiveTime::MIN),
228            _ => NaiveTime::MIN,
229        };
230        return Ok(Temporal::CivilDateTime {
231            year,
232            month,
233            day,
234            time,
235        });
236    }
237    Err(Error::ty(format!("cannot parse localdatetime '{s}'")))
238}
239
240fn parse_naive_time(s: &str) -> Result<NaiveTime> {
241    for fmt in ["%H:%M:%S%.f", "%H:%M:%S", "%H:%M", "%H%M%S", "%H%M"] {
242        if let Ok(t) = NaiveTime::parse_from_str(s, fmt) {
243            return Ok(t);
244        }
245    }
246    if let Some((hms, frac)) = s.split_once('.') {
247        if hms.len() == 6 && hms.chars().all(|c| c.is_ascii_digit()) {
248            let h: u32 = hms[..2].parse().unwrap_or(0);
249            let m: u32 = hms[2..4].parse().unwrap_or(0);
250            let sec: u32 = hms[4..].parse().unwrap_or(0);
251            let mut nano = 0u32;
252            let mut place = 100_000_000u32;
253            for c in frac.chars().filter(|c| c.is_ascii_digit()) {
254                nano += (c as u32 - b'0' as u32) * place;
255                place /= 10;
256                if place == 0 {
257                    break;
258                }
259            }
260            if let Some(t) = NaiveTime::from_hms_nano_opt(h, m, sec, nano) {
261                return Ok(t);
262            }
263        }
264    }
265    if s.chars().all(|c| c.is_ascii_digit()) {
266        let padded = match s.len() {
267            1 | 2 => format!("{s:0>2}0000"),
268            4 => format!("{s}00"),
269            6 => s.to_string(),
270            _ => String::new(),
271        };
272        if padded.len() == 6 {
273            if let Ok(t) = NaiveTime::parse_from_str(&padded, "%H%M%S") {
274                return Ok(t);
275            }
276        }
277    }
278    Err(Error::ty(format!("cannot parse time '{s}'")))
279}
280
281pub fn datetime_from_epoch(seconds: i64, nanos: i64) -> Result<Temporal> {
282    let utc = chrono::DateTime::from_timestamp(seconds, nanos.clamp(0, 999_999_999) as u32)
283        .ok_or_else(|| Error::ty("epoch out of range"))?
284        .naive_utc();
285    Ok(Temporal::DateTime {
286        utc,
287        offset: 0,
288        zone: Some("Z".into()),
289    })
290}
291
292pub fn datetime_from_epoch_millis(ms: i64) -> Result<Temporal> {
293    datetime_from_epoch(ms.div_euclid(1000), (ms.rem_euclid(1000)) * 1_000_000)
294}
295
296fn parse_naive_dt(s: &str) -> Result<NaiveDateTime> {
297    let normalized = s.replace(' ', "T");
298    let (body, _) = split_offset(&normalized);
299    // chrono's `%Y` needs the sign for a year outside `0000..=9999`
300    // (`+275760-09-13T00:00`, the reference engine's maximum datetime), so
301    // try the text as written before the unsigned spelling the shorter
302    // fast paths expect. Trimming first would turn a signed six-digit year
303    // into an unparseable unsigned one.
304    let unsigned = body.trim_start_matches('+');
305    for candidate in [body, unsigned] {
306        for fmt in [
307            "%Y-%m-%dT%H:%M:%S%.f",
308            "%Y-%m-%dT%H:%M:%S",
309            "%Y-%m-%dT%H:%M",
310            "%Y-%m-%dT%H",
311            "%Y-%m-%d",
312        ] {
313            if let Ok(dt) = NaiveDateTime::parse_from_str(candidate, fmt) {
314                return Ok(dt);
315            }
316            if fmt == "%Y-%m-%d" {
317                if let Ok(d) = NaiveDate::parse_from_str(candidate, fmt) {
318                    return Ok(d.and_time(NaiveTime::MIN));
319                }
320            }
321        }
322    }
323    let (date_s, time_s) = match unsigned.split_once('T') {
324        Some((d, t)) => (d, t),
325        None => {
326            return parse_date_flexible(unsigned)
327                .map(|d| d.and_time(NaiveTime::MIN))
328                .ok_or_else(|| Error::ty(format!("cannot parse localdatetime '{s}'")));
329        }
330    };
331    let date = parse_date_flexible(date_s)
332        .ok_or_else(|| Error::ty(format!("cannot parse localdatetime '{s}'")))?;
333    let time = if time_s.is_empty() {
334        NaiveTime::MIN
335    } else {
336        parse_naive_time(time_s)?
337    };
338    Ok(date.and_time(time))
339}
340
341fn split_offset(s: &str) -> (&str, Option<&str>) {
342    if let Some(i) = s.find('Z') {
343        return (&s[..i], Some("Z"));
344    }
345    if let Some(i) = s.rfind('+') {
346        if i > 0 {
347            return (&s[..i], Some(&s[i..]));
348        }
349    }
350    if let Some(i) = s.rfind('-') {
351        if i > 0 && s.as_bytes()[i - 1].is_ascii_digit() {
352            if s[..i].contains('T') || s[..i].contains(':') {
353                return (&s[..i], Some(&s[i..]));
354            }
355            let body = &s[..i];
356            let off = &s[i + 1..];
357            let compact_time = body.chars().all(|c| c.is_ascii_digit() || c == '.');
358            let offset_ok = off.contains(':')
359                && off.chars().all(|c| c.is_ascii_digit() || c == ':')
360                || off.chars().all(|c| c.is_ascii_digit()) && matches!(off.len(), 2 | 4);
361            if compact_time && offset_ok {
362                return (&s[..i], Some(&s[i..]));
363            }
364        }
365    }
366    (s, None)
367}
368
369/// A `time` literal's offset. The bracketed-zone rejection lives in
370/// [`parse_time_str`], which every `time` literal passes through first, so
371/// there is no second copy here.
372fn parse_zoned_time(s: &str) -> Result<Temporal> {
373    let (body, off) = split_offset(s);
374    let time = parse_naive_time(body)?;
375    let offset = off.map(parse_offset).transpose()?.unwrap_or(0);
376    Ok(Temporal::Time { time, offset })
377}
378
379/// The one spelling of a named zone contradicted by a supplied offset.
380/// A supplied offset must name the zone's own offset at that wall clock; a
381/// contradicting offset is rejected, never silently replaced by the zone's.
382/// The one check every non-overlap zone arm shares.
383fn check_matching_offset(zone: &str, want: Option<i32>, actual: i32) -> Result<()> {
384    if want.is_some_and(|want| want != actual) {
385        return Err(zone_offset_mismatch(zone));
386    }
387    Ok(())
388}
389
390fn parse_zoned_dt(s: &str) -> Result<Temporal> {
391    let (body, zone_part) = if let Some(i) = s.find('[') {
392        (&s[..i], Some(s[i + 1..].trim_end_matches(']')))
393    } else {
394        let (b, o) = split_offset(s);
395        (b, o)
396    };
397    // An offset written beside a bracketed zone disambiguates the wall clock
398    // inside a DST overlap: `datetime('2020-10-25T02:30+01:00[Europe/Stockholm]')`
399    // is the post-transition 02:30, not an error.
400    let (body, body_offset) = split_offset(body);
401    let local = parse_naive_dt(body)?;
402    if let Some(z) = zone_part {
403        let want = body_offset.map(parse_offset).transpose()?;
404        // Every arm answers the same three facts — the (possibly
405        // gap-shifted) wall clock, its offset, and the zone spelling to
406        // keep — and the value is built once.
407        let (local, offset, zone) = match zone_kind(z) {
408            ZoneSpec::Iana(_) | ZoneSpec::Other(_) => {
409                // A supplied offset must name the zone's own occurrence of
410                // the wall clock (never silently replaced), an overlap needs
411                // one, and a gap shifts forward only when none was written.
412                let policy = want.map_or(OverlapPolicy::Reject, OverlapPolicy::Require);
413                let (local, offset) = resolve_wall_forward(z, local, policy)?;
414                (local, offset, Some(z.to_string()))
415            }
416            ZoneSpec::Utc => {
417                check_matching_offset(z, want, 0)?;
418                (local, 0, Some("Z".into()))
419            }
420            // The classifier already split the two spellings: a numeric
421            // offset stays offset-only, a `GMT`/`UTC` prefixed one keeps its
422            // spelling as the value's zone.
423            ZoneSpec::Fixed(_) => {
424                let offset = parse_offset(z)?;
425                check_matching_offset(z, want, offset)?;
426                (local, offset, None)
427            }
428            ZoneSpec::Prefixed(_) => {
429                let offset = parse_offset(z)?;
430                check_matching_offset(z, want, offset)?;
431                (local, offset, Some(z.to_string()))
432            }
433        };
434        return Ok(Temporal::DateTime {
435            utc: sub_offset(local, offset)?,
436            offset,
437            zone,
438        });
439    }
440    Ok(Temporal::DateTime {
441        utc: local,
442        offset: 0,
443        zone: Some("Z".into()),
444    })
445}