temporal_rs 0.2.3

Temporal in Rust is an implementation of the TC39 Temporal Builtin Proposal in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! This module implements `TemporalError`.

use core::fmt;
use ixdtf::ParseError;
use timezone_provider::TimeZoneProviderError;

use icu_calendar::error::{DateAddError, DateFromFieldsError};

/// `TemporalError`'s error type.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub enum ErrorKind {
    /// Error.
    #[default]
    Generic,
    /// TypeError
    Type,
    /// RangeError
    Range,
    /// SyntaxError
    Syntax,
    /// Assert
    Assert,
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Generic => "Error",
            Self::Type => "TypeError",
            Self::Range => "RangeError",
            Self::Syntax => "SyntaxError",
            Self::Assert => "ImplementationError",
        }
        .fmt(f)
    }
}

/// The error type for `boa_temporal`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TemporalError {
    kind: ErrorKind,
    msg: ErrorMessage,
}

impl TemporalError {
    #[inline]
    #[must_use]
    const fn new(kind: ErrorKind) -> Self {
        Self {
            kind,
            msg: ErrorMessage::None,
        }
    }

    /// Create a generic error
    #[inline]
    #[must_use]
    pub fn general(msg: &'static str) -> Self {
        Self::new(ErrorKind::Generic).with_message(msg)
    }

    /// Create a range error.
    #[inline]
    #[must_use]
    pub const fn range() -> Self {
        Self::new(ErrorKind::Range)
    }

    /// Create a type error.
    #[inline]
    #[must_use]
    pub const fn r#type() -> Self {
        Self::new(ErrorKind::Type)
    }

    /// Create a syntax error.
    #[inline]
    #[must_use]
    pub const fn syntax() -> Self {
        Self::new(ErrorKind::Syntax)
    }

    /// Creates an assertion error
    #[inline]
    #[must_use]
    #[cfg_attr(debug_assertions, track_caller)]
    pub(crate) const fn assert() -> Self {
        #[cfg(not(debug_assertions))]
        {
            Self::new(ErrorKind::Assert)
        }
        #[cfg(debug_assertions)]
        Self {
            kind: ErrorKind::Assert,
            msg: ErrorMessage::String(core::panic::Location::caller().file()),
        }
    }

    /// Create an abrupt end error.
    #[inline]
    #[must_use]
    pub fn abrupt_end() -> Self {
        Self::syntax().with_message("Abrupt end to parsing target.")
    }

    /// Add a message to the error.
    #[inline]
    #[must_use]
    pub fn with_message(mut self, msg: &'static str) -> Self {
        self.msg = ErrorMessage::String(msg);
        self
    }

    /// Add a message enum to the error.
    #[inline]
    #[must_use]
    pub(crate) fn with_enum(mut self, msg: ErrorMessage) -> Self {
        self.msg = msg;
        self
    }

    /// Returns this error's kind.
    #[inline]
    #[must_use]
    pub const fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Extracts the error message.
    #[inline]
    #[must_use]
    pub fn into_message(self) -> &'static str {
        self.msg.to_string()
    }
}

impl core::error::Error for TemporalError {}

impl fmt::Display for TemporalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind)?;

        let msg = self.msg.to_string();
        if !msg.is_empty() {
            write!(f, ": {msg}")?;
        }

        Ok(())
    }
}

impl From<DateFromFieldsError> for TemporalError {
    fn from(error: DateFromFieldsError) -> Self {
        let kind = if error == DateFromFieldsError::NotEnoughFields {
            ErrorKind::Type
        } else {
            ErrorKind::Range
        };
        TemporalError::new(kind).with_enum(ErrorMessage::Icu4xDateFromFields(error))
    }
}

impl From<DateAddError> for TemporalError {
    fn from(error: DateAddError) -> Self {
        TemporalError::range().with_enum(ErrorMessage::Icu4xDateAdd(error))
    }
}

impl From<ParseError> for TemporalError {
    fn from(error: ParseError) -> Self {
        TemporalError::range().with_enum(ErrorMessage::Ixdtf(error))
    }
}

/// The error message
#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) enum ErrorMessage {
    // Range
    InstantOutOfRange,
    IntermediateDateTimeOutOfRange,
    ZDTOutOfDayBounds,
    LargestUnitCannotBeDateUnit,
    DateOutOfRange,
    DurationNotValid,

    // Numerical errors
    NumberNotFinite,
    NumberNotIntegral,
    NumberNotPositive,
    NumberOutOfRange,
    FractionalDigitsPrecisionInvalid,

    // Options validity
    SmallestUnitIsRequired,
    SmallestUnitNotTimeUnit,
    SmallestUnitLargerThanLargestUnit,
    UnitNotDate,
    UnitNotTime,
    UnitRequired,
    UnitNoAutoDuringComparison,
    RoundToUnitInvalid,
    RoundingModeInvalid,
    CalendarNameInvalid,
    OffsetOptionInvalid,
    TimeZoneNameInvalid,

    // Field mismatches
    CalendarMismatch,
    TzMismatch,
    EmptyFieldsIsInvalid,

    // Parsing
    ParserNeedsDate,
    FractionalTimeMoreThanNineDigits,

    // Other
    OffsetNeedsDisambiguation,

    // Typed
    None,
    String(&'static str),
    Ixdtf(ParseError),
    Icu4xDateFromFields(DateFromFieldsError),
    Icu4xDateAdd(DateAddError),
}

impl ErrorMessage {
    pub fn to_string(self) -> &'static str {
        match self {
            Self::InstantOutOfRange => "Instant nanoseconds are not within a valid epoch range.",
            Self::IntermediateDateTimeOutOfRange => {
                "Intermediate ISO datetime was not within a valid range."
            }
            Self::ZDTOutOfDayBounds => "ZonedDateTime is outside the expected day bounds",
            Self::LargestUnitCannotBeDateUnit => "Largest unit cannot be a date unit",
            Self::DateOutOfRange => "Date is not within ISO date time limits.",
            Self::DurationNotValid => "Duration was not valid.",
            Self::NumberNotFinite => "number value is not a finite value.",
            Self::NumberNotIntegral => "value must be integral.",
            Self::NumberNotPositive => "integer must be positive.",
            Self::NumberOutOfRange => "number exceeded a valid range.",
            Self::FractionalDigitsPrecisionInvalid => "Invalid fractionalDigits precision value",
            Self::SmallestUnitIsRequired => "smallestUnit is required",
            Self::SmallestUnitNotTimeUnit => "smallestUnit must be a valid time unit.",
            Self::SmallestUnitLargerThanLargestUnit => {
                "smallestUnit was larger than largestunit in DifferenceeSettings"
            }
            Self::UnitNotDate => "Unit was not part of the date unit group.",
            Self::UnitNotTime => "Unit was not part of the time unit group.",
            Self::UnitRequired => "Unit is required",
            Self::UnitNoAutoDuringComparison => "'auto' units are not allowed during comparison",
            Self::RoundToUnitInvalid => "Invalid roundTo unit provided.",
            Self::RoundingModeInvalid => "Invalid roundingMode option provided",
            Self::CalendarNameInvalid => "Invalid calendarName option provided",
            Self::OffsetOptionInvalid => "Invalid offsetOption option provided",
            Self::TimeZoneNameInvalid => "Invalid timeZoneName option provided",
            Self::CalendarMismatch => {
                "Calendar must be the same for operations involving two calendared types."
            }
            Self::TzMismatch => "Timezones must be the same if unit is a day unit.",
            Self::EmptyFieldsIsInvalid => "fields cannot be empty",

            Self::ParserNeedsDate => "Could not find a valid DateRecord node during parsing.",
            Self::FractionalTimeMoreThanNineDigits => "Fractional time exceeds nine digits.",
            Self::OffsetNeedsDisambiguation => {
                "Offsets could not be determined without disambiguation"
            }
            Self::None => "",
            Self::String(s) => s,
            Self::Ixdtf(s) => ixdtf_error_to_static_string(s),

            Self::Icu4xDateFromFields(DateFromFieldsError::InvalidEra) => "Unknown era.",
            Self::Icu4xDateFromFields(DateFromFieldsError::InvalidDay { .. })
            | Self::Icu4xDateAdd(DateAddError::InvalidDay { .. }) => "Day out of range",
            Self::Icu4xDateFromFields(DateFromFieldsError::InvalidOrdinalMonth { .. }) => {
                "Month out of range"
            }
            Self::Icu4xDateFromFields(DateFromFieldsError::MonthCodeInvalidSyntax) => {
                "Invalid month code."
            }
            Self::Icu4xDateFromFields(DateFromFieldsError::MonthNotInCalendar) => {
                "Month code not in calendar."
            }
            Self::Icu4xDateFromFields(DateFromFieldsError::MonthNotInYear)
            | Self::Icu4xDateAdd(DateAddError::MonthNotInYear) => "Month code not in year.",
            Self::Icu4xDateFromFields(DateFromFieldsError::InconsistentYear) => {
                "Inconsistent year."
            }
            Self::Icu4xDateFromFields(DateFromFieldsError::InconsistentMonth) => {
                "Inconsistent month/monthCode."
            }
            Self::Icu4xDateFromFields(DateFromFieldsError::NotEnoughFields) => {
                "Insufficient fields."
            }
            Self::Icu4xDateAdd(DateAddError::Overflow) => "Overflow during addition.",
            Self::Icu4xDateFromFields(_) | Self::Icu4xDateAdd(_) => "Date error.",
        }
    }
}

impl From<TimeZoneProviderError> for TemporalError {
    fn from(other: TimeZoneProviderError) -> Self {
        match other {
            TimeZoneProviderError::InstantOutOfRange => {
                Self::range().with_enum(ErrorMessage::InstantOutOfRange)
            }
            TimeZoneProviderError::Assert(s) => Self::assert().with_message(s),
            TimeZoneProviderError::Range(s) => Self::range().with_message(s),
            _ => Self::assert().with_message("Unknown TimeZoneProviderError"),
        }
    }
}

// ICU4X will get this API natively eventually
// https://github.com/unicode-org/icu4x/issues/6904
pub fn ixdtf_error_to_static_string(error: ParseError) -> &'static str {
    match error {
        ParseError::ImplAssert => "Implementation error: this error must not throw.",

        ParseError::NonAsciiCodePoint => "Code point was not ASCII",

        ParseError::ParseFloat => "Invalid float while parsing fraction part.",

        ParseError::AbruptEnd { .. } => "Parsing ended abruptly.",

        ParseError::InvalidEnd => "Unexpected character found after parsing was completed.",
        // Date related errors
        ParseError::InvalidMonthRange => "Parsed month value not in a valid range.",

        ParseError::InvalidDayRange => "Parsed day value not in a valid range.",

        ParseError::DateYear => "Invalid character while parsing year value.",

        ParseError::DateExtendedYear => "Invalid character while parsing extended year value.",

        ParseError::DateMonth => "Invalid character while parsing month value.",

        ParseError::DateDay => "Invalid character while parsing day value.",

        ParseError::DateUnexpectedEnd => "Unexpected end while parsing a date value.",

        ParseError::TimeRequired => "Time is required.",

        ParseError::TimeHour => "Invalid character while parsing hour value.",

        ParseError::TimeMinuteSecond => {
            "Invalid character while parsing minute/second value in (0, 59] range."
        }

        ParseError::TimeSecond => "Invalid character while parsing second value in (0, 60] range.",

        ParseError::FractionPart => "Invalid character while parsing fraction part value.",

        ParseError::DateSeparator => "Invalid character while parsing date separator.",

        ParseError::TimeSeparator => "Invalid character while parsing time separator.",

        ParseError::DecimalSeparator => "Invalid character while parsing decimal separator.",
        // Annotation Related Errors
        ParseError::InvalidAnnotation => "Invalid annotation.",

        ParseError::AnnotationOpen => "Invalid annotation open character.",

        ParseError::AnnotationClose => "Invalid annotation close character.",

        ParseError::AnnotationChar => "Invalid annotation character.",

        ParseError::AnnotationKeyValueSeparator => {
            "Invalid annotation key-value separator character."
        }

        ParseError::AnnotationKeyLeadingChar => "Invalid annotation key leading character.",

        ParseError::AnnotationKeyChar => "Invalid annotation key character.",

        ParseError::AnnotationValueCharPostHyphen => {
            "Expected annotation value character must exist after hyphen."
        }

        ParseError::AnnotationValueChar => "Invalid annotation value character.",

        ParseError::InvalidMinutePrecisionOffset => "Offset must be minute precision",

        ParseError::CriticalDuplicateCalendar => {
            "Duplicate calendars cannot be provided when one is critical."
        }

        ParseError::UnrecognizedCritical => "Unrecognized annoation is marked as critical.",

        ParseError::TzLeadingChar => "Invalid time zone leading character.",

        ParseError::IanaCharPostSeparator => "Expected time zone character after '/'.",

        ParseError::IanaChar => "Invalid IANA time zone character after '/'.",

        ParseError::UtcTimeSeparator => "Invalid time zone character after '/'.",

        ParseError::OffsetNeedsSign => "UTC offset needs a sign",

        ParseError::MonthDayHyphen => "MonthDay must begin with a month or '--'",

        ParseError::DurationDisgnator => "Invalid duration designator.",

        ParseError::DurationValueExceededRange => {
            "Provided Duration field value exceeds supported range."
        }

        ParseError::DateDurationPartOrder => "Invalid date duration part order.",

        ParseError::TimeDurationPartOrder => "Invalid time duration part order.",

        ParseError::TimeDurationDesignator => "Invalid time duration designator.",

        ParseError::AmbiguousTimeMonthDay => "Time is ambiguous with MonthDay",

        ParseError::AmbiguousTimeYearMonth => "Time is ambiguous with YearMonth",

        ParseError::InvalidMonthDay => "MonthDay was not valid.",
        _ => "General IXDTF parsing error",
    }
}