diff --git a/codecov.yml b/codecov.yml index d47ea72..318fccb 100644 --- a/codecov.yml +++ b/codecov.yml @@ -2,3 +2,6 @@ codecov: notify: after_n_builds: 3 wait_for_ci: true + +ignore: + - "tests/**" diff --git a/src/items/builder.rs b/src/items/builder.rs index 7782674..e561e9d 100644 --- a/src/items/builder.rs +++ b/src/items/builder.rs @@ -1,7 +1,7 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -use jiff::{civil, Span, ToSpan, Zoned}; +use jiff::{civil, Span, Zoned}; use super::{date, epoch, error, offset, relative, time, weekday, year, Item}; use crate::extended::{DateParts, TimeParts}; @@ -284,6 +284,8 @@ impl DateTimeBuilder { } else { base }; + let mut named_fixed_zone_applied = false; + let mut named_fixed_hour_adjustment = 0; // 4a. Apply date. if let Some(date) = self.date { @@ -304,7 +306,38 @@ impl DateTimeBuilder { } let t: civil::Time = time.try_into()?; + let local = civil::DateTime::new( + dt.year(), + dt.month(), + dt.day(), + t.hour(), + t.minute(), + t.second(), + t.subsec_nanosecond(), + )?; + let named_zone_is_local = self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .is_some_and(|name| matching_local_zone_at(&dt, local, name).is_some()); + if !named_zone_is_local + && self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .is_some() + { + if let Some(offset) = self.offset.as_ref() { + let (offset, hour_adjustment) = offset.clone().normalize(); + dt = dt.datetime().to_zoned((&offset).try_into()?)?; + named_fixed_hour_adjustment = hour_adjustment; + named_fixed_zone_applied = true; + } + } dt = dt.with().time(t).build()?; + if named_fixed_hour_adjustment != 0 { + dt = dt.checked_add(Span::new().hours(i64::from(named_fixed_hour_adjustment)))?; + } } // 4c. Apply weekday. @@ -349,35 +382,55 @@ impl DateTimeBuilder { dt = dt.checked_add(Span::new().try_days(delta)?)?; } - // 4d. Apply fixed offset. This anchors the instant before relative - // adjustments so that "1970/01/01 UTC N seconds" adds N seconds to the - // fixed-offset instant rather than to a local wall-clock that may drift - // across a DST boundary (see issue uutils/coreutils#12555). - if let Some(offset) = self.offset { - let (offset, hour_adjustment) = offset.normalize(); - dt = dt.checked_add(Span::new().hours(hour_adjustment))?; - dt = dt.datetime().to_zoned((&offset).try_into()?)?; + // 4d. Apply the named or fixed offset. A named abbreviation can + // describe the active local timezone rather than a fixed offset. + // Preserve that zone when the abbreviation matches the requested wall + // clock so daylight-saving transitions are resolved using the base + // zone's rules. + let named_local_zone = self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .and_then(|name| matching_local_zone(&dt, name)); + let use_named_local_zone = named_local_zone.is_some(); + if use_named_local_zone { + if let Some(offset) = self.offset.as_ref() { + let (offset, hour_adjustment) = offset.clone().normalize(); + dt = dt.checked_add(Span::new().hours(i64::from(hour_adjustment)))?; + dt = dt.datetime().to_zoned((&offset).try_into()?)?; + } } - // 4e. Apply relative adjustments. - for rel in self.relative { - dt = match rel { - relative::Relative::Years(_) | relative::Relative::Months(_) => { - // GNU way of calculating relative months and years. - // GNU changes the month/year and then checks if the target month has - // this day. If this day does not exist in the target month it overflows - // the difference. - let original_day_of_month = dt.day(); - dt = dt.checked_add::(rel.try_into()?)?; - if original_day_of_month != dt.day() { - dt = dt.checked_add( - (original_day_of_month.checked_sub(dt.day()).unwrap_or(0)).days(), - )?; - } - dt - } - _ => dt.checked_add::(rel.try_into()?)?, - }; + // Apply a fixed offset before relative adjustments. For offsets larger + // than 24 hours, first reinterpret the wall clock in the normalized + // zone and then apply the remaining hour correction. + if !use_named_local_zone && !named_fixed_zone_applied { + if let Some(offset) = self.offset { + let (offset, hour_adjustment) = offset.normalize(); + dt = dt.datetime().to_zoned((&offset).try_into()?)?; + dt = dt.checked_add(Span::new().hours(i64::from(hour_adjustment)))?; + } + } + + // Apply relative date adjustments first, then relative time + // adjustments. GNU groups all year/month fields before normalizing + // the day, rather than applying each relative item in input order. + let relative = relative_adjustment(&self.relative)?; + if let Some(zone) = named_local_zone { + if relative.has_date_component() { + dt = apply_relative_date(dt, relative)?; + } + dt = dt.with_time_zone(zone); + if relative.has_time_component() { + dt = apply_relative_time(dt, relative)?; + } + } else { + if relative.has_date_component() { + dt = apply_relative_date(dt, relative)?; + } + if relative.has_time_component() { + dt = apply_relative_time(dt, relative)?; + } } Ok(dt) @@ -550,6 +603,182 @@ fn weekday_monday0(day: weekday::Day) -> u8 { } } +fn matching_local_zone(dt: &Zoned, name: &str) -> Option { + matching_local_zone_at(dt, dt.datetime(), name) +} + +fn matching_local_zone_at( + dt: &Zoned, + local: civil::DateTime, + name: &str, +) -> Option { + // GNU's universal abbreviations always denote fixed UTC, even if the + // active local zone happens to use the same abbreviation. + if matches!(name, "utc" | "ut" | "gmt" | "z") { + return None; + } + + let zone = dt.time_zone(); + zone.iana_name()?; + let ambiguous = zone.to_ambiguous_zoned(local); + for candidate in [ + ambiguous.clone().compatible(), + ambiguous.clone().earlier(), + ambiguous.later(), + ] + .into_iter() + .flatten() + { + if candidate + .strftime("%Z") + .to_string() + .eq_ignore_ascii_case(name) + { + return Some(zone.clone()); + } + } + None +} + +/// Relative values are accumulated by unit before they are applied. GNU +/// applies all year/month changes together, followed by days and then the +/// clock units, rather than applying the input items one at a time. +#[derive(Clone, Copy, Debug, Default)] +struct RelativeAdjustment { + years: i64, + months: i64, + days: i64, + hours: i64, + minutes: i64, + seconds: i64, + nanoseconds: i64, +} + +impl RelativeAdjustment { + fn has_date_component(self) -> bool { + self.years != 0 || self.months != 0 || self.days != 0 + } + + fn has_time_component(self) -> bool { + self.hours != 0 || self.minutes != 0 || self.seconds != 0 || self.nanoseconds != 0 + } +} + +fn relative_adjustment( + relative: &[relative::Relative], +) -> Result { + let mut result = RelativeAdjustment::default(); + for rel in relative { + match *rel { + relative::Relative::Years(value) => { + result.years = result + .years + .checked_add(i64::from(value)) + .ok_or("relative year adjustment overflow")?; + } + relative::Relative::Months(value) => { + result.months = result + .months + .checked_add(i64::from(value)) + .ok_or("relative month adjustment overflow")?; + } + relative::Relative::Days(value) => { + result.days = result + .days + .checked_add(i64::from(value)) + .ok_or("relative day adjustment overflow")?; + } + relative::Relative::Hours(value) => { + result.hours = result + .hours + .checked_add(i64::from(value)) + .ok_or("relative hour adjustment overflow")?; + } + relative::Relative::Minutes(value) => { + result.minutes = result + .minutes + .checked_add(i64::from(value)) + .ok_or("relative minute adjustment overflow")?; + } + relative::Relative::Seconds(seconds, nanoseconds) => { + result.seconds = result + .seconds + .checked_add(seconds) + .ok_or("relative second adjustment overflow")?; + result.nanoseconds = result + .nanoseconds + .checked_add(i64::from(nanoseconds)) + .ok_or("relative nanosecond adjustment overflow")?; + } + } + } + Ok(result) +} + +fn apply_relative_date(mut dt: Zoned, relative: RelativeAdjustment) -> Result { + // Change the year and month as one calendar operation. This intentionally + // preserves the original day until the target month is known, so a date + // such as January 31 overflows into March rather than clamping to February. + if relative.years != 0 || relative.months != 0 { + let (year, month) = shifted_year_month(&dt, relative)?; + let first = civil::Date::new(year, month as i8, 1)?; + let target = first.checked_add(Span::new().try_days(i64::from(dt.day() - 1))?)?; + dt = dt.with().date(target).build()?; + } + if relative.days != 0 { + dt = dt.checked_add(Span::new().try_days(relative.days)?)?; + } + Ok(dt) +} + +fn shifted_year_month(dt: &Zoned, relative: RelativeAdjustment) -> Result<(i16, u8), error::Error> { + let month_index = i64::from(dt.year()) + .checked_mul(12) + .and_then(|value| value.checked_add(i64::from(dt.month()) - 1)) + .and_then(|value| value.checked_add(relative.years.checked_mul(12)?)) + .and_then(|value| value.checked_add(relative.months)) + .ok_or("relative month/year overflow")?; + let year = month_index.div_euclid(12); + let month = month_index.rem_euclid(12) + 1; + let year = i16::try_from(year).map_err(|_| "relative year overflow")?; + Ok((year, month as u8)) +} + +fn apply_relative_time(dt: Zoned, relative: RelativeAdjustment) -> Result { + let seconds = relative + .hours + .checked_mul(3_600) + .and_then(|hours| { + relative + .minutes + .checked_mul(60) + .and_then(|minutes| hours.checked_add(minutes)) + }) + .and_then(|seconds| seconds.checked_add(relative.seconds)) + .ok_or("relative time overflow")?; + let extra_seconds = relative.nanoseconds.div_euclid(1_000_000_000); + let nanoseconds = relative.nanoseconds.rem_euclid(1_000_000_000); + let seconds = seconds + .checked_add(extra_seconds) + .ok_or("relative time overflow")?; + + // Relative::Seconds stores negative fractional values in timestamp form, + // e.g. (-1, 500_000_000) for -0.5 seconds. Jiff spans require the seconds + // and nanoseconds components to have the same sign, so normalize them. + let (seconds, nanoseconds) = if seconds < 0 && nanoseconds > 0 { + ( + seconds.checked_add(1).ok_or("relative time overflow")?, + -(1_000_000_000 - nanoseconds), + ) + } else { + (seconds, nanoseconds) + }; + let span = Span::new() + .try_seconds(seconds)? + .try_nanoseconds(nanoseconds)?; + Ok(dt.checked_add(span)?) +} + impl TryFrom> for DateTimeBuilder { type Error = &'static str; diff --git a/src/items/date.rs b/src/items/date.rs index 69cbf38..5a2078f 100644 --- a/src/items/date.rs +++ b/src/items/date.rs @@ -28,15 +28,15 @@ use winnow::{ ascii::alpha1, - combinator::{alt, eof, opt, preceded, terminated}, - error::ErrMode, + combinator::{alt, dispatch, eof, fail, not, opt, peek, preceded, terminated}, + error::{ContextError, ErrMode}, stream::AsChar, - token::take_while, + token::{any, one_of, take_while}, ModalResult, Parser, }; use super::{ - primitive::{ctx_err, dec_uint, multispace1, s}, + primitive::{ctx_err, dec_uint, dec_uint_str, multispace1, s}, year::{year_from_str, year_str}, }; @@ -130,13 +130,30 @@ impl TryFrom for jiff::civil::Date { /// Parse a date that is not in ISO format. ISO dates are parsed by [`iso1`] /// and [`iso2`], which the caller tries first. pub(super) fn parse_non_iso(input: &mut &str) -> ModalResult { - alt((dotted, us, literal1, literal2, literal3)).parse_next(input) + dispatch! { s(peek(any)); + '0'..='9' => numeric, + 'a'..='z' => literal_month_first, + _ => fail, + } + .parse_next(input) } -/// Parse the European `DD.MM.[YYYY]` spelling. -fn dotted(input: &mut &str) -> ModalResult { - let (day, _, month, _, year) = ( - s(dec_uint), +fn numeric(input: &mut &str) -> ModalResult { + let first = s(dec_uint_str).parse_next(input)?; + + dispatch! { s(peek(any)); + '.' => move |input: &mut &str| dotted_after(first, input), + '/' => move |input: &mut &str| us_after(first, input), + '-' | 'a'..='z' => move |input: &mut &str| literal1_after(first, input), + _ => fail, + } + .parse_next(input) +} + +/// Parse the European `DD.MM.[YYYY]` spelling after the shared numeric prefix. +fn dotted_after(first: &str, input: &mut &str) -> ModalResult { + let day = day_from_str(first)?; + let (_, month, _, year) = ( s('.'), s(dec_uint), s('.'), @@ -181,10 +198,33 @@ pub(super) fn iso2(input: &mut &str) -> ModalResult { .map_err(|e| ErrMode::Backtrack(ctx_err(e))) } -/// Parse `[year]/[month]/[day]` or `[month]/[day]/[year]` or `[month]/[day]`. -fn us(input: &mut &str) -> ModalResult { - let (s1, _, n, s2) = ( - s(take_while(1.., AsChar::is_dec_digit)), +/// Parse either of the compact or separated ISO date forms. +/// +/// Compact dates contain at least five consecutive digits and do not have a +/// possible ISO separator after that digit run. In that case, skip the failed +/// `iso1` attempt. Inputs that could use whitespace/comments before a separator +/// retain the original alternative ordering for compatibility. +pub(super) fn iso(input: &mut &str) -> ModalResult { + if compact_iso_candidate(input) { + iso2.parse_next(input) + } else { + alt((iso1, iso2)).parse_next(input) + } +} + +fn compact_iso_candidate(input: &str) -> bool { + ( + take_while(5.., AsChar::is_dec_digit), + peek(not(one_of::<_, _, ErrMode>([ + ' ', '\t', '\n', '\x0B', '\x0C', '\r', '(', '+', '-', + ]))), + ) + .parse_peek(input) + .is_ok() +} + +fn us_after(first: &str, input: &mut &str) -> ModalResult { + let (_, n, s2) = ( s('/'), s(dec_uint), opt(preceded(s('/'), s(take_while(1.., AsChar::is_dec_digit)))), @@ -192,26 +232,26 @@ fn us(input: &mut &str) -> ModalResult { .parse_next(input)?; match s2 { - Some(s2) if s1.len() >= 4 => { + Some(s2) if first.len() >= 4 => { // [year]/[month]/[day] // // GNU quirk: interpret as [year]/[month]/[day] if the first part is at // least 4 characters long. let day = day_from_str(s2)?; - (s1, n, day) + (first, n, day) .try_into() .map_err(|e| ErrMode::Backtrack(ctx_err(e))) } Some(s2) => { // [month]/[day]/[year] - let month = month_from_str(s1)?; + let month = month_from_str(first)?; (s2, month, n) .try_into() .map_err(|e| ErrMode::Backtrack(ctx_err(e))) } None => { // [month]/[day] - let month = month_from_str(s1)?; + let month = month_from_str(first)?; (month, n) .try_into() .map_err(|e| ErrMode::Backtrack(ctx_err(e))) @@ -219,11 +259,9 @@ fn us(input: &mut &str) -> ModalResult { } } -/// Parse `14 November 2022`, `14 Nov 2022`, "14nov2022", "14-nov-2022", -/// "14-nov2022", "14nov-2022". -fn literal1(input: &mut &str) -> ModalResult { - let (day, _, month, year) = ( - s(dec_uint), +fn literal1_after(first: &str, input: &mut &str) -> ModalResult { + let day = day_from_str(first)?; + let (_, month, year) = ( opt(s('-')), s(literal_month), opt(terminated( @@ -244,10 +282,19 @@ fn literal1(input: &mut &str) -> ModalResult { } } -/// Parse `November 14, 2022`, `Nov 14, 2022`, and `Nov 14 2022`. -fn literal2(input: &mut &str) -> ModalResult { - let (month, day, year) = ( - s(literal_month), +fn literal_month_first(input: &mut &str) -> ModalResult { + let month = s(literal_month).parse_next(input)?; + + dispatch! { s(peek(any)); + '-' => move |input: &mut &str| literal3_after(month, input), + '0'..='9' => move |input: &mut &str| literal2_after(month, input), + _ => fail, + } + .parse_next(input) +} + +fn literal2_after(month: u8, input: &mut &str) -> ModalResult { + let (day, year) = ( s(dec_uint), opt(terminated( preceded( @@ -273,11 +320,8 @@ fn literal2(input: &mut &str) -> ModalResult { } } -/// Parse `November-14-2022` and `Nov-14-2022`. Unlike `literal2`, the year is mandatory -/// to match the behavior of GNU `date`. -fn literal3(input: &mut &str) -> ModalResult { - let (month, _, day, _, year) = - (s(literal_month), s('-'), s(dec_uint), s('-'), year_str).parse_next(input)?; +fn literal3_after(month: u8, input: &mut &str) -> ModalResult { + let (_, day, _, year) = (s('-'), s(dec_uint), s('-'), year_str).parse_next(input)?; // Map err to Backtrack instead of Cut to avoid early termination of parsing (year, month, day) diff --git a/src/items/epoch.rs b/src/items/epoch.rs index 6661fd0..ff70f8f 100644 --- a/src/items/epoch.rs +++ b/src/items/epoch.rs @@ -19,12 +19,12 @@ use winnow::{ ascii::digit1, - combinator::{opt, preceded}, - token::one_of, + combinator::{dispatch, opt, peek, preceded}, + token::{any, one_of}, ModalResult, Parser, }; -use super::primitive::{dec_uint, plus_or_minus, s}; +use super::primitive::{dec_uint, plus_or_minus, s, space}; /// Represents a timestamp with nanosecond accuracy. /// @@ -54,17 +54,26 @@ impl TryFrom for jiff::Timestamp { /// Parse a timestamp in the form of `@1234567890` or `@-1234567890.12345` or /// `@1234567890,12345`. pub(super) fn parse(input: &mut &str) -> ModalResult { - (s("@"), opt(plus_or_minus), s(sec_and_nsec)) - .verify_map(|(_, sign, (sec, nsec))| { - let sec = i64::try_from(sec).ok()?; - let (second, nanosecond) = match (sign, nsec) { - (Some('-'), 0) => (-sec, 0), - // Truncate towards minus infinity. - (Some('-'), _) => ((-sec).checked_sub(1)?, 1_000_000_000 - nsec), - _ => (sec, nsec), - }; - Some(Timestamp { second, nanosecond }) - }) + dispatch! { peek(opt(any)); + Some('@') => parse_at, + _ => (space, parse_at).map(|(_, value)| value), + } + .verify_map(|(sign, (sec, nsec))| { + let (second, nanosecond) = normalize_seconds(sign == Some('-'), sec, nsec)?; + Some(Timestamp { second, nanosecond }) + }) + .parse_next(input) +} + +fn parse_at(input: &mut &str) -> ModalResult<(Option, (u64, u32))> { + ( + '@', + dispatch! { peek(opt(any)); + Some('0'..='9') => sec_and_nsec.map(|value| (None, value)), + _ => (opt(plus_or_minus), s(sec_and_nsec)).map(|(sign, value)| (sign, value)), + }, + ) + .map(|(_, value)| value) .parse_next(input) } @@ -88,6 +97,16 @@ pub(super) fn sec_and_nsec(input: &mut &str) -> ModalResult<(u64, u32)> { .parse_next(input) } +pub(super) fn normalize_seconds(negative: bool, sec: u64, nsec: u32) -> Option<(i64, u32)> { + let sec = i64::try_from(sec).ok()?; + match (negative, nsec) { + (true, 0) => Some((-sec, 0)), + // Truncate towards minus infinity. + (true, _) => Some(((-sec).checked_sub(1)?, 1_000_000_000 - nsec)), + _ => Some((sec, nsec)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/items/mod.rs b/src/items/mod.rs index 0f31f06..e1c69db 100644 --- a/src/items/mod.rs +++ b/src/items/mod.rs @@ -54,9 +54,10 @@ use crate::ParsedDateTime; use jiff::Zoned; use primitive::space; use winnow::{ - combinator::{alt, eof, preceded, repeat_till, terminated, trace}, + combinator::{alt, dispatch, eof, opt, peek, preceded, repeat_till, terminated, trace}, error::{AddContext, ContextError, ErrMode, StrContext, StrContextValue}, stream::Stream, + token::any, ModalResult, Parser, }; @@ -105,7 +106,7 @@ pub(crate) fn parse_at_local + Clone>(input: S) -> Result + Clone>(input: S) -> Result ModalResult { - trace("parse", alt((parse_timestamp, parse_items))).parse_next(input) + trace( + "parse", + dispatch! { peek(opt(any)); + Some('@') => parse_timestamp, + Some('T') => parse_t_prefix, + Some(c) if c.is_ascii_whitespace() || matches!(c, '(' | '+' | '-') => { + alt((parse_timestamp, parse_items_without_timezone)) + }, + _ => parse_items_without_timezone, + }, + ) + .parse_next(input) +} + +fn parse_t_prefix(input: &mut &str) -> ModalResult { + dispatch! { peek(opt("TZ=\"")); + Some(_) => parse_timezone_prefix, + None => parse_items_without_timezone, + } + .parse_next(input) +} + +fn parse_timezone_prefix(input: &mut &str) -> ModalResult { + let tz = timezone::parse.parse_next(input)?; + alt((parse_timestamp, move |input: &mut &str| { + parse_items_after_timezone(input, Some(Item::TimeZone(tz.clone()))) + })) + .parse_next(input) } /// Parse a standalone epoch timestamp (e.g., `@1758724019`). @@ -215,9 +243,6 @@ fn parse(input: &mut &str) -> ModalResult { /// has no effect on the epoch value. We intentionally parse and ignore it. /// - Trailing input (aside from optional whitespaces) is rejected. fn parse_timestamp(input: &mut &str) -> ModalResult { - // Parse and ignore an optional leading timezone rule. - let _ = timezone::parse(input); - trace( "parse_timestamp", // Expect exactly one timestamp and then EOF (allowing trailing spaces). @@ -227,19 +252,12 @@ fn parse_timestamp(input: &mut &str) -> ModalResult { .parse_next(input) } -/// Parse a sequence of date/time items, honoring an optional leading TZ rule. -/// -/// Notes: -/// -/// - If a timezone rule (`TZ="..."`) appears at the beginning of the input, -/// parse it first. The timezone rule is case-sensitive. -/// - After the optional timezone rule is parsed, we convert the input to -/// lowercase to allow case-insensitive parsing of the remaining items. -/// - Trailing input (aside from optional whitespaces) is rejected. -fn parse_items(input: &mut &str) -> ModalResult { - // Parse and consume an optional leading timezone rule. - let tz = timezone::parse(input).map(Item::TimeZone); +/// Parse a sequence of date/time items without a leading TZ rule. +fn parse_items_without_timezone(input: &mut &str) -> ModalResult { + parse_items_after_timezone(input, None) +} +fn parse_items_after_timezone(input: &mut &str, tz: Option) -> ModalResult { // Convert input to lowercase for case-insensitive parsing. let lower: Cow = if input.bytes().any(|b| b.is_ascii_uppercase()) { input.to_ascii_lowercase().into() @@ -255,7 +273,7 @@ fn parse_items(input: &mut &str) -> ModalResult { ) .parse_next(input)?; - if let Ok(tz) = tz { + if let Some(tz) = tz { items.push(tz); } @@ -267,7 +285,7 @@ fn parse_item(input: &mut &str) -> ModalResult { // An ISO date is either the start of a combined date and time item or a // date item on its own. Parse it once instead of once per alternative. let start = input.checkpoint(); - if let Ok(date) = alt((date::iso1, date::iso2)).parse_next(input) { + if let Ok(date) = date::iso.parse_next(input) { let after_date = input.checkpoint(); match combined::parse_time_after_date(input, date.clone()) { Ok(dt) => return Ok(Item::DateTime(dt)), diff --git a/src/items/offset.rs b/src/items/offset.rs index a4f3342..764159d 100644 --- a/src/items/offset.rs +++ b/src/items/offset.rs @@ -28,10 +28,10 @@ use std::fmt::Display; use winnow::{ - combinator::{alt, peek}, + combinator::{alt, dispatch, eof, opt, peek, repeat}, error::{ContextError, ErrMode}, stream::{AsChar, Stream}, - token::{one_of, take_while}, + token::{one_of, take, take_while}, ModalResult, Parser, }; @@ -48,8 +48,9 @@ use super::{ #[derive(PartialEq, Debug, Clone, Default)] pub(super) struct Offset { negative: bool, - hours: u8, - minutes: u8, + hours: u16, + minutes: u16, + name: Option, } impl Offset { @@ -70,18 +71,19 @@ impl Offset { } } let (total_minutes, negative) = combine( - (self.hours as u16) * 60 + (self.minutes as u16), + self.hours * 60 + self.minutes, self.negative, - (offset.hours as u16) * 60 + (offset.minutes as u16), + offset.hours * 60 + offset.minutes, offset.negative, ); - let hours = (total_minutes / 60) as u8; - let minutes = (total_minutes % 60) as u8; + let hours = total_minutes / 60; + let minutes = total_minutes % 60; Offset { negative, hours, minutes, + name: self.name.or(offset.name), } } @@ -93,17 +95,18 @@ impl Offset { /// - Otherwise, the hour field is reduced to 23 while preserving the minute /// field, and the function returns the normalized offset along with the /// hour adjustment needed to reach the original offset. - pub(super) fn normalize(self) -> (Offset, i8) { + pub(super) fn normalize(self) -> (Offset, i32) { if self.hours < 24 || (self.hours == 24 && self.minutes == 0) { return (self, 0); } - let hour_adjustment = (self.hours as i8 - 23) * if self.negative { 1 } else { -1 }; + let hour_adjustment = (self.hours as i32 - 23) * if self.negative { 1 } else { -1 }; ( Offset { negative: self.negative, hours: 23, minutes: self.minutes, + name: self.name, }, hour_adjustment, ) @@ -117,23 +120,38 @@ impl Offset { secs } } + + pub(super) fn name(&self) -> Option<&str> { + self.name.as_deref() + } } impl TryFrom<(bool, u8, u8)> for Offset { type Error = &'static str; fn try_from((negative, hours, minutes): (bool, u8, u8)) -> Result { - if hours > 24 { - return Err("timezone hour must be between 0 and 24"); - } - if minutes > 60 || (hours == 24 && minutes != 0) { - return Err("timezone minute must be between 0 and 60"); + Self::from_parts(negative, u32::from(hours), u32::from(minutes)) + } +} + +impl Offset { + /// Construct an offset from raw hour and minute fields. GNU normalizes + /// excess minutes into hours, but rejects offsets whose total magnitude + /// exceeds 24 hours. + fn from_parts(negative: bool, hours: u32, minutes: u32) -> Result { + let total_minutes = hours + .checked_mul(60) + .and_then(|hours| hours.checked_add(minutes)) + .ok_or("timezone offset is too large")?; + if total_minutes > 24 * 60 { + return Err("timezone offset must be between -24:00 and +24:00"); } - Ok(Offset { + Ok(Self { negative, - hours, - minutes, + hours: (total_minutes / 60) as u16, + minutes: (total_minutes % 60) as u16, + name: None, }) } } @@ -146,6 +164,7 @@ impl TryFrom<&Offset> for jiff::tz::TimeZone { negative, hours, minutes, + .. }: &Offset, ) -> Result { let secs = (*hours as i32) * 3600 + (*minutes as i32) * 60; @@ -209,7 +228,7 @@ pub(super) fn time_zone_correction(input: &mut &str) -> ModalResult { if has_fraction { return Err(ErrMode::Backtrack(ContextError::new())); } - alt((timezone_offset_colon, timezone_offset_colonless)).parse_next(input) + timezone_offset_parts.parse_next(input) } /// Parse a timezone starting with `+` or `-`. @@ -217,7 +236,7 @@ pub(super) fn timezone_offset(input: &mut &str) -> ModalResult { // Like GNU, read "+8 years" as a relative item, not as "+8" and "years". // The costlier relative check only runs once an offset has parsed. let start = input.checkpoint(); - let result = alt((timezone_offset_colon, timezone_offset_colonless)).parse_next(input); + let result = timezone_offset_parts.parse_next(input); if matches!(result, Err(ErrMode::Backtrack(_))) { return result; } @@ -247,6 +266,7 @@ fn timezone_name_offset(input: &mut &str) -> ModalResult { negative: false, hours: 1, minutes: 0, + name: None, })); } input.reset(&start); @@ -263,57 +283,67 @@ fn timezone_name_offset(input: &mut &str) -> ModalResult { Ok(tz) } -/// Parse a timezone offset with a colon separating hours and minutes, e.g., -/// `+08:00`, `+8:00`, `+8:0`. -fn timezone_offset_colon(input: &mut &str) -> ModalResult { - (plus_or_minus, s(dec_uint), s(colon), s(dec_uint)) - .parse_next(input) - .and_then(|(sign, hours, _, minutes)| { - (sign == '-', hours, minutes) - .try_into() - .map_err(|e| ErrMode::Cut(ctx_err(e))) - }) +fn timezone_offset_parts(input: &mut &str) -> ModalResult { + let (sign, digits) = (plus_or_minus, s(dec_uint_str)).parse_next(input)?; + + dispatch! { peek(opt(colon)); + Some(()) => move |input: &mut &str| timezone_offset_colon_after(sign, digits, input), + None => move |_: &mut &str| timezone_offset_colonless_after(sign, digits), + } + .parse_next(input) } -/// Parse a timezone offset without colon, e.g., `+0800`, `+800`, `+08`, `+8`. -fn timezone_offset_colonless(input: &mut &str) -> ModalResult { - (plus_or_minus, s(dec_uint_str)) - .verify_map(|(sign, s)| { - // GNU date accepts numeric offset strings with leading zeroes. For - // example, `+000000110` is valid. In such cases, the string is - // truncated to the last four characters. Thus, `+000000110` becomes - // `+0110` (note that one leading zero is kept). - let s = if s.len() > 4 && s.trim_start_matches('0').len() <= 4 { - &s[s.len() - 4..] - } else { - s - }; - - // Hour and minute values are dependent on the length of the string. - // For example: - // - // - "5" -> 05:00 - // - "05" -> 05:00 - // - "530" -> 05:30 (the minute is the last two characters here) - // - "0530"-> 05:30 - // - "0000530" -> 05:30 - let (h_str, m_str) = match s.len() { - 1 | 2 => (s, "0"), - 3 => s.split_at(1), - 4 => s.split_at(2), - _ => return None, - }; - - let hours = h_str.parse::().ok()?; - let minutes = m_str.parse::().ok()?; - Some((sign, hours, minutes)) - }) - .parse_next(input) - .and_then(|(sign, hours, minutes)| { - (sign == '-', hours, minutes) - .try_into() - .map_err(|e| ErrMode::Cut(ctx_err(e))) - }) +fn timezone_offset_colon_after(sign: char, digits: &str, input: &mut &str) -> ModalResult { + let (_, hours) = dec_uint:: + .parse_peek(digits) + .map_err(|_| ErrMode::Backtrack(ctx_err("timezone hour must be a valid u8 number")))?; + let (_, minutes) = (s(colon), s(dec_uint)).parse_next(input)?; + (sign == '-', hours, minutes) + .try_into() + .map_err(|e| ErrMode::Cut(ctx_err(e))) +} + +fn timezone_offset_colonless_after(sign: char, digits: &str) -> ModalResult { + // GNU date reads one or two digits as hours, three digits as HMM, and four + // digits as HHMM. Extra digits are accepted only when they are leading + // zeroes; the final four digits then provide the HHMM value. + let (_, (hours, minutes)) = alt(( + // One or two digits: hours only, with zero minutes. + ( + take_while(1..=2, AsChar::is_dec_digit).parse_to::(), + eof::<&str, ContextError>, + ) + .map(|(hours, _)| (hours, 0)), + // Three digits: one hour digit followed by two minute digits. + ( + take(1usize).parse_to::(), + take(2usize).parse_to::(), + eof::<&str, ContextError>, + ) + .map(|(hours, minutes, _)| (hours, minutes)), + // Four digits: two hour digits followed by two minute digits. + ( + take(2usize).parse_to::(), + take(2usize).parse_to::(), + eof::<&str, ContextError>, + ) + .map(|(hours, minutes, _)| (hours, minutes)), + // Longer values: consume leading zeroes while four digits remain, + // then split those final four digits into hours and minutes. + ( + repeat::<_, _, (), _, _>(0.., ('0', peek(take(4usize)))).void(), + take(2usize).parse_to::(), + take(2usize).parse_to::(), + eof::<&str, ContextError>, + ) + .map(|(_, hours, minutes, _)| (hours, minutes)), + )) + .parse_peek(digits) + .map_err(|_| ErrMode::Backtrack(ctx_err("timezone offset must be 1-4 digits")))?; + + (sign == '-', hours, minutes) + .try_into() + .map_err(|e| ErrMode::Cut(ctx_err(e))) } /// Named timezone list. @@ -401,14 +431,21 @@ fn timezone_name_to_offset(input: &str) -> ModalResult<(Offset, bool)> { "akdt" => (true, 8, 0, false), "adt" => (true, 3, 0, false), "a" => (false, 1, 0, true), + // Australian abbreviations accepted by GNU date. + "aest" => (false, 10, 0, true), + "aedt" => (false, 11, 0, false), + "acst" => (false, 9, 30, true), + "acdt" => (false, 10, 30, false), + "awst" => (false, 8, 0, false), _ => return Err(ErrMode::Backtrack(ContextError::new())), }; Ok(( Offset { negative, - hours, - minutes, + hours: hours as u16, + minutes: minutes as u16, + name: Some(input.to_owned()), }, takes_dst, )) @@ -421,11 +458,17 @@ mod tests { fn off(negative: bool, hours: u8, minutes: u8) -> Offset { Offset { negative, - hours, - minutes, + hours: u16::from(hours), + minutes: u16::from(minutes), + name: None, } } + fn unnamed(mut offset: Offset) -> Offset { + offset.name = None; + offset + } + #[test] fn timezone_offset_with_colon() { for (input, expected) in [ @@ -460,17 +503,19 @@ mod tests { #[test] fn timezone_offset_without_colon() { for (input, expected) in [ - ("+0000", off(false, 0, 0)), // UTC - ("-0000", off(true, 0, 0)), // UTC - ("+0100", off(false, 1, 0)), // positive offset - ("-0600", off(true, 6, 0)), // negative offset - ("+0530", off(false, 5, 30)), // positive offset with non-zero minutes - ("-0330", off(true, 3, 30)), // negative offset with non-zero minutes - ("- 0330", off(true, 3, 30)), // space after sign - ("+530", off(false, 5, 30)), // single-digit hours - ("+05", off(false, 5, 0)), // double-digit hours and no minutes - ("+5", off(false, 5, 0)), // single-digit hours and no minutes - ("+00000530", off(false, 5, 30)), // leading zeroes + ("+0000", off(false, 0, 0)), // UTC + ("-0000", off(true, 0, 0)), // UTC + ("+0100", off(false, 1, 0)), // positive offset + ("-0600", off(true, 6, 0)), // negative offset + ("+0530", off(false, 5, 30)), // positive offset with non-zero minutes + ("-0330", off(true, 3, 30)), // negative offset with non-zero minutes + ("- 0330", off(true, 3, 30)), // space after sign + ("+530", off(false, 5, 30)), // single-digit hours + ("+05", off(false, 5, 0)), // double-digit hours and no minutes + ("+5", off(false, 5, 0)), // single-digit hours and no minutes + ("+00000530", off(false, 5, 30)), // leading zeroes + ("+000000110", off(false, 1, 10)), // leading zeroes before four digits + ("+00000", off(false, 0, 0)), // leading zeroes before zero offset ("+0000abc", off(false, 0, 0)), // space separator can be ignored if immediately followed by alphas (GNU date behavior) ] { let mut s = input; @@ -481,6 +526,7 @@ mod tests { "+2500", // invalid: hours > 24 "-2361", // invalid: minutes > 60 "+2401", // invalid: minutes > 0 when hours == 24 + "+12345", // invalid: too many non-zero digits "+23 days", // invalid: ambiguous with relative time parsing ] { let mut s = input; @@ -488,6 +534,12 @@ mod tests { } } + #[test] + fn timezone_offset_normalizes_excess_minutes() { + let mut input = "+0060"; + assert_eq!(timezone_offset(&mut input).unwrap(), off(false, 1, 0)); + } + #[test] fn timezone_name_without_offset() { for (input, expected) in [ @@ -514,7 +566,11 @@ mod tests { ("z123", off(false, 0, 0)), // space separator can be ignored if immediately followed by digits (GNU date behavior) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); } for input in [ @@ -541,7 +597,11 @@ mod tests { ("y-24", off(true, 36, 0)), // maximum possible negative offset (y=-12) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); } for input in [ @@ -567,7 +627,11 @@ mod tests { ("a dst", off(false, 2, 0)), // military letter (a=+1) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); assert!(s.is_empty(), "{input}"); } @@ -594,12 +658,18 @@ mod tests { // "utc +8 years" is "utc" followed by the relative item "+8 years". let mut s = "utc +8 years"; - assert_eq!(timezone_name_offset(&mut s).unwrap(), off(false, 0, 0)); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + off(false, 0, 0) + ); assert_eq!(s, " +8 years"); // Without a relative item, the offset is still merged. let mut s = "utc +8"; - assert_eq!(timezone_name_offset(&mut s).unwrap(), off(false, 8, 0)); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + off(false, 8, 0) + ); assert!(s.is_empty()); } diff --git a/src/items/ordinal.rs b/src/items/ordinal.rs index d80b32a..bc90aff 100644 --- a/src/items/ordinal.rs +++ b/src/items/ordinal.rs @@ -3,14 +3,20 @@ use winnow::{ ascii::alpha1, - combinator::{alt, opt}, + combinator::{alt, dispatch, fail, opt, peek}, + token::any, ModalResult, Parser, }; use super::primitive::{dec_uint, s}; pub(super) fn ordinal(input: &mut &str) -> ModalResult { - alt((text_ordinal, number_ordinal)).parse_next(input) + dispatch! { s(peek(any)); + 'a'..='z' => text_ordinal, + '+' | '-' | '0'..='9' => number_ordinal, + _ => fail, + } + .parse_next(input) } fn number_ordinal(input: &mut &str) -> ModalResult { diff --git a/src/items/primitive.rs b/src/items/primitive.rs index f8e0709..cc14207 100644 --- a/src/items/primitive.rs +++ b/src/items/primitive.rs @@ -89,8 +89,9 @@ where /// Parse a comment /// -/// A comment is given between parentheses, which must be balanced. Any other -/// tokens can be within the comment. +/// A comment is given between parentheses. Any other tokens can be within the +/// comment. GNU treats an unmatched opening parenthesis as a comment through +/// the end of the input, so the closing parenthesis is optional here. fn comment<'a, E>(input: &mut &'a str) -> winnow::Result<(), E> where E: ParserError<&'a str>, @@ -98,7 +99,7 @@ where delimited( '(', repeat(0.., alt((none_of(['(', ')']).void(), comment))), - ')', + opt(')'), ) .parse_next(input) } @@ -245,8 +246,8 @@ mod tests { // A sign followed by a digit is not ignored. ("- 12", "- 12"), (" +12", "+12"), - // An unbalanced comment is not skipped. - ("(foo abc", "(foo abc"), + // An unbalanced comment runs through the end of the input. + ("(foo abc", ""), ] { let mut s = input; space::(&mut s).unwrap(); diff --git a/src/items/relative.rs b/src/items/relative.rs index 93bed09..0152ab1 100644 --- a/src/items/relative.rs +++ b/src/items/relative.rs @@ -33,11 +33,16 @@ use winnow::{ ascii::alpha1, - combinator::{alt, opt}, + combinator::{alt, dispatch, opt, peek}, + token::any, ModalResult, Parser, }; -use super::{epoch::sec_and_nsec, ordinal::ordinal, primitive::s}; +use super::{ + epoch::{normalize_seconds, sec_and_nsec}, + ordinal::ordinal, + primitive::s, +}; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Relative { @@ -78,18 +83,31 @@ impl TryFrom for jiff::Span { } pub(super) fn parse(input: &mut &str) -> ModalResult { - alt(( - s("tomorrow").value(Relative::Days(1)), - s("yesterday").value(Relative::Days(-1)), - // For "today" and "now", the unit is arbitrary - s("today").value(Relative::Days(0)), - s("now").value(Relative::Days(0)), - seconds, - displacement, - )) + dispatch! { s(peek(any)); + 't' => alt(( + s("tomorrow").value(Relative::Days(1)), + // For "today", the unit is arbitrary + s("today").value(Relative::Days(0)), + displacement, + )), + 'y' => alt(( + s("yesterday").value(Relative::Days(-1)), + displacement, + )), + 'n' => alt(( + // For "now", the unit is arbitrary + s("now").value(Relative::Days(0)), + displacement, + )), + _ => numeric_or_displacement, + } .parse_next(input) } +fn numeric_or_displacement(input: &mut &str) -> ModalResult { + alt((seconds, displacement)).parse_next(input) +} + fn seconds(input: &mut &str) -> ModalResult { ( opt(alt((s('+').value(1), s('-').value(-1)))), @@ -98,14 +116,8 @@ fn seconds(input: &mut &str) -> ModalResult { direction, ) .verify_map(|(sign, (sec, nsec), _, ago)| { - let sec = i64::try_from(sec).ok()?; let sign = sign.unwrap_or(1) * if ago { -1 } else { 1 }; - let (second, nanosecond) = match (sign, nsec) { - (-1, 0) => (-sec, 0), - // Truncate towards minus infinity. - (-1, _) => ((-sec).checked_sub(1)?, 1_000_000_000 - nsec), - _ => (sec, nsec), - }; + let (second, nanosecond) = normalize_seconds(sign < 0, sec, nsec)?; Some(Relative::Seconds(second, nanosecond)) }) .parse_next(input) diff --git a/src/items/time.rs b/src/items/time.rs index 893ef5e..f3b4ba2 100644 --- a/src/items/time.rs +++ b/src/items/time.rs @@ -38,7 +38,7 @@ //! > Either ‘am’/‘pm’ or a time zone correction may be specified, but not both. use winnow::{ - combinator::{alt, opt, preceded}, + combinator::{alt, dispatch, fail, opt, peek, preceded}, error::ErrMode, ModalResult, Parser, }; @@ -46,7 +46,7 @@ use winnow::{ use super::{ epoch::sec_and_nsec, offset::{time_zone_correction, timezone_offset, Offset}, - primitive::{colon, ctx_err, dec_uint, s}, + primitive::{colon, ctx_err, dec_uint, s, space}, }; #[derive(PartialEq, Clone, Debug, Default)] @@ -86,30 +86,42 @@ pub(crate) fn parse(input: &mut &str) -> ModalResult