diff options
Diffstat (limited to 'vendor/time-macros/src')
-rw-r--r-- | vendor/time-macros/src/date.rs | 137 | ||||
-rw-r--r-- | vendor/time-macros/src/datetime.rs | 57 | ||||
-rw-r--r-- | vendor/time-macros/src/error.rs | 136 | ||||
-rw-r--r-- | vendor/time-macros/src/format_description/component.rs | 168 | ||||
-rw-r--r-- | vendor/time-macros/src/format_description/error.rs | 29 | ||||
-rw-r--r-- | vendor/time-macros/src/format_description/mod.rs | 40 | ||||
-rw-r--r-- | vendor/time-macros/src/format_description/modifier.rs | 417 | ||||
-rw-r--r-- | vendor/time-macros/src/format_description/parse.rs | 84 | ||||
-rw-r--r-- | vendor/time-macros/src/helpers/mod.rs | 129 | ||||
-rw-r--r-- | vendor/time-macros/src/helpers/string.rs | 188 | ||||
-rw-r--r-- | vendor/time-macros/src/lib.rs | 167 | ||||
-rw-r--r-- | vendor/time-macros/src/offset.rs | 95 | ||||
-rw-r--r-- | vendor/time-macros/src/quote.rs | 134 | ||||
-rw-r--r-- | vendor/time-macros/src/serde_format_description.rs | 163 | ||||
-rw-r--r-- | vendor/time-macros/src/time.rs | 118 | ||||
-rw-r--r-- | vendor/time-macros/src/to_tokens.rs | 68 |
16 files changed, 2130 insertions, 0 deletions
diff --git a/vendor/time-macros/src/date.rs b/vendor/time-macros/src/date.rs new file mode 100644 index 000000000..574ef8ce6 --- /dev/null +++ b/vendor/time-macros/src/date.rs @@ -0,0 +1,137 @@ +use std::iter::Peekable; + +use proc_macro::{token_stream, TokenTree}; +use time_core::util::{days_in_year, weeks_in_year}; + +use crate::helpers::{ + consume_any_ident, consume_number, consume_punct, days_in_year_month, ymd_to_yo, ywd_to_yo, +}; +use crate::to_tokens::ToTokenTree; +use crate::Error; + +#[cfg(feature = "large-dates")] +const MAX_YEAR: i32 = 999_999; +#[cfg(not(feature = "large-dates"))] +const MAX_YEAR: i32 = 9_999; + +pub(crate) struct Date { + pub(crate) year: i32, + pub(crate) ordinal: u16, +} + +pub(crate) fn parse(chars: &mut Peekable<token_stream::IntoIter>) -> Result<Date, Error> { + let (year_sign_span, year_sign, explicit_sign) = if let Ok(span) = consume_punct('-', chars) { + (Some(span), -1, true) + } else if let Ok(span) = consume_punct('+', chars) { + (Some(span), 1, true) + } else { + (None, 1, false) + }; + let (year_span, mut year) = consume_number::<i32>("year", chars)?; + year *= year_sign; + if year.abs() > MAX_YEAR { + return Err(Error::InvalidComponent { + name: "year", + value: year.to_string(), + span_start: Some(year_sign_span.unwrap_or(year_span)), + span_end: Some(year_span), + }); + } + if !explicit_sign && year.abs() >= 10_000 { + return Err(Error::Custom { + message: "years with more than four digits must have an explicit sign".into(), + span_start: Some(year_sign_span.unwrap_or(year_span)), + span_end: Some(year_span), + }); + } + + consume_punct('-', chars)?; + + // year-week-day + if let Ok(w_span) = consume_any_ident(&["W"], chars) { + let (week_span, week) = consume_number::<u8>("week", chars)?; + consume_punct('-', chars)?; + let (day_span, day) = consume_number::<u8>("day", chars)?; + + if week > weeks_in_year(year) { + return Err(Error::InvalidComponent { + name: "week", + value: week.to_string(), + span_start: Some(w_span), + span_end: Some(week_span), + }); + } + if day == 0 || day > 7 { + return Err(Error::InvalidComponent { + name: "day", + value: day.to_string(), + span_start: Some(day_span), + span_end: Some(day_span), + }); + } + + let (year, ordinal) = ywd_to_yo(year, week, day); + + return Ok(Date { year, ordinal }); + } + + // We don't yet know whether it's year-month-day or year-ordinal. + let (month_or_ordinal_span, month_or_ordinal) = + consume_number::<u16>("month or ordinal", chars)?; + + // year-month-day + #[allow(clippy::branches_sharing_code)] // clarity + if consume_punct('-', chars).is_ok() { + let (month_span, month) = (month_or_ordinal_span, month_or_ordinal); + let (day_span, day) = consume_number::<u8>("day", chars)?; + + if month == 0 || month > 12 { + return Err(Error::InvalidComponent { + name: "month", + value: month.to_string(), + span_start: Some(month_span), + span_end: Some(month_span), + }); + } + let month = month as _; + if day == 0 || day > days_in_year_month(year, month) { + return Err(Error::InvalidComponent { + name: "day", + value: day.to_string(), + span_start: Some(day_span), + span_end: Some(day_span), + }); + } + + let (year, ordinal) = ymd_to_yo(year, month, day); + + Ok(Date { year, ordinal }) + } + // year-ordinal + else { + let (ordinal_span, ordinal) = (month_or_ordinal_span, month_or_ordinal); + + if ordinal == 0 || ordinal > days_in_year(year) { + return Err(Error::InvalidComponent { + name: "ordinal", + value: ordinal.to_string(), + span_start: Some(ordinal_span), + span_end: Some(ordinal_span), + }); + } + + Ok(Date { year, ordinal }) + } +} + +impl ToTokenTree for Date { + fn into_token_tree(self) -> TokenTree { + quote_group! {{ + const DATE: ::time::Date = ::time::Date::__from_ordinal_date_unchecked( + #(self.year), + #(self.ordinal), + ); + DATE + }} + } +} diff --git a/vendor/time-macros/src/datetime.rs b/vendor/time-macros/src/datetime.rs new file mode 100644 index 000000000..2d41e9a53 --- /dev/null +++ b/vendor/time-macros/src/datetime.rs @@ -0,0 +1,57 @@ +use std::iter::Peekable; + +use proc_macro::{token_stream, Ident, Span, TokenTree}; + +use crate::date::Date; +use crate::error::Error; +use crate::offset::Offset; +use crate::time::Time; +use crate::to_tokens::ToTokenTree; +use crate::{date, offset, time}; + +pub(crate) struct DateTime { + date: Date, + time: Time, + offset: Option<Offset>, +} + +pub(crate) fn parse(chars: &mut Peekable<token_stream::IntoIter>) -> Result<DateTime, Error> { + let date = date::parse(chars)?; + let time = time::parse(chars)?; + let offset = match offset::parse(chars) { + Ok(offset) => Some(offset), + Err(Error::UnexpectedEndOfInput | Error::MissingComponent { name: "sign", .. }) => None, + Err(err) => return Err(err), + }; + + if let Some(token) = chars.peek() { + return Err(Error::UnexpectedToken { + tree: token.clone(), + }); + } + + Ok(DateTime { date, time, offset }) +} + +impl ToTokenTree for DateTime { + fn into_token_tree(self) -> TokenTree { + let (type_name, maybe_offset) = match self.offset { + Some(offset) => ( + Ident::new("OffsetDateTime", Span::mixed_site()), + quote!(.assume_offset(#(offset))), + ), + None => ( + Ident::new("PrimitiveDateTime", Span::mixed_site()), + quote!(), + ), + }; + + quote_group! {{ + const DATE_TIME: ::time::#(type_name) = ::time::PrimitiveDateTime::new( + #(self.date), + #(self.time), + ) #S(maybe_offset); + DATE_TIME + }} + } +} diff --git a/vendor/time-macros/src/error.rs b/vendor/time-macros/src/error.rs new file mode 100644 index 000000000..4de369daf --- /dev/null +++ b/vendor/time-macros/src/error.rs @@ -0,0 +1,136 @@ +use std::borrow::Cow; +use std::fmt; + +use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; + +#[cfg(any(feature = "formatting", feature = "parsing"))] +use crate::format_description::error::InvalidFormatDescription; + +trait WithSpan { + fn with_span(self, span: Span) -> Self; +} + +impl WithSpan for TokenTree { + fn with_span(mut self, span: Span) -> Self { + self.set_span(span); + self + } +} + +pub(crate) enum Error { + MissingComponent { + name: &'static str, + span_start: Option<Span>, + span_end: Option<Span>, + }, + InvalidComponent { + name: &'static str, + value: String, + span_start: Option<Span>, + span_end: Option<Span>, + }, + #[cfg(any(feature = "formatting", feature = "parsing"))] + ExpectedString { + span_start: Option<Span>, + span_end: Option<Span>, + }, + UnexpectedToken { + tree: TokenTree, + }, + UnexpectedEndOfInput, + #[cfg(any(feature = "formatting", feature = "parsing"))] + InvalidFormatDescription { + error: InvalidFormatDescription, + span_start: Option<Span>, + span_end: Option<Span>, + }, + Custom { + message: Cow<'static, str>, + span_start: Option<Span>, + span_end: Option<Span>, + }, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingComponent { name, .. } => write!(f, "missing component: {name}"), + Self::InvalidComponent { name, value, .. } => { + write!(f, "invalid component: {name} was {value}") + } + #[cfg(any(feature = "formatting", feature = "parsing"))] + Self::ExpectedString { .. } => f.write_str("expected string"), + Self::UnexpectedToken { tree } => write!(f, "unexpected token: {tree}"), + Self::UnexpectedEndOfInput => f.write_str("unexpected end of input"), + #[cfg(any(feature = "formatting", feature = "parsing"))] + Self::InvalidFormatDescription { error, .. } => error.fmt(f), + Self::Custom { message, .. } => f.write_str(message), + } + } +} + +impl Error { + fn span_start(&self) -> Span { + match self { + Self::MissingComponent { span_start, .. } + | Self::InvalidComponent { span_start, .. } + | Self::Custom { span_start, .. } => *span_start, + #[cfg(any(feature = "formatting", feature = "parsing"))] + Self::ExpectedString { span_start, .. } + | Self::InvalidFormatDescription { span_start, .. } => *span_start, + Self::UnexpectedToken { tree } => Some(tree.span()), + Self::UnexpectedEndOfInput => Some(Span::mixed_site()), + } + .unwrap_or_else(Span::mixed_site) + } + + fn span_end(&self) -> Span { + match self { + Self::MissingComponent { span_end, .. } + | Self::InvalidComponent { span_end, .. } + | Self::Custom { span_end, .. } => *span_end, + #[cfg(any(feature = "formatting", feature = "parsing"))] + Self::ExpectedString { span_end, .. } + | Self::InvalidFormatDescription { span_end, .. } => *span_end, + Self::UnexpectedToken { tree, .. } => Some(tree.span()), + Self::UnexpectedEndOfInput => Some(Span::mixed_site()), + } + .unwrap_or_else(|| self.span_start()) + } + + pub(crate) fn to_compile_error(&self) -> TokenStream { + let (start, end) = (self.span_start(), self.span_end()); + + [ + TokenTree::from(Punct::new(':', Spacing::Joint)).with_span(start), + TokenTree::from(Punct::new(':', Spacing::Alone)).with_span(start), + TokenTree::from(Ident::new("core", start)), + TokenTree::from(Punct::new(':', Spacing::Joint)).with_span(start), + TokenTree::from(Punct::new(':', Spacing::Alone)).with_span(start), + TokenTree::from(Ident::new("compile_error", start)), + TokenTree::from(Punct::new('!', Spacing::Alone)).with_span(start), + TokenTree::from(Group::new( + Delimiter::Parenthesis, + TokenStream::from( + TokenTree::from(Literal::string(&self.to_string())).with_span(end), + ), + )) + .with_span(end), + ] + .iter() + .cloned() + .collect() + } + + /// Like `to_compile_error`, but for use in macros that produce items. + #[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] + pub(crate) fn to_compile_error_standalone(&self) -> TokenStream { + let end = self.span_end(); + self.to_compile_error() + .into_iter() + .chain(std::iter::once( + TokenTree::from(Punct::new(';', Spacing::Alone)).with_span(end), + )) + .collect() + } +} diff --git a/vendor/time-macros/src/format_description/component.rs b/vendor/time-macros/src/format_description/component.rs new file mode 100644 index 000000000..850da91d2 --- /dev/null +++ b/vendor/time-macros/src/format_description/component.rs @@ -0,0 +1,168 @@ +use proc_macro::{Ident, Span, TokenStream}; + +use crate::format_description::error::InvalidFormatDescription; +use crate::format_description::modifier; +use crate::format_description::modifier::Modifiers; +use crate::to_tokens::ToTokenStream; + +pub(crate) enum Component { + Day(modifier::Day), + Month(modifier::Month), + Ordinal(modifier::Ordinal), + Weekday(modifier::Weekday), + WeekNumber(modifier::WeekNumber), + Year(modifier::Year), + Hour(modifier::Hour), + Minute(modifier::Minute), + Period(modifier::Period), + Second(modifier::Second), + Subsecond(modifier::Subsecond), + OffsetHour(modifier::OffsetHour), + OffsetMinute(modifier::OffsetMinute), + OffsetSecond(modifier::OffsetSecond), +} + +impl ToTokenStream for Component { + fn append_to(self, ts: &mut TokenStream) { + let mut mts = TokenStream::new(); + + macro_rules! component_name_and_append { + ($($name:ident)*) => { + match self { + $(Self::$name(modifier) => { + modifier.append_to(&mut mts); + stringify!($name) + })* + } + }; + } + + let component = component_name_and_append![ + Day + Month + Ordinal + Weekday + WeekNumber + Year + Hour + Minute + Period + Second + Subsecond + OffsetHour + OffsetMinute + OffsetSecond + ]; + let component = Ident::new(component, Span::mixed_site()); + + quote_append! { ts + ::time::format_description::Component::#(component)(#S(mts)) + } + } +} + +pub(crate) enum NakedComponent { + Day, + Month, + Ordinal, + Weekday, + WeekNumber, + Year, + Hour, + Minute, + Period, + Second, + Subsecond, + OffsetHour, + OffsetMinute, + OffsetSecond, +} + +impl NakedComponent { + pub(crate) fn parse( + component_name: &[u8], + component_index: usize, + ) -> Result<Self, InvalidFormatDescription> { + match component_name { + b"day" => Ok(Self::Day), + b"month" => Ok(Self::Month), + b"ordinal" => Ok(Self::Ordinal), + b"weekday" => Ok(Self::Weekday), + b"week_number" => Ok(Self::WeekNumber), + b"year" => Ok(Self::Year), + b"hour" => Ok(Self::Hour), + b"minute" => Ok(Self::Minute), + b"period" => Ok(Self::Period), + b"second" => Ok(Self::Second), + b"subsecond" => Ok(Self::Subsecond), + b"offset_hour" => Ok(Self::OffsetHour), + b"offset_minute" => Ok(Self::OffsetMinute), + b"offset_second" => Ok(Self::OffsetSecond), + b"" => Err(InvalidFormatDescription::MissingComponentName { + index: component_index, + }), + _ => Err(InvalidFormatDescription::InvalidComponentName { + name: String::from_utf8_lossy(component_name).into_owned(), + index: component_index, + }), + } + } + + pub(crate) fn attach_modifiers(self, modifiers: Modifiers) -> Component { + match self { + Self::Day => Component::Day(modifier::Day { + padding: modifiers.padding.unwrap_or_default(), + }), + Self::Month => Component::Month(modifier::Month { + padding: modifiers.padding.unwrap_or_default(), + repr: modifiers.month_repr.unwrap_or_default(), + case_sensitive: modifiers.case_sensitive.unwrap_or(true), + }), + Self::Ordinal => Component::Ordinal(modifier::Ordinal { + padding: modifiers.padding.unwrap_or_default(), + }), + Self::Weekday => Component::Weekday(modifier::Weekday { + repr: modifiers.weekday_repr.unwrap_or_default(), + one_indexed: modifiers.weekday_is_one_indexed.unwrap_or(true), + case_sensitive: modifiers.case_sensitive.unwrap_or(true), + }), + Self::WeekNumber => Component::WeekNumber(modifier::WeekNumber { + padding: modifiers.padding.unwrap_or_default(), + repr: modifiers.week_number_repr.unwrap_or_default(), + }), + Self::Year => Component::Year(modifier::Year { + padding: modifiers.padding.unwrap_or_default(), + repr: modifiers.year_repr.unwrap_or_default(), + iso_week_based: modifiers.year_is_iso_week_based.unwrap_or_default(), + sign_is_mandatory: modifiers.sign_is_mandatory.unwrap_or_default(), + }), + Self::Hour => Component::Hour(modifier::Hour { + padding: modifiers.padding.unwrap_or_default(), + is_12_hour_clock: modifiers.hour_is_12_hour_clock.unwrap_or_default(), + }), + Self::Minute => Component::Minute(modifier::Minute { + padding: modifiers.padding.unwrap_or_default(), + }), + Self::Period => Component::Period(modifier::Period { + is_uppercase: modifiers.period_is_uppercase.unwrap_or(true), + case_sensitive: modifiers.case_sensitive.unwrap_or(true), + }), + Self::Second => Component::Second(modifier::Second { + padding: modifiers.padding.unwrap_or_default(), + }), + Self::Subsecond => Component::Subsecond(modifier::Subsecond { + digits: modifiers.subsecond_digits.unwrap_or_default(), + }), + Self::OffsetHour => Component::OffsetHour(modifier::OffsetHour { + sign_is_mandatory: modifiers.sign_is_mandatory.unwrap_or_default(), + padding: modifiers.padding.unwrap_or_default(), + }), + Self::OffsetMinute => Component::OffsetMinute(modifier::OffsetMinute { + padding: modifiers.padding.unwrap_or_default(), + }), + Self::OffsetSecond => Component::OffsetSecond(modifier::OffsetSecond { + padding: modifiers.padding.unwrap_or_default(), + }), + } + } +} diff --git a/vendor/time-macros/src/format_description/error.rs b/vendor/time-macros/src/format_description/error.rs new file mode 100644 index 000000000..9aacd7dc9 --- /dev/null +++ b/vendor/time-macros/src/format_description/error.rs @@ -0,0 +1,29 @@ +use std::fmt; + +pub(crate) enum InvalidFormatDescription { + UnclosedOpeningBracket { index: usize }, + InvalidComponentName { name: String, index: usize }, + InvalidModifier { value: String, index: usize }, + MissingComponentName { index: usize }, +} + +impl fmt::Display for InvalidFormatDescription { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + #[allow(clippy::enum_glob_use)] + use InvalidFormatDescription::*; + match self { + UnclosedOpeningBracket { index } => { + write!(f, "unclosed opening bracket at byte index {index}") + } + InvalidComponentName { name, index } => { + write!(f, "invalid component name `{name}` at byte index {index}",) + } + InvalidModifier { value, index } => { + write!(f, "invalid modifier `{value}` at byte index {index}") + } + MissingComponentName { index } => { + write!(f, "missing component name at byte index {index}") + } + } + } +} diff --git a/vendor/time-macros/src/format_description/mod.rs b/vendor/time-macros/src/format_description/mod.rs new file mode 100644 index 000000000..dd32db74d --- /dev/null +++ b/vendor/time-macros/src/format_description/mod.rs @@ -0,0 +1,40 @@ +mod component; +pub(crate) mod error; +pub(crate) mod modifier; +pub(crate) mod parse; + +use proc_macro::{Literal, TokenStream}; + +pub(crate) use self::component::Component; +pub(crate) use self::parse::parse; +use crate::to_tokens::ToTokenStream; + +mod helper { + #[must_use = "This does not modify the original slice."] + pub(crate) fn consume_whitespace<'a>(bytes: &'a [u8], index: &mut usize) -> &'a [u8] { + let first_non_whitespace = bytes + .iter() + .position(|c| !c.is_ascii_whitespace()) + .unwrap_or(bytes.len()); + *index += first_non_whitespace; + &bytes[first_non_whitespace..] + } +} + +#[allow(single_use_lifetimes)] // false positive +#[allow(variant_size_differences)] +pub(crate) enum FormatItem<'a> { + Literal(&'a [u8]), + Component(Component), +} + +impl ToTokenStream for FormatItem<'_> { + fn append_to(self, ts: &mut TokenStream) { + quote_append! { ts + ::time::format_description::FormatItem::#S(match self { + FormatItem::Literal(bytes) => quote! { Literal(#(Literal::byte_string(bytes))) }, + FormatItem::Component(component) => quote! { Component(#S(component)) }, + }) + } + } +} diff --git a/vendor/time-macros/src/format_description/modifier.rs b/vendor/time-macros/src/format_description/modifier.rs new file mode 100644 index 000000000..f4e641a7b --- /dev/null +++ b/vendor/time-macros/src/format_description/modifier.rs @@ -0,0 +1,417 @@ +use core::mem; + +use proc_macro::{Ident, Span, TokenStream, TokenTree}; + +use crate::format_description::error::InvalidFormatDescription; +use crate::format_description::helper; +use crate::to_tokens::{ToTokenStream, ToTokenTree}; + +macro_rules! to_tokens { + ( + $(#[$struct_attr:meta])* + $struct_vis:vis struct $struct_name:ident {$( + $(#[$field_attr:meta])* + $field_vis:vis $field_name:ident : $field_ty:ty + ),+ $(,)?} + ) => { + $(#[$struct_attr])* + $struct_vis struct $struct_name {$( + $(#[$field_attr])* + $field_vis $field_name: $field_ty + ),+} + + impl ToTokenTree for $struct_name { + fn into_token_tree(self) -> TokenTree { + let mut tokens = TokenStream::new(); + let Self {$($field_name),+} = self; + + quote_append! { tokens + let mut value = ::time::format_description::modifier::$struct_name::default(); + }; + $( + quote_append!(tokens value.$field_name =); + $field_name.append_to(&mut tokens); + quote_append!(tokens ;); + )+ + quote_append!(tokens value); + + proc_macro::TokenTree::Group(proc_macro::Group::new( + proc_macro::Delimiter::Brace, + tokens, + )) + } + } + }; + + ( + $(#[$enum_attr:meta])* + $enum_vis:vis enum $enum_name:ident {$( + $(#[$variant_attr:meta])* + $variant_name:ident + ),+ $(,)?} + ) => { + $(#[$enum_attr])* + $enum_vis enum $enum_name {$( + $(#[$variant_attr])* + $variant_name + ),+} + + impl ToTokenStream for $enum_name { + fn append_to(self, ts: &mut TokenStream) { + quote_append! { ts + ::time::format_description::modifier::$enum_name:: + }; + let name = match self { + $(Self::$variant_name => stringify!($variant_name)),+ + }; + ts.extend([TokenTree::Ident(Ident::new(name, Span::mixed_site()))]); + } + } + } +} + +to_tokens! { + pub(crate) struct Day { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) enum MonthRepr { + Numerical, + Long, + Short, + } +} + +to_tokens! { + pub(crate) struct Month { + pub(crate) padding: Padding, + pub(crate) repr: MonthRepr, + pub(crate) case_sensitive: bool, + } +} + +to_tokens! { + pub(crate) struct Ordinal { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) enum WeekdayRepr { + Short, + Long, + Sunday, + Monday, + } +} + +to_tokens! { + pub(crate) struct Weekday { + pub(crate) repr: WeekdayRepr, + pub(crate) one_indexed: bool, + pub(crate) case_sensitive: bool, + } +} + +to_tokens! { + pub(crate) enum WeekNumberRepr { + Iso, + Sunday, + Monday, + } +} + +to_tokens! { + pub(crate) struct WeekNumber { + pub(crate) padding: Padding, + pub(crate) repr: WeekNumberRepr, + } +} + +to_tokens! { + pub(crate) enum YearRepr { + Full, + LastTwo, + } +} + +to_tokens! { + pub(crate) struct Year { + pub(crate) padding: Padding, + pub(crate) repr: YearRepr, + pub(crate) iso_week_based: bool, + pub(crate) sign_is_mandatory: bool, + } +} + +to_tokens! { + pub(crate) struct Hour { + pub(crate) padding: Padding, + pub(crate) is_12_hour_clock: bool, + } +} + +to_tokens! { + pub(crate) struct Minute { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) struct Period { + pub(crate) is_uppercase: bool, + pub(crate) case_sensitive: bool, + } +} + +to_tokens! { + pub(crate) struct Second { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) enum SubsecondDigits { + One, + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine, + OneOrMore, + } +} + +to_tokens! { + pub(crate) struct Subsecond { + pub(crate) digits: SubsecondDigits, + } +} + +to_tokens! { + pub(crate) struct OffsetHour { + pub(crate) sign_is_mandatory: bool, + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) struct OffsetMinute { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) struct OffsetSecond { + pub(crate) padding: Padding, + } +} + +to_tokens! { + pub(crate) enum Padding { + Space, + Zero, + None, + } +} + +macro_rules! impl_default { + ($($type:ty => $default:expr;)*) => {$( + impl Default for $type { + fn default() -> Self { + $default + } + } + )*}; +} + +impl_default! { + Day => Self { padding: Padding::default() }; + MonthRepr => Self::Numerical; + Month => Self { + padding: Padding::default(), + repr: MonthRepr::default(), + case_sensitive: true, + }; + Ordinal => Self { padding: Padding::default() }; + WeekdayRepr => Self::Long; + Weekday => Self { + repr: WeekdayRepr::default(), + one_indexed: true, + case_sensitive: true, + }; + WeekNumberRepr => Self::Iso; + WeekNumber => Self { + padding: Padding::default(), + repr: WeekNumberRepr::default(), + }; + YearRepr => Self::Full; + Year => Self { + padding: Padding::default(), + repr: YearRepr::default(), + iso_week_based: false, + sign_is_mandatory: false, + }; + Hour => Self { + padding: Padding::default(), + is_12_hour_clock: false, + }; + Minute => Self { padding: Padding::default() }; + Period => Self { is_uppercase: true, case_sensitive: true }; + Second => Self { padding: Padding::default() }; + SubsecondDigits => Self::OneOrMore; + Subsecond => Self { digits: SubsecondDigits::default() }; + OffsetHour => Self { + sign_is_mandatory: true, + padding: Padding::default(), + }; + OffsetMinute => Self { padding: Padding::default() }; + OffsetSecond => Self { padding: Padding::default() }; + Padding => Self::Zero; +} + +#[derive(Default)] +pub(crate) struct Modifiers { + pub(crate) padding: Option<Padding>, + pub(crate) hour_is_12_hour_clock: Option<bool>, + pub(crate) period_is_uppercase: Option<bool>, + pub(crate) month_repr: Option<MonthRepr>, + pub(crate) subsecond_digits: Option<SubsecondDigits>, + pub(crate) weekday_repr: Option<WeekdayRepr>, + pub(crate) weekday_is_one_indexed: Option<bool>, + pub(crate) week_number_repr: Option<WeekNumberRepr>, + pub(crate) year_repr: Option<YearRepr>, + pub(crate) year_is_iso_week_based: Option<bool>, + pub(crate) sign_is_mandatory: Option<bool>, + pub(crate) case_sensitive: Option<bool>, +} + +impl Modifiers { + #[allow(clippy::too_many_lines)] + pub(crate) fn parse( + component_name: &[u8], + mut bytes: &[u8], + index: &mut usize, + ) -> Result<Self, InvalidFormatDescription> { + let mut modifiers = Self::default(); + + while !bytes.is_empty() { + // Trim any whitespace between modifiers. + bytes = helper::consume_whitespace(bytes, index); + + let modifier; + if let Some(whitespace_loc) = bytes.iter().position(u8::is_ascii_whitespace) { + *index += whitespace_loc; + modifier = &bytes[..whitespace_loc]; + bytes = &bytes[whitespace_loc..]; + } else { + modifier = mem::take(&mut bytes); + } + + if modifier.is_empty() { + break; + } + + match (component_name, modifier) { + ( + b"day" | b"hour" | b"minute" | b"month" | b"offset_hour" | b"offset_minute" + | b"offset_second" | b"ordinal" | b"second" | b"week_number" | b"year", + b"padding:space", + ) => modifiers.padding = Some(Padding::Space), + ( + b"day" | b"hour" | b"minute" | b"month" | b"offset_hour" | b"offset_minute" + | b"offset_second" | b"ordinal" | b"second" | b"week_number" | b"year", + b"padding:zero", + ) => modifiers.padding = Some(Padding::Zero), + ( + b"day" | b"hour" | b"minute" | b"month" | b"offset_hour" | b"offset_minute" + | b"offset_second" | b"ordinal" | b"second" | b"week_number" | b"year", + b"padding:none", + ) => modifiers.padding = Some(Padding::None), + (b"hour", b"repr:24") => modifiers.hour_is_12_hour_clock = Some(false), + (b"hour", b"repr:12") => modifiers.hour_is_12_hour_clock = Some(true), + (b"month" | b"period" | b"weekday", b"case_sensitive:true") => { + modifiers.case_sensitive = Some(true) + } + (b"month" | b"period" | b"weekday", b"case_sensitive:false") => { + modifiers.case_sensitive = Some(false) + } + (b"month", b"repr:numerical") => modifiers.month_repr = Some(MonthRepr::Numerical), + (b"month", b"repr:long") => modifiers.month_repr = Some(MonthRepr::Long), + (b"month", b"repr:short") => modifiers.month_repr = Some(MonthRepr::Short), + (b"offset_hour" | b"year", b"sign:automatic") => { + modifiers.sign_is_mandatory = Some(false); + } + (b"offset_hour" | b"year", b"sign:mandatory") => { + modifiers.sign_is_mandatory = Some(true); + } + (b"period", b"case:upper") => modifiers.period_is_uppercase = Some(true), + (b"period", b"case:lower") => modifiers.period_is_uppercase = Some(false), + (b"subsecond", b"digits:1") => { + modifiers.subsecond_digits = Some(SubsecondDigits::One); + } + (b"subsecond", b"digits:2") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Two); + } + (b"subsecond", b"digits:3") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Three); + } + (b"subsecond", b"digits:4") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Four); + } + (b"subsecond", b"digits:5") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Five); + } + (b"subsecond", b"digits:6") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Six); + } + (b"subsecond", b"digits:7") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Seven); + } + (b"subsecond", b"digits:8") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Eight); + } + (b"subsecond", b"digits:9") => { + modifiers.subsecond_digits = Some(SubsecondDigits::Nine); + } + (b"subsecond", b"digits:1+") => { + modifiers.subsecond_digits = Some(SubsecondDigits::OneOrMore); + } + (b"weekday", b"repr:short") => modifiers.weekday_repr = Some(WeekdayRepr::Short), + (b"weekday", b"repr:long") => modifiers.weekday_repr = Some(WeekdayRepr::Long), + (b"weekday", b"repr:sunday") => modifiers.weekday_repr = Some(WeekdayRepr::Sunday), + (b"weekday", b"repr:monday") => modifiers.weekday_repr = Some(WeekdayRepr::Monday), + (b"weekday", b"one_indexed:true") => modifiers.weekday_is_one_indexed = Some(true), + (b"weekday", b"one_indexed:false") => { + modifiers.weekday_is_one_indexed = Some(false); + } + (b"week_number", b"repr:iso") => { + modifiers.week_number_repr = Some(WeekNumberRepr::Iso); + } + (b"week_number", b"repr:sunday") => { + modifiers.week_number_repr = Some(WeekNumberRepr::Sunday); + } + (b"week_number", b"repr:monday") => { + modifiers.week_number_repr = Some(WeekNumberRepr::Monday); + } + (b"year", b"repr:full") => modifiers.year_repr = Some(YearRepr::Full), + (b"year", b"repr:last_two") => modifiers.year_repr = Some(YearRepr::LastTwo), + (b"year", b"base:calendar") => modifiers.year_is_iso_week_based = Some(false), + (b"year", b"base:iso_week") => modifiers.year_is_iso_week_based = Some(true), + _ => { + return Err(InvalidFormatDescription::InvalidModifier { + value: String::from_utf8_lossy(modifier).into_owned(), + index: *index, + }); + } + } + } + + Ok(modifiers) + } +} diff --git a/vendor/time-macros/src/format_description/parse.rs b/vendor/time-macros/src/format_description/parse.rs new file mode 100644 index 000000000..19c7bf608 --- /dev/null +++ b/vendor/time-macros/src/format_description/parse.rs @@ -0,0 +1,84 @@ +use proc_macro::Span; + +use crate::format_description::component::{Component, NakedComponent}; +use crate::format_description::error::InvalidFormatDescription; +use crate::format_description::{helper, modifier, FormatItem}; +use crate::Error; + +struct ParsedItem<'a> { + item: FormatItem<'a>, + remaining: &'a [u8], +} + +fn parse_component(mut s: &[u8], index: &mut usize) -> Result<Component, InvalidFormatDescription> { + s = helper::consume_whitespace(s, index); + + let component_index = *index; + let whitespace_loc = s + .iter() + .position(u8::is_ascii_whitespace) + .unwrap_or(s.len()); + *index += whitespace_loc; + let component_name = &s[..whitespace_loc]; + s = &s[whitespace_loc..]; + s = helper::consume_whitespace(s, index); + + Ok(NakedComponent::parse(component_name, component_index)? + .attach_modifiers(modifier::Modifiers::parse(component_name, s, index)?)) +} + +fn parse_literal<'a>(s: &'a [u8], index: &mut usize) -> ParsedItem<'a> { + let loc = s.iter().position(|&c| c == b'[').unwrap_or(s.len()); + *index += loc; + ParsedItem { + item: FormatItem::Literal(&s[..loc]), + remaining: &s[loc..], + } +} + +fn parse_item<'a>( + s: &'a [u8], + index: &mut usize, +) -> Result<ParsedItem<'a>, InvalidFormatDescription> { + if let [b'[', b'[', remaining @ ..] = s { + *index += 2; + return Ok(ParsedItem { + item: FormatItem::Literal(b"["), + remaining, + }); + }; + + if s.starts_with(b"[") { + if let Some(bracket_index) = s.iter().position(|&c| c == b']') { + *index += 1; // opening bracket + let ret_val = ParsedItem { + item: FormatItem::Component(parse_component(&s[1..bracket_index], index)?), + remaining: &s[bracket_index + 1..], + }; + *index += 1; // closing bracket + Ok(ret_val) + } else { + Err(InvalidFormatDescription::UnclosedOpeningBracket { index: *index }) + } + } else { + Ok(parse_literal(s, index)) + } +} + +pub(crate) fn parse(mut s: &[u8], span: Span) -> Result<Vec<FormatItem<'_>>, Error> { + let mut compound = Vec::new(); + let mut loc = 0; + + while !s.is_empty() { + let ParsedItem { item, remaining } = + parse_item(s, &mut loc).map_err(|error| Error::InvalidFormatDescription { + error, + span_start: Some(span), + span_end: Some(span), + })?; + s = remaining; + compound.push(item); + } + + Ok(compound) +} diff --git a/vendor/time-macros/src/helpers/mod.rs b/vendor/time-macros/src/helpers/mod.rs new file mode 100644 index 000000000..cbf3ba3ed --- /dev/null +++ b/vendor/time-macros/src/helpers/mod.rs @@ -0,0 +1,129 @@ +#[cfg(any(feature = "formatting", feature = "parsing"))] +mod string; + +use std::iter::Peekable; +use std::str::FromStr; + +#[cfg(any(feature = "formatting", feature = "parsing"))] +use proc_macro::TokenStream; +use proc_macro::{token_stream, Span, TokenTree}; +use time_core::util::{days_in_year, is_leap_year}; + +use crate::Error; + +#[cfg(any(feature = "formatting", feature = "parsing"))] +pub(crate) fn get_string_literal(tokens: TokenStream) -> Result<(Span, Vec<u8>), Error> { + let mut tokens = tokens.into_iter(); + + match (tokens.next(), tokens.next()) { + (Some(TokenTree::Literal(literal)), None) => string::parse(&literal), + (Some(tree), None) => Err(Error::ExpectedString { + span_start: Some(tree.span()), + span_end: Some(tree.span()), + }), + (_, Some(tree)) => Err(Error::UnexpectedToken { tree }), + (None, None) => Err(Error::ExpectedString { + span_start: None, + span_end: None, + }), + } +} + +pub(crate) fn consume_number<T: FromStr>( + component_name: &'static str, + chars: &mut Peekable<token_stream::IntoIter>, +) -> Result<(Span, T), Error> { + let (span, digits) = match chars.next() { + Some(TokenTree::Literal(literal)) => (literal.span(), literal.to_string()), + Some(tree) => return Err(Error::UnexpectedToken { tree }), + None => return Err(Error::UnexpectedEndOfInput), + }; + + if let Ok(value) = digits.replace('_', "").parse() { + Ok((span, value)) + } else { + Err(Error::InvalidComponent { + name: component_name, + value: digits, + span_start: Some(span), + span_end: Some(span), + }) + } +} + +pub(crate) fn consume_any_ident( + idents: &[&str], + chars: &mut Peekable<token_stream::IntoIter>, +) -> Result<Span, Error> { + match chars.peek() { + Some(TokenTree::Ident(char)) if idents.contains(&char.to_string().as_str()) => { + let ret = Ok(char.span()); + drop(chars.next()); + ret + } + Some(tree) => Err(Error::UnexpectedToken { tree: tree.clone() }), + None => Err(Error::UnexpectedEndOfInput), + } +} + +pub(crate) fn consume_punct( + c: char, + chars: &mut Peekable<token_stream::IntoIter>, +) -> Result<Span, Error> { + match chars.peek() { + Some(TokenTree::Punct(punct)) if *punct == c => { + let ret = Ok(punct.span()); + drop(chars.next()); + ret + } + Some(tree) => Err(Error::UnexpectedToken { tree: tree.clone() }), + None => Err(Error::UnexpectedEndOfInput), + } +} + +fn jan_weekday(year: i32, ordinal: i32) -> u8 { + macro_rules! div_floor { + ($a:expr, $b:expr) => {{ + let (_quotient, _remainder) = ($a / $b, $a % $b); + if (_remainder > 0 && $b < 0) || (_remainder < 0 && $b > 0) { + _quotient - 1 + } else { + _quotient + } + }}; + } + + let adj_year = year - 1; + ((ordinal + adj_year + div_floor!(adj_year, 4) - div_floor!(adj_year, 100) + + div_floor!(adj_year, 400) + + 6) + .rem_euclid(7)) as _ +} + +pub(crate) fn days_in_year_month(year: i32, month: u8) -> u8 { + [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month as usize - 1] + + (month == 2 && is_leap_year(year)) as u8 +} + +pub(crate) fn ywd_to_yo(year: i32, week: u8, iso_weekday_number: u8) -> (i32, u16) { + let (ordinal, overflow) = (u16::from(week) * 7 + u16::from(iso_weekday_number)) + .overflowing_sub(u16::from(jan_weekday(year, 4)) + 4); + + if overflow || ordinal == 0 { + return (year - 1, (ordinal.wrapping_add(days_in_year(year - 1)))); + } + + let days_in_cur_year = days_in_year(year); + if ordinal > days_in_cur_year { + (year + 1, ordinal - days_in_cur_year) + } else { + (year, ordinal) + } +} + +pub(crate) fn ymd_to_yo(year: i32, month: u8, day: u8) -> (i32, u16) { + let ordinal = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334][month as usize - 1] + + (month > 2 && is_leap_year(year)) as u16; + + (year, ordinal + u16::from(day)) +} diff --git a/vendor/time-macros/src/helpers/string.rs b/vendor/time-macros/src/helpers/string.rs new file mode 100644 index 000000000..fa3780f5e --- /dev/null +++ b/vendor/time-macros/src/helpers/string.rs @@ -0,0 +1,188 @@ +use std::ops::{Index, RangeFrom}; + +use proc_macro::Span; + +use crate::Error; + +pub(crate) fn parse(token: &proc_macro::Literal) -> Result<(Span, Vec<u8>), Error> { + let span = token.span(); + let repr = token.to_string(); + + match repr.as_bytes() { + [b'"', ..] => Ok((span, parse_lit_str_cooked(&repr[1..]))), + [b'b', b'"', rest @ ..] => Ok((span, parse_lit_byte_str_cooked(rest))), + [b'r', rest @ ..] | [b'b', b'r', rest @ ..] => Ok((span, parse_lit_str_raw(rest))), + _ => Err(Error::ExpectedString { + span_start: Some(span), + span_end: Some(span), + }), + } +} + +fn byte(s: impl AsRef<[u8]>, idx: usize) -> u8 { + s.as_ref().get(idx).copied().unwrap_or_default() +} + +fn parse_lit_str_cooked(mut s: &str) -> Vec<u8> { + let mut content = String::new(); + 'outer: loop { + let ch = match byte(s, 0) { + b'"' => break, + b'\\' => { + let b = byte(s, 1); + s = &s[2..]; + match b { + b'x' => { + let (byte, rest) = backslash_x(s); + s = rest; + char::from_u32(u32::from(byte)).expect("byte was just validated") + } + b'u' => { + let (chr, rest) = backslash_u(s); + s = rest; + chr + } + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'\\' => '\\', + b'0' => '\0', + b'\'' => '\'', + b'"' => '"', + b'\r' | b'\n' => loop { + let ch = s.chars().next().unwrap_or_default(); + if ch.is_whitespace() { + s = &s[ch.len_utf8()..]; + } else { + continue 'outer; + } + }, + _ => unreachable!("invalid escape"), + } + } + b'\r' => { + // bare CR not permitted + s = &s[2..]; + '\n' + } + _ => { + let ch = s.chars().next().unwrap_or_default(); + s = &s[ch.len_utf8()..]; + ch + } + }; + content.push(ch); + } + + content.into_bytes() +} + +fn parse_lit_str_raw(s: &[u8]) -> Vec<u8> { + let mut pounds = 0; + while byte(s, pounds) == b'#' { + pounds += 1; + } + let close = s + .iter() + .rposition(|&b| b == b'"') + .expect("had a string without trailing \""); + + s[pounds + 1..close].to_owned() +} + +fn parse_lit_byte_str_cooked(mut v: &[u8]) -> Vec<u8> { + let mut out = Vec::new(); + 'outer: loop { + let byte = match byte(v, 0) { + b'"' => break, + b'\\' => { + let b = byte(v, 1); + v = &v[2..]; + match b { + b'x' => { + let (byte, rest) = backslash_x(v); + v = rest; + byte + } + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'0' => b'\0', + b'\'' => b'\'', + b'"' => b'"', + b'\r' | b'\n' => loop { + let byte = byte(v, 0); + let ch = char::from_u32(u32::from(byte)).expect("invalid byte"); + if ch.is_whitespace() { + v = &v[1..]; + } else { + continue 'outer; + } + }, + _ => unreachable!("invalid escape"), + } + } + b'\r' => { + // bare CR not permitted + v = &v[2..]; + b'\n' + } + b => { + v = &v[1..]; + b + } + }; + out.push(byte); + } + + out +} + +fn backslash_x<S>(s: &S) -> (u8, &S) +where + S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized, +{ + let mut ch = 0; + let b0 = byte(s, 0); + let b1 = byte(s, 1); + ch += 0x10 * (b0 - b'0'); + ch += match b1 { + b'0'..=b'9' => b1 - b'0', + b'a'..=b'f' => 10 + (b1 - b'a'), + b'A'..=b'F' => 10 + (b1 - b'A'), + _ => unreachable!("invalid hex escape"), + }; + (ch, &s[2..]) +} + +fn backslash_u(mut s: &str) -> (char, &str) { + s = &s[1..]; + + let mut ch = 0; + let mut digits = 0; + loop { + let b = byte(s, 0); + let digit = match b { + b'0'..=b'9' => b - b'0', + b'a'..=b'f' => 10 + b - b'a', + b'A'..=b'F' => 10 + b - b'A', + b'_' if digits > 0 => { + s = &s[1..]; + continue; + } + b'}' if digits != 0 => break, + _ => unreachable!("invalid unicode escape"), + }; + ch *= 0x10; + ch += u32::from(digit); + digits += 1; + s = &s[1..]; + } + s = &s[1..]; + + ( + char::from_u32(ch).expect("invalid unicode escape passed by compiler"), + s, + ) +} diff --git a/vendor/time-macros/src/lib.rs b/vendor/time-macros/src/lib.rs new file mode 100644 index 000000000..1afc313ea --- /dev/null +++ b/vendor/time-macros/src/lib.rs @@ -0,0 +1,167 @@ +#![deny( + anonymous_parameters, + clippy::all, + const_err, + illegal_floating_point_literal_pattern, + late_bound_lifetime_arguments, + path_statements, + patterns_in_fns_without_body, + rust_2018_idioms, + trivial_casts, + trivial_numeric_casts, + unreachable_pub, + unsafe_code, + unused_extern_crates +)] +#![warn( + clippy::dbg_macro, + clippy::decimal_literal_representation, + clippy::get_unwrap, + clippy::nursery, + clippy::print_stdout, + clippy::todo, + clippy::unimplemented, + clippy::unnested_or_patterns, + clippy::unwrap_used, + clippy::use_debug, + single_use_lifetimes, + unused_qualifications, + variant_size_differences +)] +#![allow( + clippy::missing_const_for_fn, // useless in proc macro + clippy::redundant_pub_crate, // suggests bad style + clippy::option_if_let_else, // suggests terrible code +)] + +#[macro_use] +mod quote; + +mod date; +mod datetime; +mod error; +#[cfg(any(feature = "formatting", feature = "parsing"))] +mod format_description; +mod helpers; +mod offset; +#[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] +mod serde_format_description; +mod time; +mod to_tokens; + +use proc_macro::TokenStream; +#[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] +use proc_macro::TokenTree; + +use self::error::Error; + +macro_rules! impl_macros { + ($($name:ident)*) => {$( + #[proc_macro] + pub fn $name(input: TokenStream) -> TokenStream { + use crate::to_tokens::ToTokenTree; + + let mut iter = input.into_iter().peekable(); + match $name::parse(&mut iter) { + Ok(value) => match iter.peek() { + Some(tree) => Error::UnexpectedToken { tree: tree.clone() }.to_compile_error(), + None => TokenStream::from(value.into_token_tree()), + }, + Err(err) => err.to_compile_error(), + } + } + )*}; +} + +impl_macros![date datetime offset time]; + +#[cfg(any(feature = "formatting", feature = "parsing"))] +#[proc_macro] +pub fn format_description(input: TokenStream) -> TokenStream { + (|| { + let (span, string) = helpers::get_string_literal(input)?; + let items = format_description::parse(&string, span)?; + + Ok(quote! {{ + const DESCRIPTION: &[::time::format_description::FormatItem<'_>] = &[#S( + items + .into_iter() + .map(|item| quote! { #S(item), }) + .collect::<TokenStream>() + )]; + DESCRIPTION + }}) + })() + .unwrap_or_else(|err: Error| err.to_compile_error()) +} + +#[cfg(all(feature = "serde", any(feature = "formatting", feature = "parsing")))] +#[proc_macro] +pub fn serde_format_description(input: TokenStream) -> TokenStream { + (|| { + let mut tokens = input.into_iter().peekable(); + // First, an identifier (the desired module name) + let mod_name = match tokens.next() { + Some(TokenTree::Ident(ident)) => Ok(ident), + Some(tree) => Err(Error::UnexpectedToken { tree }), + None => Err(Error::UnexpectedEndOfInput), + }?; + + // Followed by a comma + helpers::consume_punct(',', &mut tokens)?; + + // Then, the type to create serde serializers for (e.g., `OffsetDateTime`). + let formattable = match tokens.next() { + Some(tree @ TokenTree::Ident(_)) => Ok(tree), + Some(tree) => Err(Error::UnexpectedToken { tree }), + None => Err(Error::UnexpectedEndOfInput), + }?; + + // Another comma + helpers::consume_punct(',', &mut tokens)?; + + // We now have two options. The user can either provide a format description as a string or + // they can provide a path to a format description. If the latter, all remaining tokens are + // assumed to be part of the path. + let (format, raw_format_string) = match tokens.peek() { + // string literal + Some(TokenTree::Literal(_)) => { + let (span, format_string) = helpers::get_string_literal(tokens.collect())?; + let items = format_description::parse(&format_string, span)?; + let items: TokenStream = + items.into_iter().map(|item| quote! { #S(item), }).collect(); + let items = quote! { &[#S(items)] }; + + ( + items, + Some(String::from_utf8_lossy(&format_string).into_owned()), + ) + } + // path + Some(_) => ( + quote! {{ + // We can't just do `super::path` because the path could be an absolute path. In + // that case, we'd be generating `super::::path`, which is invalid. Even if we + // took that into account, it's not possible to know if it's an external crate, + // which would just require emitting `path` directly. By taking this approach, + // we can leave it to the compiler to do the actual resolution. + mod __path_hack { + pub(super) use super::super::*; + pub(super) use #S(tokens.collect::<TokenStream>()) as FORMAT; + } + __path_hack::FORMAT + }}, + None, + ), + None => return Err(Error::UnexpectedEndOfInput), + }; + + Ok(serde_format_description::build( + mod_name, + formattable, + format, + raw_format_string, + )) + })() + .unwrap_or_else(|err: Error| err.to_compile_error_standalone()) +} diff --git a/vendor/time-macros/src/offset.rs b/vendor/time-macros/src/offset.rs new file mode 100644 index 000000000..c2099073f --- /dev/null +++ b/vendor/time-macros/src/offset.rs @@ -0,0 +1,95 @@ +use std::iter::Peekable; + +use proc_macro::{token_stream, Span, TokenTree}; + +use crate::helpers::{consume_any_ident, consume_number, consume_punct}; +use crate::to_tokens::ToTokenTree; +use crate::Error; + +pub(crate) struct Offset { + pub(crate) hours: i8, + pub(crate) minutes: i8, + pub(crate) seconds: i8, +} + +pub(crate) fn parse(chars: &mut Peekable<token_stream::IntoIter>) -> Result<Offset, Error> { + if consume_any_ident(&["utc", "UTC"], chars).is_ok() { + return Ok(Offset { + hours: 0, + minutes: 0, + seconds: 0, + }); + } + + let sign = if consume_punct('+', chars).is_ok() { + 1 + } else if consume_punct('-', chars).is_ok() { + -1 + } else if let Some(tree) = chars.next() { + return Err(Error::UnexpectedToken { tree }); + } else { + return Err(Error::MissingComponent { + name: "sign", + span_start: None, + span_end: None, + }); + }; + + let (hours_span, hours) = consume_number::<i8>("hour", chars)?; + let (mut minutes_span, mut minutes) = (Span::mixed_site(), 0); + let (mut seconds_span, mut seconds) = (Span::mixed_site(), 0); + + if consume_punct(':', chars).is_ok() { + let min = consume_number::<i8>("minute", chars)?; + minutes_span = min.0; + minutes = min.1; + + if consume_punct(':', chars).is_ok() { + let sec = consume_number::<i8>("second", chars)?; + seconds_span = sec.0; + seconds = sec.1; + } + } + + if hours >= 24 { + Err(Error::InvalidComponent { + name: "hour", + value: hours.to_string(), + span_start: Some(hours_span), + span_end: Some(hours_span), + }) + } else if minutes >= 60 { + Err(Error::InvalidComponent { + name: "minute", + value: minutes.to_string(), + span_start: Some(minutes_span), + span_end: Some(minutes_span), + }) + } else if seconds >= 60 { + Err(Error::InvalidComponent { + name: "second", + value: seconds.to_string(), + span_start: Some(seconds_span), + span_end: Some(seconds_span), + }) + } else { + Ok(Offset { + hours: sign * hours, + minutes: sign * minutes, + seconds: sign * seconds, + }) + } +} + +impl ToTokenTree for Offset { + fn into_token_tree(self) -> TokenTree { + quote_group! {{ + const OFFSET: ::time::UtcOffset = ::time::UtcOffset::__from_hms_unchecked( + #(self.hours), + #(self.minutes), + #(self.seconds), + ); + OFFSET + }} + } +} diff --git a/vendor/time-macros/src/quote.rs b/vendor/time-macros/src/quote.rs new file mode 100644 index 000000000..2fe86cc98 --- /dev/null +++ b/vendor/time-macros/src/quote.rs @@ -0,0 +1,134 @@ +macro_rules! quote { + () => (::proc_macro::TokenStream::new()); + ($($x:tt)*) => {{ + let mut ts = ::proc_macro::TokenStream::new(); + let ts_mut = &mut ts; + quote_inner!(ts_mut $($x)*); + ts + }}; +} + +#[cfg(any(feature = "formatting", feature = "parsing"))] +macro_rules! quote_append { + ($ts:ident $($x:tt)*) => {{ + quote_inner!($ts $($x)*); + }}; +} + +macro_rules! quote_group { + ({ $($x:tt)* }) => { + ::proc_macro::TokenTree::Group(::proc_macro::Group::new( + ::proc_macro::Delimiter::Brace, + quote!($($x)*) + )) + }; +} + +macro_rules! sym { + ($ts:ident $x:tt $y:tt) => { + $ts.extend([ + ::proc_macro::TokenTree::from(::proc_macro::Punct::new( + $x, + ::proc_macro::Spacing::Joint, + )), + ::proc_macro::TokenTree::from(::proc_macro::Punct::new( + $y, + ::proc_macro::Spacing::Alone, + )), + ]); + }; + ($ts:ident $x:tt) => { + $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Punct::new( + $x, + ::proc_macro::Spacing::Alone, + ))]); + }; +} + +macro_rules! quote_inner { + // Base case + ($ts:ident) => {}; + + // Single or double symbols + ($ts:ident :: $($tail:tt)*) => { sym!($ts ':' ':'); quote_inner!($ts $($tail)*); }; + ($ts:ident .. $($tail:tt)*) => { sym!($ts '.' '.'); quote_inner!($ts $($tail)*); }; + ($ts:ident : $($tail:tt)*) => { sym!($ts ':'); quote_inner!($ts $($tail)*); }; + ($ts:ident = $($tail:tt)*) => { sym!($ts '='); quote_inner!($ts $($tail)*); }; + ($ts:ident ; $($tail:tt)*) => { sym!($ts ';'); quote_inner!($ts $($tail)*); }; + ($ts:ident , $($tail:tt)*) => { sym!($ts ','); quote_inner!($ts $($tail)*); }; + ($ts:ident . $($tail:tt)*) => { sym!($ts '.'); quote_inner!($ts $($tail)*); }; + ($ts:ident & $($tail:tt)*) => { sym!($ts '&'); quote_inner!($ts $($tail)*); }; + ($ts:ident << $($tail:tt)*) => { sym!($ts '<' '<'); quote_inner!($ts $($tail)*); }; + ($ts:ident < $($tail:tt)*) => { sym!($ts '<'); quote_inner!($ts $($tail)*); }; + ($ts:ident >> $($tail:tt)*) => { sym!($ts '>' '>'); quote_inner!($ts $($tail)*); }; + ($ts:ident > $($tail:tt)*) => { sym!($ts '>'); quote_inner!($ts $($tail)*); }; + ($ts:ident -> $($tail:tt)*) => { sym!($ts '-' '>'); quote_inner!($ts $($tail)*); }; + ($ts:ident ? $($tail:tt)*) => { sym!($ts '?'); quote_inner!($ts $($tail)*); }; + ($ts:ident ! $($tail:tt)*) => { sym!($ts '!'); quote_inner!($ts $($tail)*); }; + ($ts:ident | $($tail:tt)*) => { sym!($ts '|'); quote_inner!($ts $($tail)*); }; + ($ts:ident * $($tail:tt)*) => { sym!($ts '*'); quote_inner!($ts $($tail)*); }; + + // Identifier + ($ts:ident $i:ident $($tail:tt)*) => { + $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Ident::new( + &stringify!($i), + ::proc_macro::Span::mixed_site(), + ))]); + quote_inner!($ts $($tail)*); + }; + + // Literal + ($ts:ident $l:literal $($tail:tt)*) => { + $ts.extend([::proc_macro::TokenTree::from(::proc_macro::Literal::string(&$l))]); + quote_inner!($ts $($tail)*); + }; + + // Lifetime + ($ts:ident $l:lifetime $($tail:tt)*) => { + $ts.extend([ + ::proc_macro::TokenTree::from( + ::proc_macro::Punct::new('\'', ::proc_macro::Spacing::Joint) + ), + ::proc_macro::TokenTree::from(::proc_macro::Ident::new( + stringify!($l).trim_start_matches(|c| c == '\''), + ::proc_macro::Span::mixed_site(), + )), + ]); + quote_inner!($ts $($tail)*); + }; + + // Groups + ($ts:ident ($($inner:tt)*) $($tail:tt)*) => { + $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( + ::proc_macro::Delimiter::Parenthesis, + quote!($($inner)*) + ))]); + quote_inner!($ts $($tail)*); + }; + ($ts:ident [$($inner:tt)*] $($tail:tt)*) => { + $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( + ::proc_macro::Delimiter::Bracket, + quote!($($inner)*) + ))]); + quote_inner!($ts $($tail)*); + }; + ($ts:ident {$($inner:tt)*} $($tail:tt)*) => { + $ts.extend([::proc_macro::TokenTree::Group(::proc_macro::Group::new( + ::proc_macro::Delimiter::Brace, + quote!($($inner)*) + ))]); + quote_inner!($ts $($tail)*); + }; + + // Interpolated values + // TokenTree by default + ($ts:ident #($e:expr) $($tail:tt)*) => { + $ts.extend([$crate::to_tokens::ToTokenTree::into_token_tree($e)]); + quote_inner!($ts $($tail)*); + }; + // Allow a TokenStream by request. It's more expensive, so avoid if possible. + ($ts:ident #S($e:expr) $($tail:tt)*) => { + $crate::to_tokens::ToTokenStream::append_to($e, $ts); + quote_inner!($ts $($tail)*); + }; +} diff --git a/vendor/time-macros/src/serde_format_description.rs b/vendor/time-macros/src/serde_format_description.rs new file mode 100644 index 000000000..c09a4e9e2 --- /dev/null +++ b/vendor/time-macros/src/serde_format_description.rs @@ -0,0 +1,163 @@ +use proc_macro::{Ident, TokenStream, TokenTree}; + +pub(crate) fn build( + mod_name: Ident, + ty: TokenTree, + format: TokenStream, + raw_format_string: Option<String>, +) -> TokenStream { + let ty_s = &*ty.to_string(); + + let format_description_display = raw_format_string.unwrap_or_else(|| format.to_string()); + + let visitor = if cfg!(feature = "parsing") { + quote! { + struct Visitor; + struct OptionVisitor; + + impl<'a> ::serde::de::Visitor<'a> for Visitor { + type Value = __TimeSerdeType; + + fn expecting(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!( + f, + concat!( + "a(n) `", + #(ty_s), + "` in the format \"{}\"", + ), + #(format_description_display.as_str()) + ) + } + + fn visit_str<E: ::serde::de::Error>( + self, + value: &str + ) -> Result<__TimeSerdeType, E> { + __TimeSerdeType::parse(value, &DESCRIPTION).map_err(E::custom) + } + } + + impl<'a> ::serde::de::Visitor<'a> for OptionVisitor { + type Value = Option<__TimeSerdeType>; + + fn expecting(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + write!( + f, + concat!( + "an `Option<", + #(ty_s), + ">` in the format \"{}\"", + ), + #(format_description_display.as_str()) + ) + } + + fn visit_some<D: ::serde::de::Deserializer<'a>>( + self, + deserializer: D + ) -> Result<Option<__TimeSerdeType>, D::Error> { + deserializer + .deserialize_any(Visitor) + .map(Some) + } + + fn visit_none<E: ::serde::de::Error>( + self + ) -> Result<Option<__TimeSerdeType>, E> { + Ok(None) + } + } + } + } else { + quote!() + }; + + let serialize_primary = if cfg!(feature = "formatting") { + quote! { + pub fn serialize<S: ::serde::Serializer>( + datetime: &__TimeSerdeType, + serializer: S, + ) -> Result<S::Ok, S::Error> { + use ::serde::Serialize; + datetime + .format(&DESCRIPTION) + .map_err(::time::error::Format::into_invalid_serde_value::<S>)? + .serialize(serializer) + } + } + } else { + quote!() + }; + + let deserialize_primary = if cfg!(feature = "parsing") { + quote! { + pub fn deserialize<'a, D: ::serde::Deserializer<'a>>( + deserializer: D + ) -> Result<__TimeSerdeType, D::Error> { + use ::serde::Deserialize; + deserializer.deserialize_any(Visitor) + } + } + } else { + quote!() + }; + + let serialize_option = if cfg!(feature = "formatting") { + quote! { + pub fn serialize<S: ::serde::Serializer>( + option: &Option<__TimeSerdeType>, + serializer: S, + ) -> Result<S::Ok, S::Error> { + use ::serde::Serialize; + option.map(|datetime| datetime.format(&DESCRIPTION)) + .transpose() + .map_err(::time::error::Format::into_invalid_serde_value::<S>)? + .serialize(serializer) + } + } + } else { + quote!() + }; + + let deserialize_option = if cfg!(feature = "parsing") { + quote! { + pub fn deserialize<'a, D: ::serde::Deserializer<'a>>( + deserializer: D + ) -> Result<Option<__TimeSerdeType>, D::Error> { + use ::serde::Deserialize; + deserializer.deserialize_option(OptionVisitor) + } + } + } else { + quote!() + }; + + let deserialize_option_imports = if cfg!(feature = "parsing") { + quote! { + use super::{OptionVisitor, Visitor}; + } + } else { + quote!() + }; + + quote! { + mod #(mod_name) { + use ::time::#(ty) as __TimeSerdeType; + + const DESCRIPTION: &[::time::format_description::FormatItem<'_>] = #S(format); + + #S(visitor) + #S(serialize_primary) + #S(deserialize_primary) + + pub(super) mod option { + use super::{DESCRIPTION, __TimeSerdeType}; + #S(deserialize_option_imports) + + #S(serialize_option) + #S(deserialize_option) + } + } + } +} diff --git a/vendor/time-macros/src/time.rs b/vendor/time-macros/src/time.rs new file mode 100644 index 000000000..719e2051f --- /dev/null +++ b/vendor/time-macros/src/time.rs @@ -0,0 +1,118 @@ +use std::iter::Peekable; + +use proc_macro::{token_stream, Span, TokenTree}; + +use crate::helpers::{consume_any_ident, consume_number, consume_punct}; +use crate::to_tokens::ToTokenTree; +use crate::Error; + +enum Period { + Am, + Pm, + _24, +} + +pub(crate) struct Time { + pub(crate) hour: u8, + pub(crate) minute: u8, + pub(crate) second: u8, + pub(crate) nanosecond: u32, +} + +pub(crate) fn parse(chars: &mut Peekable<token_stream::IntoIter>) -> Result<Time, Error> { + fn consume_period(chars: &mut Peekable<token_stream::IntoIter>) -> (Option<Span>, Period) { + if let Ok(span) = consume_any_ident(&["am", "AM"], chars) { + (Some(span), Period::Am) + } else if let Ok(span) = consume_any_ident(&["pm", "PM"], chars) { + (Some(span), Period::Pm) + } else { + (None, Period::_24) + } + } + + let (hour_span, hour) = consume_number("hour", chars)?; + + let ((minute_span, minute), (second_span, second), (period_span, period)) = + match consume_period(chars) { + // Nothing but the 12-hour clock hour and AM/PM + (period_span @ Some(_), period) => ( + (Span::mixed_site(), 0), + (Span::mixed_site(), 0.), + (period_span, period), + ), + (None, _) => { + consume_punct(':', chars)?; + let (minute_span, minute) = consume_number::<u8>("minute", chars)?; + let (second_span, second): (_, f64) = if consume_punct(':', chars).is_ok() { + consume_number("second", chars)? + } else { + (Span::mixed_site(), 0.) + }; + let (period_span, period) = consume_period(chars); + ( + (minute_span, minute), + (second_span, second), + (period_span, period), + ) + } + }; + + let hour = match (hour, period) { + (0, Period::Am | Period::Pm) => { + return Err(Error::InvalidComponent { + name: "hour", + value: hour.to_string(), + span_start: Some(hour_span), + span_end: Some(period_span.unwrap_or(hour_span)), + }); + } + (12, Period::Am) => 0, + (12, Period::Pm) => 12, + (hour, Period::Am | Period::_24) => hour, + (hour, Period::Pm) => hour + 12, + }; + + if hour >= 24 { + Err(Error::InvalidComponent { + name: "hour", + value: hour.to_string(), + span_start: Some(hour_span), + span_end: Some(period_span.unwrap_or(hour_span)), + }) + } else if minute >= 60 { + Err(Error::InvalidComponent { + name: "minute", + value: minute.to_string(), + span_start: Some(minute_span), + span_end: Some(minute_span), + }) + } else if second >= 60. { + Err(Error::InvalidComponent { + name: "second", + value: second.to_string(), + span_start: Some(second_span), + span_end: Some(second_span), + }) + } else { + Ok(Time { + hour, + minute, + second: second.trunc() as _, + nanosecond: (second.fract() * 1_000_000_000.).round() as _, + }) + } +} + +impl ToTokenTree for Time { + fn into_token_tree(self) -> TokenTree { + quote_group! {{ + const TIME: ::time::Time = ::time::Time::__from_hms_nanos_unchecked( + #(self.hour), + #(self.minute), + #(self.second), + #(self.nanosecond), + ); + TIME + }} + } +} diff --git a/vendor/time-macros/src/to_tokens.rs b/vendor/time-macros/src/to_tokens.rs new file mode 100644 index 000000000..3a293925c --- /dev/null +++ b/vendor/time-macros/src/to_tokens.rs @@ -0,0 +1,68 @@ +use proc_macro::{Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; + +pub(crate) trait ToTokenStream: Sized { + fn append_to(self, ts: &mut TokenStream); +} + +pub(crate) trait ToTokenTree: Sized { + fn into_token_tree(self) -> TokenTree; +} + +impl<T: ToTokenTree> ToTokenStream for T { + fn append_to(self, ts: &mut TokenStream) { + ts.extend([self.into_token_tree()]) + } +} + +impl ToTokenTree for bool { + fn into_token_tree(self) -> TokenTree { + let lit = if self { "true" } else { "false" }; + TokenTree::Ident(Ident::new(lit, Span::mixed_site())) + } +} + +impl ToTokenStream for TokenStream { + fn append_to(self, ts: &mut TokenStream) { + ts.extend(self) + } +} + +impl ToTokenTree for TokenTree { + fn into_token_tree(self) -> TokenTree { + self + } +} + +impl ToTokenTree for &str { + fn into_token_tree(self) -> TokenTree { + TokenTree::Literal(Literal::string(self)) + } +} + +macro_rules! impl_for_tree_types { + ($($type:ty)*) => {$( + impl ToTokenTree for $type { + fn into_token_tree(self) -> TokenTree { + TokenTree::from(self) + } + } + )*}; +} +impl_for_tree_types![Ident Literal Group Punct]; + +macro_rules! impl_for_int { + ($($type:ty => $method:ident)*) => {$( + impl ToTokenTree for $type { + fn into_token_tree(self) -> TokenTree { + TokenTree::from(Literal::$method(self)) + } + } + )*}; +} +impl_for_int! { + i8 => i8_unsuffixed + u8 => u8_unsuffixed + u16 => u16_unsuffixed + i32 => i32_unsuffixed + u32 => u32_unsuffixed +} |