Debian Codegraph @

js/src/builtin/temporal/TemporalParser.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "builtin/temporal/TemporalParser.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Attributes.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/Range.h"
13 #include "mozilla/Result.h"
14 #include "mozilla/Span.h"
15 #include "mozilla/TextUtils.h"
16 #include "mozilla/Try.h"
17
18 #include <algorithm>
19 #include <cstdlib>
20 #include <initializer_list>
21 #include <limits>
22 #include <stdint.h>
23 #include <string_view>
24 #include <type_traits>
25 #include <utility>
26
27 #include "jsnum.h"
28 #include "NamespaceImports.h"
29
30 #include "builtin/temporal/Calendar.h"
31 #include "builtin/temporal/Duration.h"
32 #include "builtin/temporal/PlainDate.h"
33 #include "builtin/temporal/PlainTime.h"
34 #include "builtin/temporal/TemporalTypes.h"
35 #include "builtin/temporal/TemporalUnit.h"
36 #include "gc/Barrier.h"
37 #include "gc/Tracer.h"
38 #include "js/ErrorReport.h"
39 #include "js/friend/ErrorMessages.h"
40 #include "js/GCAPI.h"
41 #include "js/RootingAPI.h"
42 #include "js/TypeDecls.h"
43 #include "util/Text.h"
44 #include "vm/JSAtomState.h"
45 #include "vm/JSContext.h"
46 #include "vm/StringType.h"
47
48 using namespace js;
49 using namespace js::temporal;
50
51 struct StringName final {
52 // Start position and length of this name.
53 size_t start = 0;
54 size_t length = 0;
55
56 bool present() const { return length > 0; }
57 };
58
59 static JSLinearString* ToString(JSContext* cx, JSString* string,
60 const StringName& name) {
61 MOZ_ASSERT(name.present());
62 return NewDependentString(cx, string, name.start, name.length);
63 }
64
65 template <typename CharT>
66 bool EqualCharIgnoreCaseAscii(CharT c1, char c2) {
67 if constexpr (sizeof(CharT) > sizeof(char)) {
68 if (!mozilla::IsAscii(c1)) {
69 return false;
70 }
71 }
72
73 static constexpr auto toLower = 0x20;
74 static_assert('a' - 'A' == toLower);
75
76 // Convert both characters to lower case before the comparison.
77 char c = c1;
78 if (mozilla::IsAsciiUppercaseAlpha(c1)) {
79 c = char(c + toLower);
80 }
81 char d = c2;
82 if (mozilla::IsAsciiUppercaseAlpha(c2)) {
83 d = char(d + toLower);
84 }
85 return c == d;
86 }
87
88 using CalendarName = StringName;
89 using AnnotationKey = StringName;
90 using AnnotationValue = StringName;
91 using TimeZoneName = StringName;
92
93 struct Annotation final {
94 AnnotationKey key;
95 AnnotationValue value;
96 bool critical = false;
97 };
98
99 struct TimeSpec final {
100 Time time;
101 };
102
103 struct TimeZoneUTCOffset final {
104 // ±1 for time zones with an offset, otherwise 0.
105 int32_t sign = 0;
106
107 // An integer in the range [0, 23].
108 int32_t hour = 0;
109
110 // An integer in the range [0, 59].
111 int32_t minute = 0;
112 };
113
114 struct DateTimeUTCOffset final {
115 // ±1 for time zones with an offset, otherwise 0.
116 int32_t sign = 0;
117
118 // An integer in the range [0, 23].
119 int32_t hour = 0;
120
121 // An integer in the range [0, 59].
122 int32_t minute = 0;
123
124 // An integer in the range [0, 59].
125 int32_t second = 0;
126
127 // An integer in the range [0, 999'999].
128 int32_t fractionalPart = 0;
129
130 // Time zone with sub-minute precision.
131 bool subMinutePrecision = false;
132
133 // Convert to a TimeZoneUTCOffset.
134 TimeZoneUTCOffset toTimeZoneUTCOffset() const {
135 MOZ_ASSERT(!subMinutePrecision, "unexpected sub-minute precision");
136 return {sign, hour, minute};
137 }
138 };
139
140 /**
141 * ParseDateTimeUTCOffset ( offsetString )
142 */
143 static int64_t ParseDateTimeUTCOffset(const DateTimeUTCOffset& offset) {
144 constexpr int64_t nanoPerSec = 1'000'000'000;
145
146 MOZ_ASSERT(offset.sign == -1 || offset.sign == +1);
147 MOZ_ASSERT(0 <= offset.hour && offset.hour < 24);
148 MOZ_ASSERT(0 <= offset.minute && offset.minute < 60);
149 MOZ_ASSERT(0 <= offset.second && offset.second < 60);
150 MOZ_ASSERT(0 <= offset.fractionalPart && offset.fractionalPart < nanoPerSec);
151
152 // sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
153 int64_t seconds = (offset.hour * 60 + offset.minute) * 60 + offset.second;
154 int64_t nanos = (seconds * nanoPerSec) + offset.fractionalPart;
155 int64_t result = offset.sign * nanos;
156
157 MOZ_ASSERT(std::abs(result) < ToNanoseconds(TemporalUnit::Day),
158 "time zone offset is less than 24:00 hours");
159
160 return result;
161 }
162
163 static int32_t ParseTimeZoneOffset(const TimeZoneUTCOffset& offset) {
164 MOZ_ASSERT(offset.sign == -1 || offset.sign == +1);
165 MOZ_ASSERT(0 <= offset.hour && offset.hour < 24);
166 MOZ_ASSERT(0 <= offset.minute && offset.minute < 60);
167
168 // sign × (hour × 60 + minute).
169 int32_t result = offset.sign * (offset.hour * 60 + offset.minute);
170
171 MOZ_ASSERT(std::abs(result) < UnitsPerDay(TemporalUnit::Minute),
172 "time zone offset is less than 24:00 hours");
173
174 return result;
175 }
176
177 /**
178 * Struct to hold time zone annotations.
179 */
180 struct TimeZoneAnnotation final {
181 // Time zone offset.
182 TimeZoneUTCOffset offset;
183
184 // Time zone name.
185 TimeZoneName name;
186
187 /**
188 * Returns true iff the time zone has an offset part, e.g. "+01:00".
189 */
190 bool hasOffset() const { return offset.sign != 0; }
191
192 /**
193 * Returns true iff the time zone has an IANA name, e.g. "Asia/Tokyo".
194 */
195 bool hasName() const { return name.present(); }
196 };
197
198 /**
199 * Struct to hold any time zone parts of a parsed string.
200 */
201 struct TimeZoneString final {
202 // Date-time UTC offset.
203 DateTimeUTCOffset offset;
204
205 // Time zone annotation;
206 TimeZoneAnnotation annotation;
207
208 // UTC time zone.
209 bool utc = false;
210
211 static auto from(DateTimeUTCOffset offset) {
212 TimeZoneString timeZone{};
213 timeZone.offset = offset;
214 return timeZone;
215 }
216
217 static auto from(TimeZoneUTCOffset offset) {
218 TimeZoneString timeZone{};
219 timeZone.annotation.offset = offset;
220 return timeZone;
221 }
222
223 static auto from(TimeZoneName name) {
224 TimeZoneString timeZone{};
225 timeZone.annotation.name = name;
226 return timeZone;
227 }
228
229 static auto UTC() {
230 TimeZoneString timeZone{};
231 timeZone.utc = true;
232 return timeZone;
233 }
234
235 /**
236 * Returns true iff the time zone has an offset part, e.g. "+01:00".
237 */
238 bool hasOffset() const { return offset.sign != 0; }
239
240 /**
241 * Returns true iff the time zone has an annotation.
242 */
243 bool hasAnnotation() const {
244 return annotation.hasName() || annotation.hasOffset();
245 }
246
247 /**
248 * Returns true iff the time zone uses the "Z" abbrevation to denote UTC time.
249 */
250 bool isUTC() const { return utc; }
251 };
252
253 /**
254 * Struct to hold the parsed date, time, time zone, and calendar components.
255 */
256 struct ZonedDateTimeString final {
257 ISODate date;
258 Time time;
259 TimeZoneString timeZone;
260 CalendarName calendar;
261 bool startOfDay;
262 };
263
264 template <typename CharT>
265 static bool IsISO8601Calendar(mozilla::Span<const CharT> calendar) {
266 static constexpr std::string_view iso8601 = "iso8601";
267
268 if (calendar.size() != iso8601.length()) {
269 return false;
270 }
271
272 for (size_t i = 0; i < iso8601.length(); i++) {
273 if (!EqualCharIgnoreCaseAscii(calendar[i], iso8601[i])) {
274 return false;
275 }
276 }
277 return true;
278 }
279
280 static constexpr int32_t AbsentYear = INT32_MAX;
281
282 /**
283 * ParseISODateTime ( isoString )
284 */
285 static bool ParseISODateTime(JSContext* cx, const ZonedDateTimeString& parsed,
286 ISODateTime* result) {
287 // Steps 1-7, 9, 11-16 (Not applicable here).
288
289 ISODateTime dateTime = {parsed.date, parsed.time};
290
291 // NOTE: ToIntegerOrInfinity("") is 0.
292 if (dateTime.date.year == AbsentYear) {
293 dateTime.date.year = 0;
294 }
295
296 // Step 8.
297 if (dateTime.date.month == 0) {
298 dateTime.date.month = 1;
299 }
300
301 // Step 10.
302 if (dateTime.date.day == 0) {
303 dateTime.date.day = 1;
304 }
305
306 // Step 17.b.
307 if (dateTime.time.second == 60) {
308 dateTime.time.second = 59;
309 }
310
311 // ParseISODateTime, steps 18-19 (Not applicable in our implementation).
312
313 // Perform early error checks now that absent |day| and |month| values were
314 // handled:
315 // `IsValidDate(DateSpec)` and `IsValidMonthDay(DateSpecMonthDay)` validate
316 // that |day| doesn't exceed the number of days in |month|. This check can be
317 // implemented by calling `ThrowIfInvalidISODate`.
318 //
319 // All other values are already in-bounds.
320 MOZ_ASSERT(std::abs(dateTime.date.year) <= 999'999);
321 MOZ_ASSERT(1 <= dateTime.date.month && dateTime.date.month <= 12);
322 MOZ_ASSERT(1 <= dateTime.date.day && dateTime.date.day <= 31);
323
324 if (!ThrowIfInvalidISODate(cx, dateTime.date)) {
325 return false;
326 }
327
328 // Step 20.
329 MOZ_ASSERT(IsValidISODate(dateTime.date));
330
331 // Step 21.
332 MOZ_ASSERT(IsValidTime(dateTime.time));
333
334 // Steps 22-28. (Handled in caller.)
335
336 *result = dateTime;
337 return true;
338 }
339
340 static bool ParseTimeZoneAnnotation(JSContext* cx,
341 const TimeZoneAnnotation& annotation,
342 JSLinearString* linear,
343 MutableHandle<ParsedTimeZone> result) {
344 MOZ_ASSERT(annotation.hasOffset() || annotation.hasName());
345
346 if (annotation.hasOffset()) {
347 int32_t offset = ParseTimeZoneOffset(annotation.offset);
348 result.set(ParsedTimeZone::fromOffset(offset));
349 return true;
350 }
351
352 auto* str = ToString(cx, linear, annotation.name);
353 if (!str) {
354 return false;
355 }
356 result.set(ParsedTimeZone::fromName(str));
357 return true;
358 }
359
360 /**
361 * Struct for the parsed duration components.
362 */
363 struct TemporalDurationString final {
364 // A non-negative integer or +Infinity.
365 double years = 0;
366
367 // A non-negative integer or +Infinity.
368 double months = 0;
369
370 // A non-negative integer or +Infinity.
371 double weeks = 0;
372
373 // A non-negative integer or +Infinity.
374 double days = 0;
375
376 // A non-negative integer or +Infinity.
377 double hours = 0;
378
379 // A non-negative integer or +Infinity.
380 double minutes = 0;
381
382 // A non-negative integer or +Infinity.
383 double seconds = 0;
384
385 // An integer in the range [0, 999'999].
386 int32_t hoursFraction = 0;
387
388 // An integer in the range [0, 999'999].
389 int32_t minutesFraction = 0;
390
391 // An integer in the range [0, 999'999].
392 int32_t secondsFraction = 0;
393
394 // ±1 when an offset is present, otherwise 0.
395 int32_t sign = 0;
396 };
397
398 class ParserError final {
399 JSErrNum error_ = JSMSG_NOT_AN_ERROR;
400
401 public:
402 constexpr ParserError() = default;
403
404 constexpr MOZ_IMPLICIT ParserError(JSErrNum error) : error_(error) {}
405
406 constexpr JSErrNum error() const { return error_; }
407
408 constexpr operator JSErrNum() const { return error(); }
409 };
410
411 namespace mozilla::detail {
412 // Zero is used for tagging, so it mustn't be an error.
413 static_assert(static_cast<JSErrNum>(0) == JSMSG_NOT_AN_ERROR);
414
415 // Ensure efficient packing of the error type.
416 template <>
417 struct UnusedZero<::ParserError> {
418 private:
419 using Error = ::ParserError;
420 using ErrorKind = JSErrNum;
421
422 public:
423 using StorageType = std::underlying_type_t<ErrorKind>;
424
425 static constexpr bool value = true;
426 static constexpr StorageType nullValue = 0;
427
428 static constexpr Error Inspect(const StorageType& aValue) {
429 return Error(static_cast<ErrorKind>(aValue));
430 }
431 static constexpr Error Unwrap(StorageType aValue) {
432 return Error(static_cast<ErrorKind>(aValue));
433 }
434 static constexpr StorageType Store(Error aValue) {
435 return static_cast<StorageType>(aValue.error());
436 }
437 };
438 } // namespace mozilla::detail
439
440 static_assert(mozilla::Result<ZonedDateTimeString, ParserError>::Strategy !=
441 mozilla::detail::PackingStrategy::Variant);
442
443 /**
444 * Track the error and reader index of the last largest successful parse.
445 */
446 class LikelyError final {
447 size_t index_ = 0;
448 ParserError error_{};
449
450 public:
451 template <typename V>
452 void update(const mozilla::Result<V, ParserError>& result, size_t index) {
453 MOZ_ASSERT(result.isErr());
454
455 if (index >= index_) {
456 index_ = index;
457 error_ = result.inspectErr();
458 }
459 }
460
461 size_t index() const { return index_; }
462
463 auto propagate() const { return mozilla::Err(error_); }
464 };
465
466 template <typename CharT>
467 class StringReader final {
468 mozilla::Span<const CharT> string_;
469
470 // Current position in the string.
471 size_t index_ = 0;
472
473 public:
474 explicit StringReader(mozilla::Span<const CharT> string) : string_(string) {}
475
476 /**
477 * Returns the input string.
478 */
479 mozilla::Span<const CharT> string() const { return string_; }
480
481 /**
482 * Returns a substring of the input string.
483 */
484 mozilla::Span<const CharT> substring(const StringName& name) const {
485 MOZ_ASSERT(name.present());
486 return string_.Subspan(name.start, name.length);
487 }
488
489 /**
490 * Returns the current parse position.
491 */
492 size_t index() const { return index_; }
493
494 /**
495 * Returns the length of the input string-
496 */
497 size_t length() const { return string_.size(); }
498
499 /**
500 * Returns true iff the whole string has been parsed.
501 */
502 bool atEnd() const { return index() == length(); }
503
504 /**
505 * Reset the parser to a previous parse position.
506 */
507 void reset(size_t index = 0) {
508 MOZ_ASSERT(index <= length());
509 index_ = index;
510 }
511
512 /**
513 * Returns true if at least `amount` characters can be read from the current
514 * parse position.
515 */
516 bool hasMore(size_t amount) const { return index() + amount <= length(); }
517
518 /**
519 * Advances the parse position by `amount` characters.
520 */
521 void advance(size_t amount) {
522 MOZ_ASSERT(hasMore(amount));
523 index_ += amount;
524 }
525
526 /**
527 * Returns the character at the current parse position.
528 */
529 CharT current() const { return string()[index()]; }
530
531 /**
532 * Returns the character at the next parse position.
533 */
534 CharT next() const { return string()[index() + 1]; }
535
536 /**
537 * Returns the character at position `index`.
538 */
539 CharT at(size_t index) const { return string()[index]; }
540 };
541
542 template <typename CharT>
543 class TemporalParser final {
544 StringReader<CharT> reader_;
545
546 /**
547 * Read an unlimited amount of decimal digits, returning `Nothing` if no
548 * digits were read.
549 */
550 mozilla::Maybe<double> digits(JSContext* cx);
551
552 /**
553 * Read exactly `length` digits, returning `Nothing` on failure.
554 */
555 mozilla::Maybe<int32_t> digits(size_t length) {
556 MOZ_ASSERT(length > 0, "can't read zero digits");
557 MOZ_ASSERT(length <= std::numeric_limits<int32_t>::digits10,
558 "can't read more than digits10 digits without overflow");
559
560 if (!reader_.hasMore(length)) {
561 return mozilla::Nothing();
562 }
563 int32_t num = 0;
564 size_t index = reader_.index();
565 for (size_t i = 0; i < length; i++) {
566 auto ch = reader_.at(index + i);
567 if (!mozilla::IsAsciiDigit(ch)) {
568 return mozilla::Nothing();
569 }
570 num = num * 10 + AsciiDigitToNumber(ch);
571 }
572 reader_.advance(length);
573 return mozilla::Some(num);
574 }
575
576 // TemporalDecimalFraction :::
577 // TemporalDecimalSeparator DecimalDigit{1,9}
578 mozilla::Maybe<int32_t> fraction() {
579 if (!reader_.hasMore(2)) {
580 return mozilla::Nothing();
581 }
582 if (!hasDecimalSeparator() || !mozilla::IsAsciiDigit(reader_.next())) {
583 return mozilla::Nothing();
584 }
585
586 // Consume the decimal separator.
587 MOZ_ALWAYS_TRUE(decimalSeparator());
588
589 // Maximal nine fractional digits are supported.
590 constexpr size_t maxFractions = 9;
591
592 // Read up to |maxFractions| digits.
593 int32_t num = 0;
594 size_t index = reader_.index();
595 size_t i = 0;
596 for (; i < std::min(reader_.length() - index, maxFractions); i++) {
597 CharT ch = reader_.at(index + i);
598 if (!mozilla::IsAsciiDigit(ch)) {
599 break;
600 }
601 num = num * 10 + AsciiDigitToNumber(ch);
602 }
603
604 // Skip past the read digits.
605 reader_.advance(i);
606
607 // Normalize the fraction to |maxFractions| digits.
608 for (; i < maxFractions; i++) {
609 num *= 10;
610 }
611 return mozilla::Some(num);
612 }
613
614 /**
615 * Returns true iff the current character is `ch`.
616 */
617 bool hasCharacter(CharT ch) const {
618 return reader_.hasMore(1) && reader_.current() == ch;
619 }
620
621 /**
622 * Consumes the current character if it's equal to `ch` and then returns
623 * `true`. Otherwise returns `false`.
624 */
625 bool character(CharT ch) {
626 if (!hasCharacter(ch)) {
627 return false;
628 }
629 reader_.advance(1);
630 return true;
631 }
632
633 /**
634 * Consumes the next characters if they're equal to `str` and then returns
635 * `true`. Otherwise returns `false`.
636 */
637 template <size_t N>
638 bool string(const char (&str)[N]) {
639 static_assert(N > 2, "use character() for one element strings");
640
641 if (!reader_.hasMore(N - 1)) {
642 return false;
643 }
644 size_t index = reader_.index();
645 for (size_t i = 0; i < N - 1; i++) {
646 if (reader_.at(index + i) != str[i]) {
647 return false;
648 }
649 }
650 reader_.advance(N - 1);
651 return true;
652 }
653
654 /**
655 * Returns true if the next two characters are ASCII alphabetic characters.
656 */
657 bool hasTwoAsciiAlpha() {
658 if (!reader_.hasMore(2)) {
659 return false;
660 }
661 size_t index = reader_.index();
662 return mozilla::IsAsciiAlpha(reader_.at(index)) &&
663 mozilla::IsAsciiAlpha(reader_.at(index + 1));
664 }
665
666 /**
667 * Returns true iff the current character is one of `chars`.
668 */
669 bool hasOneOf(std::initializer_list<char16_t> chars) const {
670 if (!reader_.hasMore(1)) {
671 return false;
672 }
673 auto ch = reader_.current();
674 return std::find(chars.begin(), chars.end(), ch) != chars.end();
675 }
676
677 /**
678 * Consumes the current character if it's in `chars` and then returns `true`.
679 * Otherwise returns `false`.
680 */
681 bool oneOf(std::initializer_list<char16_t> chars) {
682 if (!hasOneOf(chars)) {
683 return false;
684 }
685 reader_.advance(1);
686 return true;
687 }
688
689 /**
690 * Consumes the current character if it matches the predicate and then returns
691 * `true`. Otherwise returns `false`.
692 */
693 template <typename Predicate>
694 bool matches(Predicate&& predicate) {
695 if (!reader_.hasMore(1)) {
696 return false;
697 }
698
699 CharT ch = reader_.current();
700 if (!predicate(ch)) {
701 return false;
702 }
703
704 reader_.advance(1);
705 return true;
706 }
707
708 // ASCIISign ::: one of
709 // + -
710 bool hasSign() const { return hasOneOf({'+', '-'}); }
711
712 /**
713 * Consumes the current character, which must be a sign character, and returns
714 * its numeric value.
715 */
716 int32_t sign() {
717 MOZ_ASSERT(hasSign());
718 int32_t plus = hasCharacter('+');
719 reader_.advance(1);
720 return plus ? 1 : -1;
721 }
722
723 // DateSeparator[Extended] :::
724 // [+Extended] -
725 // [~Extended] [empty]
726 bool dateSeparator() { return character('-'); }
727
728 // TimeSeparator[Extended] :::
729 // [+Extended] :
730 // [~Extended] [empty]
731 bool hasTimeSeparator() const { return hasCharacter(':'); }
732
733 bool timeSeparator() { return character(':'); }
734
735 // TemporalDecimalSeparator ::: one of
736 // . ,
737 bool hasDecimalSeparator() const { return hasOneOf({'.', ','}); }
738
739 bool decimalSeparator() { return oneOf({'.', ','}); }
740
741 // DaysDesignator ::: one of
742 // D d
743 bool daysDesignator() { return oneOf({'D', 'd'}); }
744
745 // HoursDesignator ::: one of
746 // H h
747 bool hoursDesignator() { return oneOf({'H', 'h'}); }
748
749 // MinutesDesignator ::: one of
750 // M m
751 bool minutesDesignator() { return oneOf({'M', 'm'}); }
752
753 // MonthsDesignator ::: one of
754 // M m
755 bool monthsDesignator() { return oneOf({'M', 'm'}); }
756
757 // DurationDesignator ::: one of
758 // P p
759 bool durationDesignator() { return oneOf({'P', 'p'}); }
760
761 // SecondsDesignator ::: one of
762 // S s
763 bool secondsDesignator() { return oneOf({'S', 's'}); }
764
765 // DateTimeSeparator :::
766 // <SP>
767 // T
768 // t
769 bool dateTimeSeparator() { return oneOf({' ', 'T', 't'}); }
770
771 // TimeDesignator ::: one of
772 // T t
773 bool hasTimeDesignator() const { return hasOneOf({'T', 't'}); }
774
775 bool timeDesignator() { return oneOf({'T', 't'}); }
776
777 // WeeksDesignator ::: one of
778 // W w
779 bool weeksDesignator() { return oneOf({'W', 'w'}); }
780
781 // YearsDesignator ::: one of
782 // Y y
783 bool yearsDesignator() { return oneOf({'Y', 'y'}); }
784
785 // UTCDesignator ::: one of
786 // Z z
787 bool utcDesignator() { return oneOf({'Z', 'z'}); }
788
789 // TZLeadingChar :::
790 // Alpha
791 // .
792 // _
793 bool tzLeadingChar() {
794 return matches([](auto ch) {
795 return mozilla::IsAsciiAlpha(ch) || ch == '.' || ch == '_';
796 });
797 }
798
799 // TZChar :::
800 // TZLeadingChar
801 // DecimalDigit
802 // -
803 // +
804 bool tzChar() {
805 return matches([](auto ch) {
806 return mozilla::IsAsciiAlphanumeric(ch) || ch == '.' || ch == '_' ||
807 ch == '-' || ch == '+';
808 });
809 }
810
811 // AnnotationCriticalFlag :::
812 // !
813 bool annotationCriticalFlag() { return character('!'); }
814
815 // AKeyLeadingChar :::
816 // LowercaseAlpha
817 // _
818 bool aKeyLeadingChar() {
819 return matches([](auto ch) {
820 return mozilla::IsAsciiLowercaseAlpha(ch) || ch == '_';
821 });
822 }
823
824 // AKeyChar :::
825 // AKeyLeadingChar
826 // DecimalDigit
827 // -
828 bool aKeyChar() {
829 return matches([](auto ch) {
830 return mozilla::IsAsciiLowercaseAlpha(ch) || mozilla::IsAsciiDigit(ch) ||
831 ch == '-' || ch == '_';
832 });
833 }
834
835 // AnnotationValueComponent :::
836 // Alpha AnnotationValueComponent?
837 // DecimalDigit AnnotationValueComponent?
838 bool annotationValueComponent() {
839 size_t index = reader_.index();
840 size_t i = 0;
841 for (; index + i < reader_.length(); i++) {
842 auto ch = reader_.at(index + i);
843 if (!mozilla::IsAsciiAlphanumeric(ch)) {
844 break;
845 }
846 }
847 if (i == 0) {
848 return false;
849 }
850 reader_.advance(i);
851 return true;
852 }
853
854 template <typename T>
855 static constexpr bool inBounds(const T& x, const T& min, const T& max) {
856 return min <= x && x <= max;
857 }
858
859 static auto err(JSErrNum error) {
860 // Explicitly create |ParserError| when JSErrNum is auto-convertible to the
861 // success type.
862 return mozilla::Err(ParserError{error});
863 }
864
865 mozilla::Result<int32_t, ParserError> dateYear();
866 mozilla::Result<int32_t, ParserError> dateMonth();
867 mozilla::Result<int32_t, ParserError> dateDay();
868 mozilla::Result<int32_t, ParserError> hour();
869 mozilla::Result<mozilla::Maybe<int32_t>, ParserError> minute(bool required);
870 mozilla::Result<mozilla::Maybe<int32_t>, ParserError> second(bool required);
871 mozilla::Result<mozilla::Maybe<int32_t>, ParserError> timeSecond(
872 bool required);
873
874 mozilla::Result<ISODate, ParserError> date();
875
876 mozilla::Result<Time, ParserError> time();
877
878 mozilla::Result<ZonedDateTimeString, ParserError> dateTime(bool allowZ);
879
880 mozilla::Result<ISODate, ParserError> dateSpecYearMonth();
881
882 mozilla::Result<ISODate, ParserError> dateSpecMonthDay();
883
884 // Return true when |Annotation| can start at the current position.
885 bool hasAnnotationStart() const { return hasCharacter('['); }
886
887 // Return true when |TimeZoneAnnotation| can start at the current position.
888 bool hasTimeZoneAnnotationStart() const {
889 if (!hasCharacter('[')) {
890 return false;
891 }
892
893 // Ensure no '=' is found before the closing ']', otherwise the opening '['
894 // may actually start an |Annotation| instead of a |TimeZoneAnnotation|.
895 for (size_t i = reader_.index() + 1; i < reader_.length(); i++) {
896 CharT ch = reader_.at(i);
897 if (ch == '=') {
898 return false;
899 }
900 if (ch == ']') {
901 break;
902 }
903 }
904 return true;
905 }
906
907 // Return true when |DateTimeUTCOffset| can start at the current position.
908 bool hasDateTimeUTCOffsetStart() { return hasOneOf({'Z', 'z', '+', '-'}); }
909
910 mozilla::Result<TimeZoneString, ParserError> dateTimeUTCOffset(bool allowZ);
911
912 mozilla::Result<DateTimeUTCOffset, ParserError> utcOffsetSubMinutePrecision();
913
914 mozilla::Result<TimeZoneUTCOffset, ParserError> timeZoneUTCOffsetName();
915
916 mozilla::Result<TimeZoneAnnotation, ParserError> timeZoneIdentifier();
917
918 mozilla::Result<TimeZoneAnnotation, ParserError> timeZoneAnnotation();
919
920 mozilla::Result<TimeZoneName, ParserError> timeZoneIANAName();
921
922 mozilla::Result<AnnotationKey, ParserError> annotationKey();
923 mozilla::Result<AnnotationValue, ParserError> annotationValue();
924 mozilla::Result<Annotation, ParserError> annotation();
925 mozilla::Result<CalendarName, ParserError> annotations();
926
927 mozilla::Result<ZonedDateTimeString, ParserError> annotatedTime();
928
929 mozilla::Result<ZonedDateTimeString, ParserError> annotatedDateTime();
930
931 mozilla::Result<ZonedDateTimeString, ParserError>
932 annotatedDateTimeTimeRequired();
933
934 mozilla::Result<ZonedDateTimeString, ParserError> annotatedYearMonth();
935
936 mozilla::Result<ZonedDateTimeString, ParserError> annotatedMonthDay();
937
938 mozilla::Result<double, ParserError> durationDigits(JSContext* cx);
939
940 template <typename T>
941 mozilla::Result<T, ParserError> parse(
942 mozilla::Result<T, ParserError>&& result) const;
943
944 template <typename T>
945 mozilla::Result<T, ParserError> complete(const T& value) const;
946
947 mozilla::Result<mozilla::Ok, ParserError> nonempty() const;
948
949 public:
950 explicit TemporalParser(mozilla::Span<const CharT> str) : reader_(str) {}
951
952 mozilla::Result<ZonedDateTimeString, ParserError>
953 parseTemporalInstantString();
954
955 mozilla::Result<ZonedDateTimeString, ParserError>
956 parseTemporalTimeZoneString();
957
958 mozilla::Result<TimeZoneAnnotation, ParserError> parseTimeZoneIdentifier();
959
960 mozilla::Result<DateTimeUTCOffset, ParserError> parseDateTimeUTCOffset();
961
962 mozilla::Result<TemporalDurationString, ParserError>
963 parseTemporalDurationString(JSContext* cx);
964
965 mozilla::Result<ZonedDateTimeString, ParserError>
966 parseTemporalCalendarString();
967
968 mozilla::Result<ZonedDateTimeString, ParserError> parseTemporalTimeString();
969
970 mozilla::Result<ZonedDateTimeString, ParserError>
971 parseTemporalMonthDayString();
972
973 mozilla::Result<ZonedDateTimeString, ParserError>
974 parseTemporalYearMonthString();
975
976 mozilla::Result<ZonedDateTimeString, ParserError>
977 parseTemporalDateTimeString();
978
979 mozilla::Result<ZonedDateTimeString, ParserError>
980 parseTemporalZonedDateTimeString();
981
982 mozilla::Result<ZonedDateTimeString, ParserError>
983 parseTemporalRelativeToString();
984 };
985
986 template <typename CharT>
987 template <typename T>
988 mozilla::Result<T, ParserError> TemporalParser<CharT>::parse(
989 mozilla::Result<T, ParserError>&& result) const {
990 if (result.isOk() && !reader_.atEnd()) {
991 return mozilla::Err(JSMSG_TEMPORAL_PARSER_UNEXPECTED_CHARACTERS_AT_END);
992 }
993 return std::move(result);
994 }
995
996 template <typename CharT>
997 template <typename T>
998 mozilla::Result<T, ParserError> TemporalParser<CharT>::complete(
999 const T& result) const {
1000 if (!reader_.atEnd()) {
1001 return mozilla::Err(JSMSG_TEMPORAL_PARSER_UNEXPECTED_CHARACTERS_AT_END);
1002 }
1003 return result;
1004 }
1005
1006 template <typename CharT>
1007 mozilla::Result<mozilla::Ok, ParserError> TemporalParser<CharT>::nonempty()
1008 const {
1009 if (reader_.length() == 0) {
1010 return mozilla::Err(JSMSG_TEMPORAL_PARSER_EMPTY_STRING);
1011 }
1012 return mozilla::Ok{};
1013 }
1014
1015 template <typename CharT>
1016 mozilla::Result<int32_t, ParserError> TemporalParser<CharT>::dateYear() {
1017 // DateYear :::
1018 // DecimalDigit{4}
1019 // ASCIISign DecimalDigit{6}
1020
1021 if (auto year = digits(4)) {
1022 return year.value();
1023 }
1024 if (hasSign()) {
1025 int32_t yearSign = sign();
1026 if (auto year = digits(6)) {
1027 int32_t result = yearSign * year.value();
1028 if (yearSign < 0 && result == 0) {
1029 return err(JSMSG_TEMPORAL_PARSER_NEGATIVE_ZERO_YEAR);
1030 }
1031 return result;
1032 }
1033 return err(JSMSG_TEMPORAL_PARSER_MISSING_EXTENDED_YEAR);
1034 }
1035 return err(JSMSG_TEMPORAL_PARSER_MISSING_YEAR);
1036 }
1037
1038 template <typename CharT>
1039 mozilla::Result<int32_t, ParserError> TemporalParser<CharT>::dateMonth() {
1040 // DateMonth :::
1041 // 0 NonzeroDigit
1042 // 10
1043 // 11
1044 // 12
1045 if (auto month = digits(2)) {
1046 int32_t result = month.value();
1047 if (!inBounds(result, 1, 12)) {
1048 return err(JSMSG_TEMPORAL_PARSER_INVALID_MONTH);
1049 }
1050 return result;
1051 }
1052 return err(JSMSG_TEMPORAL_PARSER_MISSING_MONTH);
1053 }
1054
1055 template <typename CharT>
1056 mozilla::Result<int32_t, ParserError> TemporalParser<CharT>::dateDay() {
1057 // DateDay :::
1058 // 0 NonzeroDigit
1059 // 1 DecimalDigit
1060 // 2 DecimalDigit
1061 // 30
1062 // 31
1063 if (auto day = digits(2)) {
1064 int32_t result = day.value();
1065 if (!inBounds(result, 1, 31)) {
1066 return err(JSMSG_TEMPORAL_PARSER_INVALID_DAY);
1067 }
1068 return result;
1069 }
1070 return err(JSMSG_TEMPORAL_PARSER_MISSING_DAY);
1071 }
1072
1073 template <typename CharT>
1074 mozilla::Result<int32_t, ParserError> TemporalParser<CharT>::hour() {
1075 // Hour :::
1076 // 0 DecimalDigit
1077 // 1 DecimalDigit
1078 // 20
1079 // 21
1080 // 22
1081 // 23
1082 if (auto hour = digits(2)) {
1083 int32_t result = hour.value();
1084 if (!inBounds(result, 0, 23)) {
1085 return err(JSMSG_TEMPORAL_PARSER_INVALID_HOUR);
1086 }
1087 return result;
1088 }
1089 return err(JSMSG_TEMPORAL_PARSER_MISSING_HOUR);
1090 }
1091
1092 template <typename CharT>
1093 mozilla::Result<mozilla::Maybe<int32_t>, ParserError>
1094 TemporalParser<CharT>::minute(bool required) {
1095 // MinuteSecond :::
1096 // 0 DecimalDigit
1097 // 1 DecimalDigit
1098 // 2 DecimalDigit
1099 // 3 DecimalDigit
1100 // 4 DecimalDigit
1101 // 5 DecimalDigit
1102 if (auto minute = digits(2)) {
1103 if (!inBounds(minute.value(), 0, 59)) {
1104 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_MINUTE);
1105 }
1106 return minute;
1107 }
1108 if (!required) {
1109 return mozilla::Maybe<int32_t>{mozilla::Nothing{}};
1110 }
1111 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_MINUTE);
1112 }
1113
1114 template <typename CharT>
1115 mozilla::Result<mozilla::Maybe<int32_t>, ParserError>
1116 TemporalParser<CharT>::second(bool required) {
1117 // MinuteSecond :::
1118 // 0 DecimalDigit
1119 // 1 DecimalDigit
1120 // 2 DecimalDigit
1121 // 3 DecimalDigit
1122 // 4 DecimalDigit
1123 // 5 DecimalDigit
1124 if (auto minute = digits(2)) {
1125 if (!inBounds(minute.value(), 0, 59)) {
1126 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_SECOND);
1127 }
1128 return minute;
1129 }
1130 if (!required) {
1131 return mozilla::Maybe<int32_t>{mozilla::Nothing{}};
1132 }
1133 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_SECOND);
1134 }
1135
1136 template <typename CharT>
1137 mozilla::Result<mozilla::Maybe<int32_t>, ParserError>
1138 TemporalParser<CharT>::timeSecond(bool required) {
1139 // TimeSecond :::
1140 // MinuteSecond
1141 // 60
1142 //
1143 // MinuteSecond :::
1144 // 0 DecimalDigit
1145 // 1 DecimalDigit
1146 // 2 DecimalDigit
1147 // 3 DecimalDigit
1148 // 4 DecimalDigit
1149 // 5 DecimalDigit
1150 if (auto minute = digits(2)) {
1151 if (!inBounds(minute.value(), 0, 60)) {
1152 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_LEAPSECOND);
1153 }
1154 return minute;
1155 }
1156 if (!required) {
1157 return mozilla::Maybe<int32_t>{mozilla::Nothing{}};
1158 }
1159 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_SECOND);
1160 }
1161
1162 template <typename CharT>
1163 mozilla::Result<ISODate, ParserError> TemporalParser<CharT>::date() {
1164 // clang-format off
1165 //
1166 // Date :::
1167 // DateSpec[+Extended]
1168 // DateSpec[~Extended]
1169 //
1170 // DateSpec[Extended] :::
1171 // DateYear DateSeparator[?Extended] DateMonth DateSeparator[?Extended] DateDay
1172 //
1173 // clang-format on
1174
1175 ISODate result{};
1176
1177 MOZ_TRY_VAR(result.year, dateYear());
1178
1179 // Optional |DateSeparator|.
1180 bool hasMonthSeparator = dateSeparator();
1181
1182 MOZ_TRY_VAR(result.month, dateMonth());
1183
1184 // Optional |DateSeparator|.
1185 bool hasDaySeparator = dateSeparator();
1186
1187 // Date separators must be consistent.
1188 if (hasMonthSeparator != hasDaySeparator) {
1189 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INCONSISTENT_DATE_SEPARATOR);
1190 }
1191
1192 MOZ_TRY_VAR(result.day, dateDay());
1193
1194 return result;
1195 }
1196
1197 template <typename CharT>
1198 mozilla::Result<Time, ParserError> TemporalParser<CharT>::time() {
1199 // clang-format off
1200 //
1201 // Time :::
1202 // TimeSpec[+Extended]
1203 // TimeSpec[~Extended]
1204 //
1205 // TimeSpec[Extended] :::
1206 // Hour
1207 // Hour TimeSeparator[?Extended] MinuteSecond
1208 // Hour TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] TimeSecond TemporalDecimalFraction?
1209 //
1210 // clang-format on
1211
1212 Time result{};
1213
1214 MOZ_TRY_VAR(result.hour, hour());
1215
1216 // Optional |TimeSeparator|.
1217 bool hasMinuteSeparator = timeSeparator();
1218
1219 mozilla::Maybe<int32_t> minutes;
1220 MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator));
1221 if (minutes) {
1222 result.minute = minutes.value();
1223
1224 // Optional |TimeSeparator|.
1225 bool hasSecondSeparator = timeSeparator();
1226
1227 mozilla::Maybe<int32_t> seconds;
1228 MOZ_TRY_VAR(seconds, timeSecond(hasSecondSeparator));
1229 if (seconds) {
1230 result.second = seconds.value();
1231
1232 // Time separators must be consistent.
1233 if (hasMinuteSeparator != hasSecondSeparator) {
1234 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INCONSISTENT_TIME_SEPARATOR);
1235 }
1236
1237 // TemporalDecimalFraction :::
1238 // TemporalDecimalSeparator DecimalDigit{1,9}
1239 if (auto f = fraction()) {
1240 int32_t fractionalPart = f.value();
1241 result.millisecond = fractionalPart / 1'000'000;
1242 result.microsecond = (fractionalPart % 1'000'000) / 1'000;
1243 result.nanosecond = fractionalPart % 1'000;
1244 }
1245 }
1246 }
1247
1248 return result;
1249 }
1250
1251 template <typename CharT>
1252 mozilla::Result<ZonedDateTimeString, ParserError>
1253 TemporalParser<CharT>::dateTime(bool allowZ) {
1254 // DateTime[Z, TimeRequired] :::
1255 // [~TimeRequired] Date
1256 // Date DateTimeSeparator Time DateTimeUTCOffset[?Z]?
1257 //
1258 // When called as `DateTime[?Z, ~TimeRequired]`.
1259
1260 ZonedDateTimeString result{};
1261
1262 MOZ_TRY_VAR(result.date, date());
1263
1264 if (dateTimeSeparator()) {
1265 MOZ_TRY_VAR(result.time, time());
1266
1267 if (hasDateTimeUTCOffsetStart()) {
1268 MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(allowZ));
1269 }
1270 } else {
1271 result.startOfDay = true;
1272 }
1273
1274 return result;
1275 }
1276
1277 template <typename CharT>
1278 mozilla::Result<TimeZoneString, ParserError>
1279 TemporalParser<CharT>::dateTimeUTCOffset(bool allowZ) {
1280 // DateTimeUTCOffset[Z] :::
1281 // [+Z] UTCDesignator
1282 // UTCOffset[+SubMinutePrecision]
1283
1284 if (utcDesignator()) {
1285 if (!allowZ) {
1286 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_UTC_DESIGNATOR);
1287 }
1288 return TimeZoneString::UTC();
1289 }
1290
1291 if (hasSign()) {
1292 DateTimeUTCOffset offset;
1293 MOZ_TRY_VAR(offset, utcOffsetSubMinutePrecision());
1294
1295 return TimeZoneString::from(offset);
1296 }
1297
1298 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIMEZONE);
1299 }
1300
1301 template <typename CharT>
1302 mozilla::Result<TimeZoneUTCOffset, ParserError>
1303 TemporalParser<CharT>::timeZoneUTCOffsetName() {
1304 // clang-format off
1305 //
1306 // UTCOffset[SubMinutePrecision] :::
1307 // ASCIISign Hour
1308 // ASCIISign Hour TimeSeparator[+Extended] MinuteSecond
1309 // ASCIISign Hour TimeSeparator[~Extended] MinuteSecond
1310 // [+SubMinutePrecision] ASCIISign Hour TimeSeparator[+Extended] MinuteSecond TimeSeparator[+Extended] MinuteSecond TemporalDecimalFraction?
1311 // [+SubMinutePrecision] ASCIISign Hour TimeSeparator[~Extended] MinuteSecond TimeSeparator[~Extended] MinuteSecond TemporalDecimalFraction?
1312 //
1313 // When called as `UTCOffset[~SubMinutePrecision]`.
1314 //
1315 // clang-format on
1316
1317 TimeZoneUTCOffset result{};
1318
1319 if (!hasSign()) {
1320 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIMEZONE_SIGN);
1321 }
1322 result.sign = sign();
1323
1324 MOZ_TRY_VAR(result.hour, hour());
1325
1326 // Optional |TimeSeparator|.
1327 bool hasMinuteSeparator = timeSeparator();
1328
1329 mozilla::Maybe<int32_t> minutes;
1330 MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator));
1331 if (minutes) {
1332 result.minute = minutes.value();
1333
1334 if (hasTimeSeparator()) {
1335 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_SUBMINUTE_TIMEZONE);
1336 }
1337 }
1338
1339 return result;
1340 }
1341
1342 template <typename CharT>
1343 mozilla::Result<DateTimeUTCOffset, ParserError>
1344 TemporalParser<CharT>::utcOffsetSubMinutePrecision() {
1345 // clang-format off
1346 //
1347 // UTCOffset[SubMinutePrecision] :::
1348 // ASCIISign Hour
1349 // ASCIISign Hour TimeSeparator[+Extended] MinuteSecond
1350 // ASCIISign Hour TimeSeparator[~Extended] MinuteSecond
1351 // [+SubMinutePrecision] ASCIISign Hour TimeSeparator[+Extended] MinuteSecond TimeSeparator[+Extended] MinuteSecond TemporalDecimalFraction?
1352 // [+SubMinutePrecision] ASCIISign Hour TimeSeparator[~Extended] MinuteSecond TimeSeparator[~Extended] MinuteSecond TemporalDecimalFraction?
1353 //
1354 // When called as `UTCOffset[+SubMinutePrecision]`.
1355 //
1356 // clang-format on
1357
1358 DateTimeUTCOffset result{};
1359
1360 if (!hasSign()) {
1361 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIMEZONE_SIGN);
1362 }
1363 result.sign = sign();
1364
1365 MOZ_TRY_VAR(result.hour, hour());
1366
1367 // Optional |TimeSeparator|.
1368 bool hasMinuteSeparator = timeSeparator();
1369
1370 mozilla::Maybe<int32_t> minutes;
1371 MOZ_TRY_VAR(minutes, minute(hasMinuteSeparator));
1372 if (minutes) {
1373 result.minute = minutes.value();
1374
1375 // Optional |TimeSeparator|.
1376 bool hasSecondSeparator = timeSeparator();
1377
1378 mozilla::Maybe<int32_t> seconds;
1379 MOZ_TRY_VAR(seconds, second(hasSecondSeparator));
1380 if (seconds) {
1381 result.second = seconds.value();
1382
1383 // Time separators must be consistent.
1384 if (hasMinuteSeparator != hasSecondSeparator) {
1385 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INCONSISTENT_TIME_SEPARATOR);
1386 }
1387
1388 if (auto fractionalPart = fraction()) {
1389 result.fractionalPart = fractionalPart.value();
1390 }
1391
1392 result.subMinutePrecision = true;
1393 }
1394 }
1395
1396 return result;
1397 }
1398
1399 template <typename CharT>
1400 mozilla::Result<TimeZoneAnnotation, ParserError>
1401 TemporalParser<CharT>::timeZoneIdentifier() {
1402 // TimeZoneIdentifier :::
1403 // UTCOffset[~SubMinutePrecision]
1404 // TimeZoneIANAName
1405
1406 TimeZoneAnnotation result{};
1407 if (hasSign()) {
1408 MOZ_TRY_VAR(result.offset, timeZoneUTCOffsetName());
1409 } else {
1410 MOZ_TRY_VAR(result.name, timeZoneIANAName());
1411 }
1412
1413 return result;
1414 }
1415
1416 template <typename CharT>
1417 mozilla::Result<TimeZoneAnnotation, ParserError>
1418 TemporalParser<CharT>::timeZoneAnnotation() {
1419 // TimeZoneAnnotation :::
1420 // [ AnnotationCriticalFlag? TimeZoneIdentifier ]
1421
1422 if (!character('[')) {
1423 return mozilla::Err(JSMSG_TEMPORAL_PARSER_BRACKET_BEFORE_TIMEZONE);
1424 }
1425
1426 // Skip over the optional critical flag.
1427 annotationCriticalFlag();
1428
1429 auto result = timeZoneIdentifier();
1430 if (result.isErr()) {
1431 return result.propagateErr();
1432 }
1433
1434 if (!character(']')) {
1435 return mozilla::Err(JSMSG_TEMPORAL_PARSER_BRACKET_AFTER_TIMEZONE);
1436 }
1437
1438 return result;
1439 }
1440
1441 template <typename CharT>
1442 mozilla::Result<TimeZoneName, ParserError>
1443 TemporalParser<CharT>::timeZoneIANAName() {
1444 // TimeZoneIANAName :::
1445 // TimeZoneIANANameComponent
1446 // TimeZoneIANAName / TimeZoneIANANameComponent
1447 //
1448 // TimeZoneIANANameComponent :::
1449 // TZLeadingChar
1450 // TimeZoneIANANameComponent TZChar
1451
1452 size_t start = reader_.index();
1453
1454 do {
1455 if (!tzLeadingChar()) {
1456 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIMEZONE_NAME);
1457 }
1458
1459 // Optionally followed by a sequence of |TZChar|.
1460 while (tzChar()) {
1461 }
1462 } while (character('/'));
1463
1464 return TimeZoneName{start, reader_.index() - start};
1465 }
1466
1467 template <typename CharT>
1468 mozilla::Maybe<double> TemporalParser<CharT>::digits(JSContext* cx) {
1469 auto span = reader_.string().Subspan(reader_.index());
1470
1471 // GetPrefixInteger can't fail when integer separator handling is disabled.
1472 const CharT* endp = nullptr;
1473 double num;
1474 MOZ_ALWAYS_TRUE(GetPrefixInteger(span.data(), span.data() + span.size(), 10,
1475 IntegerSeparatorHandling::None, &endp,
1476 &num));
1477
1478 size_t len = endp - span.data();
1479 if (len == 0) {
1480 return mozilla::Nothing();
1481 }
1482 reader_.advance(len);
1483 return mozilla::Some(num);
1484 }
1485
1486 template <typename CharT>
1487 mozilla::Result<ZonedDateTimeString, ParserError>
1488 TemporalParser<CharT>::parseTemporalInstantString() {
1489 MOZ_TRY(nonempty());
1490
1491 // Initialize all fields to zero.
1492 ZonedDateTimeString result{};
1493
1494 // clang-format off
1495 //
1496 // TemporalInstantString :::
1497 // Date DateTimeSeparator Time DateTimeUTCOffset[+Z] TimeZoneAnnotation? Annotations?
1498 //
1499 // clang-format on
1500
1501 MOZ_TRY_VAR(result.date, date());
1502
1503 if (!dateTimeSeparator()) {
1504 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DATE_TIME_SEPARATOR);
1505 }
1506
1507 MOZ_TRY_VAR(result.time, time());
1508
1509 MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ true));
1510
1511 if (hasTimeZoneAnnotationStart()) {
1512 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
1513 }
1514
1515 if (hasAnnotationStart()) {
1516 MOZ_TRY(annotations());
1517 }
1518
1519 return complete(result);
1520 }
1521
1522 /**
1523 * ParseTemporalInstantString ( isoString )
1524 */
1525 template <typename CharT>
1526 static auto ParseTemporalInstantString(mozilla::Span<const CharT> str) {
1527 TemporalParser<CharT> parser(str);
1528 return parser.parseTemporalInstantString();
1529 }
1530
1531 /**
1532 * ParseTemporalInstantString ( isoString )
1533 */
1534 static auto ParseTemporalInstantString(Handle<JSLinearString*> str) {
1535 JS::AutoCheckCannotGC nogc;
1536 if (str->hasLatin1Chars()) {
1537 return ParseTemporalInstantString<Latin1Char>(str->latin1Range(nogc));
1538 }
1539 return ParseTemporalInstantString<char16_t>(str->twoByteRange(nogc));
1540 }
1541
1542 /**
1543 * ParseTemporalInstantString ( isoString )
1544 */
1545 bool js::temporal::ParseTemporalInstantString(JSContext* cx,
1546 Handle<JSString*> str,
1547 ISODateTime* result,
1548 int64_t* offset) {
1549 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
1550 if (!linear) {
1551 return false;
1552 }
1553
1554 // Step 1.
1555 auto parseResult = ::ParseTemporalInstantString(linear);
1556 if (parseResult.isErr()) {
1557 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1558 parseResult.unwrapErr(), "instant");
1559 return false;
1560 }
1561 ZonedDateTimeString parsed = parseResult.unwrap();
1562
1563 // Step 2.
1564 if (!ParseISODateTime(cx, parsed, result)) {
1565 return false;
1566 }
1567
1568 // Steps 3-4.
1569 if (parsed.timeZone.hasOffset()) {
1570 *offset = ParseDateTimeUTCOffset(parsed.timeZone.offset);
1571 } else {
1572 MOZ_ASSERT(parsed.timeZone.isUTC());
1573 *offset = 0;
1574 }
1575 return true;
1576 }
1577
1578 template <typename CharT>
1579 mozilla::Result<ZonedDateTimeString, ParserError>
1580 TemporalParser<CharT>::parseTemporalTimeZoneString() {
1581 MOZ_TRY(nonempty());
1582
1583 // Handle the common case of a standalone time zone identifier first.
1584 if (auto tz = parse(timeZoneIdentifier()); tz.isOk()) {
1585 auto timeZone = tz.unwrap();
1586
1587 ZonedDateTimeString result{};
1588 if (timeZone.hasOffset()) {
1589 result.timeZone = TimeZoneString::from(timeZone.offset);
1590 } else {
1591 MOZ_ASSERT(timeZone.hasName());
1592 result.timeZone = TimeZoneString::from(timeZone.name);
1593 }
1594 return result;
1595 }
1596
1597 LikelyError likelyError{};
1598
1599 // Try all five parse goals from ParseISODateTime in order.
1600 //
1601 // TemporalDateTimeString
1602 // TemporalInstantString
1603 // TemporalTimeString
1604 // TemporalMonthDayString
1605 // TemporalYearMonthString
1606
1607 // Restart parsing from the start of the string.
1608 reader_.reset();
1609
1610 auto dateTime = parseTemporalDateTimeString();
1611 if (dateTime.isOk()) {
1612 return dateTime;
1613 }
1614 likelyError.update(dateTime, reader_.index());
1615
1616 // Restart parsing from the start of the string.
1617 reader_.reset();
1618
1619 auto instant = parseTemporalInstantString();
1620 if (instant.isOk()) {
1621 return instant;
1622 }
1623 likelyError.update(instant, reader_.index());
1624
1625 // Restart parsing from the start of the string.
1626 reader_.reset();
1627
1628 auto time = parseTemporalTimeString();
1629 if (time.isOk()) {
1630 return time;
1631 }
1632 likelyError.update(time, reader_.index());
1633
1634 // Restart parsing from the start of the string.
1635 reader_.reset();
1636
1637 auto monthDay = parseTemporalMonthDayString();
1638 if (monthDay.isOk()) {
1639 return monthDay;
1640 }
1641 likelyError.update(monthDay, reader_.index());
1642
1643 // Restart parsing from the start of the string.
1644 reader_.reset();
1645
1646 auto yearMonth = parseTemporalYearMonthString();
1647 if (yearMonth.isOk()) {
1648 return yearMonth;
1649 }
1650 likelyError.update(yearMonth, reader_.index());
1651
1652 return likelyError.propagate();
1653 }
1654
1655 /**
1656 * ParseTemporalTimeZoneString ( timeZoneString )
1657 */
1658 template <typename CharT>
1659 static auto ParseTemporalTimeZoneString(mozilla::Span<const CharT> str) {
1660 TemporalParser<CharT> parser(str);
1661 return parser.parseTemporalTimeZoneString();
1662 }
1663
1664 /**
1665 * ParseTemporalTimeZoneString ( timeZoneString )
1666 */
1667 static auto ParseTemporalTimeZoneString(Handle<JSLinearString*> str) {
1668 JS::AutoCheckCannotGC nogc;
1669 if (str->hasLatin1Chars()) {
1670 return ParseTemporalTimeZoneString<Latin1Char>(str->latin1Range(nogc));
1671 }
1672 return ParseTemporalTimeZoneString<char16_t>(str->twoByteRange(nogc));
1673 }
1674
1675 /**
1676 * ParseTemporalTimeZoneString ( timeZoneString )
1677 */
1678 bool js::temporal::ParseTemporalTimeZoneString(
1679 JSContext* cx, Handle<JSString*> str,
1680 MutableHandle<ParsedTimeZone> result) {
1681 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
1682 if (!linear) {
1683 return false;
1684 }
1685
1686 // Steps 1-4.
1687 auto parseResult = ::ParseTemporalTimeZoneString(linear);
1688 if (parseResult.isErr()) {
1689 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1690 parseResult.unwrapErr(), "time zone");
1691 return false;
1692 }
1693 ZonedDateTimeString parsed = parseResult.unwrap();
1694 const auto& timeZone = parsed.timeZone;
1695
1696 // Step 3.
1697 ISODateTime unused;
1698 if (!ParseISODateTime(cx, parsed, &unused)) {
1699 return false;
1700 }
1701
1702 if (timeZone.hasAnnotation()) {
1703 // Case 1: 19700101T00:00Z[+02:00]
1704 // Case 2: 19700101T00:00+00:00[+02:00]
1705 // Case 3: 19700101T00:00[+02:00]
1706 // Case 4: 19700101T00:00Z[Europe/Berlin]
1707 // Case 5: 19700101T00:00+00:00[Europe/Berlin]
1708 // Case 6: 19700101T00:00[Europe/Berlin]
1709
1710 if (!ParseTimeZoneAnnotation(cx, timeZone.annotation, linear, result)) {
1711 return false;
1712 }
1713 } else if (timeZone.isUTC()) {
1714 result.set(ParsedTimeZone::fromName(cx->names().UTC));
1715 } else if (timeZone.hasOffset()) {
1716 // ToTemporalTimeZoneSlotValue, step 7.
1717 //
1718 // Error reporting for sub-minute precision moved here.
1719 if (timeZone.offset.subMinutePrecision) {
1720 JS_ReportErrorNumberASCII(
1721 cx, GetErrorMessage, nullptr,
1722 JSMSG_TEMPORAL_PARSER_INVALID_SUBMINUTE_TIMEZONE, "time zone");
1723 return false;
1724 }
1725
1726 int32_t offset = ParseTimeZoneOffset(timeZone.offset.toTimeZoneUTCOffset());
1727 result.set(ParsedTimeZone::fromOffset(offset));
1728 } else {
1729 // Step 5.
1730 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1731 JSMSG_TEMPORAL_PARSER_MISSING_TIMEZONE,
1732 "time zone");
1733 return false;
1734 }
1735
1736 // Step 6.
1737 return true;
1738 }
1739
1740 template <typename CharT>
1741 mozilla::Result<TimeZoneAnnotation, ParserError>
1742 TemporalParser<CharT>::parseTimeZoneIdentifier() {
1743 MOZ_TRY(nonempty());
1744 return parse(timeZoneIdentifier());
1745 }
1746
1747 /**
1748 * ParseTimeZoneIdentifier ( identifier )
1749 */
1750 template <typename CharT>
1751 static auto ParseTimeZoneIdentifier(mozilla::Span<const CharT> str) {
1752 TemporalParser<CharT> parser(str);
1753 return parser.parseTimeZoneIdentifier();
1754 }
1755
1756 /**
1757 * ParseTimeZoneIdentifier ( identifier )
1758 */
1759 static auto ParseTimeZoneIdentifier(Handle<JSLinearString*> str) {
1760 JS::AutoCheckCannotGC nogc;
1761 if (str->hasLatin1Chars()) {
1762 return ParseTimeZoneIdentifier<Latin1Char>(str->latin1Range(nogc));
1763 }
1764 return ParseTimeZoneIdentifier<char16_t>(str->twoByteRange(nogc));
1765 }
1766
1767 /**
1768 * ParseTimeZoneIdentifier ( identifier )
1769 */
1770 bool js::temporal::ParseTimeZoneIdentifier(
1771 JSContext* cx, Handle<JSString*> str,
1772 MutableHandle<ParsedTimeZone> result) {
1773 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
1774 if (!linear) {
1775 return false;
1776 }
1777
1778 // Steps 1-2.
1779 auto parseResult = ::ParseTimeZoneIdentifier(linear);
1780 if (parseResult.isErr()) {
1781 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1782 parseResult.unwrapErr(), "time zone identifier");
1783 return false;
1784 }
1785 auto timeZone = parseResult.unwrap();
1786
1787 // Steps 3-4.
1788 return ParseTimeZoneAnnotation(cx, timeZone, linear, result);
1789 }
1790
1791 template <typename CharT>
1792 mozilla::Result<DateTimeUTCOffset, ParserError>
1793 TemporalParser<CharT>::parseDateTimeUTCOffset() {
1794 MOZ_TRY(nonempty());
1795 return parse(utcOffsetSubMinutePrecision());
1796 }
1797
1798 /**
1799 * ParseDateTimeUTCOffset ( offsetString )
1800 */
1801 template <typename CharT>
1802 static auto ParseDateTimeUTCOffset(mozilla::Span<const CharT> str) {
1803 TemporalParser<CharT> parser(str);
1804 return parser.parseDateTimeUTCOffset();
1805 }
1806
1807 /**
1808 * ParseDateTimeUTCOffset ( offsetString )
1809 */
1810 static auto ParseDateTimeUTCOffset(Handle<JSLinearString*> str) {
1811 JS::AutoCheckCannotGC nogc;
1812 if (str->hasLatin1Chars()) {
1813 return ParseDateTimeUTCOffset<Latin1Char>(str->latin1Range(nogc));
1814 }
1815 return ParseDateTimeUTCOffset<char16_t>(str->twoByteRange(nogc));
1816 }
1817
1818 /**
1819 * ParseDateTimeUTCOffset ( offsetString )
1820 */
1821 bool js::temporal::ParseDateTimeUTCOffset(JSContext* cx, Handle<JSString*> str,
1822 int64_t* result) {
1823 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
1824 if (!linear) {
1825 return false;
1826 }
1827
1828 // Steps 1-2.
1829 auto parseResult = ::ParseDateTimeUTCOffset(linear);
1830 if (parseResult.isErr()) {
1831 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1832 parseResult.unwrapErr(), "UTC offset");
1833 return false;
1834 }
1835
1836 // Steps 3-21.
1837 *result = ParseDateTimeUTCOffset(parseResult.unwrap());
1838 return true;
1839 }
1840
1841 template <typename CharT>
1842 mozilla::Result<double, ParserError> TemporalParser<CharT>::durationDigits(
1843 JSContext* cx) {
1844 auto d = digits(cx);
1845 if (!d) {
1846 return err(JSMSG_TEMPORAL_PARSER_MISSING_DURATION_DIGITS);
1847 }
1848 return *d;
1849 }
1850
1851 template <typename CharT>
1852 mozilla::Result<TemporalDurationString, ParserError>
1853 TemporalParser<CharT>::parseTemporalDurationString(JSContext* cx) {
1854 MOZ_TRY(nonempty());
1855
1856 // Initialize all fields to zero.
1857 TemporalDurationString result{};
1858
1859 // TemporalDurationString :::
1860 // Duration
1861 //
1862 // Duration :::
1863 // ASCIISign? DurationDesignator DurationDate
1864 // ASCIISign? DurationDesignator DurationTime
1865
1866 if (hasSign()) {
1867 result.sign = sign();
1868 }
1869
1870 if (!durationDesignator()) {
1871 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DURATION_DESIGNATOR);
1872 }
1873
1874 // DurationDate :::
1875 // DurationYearsPart DurationTime?
1876 // DurationMonthsPart DurationTime?
1877 // DurationWeeksPart DurationTime?
1878 // DurationDaysPart DurationTime?
1879
1880 do {
1881 if (hasTimeDesignator()) {
1882 break;
1883 }
1884
1885 double num;
1886 MOZ_TRY_VAR(num, durationDigits(cx));
1887
1888 // DurationYearsPart :::
1889 // DecimalDigits[~Sep] YearsDesignator DurationMonthsPart
1890 // DecimalDigits[~Sep] YearsDesignator DurationWeeksPart
1891 // DecimalDigits[~Sep] YearsDesignator DurationDaysPart?
1892 if (yearsDesignator()) {
1893 result.years = num;
1894 if (reader_.atEnd()) {
1895 return result;
1896 }
1897 if (hasTimeDesignator()) {
1898 break;
1899 }
1900 MOZ_TRY_VAR(num, durationDigits(cx));
1901 }
1902
1903 // DurationMonthsPart :::
1904 // DecimalDigits[~Sep] MonthsDesignator DurationWeeksPart
1905 // DecimalDigits[~Sep] MonthsDesignator DurationDaysPart?
1906 if (monthsDesignator()) {
1907 result.months = num;
1908 if (reader_.atEnd()) {
1909 return result;
1910 }
1911 if (hasTimeDesignator()) {
1912 break;
1913 }
1914 MOZ_TRY_VAR(num, durationDigits(cx));
1915 }
1916
1917 // DurationWeeksPart :::
1918 // DecimalDigits[~Sep] WeeksDesignator DurationDaysPart?
1919 if (weeksDesignator()) {
1920 result.weeks = num;
1921 if (reader_.atEnd()) {
1922 return result;
1923 }
1924 if (hasTimeDesignator()) {
1925 break;
1926 }
1927 MOZ_TRY_VAR(num, durationDigits(cx));
1928 }
1929
1930 // DurationDaysPart :::
1931 // DecimalDigits[~Sep] DaysDesignator
1932 if (daysDesignator()) {
1933 result.days = num;
1934 if (reader_.atEnd()) {
1935 return result;
1936 }
1937 if (hasTimeDesignator()) {
1938 break;
1939 }
1940 }
1941
1942 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DURATION_UNIT_DESIGNATOR);
1943 } while (false);
1944
1945 // DurationTime :::
1946 // TimeDesignator DurationHoursPart
1947 // TimeDesignator DurationMinutesPart
1948 // TimeDesignator DurationSecondsPart
1949 if (!timeDesignator()) {
1950 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_TIME_DESIGNATOR);
1951 }
1952
1953 double num;
1954 MOZ_TRY_VAR(num, durationDigits(cx));
1955
1956 auto frac = fraction();
1957
1958 // DurationHoursPart :::
1959 // DecimalDigits[~Sep] TemporalDecimalFraction HoursDesignator
1960 // DecimalDigits[~Sep] HoursDesignator DurationMinutesPart
1961 // DecimalDigits[~Sep] HoursDesignator DurationSecondsPart?
1962 bool hasHoursFraction = false;
1963 if (hoursDesignator()) {
1964 hasHoursFraction = bool(frac);
1965 result.hours = num;
1966 result.hoursFraction = frac.valueOr(0);
1967 if (reader_.atEnd()) {
1968 return result;
1969 }
1970
1971 MOZ_TRY_VAR(num, durationDigits(cx));
1972 frac = fraction();
1973 }
1974
1975 // DurationMinutesPart :::
1976 // DecimalDigits[~Sep] TemporalDecimalFraction MinutesDesignator
1977 // DecimalDigits[~Sep] MinutesDesignator DurationSecondsPart?
1978 bool hasMinutesFraction = false;
1979 if (minutesDesignator()) {
1980 if (hasHoursFraction) {
1981 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_DURATION_MINUTES);
1982 }
1983 hasMinutesFraction = bool(frac);
1984 result.minutes = num;
1985 result.minutesFraction = frac.valueOr(0);
1986 if (reader_.atEnd()) {
1987 return result;
1988 }
1989
1990 MOZ_TRY_VAR(num, durationDigits(cx));
1991 frac = fraction();
1992 }
1993
1994 // DurationSecondsPart :::
1995 // DecimalDigits[~Sep] TemporalDecimalFraction? SecondsDesignator
1996 if (secondsDesignator()) {
1997 if (hasHoursFraction || hasMinutesFraction) {
1998 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_DURATION_SECONDS);
1999 }
2000 result.seconds = num;
2001 result.secondsFraction = frac.valueOr(0);
2002 if (reader_.atEnd()) {
2003 return result;
2004 }
2005 }
2006
2007 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DURATION_UNIT_DESIGNATOR);
2008 }
2009
2010 /**
2011 * ParseTemporalDurationString ( isoString )
2012 */
2013 template <typename CharT>
2014 static auto ParseTemporalDurationString(JSContext* cx,
2015 mozilla::Span<const CharT> str) {
2016 TemporalParser<CharT> parser(str);
2017 return parser.parseTemporalDurationString(cx);
2018 }
2019
2020 /**
2021 * ParseTemporalDurationString ( isoString )
2022 */
2023 static auto ParseTemporalDurationString(JSContext* cx,
2024 Handle<JSLinearString*> str) {
2025 JS::AutoCheckCannotGC nogc;
2026 if (str->hasLatin1Chars()) {
2027 return ParseTemporalDurationString<Latin1Char>(cx, str->latin1Range(nogc));
2028 }
2029 return ParseTemporalDurationString<char16_t>(cx, str->twoByteRange(nogc));
2030 }
2031
2032 /**
2033 * ParseTemporalDurationString ( isoString )
2034 */
2035 bool js::temporal::ParseTemporalDurationString(JSContext* cx,
2036 Handle<JSString*> str,
2037 Duration* result) {
2038 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2039 if (!linear) {
2040 return false;
2041 }
2042
2043 // Steps 1-3.
2044 auto parseResult = ::ParseTemporalDurationString(cx, linear);
2045 if (parseResult.isErr()) {
2046 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2047 parseResult.unwrapErr(), "duration");
2048 return false;
2049 }
2050 TemporalDurationString parsed = parseResult.unwrap();
2051
2052 // Steps 4-8.
2053 double years = parsed.years;
2054 double months = parsed.months;
2055 double weeks = parsed.weeks;
2056 double days = parsed.days;
2057 double hours = parsed.hours;
2058
2059 // Steps 9-17.
2060 double minutes, seconds, milliseconds, microseconds, nanoseconds;
2061 if (parsed.hoursFraction) {
2062 MOZ_ASSERT(parsed.hoursFraction > 0);
2063 MOZ_ASSERT(parsed.hoursFraction < 1'000'000'000);
2064
2065 // Step 9.a.
2066 MOZ_ASSERT(parsed.minutes == 0);
2067 MOZ_ASSERT(parsed.minutesFraction == 0);
2068 MOZ_ASSERT(parsed.seconds == 0);
2069 MOZ_ASSERT(parsed.secondsFraction == 0);
2070
2071 // Steps 9.b-d.
2072 int64_t h = int64_t(parsed.hoursFraction) * 60;
2073 minutes = double(h / 1'000'000'000);
2074
2075 // Steps 13 and 15-17.
2076 int64_t min = (h % 1'000'000'000) * 60;
2077 seconds = double(min / 1'000'000'000);
2078 milliseconds = double((min % 1'000'000'000) / 1'000'000);
2079 microseconds = double((min % 1'000'000) / 1'000);
2080 nanoseconds = double(min % 1'000);
2081 }
2082
2083 // Step 11.
2084 else if (parsed.minutesFraction) {
2085 MOZ_ASSERT(parsed.minutesFraction > 0);
2086 MOZ_ASSERT(parsed.minutesFraction < 1'000'000'000);
2087
2088 // Step 11.a.
2089 MOZ_ASSERT(parsed.seconds == 0);
2090 MOZ_ASSERT(parsed.secondsFraction == 0);
2091
2092 // Step 10.
2093 minutes = parsed.minutes;
2094
2095 // Steps 11.b-d and 15-17.
2096 int64_t min = int64_t(parsed.minutesFraction) * 60;
2097 seconds = double(min / 1'000'000'000);
2098 milliseconds = double((min % 1'000'000'000) / 1'000'000);
2099 microseconds = double((min % 1'000'000) / 1'000);
2100 nanoseconds = double(min % 1'000);
2101 }
2102
2103 // Step 14.
2104 else if (parsed.secondsFraction) {
2105 MOZ_ASSERT(parsed.secondsFraction > 0);
2106 MOZ_ASSERT(parsed.secondsFraction < 1'000'000'000);
2107
2108 // Step 10.
2109 minutes = parsed.minutes;
2110
2111 // Step 12.
2112 seconds = parsed.seconds;
2113
2114 // Steps 14, 16-17
2115 milliseconds = double(parsed.secondsFraction / 1'000'000);
2116 microseconds = double((parsed.secondsFraction % 1'000'000) / 1'000);
2117 nanoseconds = double(parsed.secondsFraction % 1'000);
2118 } else {
2119 // Step 10.
2120 minutes = parsed.minutes;
2121
2122 // Step 12.
2123 seconds = parsed.seconds;
2124
2125 // Steps 15-17
2126 milliseconds = 0;
2127 microseconds = 0;
2128 nanoseconds = 0;
2129 }
2130
2131 // Steps 18-19.
2132 int32_t factor = parsed.sign ? parsed.sign : 1;
2133 MOZ_ASSERT(factor == -1 || factor == 1);
2134
2135 // Steps 20-29.
2136 *result = {
2137 (years * factor) + (+0.0), (months * factor) + (+0.0),
2138 (weeks * factor) + (+0.0), (days * factor) + (+0.0),
2139 (hours * factor) + (+0.0), (minutes * factor) + (+0.0),
2140 (seconds * factor) + (+0.0), (milliseconds * factor) + (+0.0),
2141 (microseconds * factor) + (+0.0), (nanoseconds * factor) + (+0.0),
2142 };
2143
2144 // Steps 30-31.
2145 return ThrowIfInvalidDuration(cx, *result);
2146 }
2147
2148 template <typename CharT>
2149 mozilla::Result<AnnotationKey, ParserError>
2150 TemporalParser<CharT>::annotationKey() {
2151 // AnnotationKey :::
2152 // AKeyLeadingChar
2153 // AnnotationKey AKeyChar
2154
2155 size_t start = reader_.index();
2156
2157 if (!aKeyLeadingChar()) {
2158 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_ANNOTATION_KEY);
2159 }
2160
2161 // Optionally followed by a sequence of |AKeyChar|.
2162 while (aKeyChar()) {
2163 }
2164
2165 return AnnotationKey{start, reader_.index() - start};
2166 }
2167
2168 template <typename CharT>
2169 mozilla::Result<AnnotationValue, ParserError>
2170 TemporalParser<CharT>::annotationValue() {
2171 // AnnotationValue :::
2172 // AnnotationValueComponent
2173 // AnnotationValueComponent - AnnotationValue
2174
2175 size_t start = reader_.index();
2176
2177 do {
2178 if (!annotationValueComponent()) {
2179 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_ANNOTATION_VALUE);
2180 }
2181 } while (character('-'));
2182
2183 return AnnotationValue{start, reader_.index() - start};
2184 }
2185
2186 template <typename CharT>
2187 mozilla::Result<Annotation, ParserError> TemporalParser<CharT>::annotation() {
2188 // Annotation :::
2189 // [ AnnotationCriticalFlag? AnnotationKey = AnnotationValue ]
2190
2191 if (!character('[')) {
2192 return mozilla::Err(JSMSG_TEMPORAL_PARSER_BRACKET_BEFORE_ANNOTATION);
2193 }
2194
2195 Annotation result{};
2196
2197 result.critical = annotationCriticalFlag();
2198
2199 MOZ_TRY_VAR(result.key, annotationKey());
2200
2201 if (!character('=')) {
2202 return mozilla::Err(JSMSG_TEMPORAL_PARSER_ASSIGNMENT_IN_ANNOTATION);
2203 }
2204
2205 MOZ_TRY_VAR(result.value, annotationValue());
2206
2207 if (!character(']')) {
2208 return mozilla::Err(JSMSG_TEMPORAL_PARSER_BRACKET_AFTER_ANNOTATION);
2209 }
2210
2211 return result;
2212 }
2213
2214 template <typename CharT>
2215 mozilla::Result<CalendarName, ParserError>
2216 TemporalParser<CharT>::annotations() {
2217 // Annotations :::
2218 // Annotation Annotations?
2219
2220 MOZ_ASSERT(hasAnnotationStart());
2221
2222 CalendarName calendar;
2223 bool calendarWasCritical = false;
2224 while (hasAnnotationStart()) {
2225 Annotation anno;
2226 MOZ_TRY_VAR(anno, annotation());
2227
2228 auto [key, value, critical] = anno;
2229
2230 static constexpr std::string_view ca = "u-ca";
2231
2232 auto keySpan = reader_.substring(key);
2233 if (keySpan.size() == ca.length() &&
2234 std::equal(ca.begin(), ca.end(), keySpan.data())) {
2235 if (!calendar.present()) {
2236 calendar = value;
2237 calendarWasCritical = critical;
2238 } else if (critical || calendarWasCritical) {
2239 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_CRITICAL_ANNOTATION);
2240 }
2241 } else if (critical) {
2242 return mozilla::Err(JSMSG_TEMPORAL_PARSER_INVALID_CRITICAL_ANNOTATION);
2243 }
2244 }
2245 return calendar;
2246 }
2247
2248 template <typename CharT>
2249 mozilla::Result<ZonedDateTimeString, ParserError>
2250 TemporalParser<CharT>::annotatedTime() {
2251 // clang-format off
2252 //
2253 // AnnotatedTime :::
2254 // TimeDesignator Time DateTimeUTCOffset[~Z]? TimeZoneAnnotation? Annotations?
2255 // Time DateTimeUTCOffset[~Z]? TimeZoneAnnotation? Annotations?
2256 //
2257 // clang-format on
2258
2259 ZonedDateTimeString result{};
2260
2261 size_t start = reader_.index();
2262 bool hasTimeDesignator = timeDesignator();
2263
2264 MOZ_TRY_VAR(result.time, time());
2265
2266 if (hasDateTimeUTCOffsetStart()) {
2267 MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ false));
2268 }
2269
2270 // Early error if `Time DateTimeUTCOffset[~Z]` can be parsed as either
2271 // `DateSpecMonthDay` or `DateSpecYearMonth`.
2272 if (!hasTimeDesignator) {
2273 size_t end = reader_.index();
2274
2275 auto isValidMonthDay = [](const ISODate& date) {
2276 MOZ_ASSERT(date.year == AbsentYear);
2277 MOZ_ASSERT(1 <= date.month && date.month <= 12);
2278 MOZ_ASSERT(1 <= date.day && date.day <= 31);
2279
2280 constexpr int32_t leapYear = 0;
2281 return date.day <= ISODaysInMonth(leapYear, date.month);
2282 };
2283
2284 // Reset and check if the input can also be parsed as DateSpecMonthDay.
2285 reader_.reset(start);
2286
2287 if (auto monthDay = dateSpecMonthDay(); monthDay.isOk()) {
2288 if (reader_.index() == end && isValidMonthDay(monthDay.unwrap())) {
2289 return mozilla::Err(JSMSG_TEMPORAL_PARSER_AMBIGUOUS_TIME_MONTH_DAY);
2290 }
2291 }
2292
2293 // Reset and check if the input can also be parsed as DateSpecYearMonth.
2294 reader_.reset(start);
2295
2296 if (dateSpecYearMonth().isOk()) {
2297 if (reader_.index() == end) {
2298 return mozilla::Err(JSMSG_TEMPORAL_PARSER_AMBIGUOUS_TIME_YEAR_MONTH);
2299 }
2300 }
2301
2302 // Input can neither be parsed as DateSpecMonthDay nor DateSpecYearMonth.
2303 reader_.reset(end);
2304 }
2305
2306 if (hasTimeZoneAnnotationStart()) {
2307 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2308 }
2309
2310 if (hasAnnotationStart()) {
2311 MOZ_TRY_VAR(result.calendar, annotations());
2312 }
2313
2314 return result;
2315 }
2316
2317 template <typename CharT>
2318 mozilla::Result<ZonedDateTimeString, ParserError>
2319 TemporalParser<CharT>::annotatedDateTime() {
2320 // AnnotatedDateTime[Zoned, TimeRequired] :::
2321 // [~Zoned] DateTime[~Z, ?TimeRequired] TimeZoneAnnotation? Annotations?
2322 // [+Zoned] DateTime[+Z, ?TimeRequired] TimeZoneAnnotation Annotations?
2323 //
2324 // When called as `AnnotatedDateTime[~Zoned, ~TimeRequired]`.
2325
2326 ZonedDateTimeString result;
2327 MOZ_TRY_VAR(result, dateTime(/* allowZ = */ false));
2328
2329 if (hasTimeZoneAnnotationStart()) {
2330 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2331 }
2332
2333 if (hasAnnotationStart()) {
2334 MOZ_TRY_VAR(result.calendar, annotations());
2335 }
2336
2337 return result;
2338 }
2339
2340 template <typename CharT>
2341 mozilla::Result<ZonedDateTimeString, ParserError>
2342 TemporalParser<CharT>::annotatedDateTimeTimeRequired() {
2343 // AnnotatedDateTime[Zoned, TimeRequired] :::
2344 // [~Zoned] DateTime[~Z, ?TimeRequired] TimeZoneAnnotation? Annotations?
2345 // [+Zoned] DateTime[+Z, ?TimeRequired] TimeZoneAnnotation Annotations?
2346 //
2347 // DateTime[Z, TimeRequired] :::
2348 // [~TimeRequired] Date
2349 // Date DateTimeSeparator Time DateTimeUTCOffset[?Z]?
2350 //
2351 // When called as `AnnotatedDateTime[~Zoned, +TimeRequired]`.
2352
2353 ZonedDateTimeString result{};
2354
2355 MOZ_TRY_VAR(result.date, date());
2356
2357 if (!dateTimeSeparator()) {
2358 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MISSING_DATE_TIME_SEPARATOR);
2359 }
2360
2361 MOZ_TRY_VAR(result.time, time());
2362
2363 if (hasDateTimeUTCOffsetStart()) {
2364 MOZ_TRY_VAR(result.timeZone, dateTimeUTCOffset(/* allowZ = */ false));
2365 }
2366
2367 if (hasTimeZoneAnnotationStart()) {
2368 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2369 }
2370
2371 if (hasAnnotationStart()) {
2372 MOZ_TRY_VAR(result.calendar, annotations());
2373 }
2374
2375 return result;
2376 }
2377
2378 template <typename CharT>
2379 mozilla::Result<ZonedDateTimeString, ParserError>
2380 TemporalParser<CharT>::annotatedYearMonth() {
2381 // AnnotatedYearMonth :::
2382 // DateSpecYearMonth TimeZoneAnnotation? Annotations?
2383
2384 ZonedDateTimeString result{};
2385
2386 MOZ_TRY_VAR(result.date, dateSpecYearMonth());
2387
2388 if (hasTimeZoneAnnotationStart()) {
2389 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2390 }
2391
2392 if (hasAnnotationStart()) {
2393 MOZ_TRY_VAR(result.calendar, annotations());
2394 }
2395
2396 return result;
2397 }
2398
2399 template <typename CharT>
2400 mozilla::Result<ZonedDateTimeString, ParserError>
2401 TemporalParser<CharT>::annotatedMonthDay() {
2402 // AnnotatedMonthDay :::
2403 // DateSpecMonthDay TimeZoneAnnotation? Annotations?
2404
2405 ZonedDateTimeString result{};
2406
2407 MOZ_TRY_VAR(result.date, dateSpecMonthDay());
2408
2409 if (hasTimeZoneAnnotationStart()) {
2410 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2411 }
2412
2413 if (hasAnnotationStart()) {
2414 MOZ_TRY_VAR(result.calendar, annotations());
2415 }
2416
2417 return result;
2418 }
2419
2420 template <typename CharT>
2421 mozilla::Result<ISODate, ParserError>
2422 TemporalParser<CharT>::dateSpecYearMonth() {
2423 // DateSpecYearMonth :::
2424 // DateYear DateSeparator[+Extended] DateMonth
2425 // DateYear DateSeparator[~Extended] DateMonth
2426
2427 ISODate result{};
2428
2429 MOZ_TRY_VAR(result.year, dateYear());
2430
2431 // Optional |DateSeparator|.
2432 dateSeparator();
2433
2434 MOZ_TRY_VAR(result.month, dateMonth());
2435
2436 return result;
2437 }
2438
2439 template <typename CharT>
2440 mozilla::Result<ISODate, ParserError>
2441 TemporalParser<CharT>::dateSpecMonthDay() {
2442 // DateSpecMonthDay :::
2443 // --? DateMonth DateSeparator[+Extended] DateDay
2444 // --? DateMonth DateSeparator[~Extended] DateDay
2445
2446 ISODate result{};
2447
2448 // Optional: --
2449 string("--");
2450
2451 result.year = AbsentYear;
2452
2453 MOZ_TRY_VAR(result.month, dateMonth());
2454
2455 // Optional |DateSeparator|.
2456 dateSeparator();
2457
2458 MOZ_TRY_VAR(result.day, dateDay());
2459
2460 return result;
2461 }
2462
2463 template <typename CharT>
2464 mozilla::Result<ZonedDateTimeString, ParserError>
2465 TemporalParser<CharT>::parseTemporalCalendarString() {
2466 MOZ_TRY(nonempty());
2467
2468 // Handle the common case of a standalone calendar name first.
2469 //
2470 // All valid calendar names start with two alphabetic characters and none of
2471 // the ParseISODateTime parse goals can start with two alphabetic characters.
2472 // TemporalTimeString can start with 'T', so we can't only check the first
2473 // character.
2474 if (hasTwoAsciiAlpha()) {
2475 ZonedDateTimeString result{};
2476
2477 MOZ_TRY_VAR(result.calendar, parse(annotationValue()));
2478
2479 return result;
2480 }
2481
2482 LikelyError likelyError{};
2483
2484 // Try all five parse goals from ParseISODateTime in order.
2485 //
2486 // TemporalDateTimeString
2487 // TemporalInstantString
2488 // TemporalTimeString
2489 // TemporalMonthDayString
2490 // TemporalYearMonthString
2491
2492 auto dateTime = parseTemporalDateTimeString();
2493 if (dateTime.isOk()) {
2494 return dateTime;
2495 }
2496 likelyError.update(dateTime, reader_.index());
2497
2498 // Restart parsing from the start of the string.
2499 reader_.reset();
2500
2501 auto instant = parseTemporalInstantString();
2502 if (instant.isOk()) {
2503 return instant;
2504 }
2505 likelyError.update(instant, reader_.index());
2506
2507 // Restart parsing from the start of the string.
2508 reader_.reset();
2509
2510 auto time = parseTemporalTimeString();
2511 if (time.isOk()) {
2512 return time;
2513 }
2514 likelyError.update(time, reader_.index());
2515
2516 // Restart parsing from the start of the string.
2517 reader_.reset();
2518
2519 auto monthDay = parseTemporalMonthDayString();
2520 if (monthDay.isOk()) {
2521 return monthDay;
2522 }
2523 likelyError.update(monthDay, reader_.index());
2524
2525 // Restart parsing from the start of the string.
2526 reader_.reset();
2527
2528 auto yearMonth = parseTemporalYearMonthString();
2529 if (yearMonth.isOk()) {
2530 return yearMonth;
2531 }
2532 likelyError.update(yearMonth, reader_.index());
2533
2534 return likelyError.propagate();
2535 }
2536
2537 /**
2538 * ParseTemporalCalendarString ( isoString )
2539 */
2540 template <typename CharT>
2541 static auto ParseTemporalCalendarString(mozilla::Span<const CharT> str) {
2542 TemporalParser<CharT> parser(str);
2543 return parser.parseTemporalCalendarString();
2544 }
2545
2546 /**
2547 * ParseTemporalCalendarString ( isoString )
2548 */
2549 static auto ParseTemporalCalendarString(Handle<JSLinearString*> str) {
2550 JS::AutoCheckCannotGC nogc;
2551 if (str->hasLatin1Chars()) {
2552 return ParseTemporalCalendarString<Latin1Char>(str->latin1Range(nogc));
2553 }
2554 return ParseTemporalCalendarString<char16_t>(str->twoByteRange(nogc));
2555 }
2556
2557 /**
2558 * ParseTemporalCalendarString ( isoString )
2559 */
2560 JSLinearString* js::temporal::ParseTemporalCalendarString(
2561 JSContext* cx, Handle<JSString*> str) {
2562 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2563 if (!linear) {
2564 return nullptr;
2565 }
2566
2567 // Steps 1 and 3.a.
2568 auto parseResult = ::ParseTemporalCalendarString(linear);
2569 if (parseResult.isErr()) {
2570 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2571 parseResult.unwrapErr(), "calendar");
2572 return nullptr;
2573 }
2574 ZonedDateTimeString parsed = parseResult.unwrap();
2575
2576 ISODateTime unused;
2577 if (!ParseISODateTime(cx, parsed, &unused)) {
2578 return nullptr;
2579 }
2580
2581 // Step 2.b.
2582 if (!parsed.calendar.present()) {
2583 return cx->names().iso8601;
2584 }
2585
2586 // Steps 2.c and 3.c
2587 return ToString(cx, linear, parsed.calendar);
2588 }
2589
2590 template <typename CharT>
2591 mozilla::Result<ZonedDateTimeString, ParserError>
2592 TemporalParser<CharT>::parseTemporalTimeString() {
2593 MOZ_TRY(nonempty());
2594
2595 // TemporalTimeString :::
2596 // AnnotatedTime
2597 // AnnotatedDateTime[~Zoned, +TimeRequired]
2598
2599 LikelyError likelyError{};
2600
2601 auto time = parse(annotatedTime());
2602 if (time.isOk()) {
2603 return time;
2604 }
2605 likelyError.update(time, reader_.index());
2606
2607 // Reset and try the next option.
2608 reader_.reset();
2609
2610 auto dateTime = parse(annotatedDateTimeTimeRequired());
2611 if (dateTime.isOk()) {
2612 return dateTime;
2613 }
2614 likelyError.update(time, reader_.index());
2615
2616 // Set current index to the likely error index to give better error messages
2617 // when called from parserTemporal{Calendar,TimeZone}String.
2618 reader_.reset(likelyError.index());
2619
2620 return likelyError.propagate();
2621 }
2622
2623 /**
2624 * ParseTemporalTimeString ( isoString )
2625 */
2626 template <typename CharT>
2627 static auto ParseTemporalTimeString(mozilla::Span<const CharT> str) {
2628 TemporalParser<CharT> parser(str);
2629 return parser.parseTemporalTimeString();
2630 }
2631
2632 /**
2633 * ParseTemporalTimeString ( isoString )
2634 */
2635 static auto ParseTemporalTimeString(Handle<JSLinearString*> str) {
2636 JS::AutoCheckCannotGC nogc;
2637 if (str->hasLatin1Chars()) {
2638 return ParseTemporalTimeString<Latin1Char>(str->latin1Range(nogc));
2639 }
2640 return ParseTemporalTimeString<char16_t>(str->twoByteRange(nogc));
2641 }
2642
2643 /**
2644 * ParseTemporalTimeString ( isoString )
2645 */
2646 bool js::temporal::ParseTemporalTimeString(JSContext* cx, Handle<JSString*> str,
2647 Time* result) {
2648 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2649 if (!linear) {
2650 return false;
2651 }
2652
2653 // Steps 1-2.
2654 auto parseResult = ::ParseTemporalTimeString(linear);
2655 if (parseResult.isErr()) {
2656 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2657 parseResult.unwrapErr(), "time");
2658 return false;
2659 }
2660 ZonedDateTimeString parsed = parseResult.unwrap();
2661
2662 // Step 3.
2663 ISODateTime dateTime;
2664 if (!ParseISODateTime(cx, parsed, &dateTime)) {
2665 return false;
2666 }
2667 *result = dateTime.time;
2668
2669 // Step 4.
2670 MOZ_ASSERT(!parsed.startOfDay);
2671
2672 // Step 5.
2673 return true;
2674 }
2675
2676 template <typename CharT>
2677 mozilla::Result<ZonedDateTimeString, ParserError>
2678 TemporalParser<CharT>::parseTemporalMonthDayString() {
2679 MOZ_TRY(nonempty());
2680
2681 // TemporalMonthDayString :::
2682 // AnnotatedMonthDay
2683 // AnnotatedDateTime[~Zoned, ~TimeRequired]
2684
2685 LikelyError likelyError{};
2686
2687 auto monthDay = parse(annotatedMonthDay());
2688 if (monthDay.isOk()) {
2689 auto result = monthDay.unwrap();
2690
2691 // ParseISODateTime, step 3.
2692 if (result.calendar.present() &&
2693 !IsISO8601Calendar(reader_.substring(result.calendar))) {
2694 return mozilla::Err(JSMSG_TEMPORAL_PARSER_MONTH_DAY_CALENDAR_NOT_ISO8601);
2695 }
2696 return result;
2697 }
2698 likelyError.update(monthDay, reader_.index());
2699
2700 // Reset and try the next option.
2701 reader_.reset();
2702
2703 auto dateTime = parse(annotatedDateTime());
2704 if (dateTime.isOk()) {
2705 return dateTime;
2706 }
2707 likelyError.update(dateTime, reader_.index());
2708
2709 // Set current index to the likely error index to give better error messages
2710 // when called from parserTemporal{Calendar,TimeZone}String.
2711 reader_.reset(likelyError.index());
2712
2713 return likelyError.propagate();
2714 }
2715
2716 /**
2717 * ParseTemporalMonthDayString ( isoString )
2718 */
2719 template <typename CharT>
2720 static auto ParseTemporalMonthDayString(mozilla::Span<const CharT> str) {
2721 TemporalParser<CharT> parser(str);
2722 return parser.parseTemporalMonthDayString();
2723 }
2724
2725 /**
2726 * ParseTemporalMonthDayString ( isoString )
2727 */
2728 static auto ParseTemporalMonthDayString(Handle<JSLinearString*> str) {
2729 JS::AutoCheckCannotGC nogc;
2730 if (str->hasLatin1Chars()) {
2731 return ParseTemporalMonthDayString<Latin1Char>(str->latin1Range(nogc));
2732 }
2733 return ParseTemporalMonthDayString<char16_t>(str->twoByteRange(nogc));
2734 }
2735
2736 /**
2737 * ParseTemporalMonthDayString ( isoString )
2738 */
2739 bool js::temporal::ParseTemporalMonthDayString(
2740 JSContext* cx, Handle<JSString*> str, ISODate* result, bool* hasYear,
2741 MutableHandle<JSString*> calendar) {
2742 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2743 if (!linear) {
2744 return false;
2745 }
2746
2747 // Steps 1-2.
2748 auto parseResult = ::ParseTemporalMonthDayString(linear);
2749 if (parseResult.isErr()) {
2750 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2751 parseResult.unwrapErr(), "month-day");
2752 return false;
2753 }
2754 ZonedDateTimeString parsed = parseResult.unwrap();
2755
2756 // Step 3.
2757 ISODateTime dateTime;
2758 if (!ParseISODateTime(cx, parsed, &dateTime)) {
2759 return false;
2760 }
2761 *result = dateTime.date;
2762
2763 // Steps 4-5.
2764 *hasYear = parsed.date.year != AbsentYear;
2765
2766 if (parsed.calendar.present()) {
2767 calendar.set(ToString(cx, linear, parsed.calendar));
2768 if (!calendar) {
2769 return false;
2770 }
2771 }
2772
2773 // Step 6.
2774 return true;
2775 }
2776
2777 template <typename CharT>
2778 mozilla::Result<ZonedDateTimeString, ParserError>
2779 TemporalParser<CharT>::parseTemporalYearMonthString() {
2780 MOZ_TRY(nonempty());
2781
2782 // TemporalYearMonthString :::
2783 // AnnotatedYearMonth
2784 // AnnotatedDateTime[~Zoned, ~TimeRequired]
2785
2786 LikelyError likelyError{};
2787
2788 auto yearMonth = parse(annotatedYearMonth());
2789 if (yearMonth.isOk()) {
2790 auto result = yearMonth.unwrap();
2791
2792 // ParseISODateTime, step 3.
2793 if (result.calendar.present() &&
2794 !IsISO8601Calendar(reader_.substring(result.calendar))) {
2795 return mozilla::Err(
2796 JSMSG_TEMPORAL_PARSER_YEAR_MONTH_CALENDAR_NOT_ISO8601);
2797 }
2798 return result;
2799 }
2800 likelyError.update(yearMonth, reader_.index());
2801
2802 // Reset and try the next option.
2803 reader_.reset();
2804
2805 auto dateTime = parse(annotatedDateTime());
2806 if (dateTime.isOk()) {
2807 return dateTime;
2808 }
2809 likelyError.update(dateTime, reader_.index());
2810
2811 // Set current index to the likely error index to give better error messages
2812 // when called from parserTemporal{Calendar,TimeZone}String.
2813 reader_.reset(likelyError.index());
2814
2815 return likelyError.propagate();
2816 }
2817
2818 /**
2819 * ParseTemporalYearMonthString ( isoString )
2820 */
2821 template <typename CharT>
2822 static auto ParseTemporalYearMonthString(mozilla::Span<const CharT> str) {
2823 TemporalParser<CharT> parser(str);
2824 return parser.parseTemporalYearMonthString();
2825 }
2826
2827 /**
2828 * ParseTemporalYearMonthString ( isoString )
2829 */
2830 static auto ParseTemporalYearMonthString(Handle<JSLinearString*> str) {
2831 JS::AutoCheckCannotGC nogc;
2832 if (str->hasLatin1Chars()) {
2833 return ParseTemporalYearMonthString<Latin1Char>(str->latin1Range(nogc));
2834 }
2835 return ParseTemporalYearMonthString<char16_t>(str->twoByteRange(nogc));
2836 }
2837
2838 /**
2839 * ParseTemporalYearMonthString ( isoString )
2840 */
2841 bool js::temporal::ParseTemporalYearMonthString(
2842 JSContext* cx, Handle<JSString*> str, ISODate* result,
2843 MutableHandle<JSString*> calendar) {
2844 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2845 if (!linear) {
2846 return false;
2847 }
2848
2849 // Steps 1-2.
2850 auto parseResult = ::ParseTemporalYearMonthString(linear);
2851 if (parseResult.isErr()) {
2852 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2853 parseResult.unwrapErr(), "year-month");
2854 return false;
2855 }
2856 ZonedDateTimeString parsed = parseResult.unwrap();
2857
2858 // Step 3.
2859 ISODateTime dateTime;
2860 if (!ParseISODateTime(cx, parsed, &dateTime)) {
2861 return false;
2862 }
2863 *result = dateTime.date;
2864
2865 if (parsed.calendar.present()) {
2866 calendar.set(ToString(cx, linear, parsed.calendar));
2867 if (!calendar) {
2868 return false;
2869 }
2870 }
2871
2872 return true;
2873 }
2874
2875 template <typename CharT>
2876 mozilla::Result<ZonedDateTimeString, ParserError>
2877 TemporalParser<CharT>::parseTemporalDateTimeString() {
2878 MOZ_TRY(nonempty());
2879
2880 // TemporalDateTimeString[Zoned] :::
2881 // AnnotatedDateTime[?Zoned, ~TimeRequired]
2882
2883 return parse(annotatedDateTime());
2884 }
2885
2886 /**
2887 * ParseTemporalDateTimeString ( isoString )
2888 */
2889 template <typename CharT>
2890 static auto ParseTemporalDateTimeString(mozilla::Span<const CharT> str) {
2891 TemporalParser<CharT> parser(str);
2892 return parser.parseTemporalDateTimeString();
2893 }
2894
2895 /**
2896 * ParseTemporalDateTimeString ( isoString )
2897 */
2898 static auto ParseTemporalDateTimeString(Handle<JSLinearString*> str) {
2899 JS::AutoCheckCannotGC nogc;
2900 if (str->hasLatin1Chars()) {
2901 return ParseTemporalDateTimeString<Latin1Char>(str->latin1Range(nogc));
2902 }
2903 return ParseTemporalDateTimeString<char16_t>(str->twoByteRange(nogc));
2904 }
2905
2906 /**
2907 * ParseTemporalDateTimeString ( isoString )
2908 */
2909 bool js::temporal::ParseTemporalDateTimeString(
2910 JSContext* cx, Handle<JSString*> str, ISODateTime* result,
2911 MutableHandle<JSString*> calendar) {
2912 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2913 if (!linear) {
2914 return false;
2915 }
2916
2917 // Steps 1-2.
2918 auto parseResult = ::ParseTemporalDateTimeString(linear);
2919 if (parseResult.isErr()) {
2920 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2921 parseResult.unwrapErr(), "date-time");
2922 return false;
2923 }
2924 ZonedDateTimeString parsed = parseResult.unwrap();
2925
2926 // Step 3.
2927 if (!ParseISODateTime(cx, parsed, result)) {
2928 return false;
2929 }
2930
2931 if (parsed.calendar.present()) {
2932 calendar.set(ToString(cx, linear, parsed.calendar));
2933 if (!calendar) {
2934 return false;
2935 }
2936 }
2937
2938 return true;
2939 }
2940
2941 template <typename CharT>
2942 mozilla::Result<ZonedDateTimeString, ParserError>
2943 TemporalParser<CharT>::parseTemporalZonedDateTimeString() {
2944 MOZ_TRY(nonempty());
2945
2946 // Parse goal: TemporalDateTimeString[+Zoned]
2947 //
2948 // TemporalDateTimeString[Zoned] :::
2949 // AnnotatedDateTime[?Zoned, ~TimeRequired]
2950 //
2951 // AnnotatedDateTime[Zoned, TimeRequired] :::
2952 // [~Zoned] DateTime[~Z, ?TimeRequired] TimeZoneAnnotation? Annotations?
2953 // [+Zoned] DateTime[+Z, ?TimeRequired] TimeZoneAnnotation Annotations?
2954
2955 ZonedDateTimeString result{};
2956
2957 MOZ_TRY_VAR(result, dateTime(/* allowZ = */ true));
2958
2959 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
2960
2961 if (hasAnnotationStart()) {
2962 MOZ_TRY_VAR(result.calendar, annotations());
2963 }
2964
2965 return complete(result);
2966 }
2967
2968 /**
2969 * ParseTemporalZonedDateTimeString ( isoString )
2970 */
2971 template <typename CharT>
2972 static auto ParseTemporalZonedDateTimeString(mozilla::Span<const CharT> str) {
2973 TemporalParser<CharT> parser(str);
2974 return parser.parseTemporalZonedDateTimeString();
2975 }
2976
2977 /**
2978 * ParseTemporalZonedDateTimeString ( isoString )
2979 */
2980 static auto ParseTemporalZonedDateTimeString(Handle<JSLinearString*> str) {
2981 JS::AutoCheckCannotGC nogc;
2982 if (str->hasLatin1Chars()) {
2983 return ParseTemporalZonedDateTimeString<Latin1Char>(str->latin1Range(nogc));
2984 }
2985 return ParseTemporalZonedDateTimeString<char16_t>(str->twoByteRange(nogc));
2986 }
2987
2988 /**
2989 * ParseTemporalZonedDateTimeString ( isoString )
2990 */
2991 bool js::temporal::ParseTemporalZonedDateTimeString(
2992 JSContext* cx, Handle<JSString*> str,
2993 JS::MutableHandle<ParsedZonedDateTime> result) {
2994 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
2995 if (!linear) {
2996 return false;
2997 }
2998
2999 // Step 1.
3000 auto parseResult = ::ParseTemporalZonedDateTimeString(linear);
3001 if (parseResult.isErr()) {
3002 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3003 parseResult.unwrapErr(), "zoned date-time");
3004 return false;
3005 }
3006 ZonedDateTimeString parsed = parseResult.unwrap();
3007
3008 // Step 2. (ParseISODateTime, steps 2-3.)
3009 Rooted<JSLinearString*> calendar(cx);
3010 if (parsed.calendar.present()) {
3011 calendar = ToString(cx, linear, parsed.calendar);
3012 if (!calendar) {
3013 return false;
3014 }
3015 }
3016
3017 // Step 2. (ParseISODateTime, steps 4-21.)
3018 ISODateTime dateTime;
3019 if (!ParseISODateTime(cx, parsed, &dateTime)) {
3020 return false;
3021 }
3022
3023 // Step 2. (ParseISODateTime, steps 22-23.)
3024 bool isStartOfDay = parsed.startOfDay;
3025
3026 // Step 2. (ParseISODateTime, steps 24-27.)
3027 bool isUTC;
3028 bool hasOffset;
3029 int64_t timeZoneOffset;
3030 Rooted<ParsedTimeZone> timeZoneAnnotation(cx);
3031 {
3032 MOZ_ASSERT(parsed.timeZone.hasAnnotation());
3033
3034 // Case 1: 19700101T00:00Z[+02:00]
3035 // { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: "+02:00" }
3036 //
3037 // Case 2: 19700101T00:00+02:00[+02:00]
3038 // { [[Z]]: false, [[OffsetString]]: "+02:00", [[Name]]: "+02:00" }
3039 //
3040 // Case 3: 19700101[+02:00]
3041 // { [[Z]]: false, [[OffsetString]]: undefined, [[Name]]: "+02:00" }
3042 //
3043 // Case 4: 19700101T00:00Z[Europe/Berlin]
3044 // { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: "Europe/Berlin" }
3045 //
3046 // Case 5: 19700101T00:00+01:00[Europe/Berlin]
3047 // { [[Z]]: false, [[OffsetString]]: "+01:00", [[Name]]: "Europe/Berlin" }
3048 //
3049 // Case 6: 19700101[Europe/Berlin]
3050 // { [[Z]]: false, [[OffsetString]]: undefined, [[Name]]: "Europe/Berlin" }
3051
3052 const auto& annotation = parsed.timeZone.annotation;
3053 if (!ParseTimeZoneAnnotation(cx, annotation, linear, &timeZoneAnnotation)) {
3054 return false;
3055 }
3056
3057 if (parsed.timeZone.isUTC()) {
3058 isUTC = true;
3059 hasOffset = false;
3060 timeZoneOffset = 0;
3061 } else if (parsed.timeZone.hasOffset()) {
3062 isUTC = false;
3063 hasOffset = true;
3064 timeZoneOffset = ParseDateTimeUTCOffset(parsed.timeZone.offset);
3065 } else {
3066 isUTC = false;
3067 hasOffset = false;
3068 timeZoneOffset = 0;
3069 }
3070 }
3071
3072 // Step 2. (ParseISODateTime, step 28.)
3073 result.set(ParsedZonedDateTime{
3074 dateTime,
3075 calendar,
3076 timeZoneAnnotation.get(),
3077 timeZoneOffset,
3078 isUTC,
3079 hasOffset,
3080 isStartOfDay,
3081 });
3082 return true;
3083 }
3084
3085 template <typename CharT>
3086 mozilla::Result<ZonedDateTimeString, ParserError>
3087 TemporalParser<CharT>::parseTemporalRelativeToString() {
3088 MOZ_TRY(nonempty());
3089
3090 // Parse goals:
3091 // TemporalDateTimeString[+Zoned] and TemporalDateTimeString[~Zoned]
3092 //
3093 // TemporalDateTimeString[Zoned] :::
3094 // AnnotatedDateTime[?Zoned, ~TimeRequired]
3095 //
3096 // AnnotatedDateTime[Zoned, TimeRequired] :::
3097 // [~Zoned] DateTime[~Z, ?TimeRequired] TimeZoneAnnotation? Annotations?
3098 // [+Zoned] DateTime[+Z, ?TimeRequired] TimeZoneAnnotation Annotations?
3099
3100 ZonedDateTimeString result{};
3101
3102 MOZ_TRY_VAR(result, dateTime(/* allowZ = */ true));
3103
3104 if (hasTimeZoneAnnotationStart()) {
3105 MOZ_TRY_VAR(result.timeZone.annotation, timeZoneAnnotation());
3106 }
3107
3108 if (hasAnnotationStart()) {
3109 MOZ_TRY_VAR(result.calendar, annotations());
3110 }
3111
3112 return complete(result);
3113 }
3114
3115 /**
3116 * ParseTemporalRelativeToString ( isoString )
3117 */
3118 template <typename CharT>
3119 static auto ParseTemporalRelativeToString(mozilla::Span<const CharT> str) {
3120 TemporalParser<CharT> parser(str);
3121 return parser.parseTemporalRelativeToString();
3122 }
3123
3124 /**
3125 * ParseTemporalRelativeToString ( isoString )
3126 */
3127 static auto ParseTemporalRelativeToString(Handle<JSLinearString*> str) {
3128 JS::AutoCheckCannotGC nogc;
3129 if (str->hasLatin1Chars()) {
3130 return ParseTemporalRelativeToString<Latin1Char>(str->latin1Range(nogc));
3131 }
3132 return ParseTemporalRelativeToString<char16_t>(str->twoByteRange(nogc));
3133 }
3134
3135 /**
3136 * ParseTemporalRelativeToString ( isoString )
3137 */
3138 bool js::temporal::ParseTemporalRelativeToString(
3139 JSContext* cx, Handle<JSString*> str,
3140 MutableHandle<ParsedZonedDateTime> result) {
3141 Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx));
3142 if (!linear) {
3143 return false;
3144 }
3145
3146 // Steps 1-2.
3147 auto parseResult = ::ParseTemporalRelativeToString(linear);
3148 if (parseResult.isErr()) {
3149 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3150 parseResult.unwrapErr(), "relative date-time");
3151 return false;
3152 }
3153 ZonedDateTimeString parsed = parseResult.unwrap();
3154
3155 // Step 3.
3156 if (parsed.timeZone.isUTC() && !parsed.timeZone.hasAnnotation()) {
3157 JS_ReportErrorNumberASCII(
3158 cx, GetErrorMessage, nullptr,
3159 JSMSG_TEMPORAL_PARSER_INVALID_UTC_DESIGNATOR_WITHOUT_NAME,
3160 "relative date-time");
3161 return false;
3162 }
3163
3164 // Step 4. (ParseISODateTime, steps 1-18.)
3165 ISODateTime dateTime;
3166 if (!ParseISODateTime(cx, parsed, &dateTime)) {
3167 return false;
3168 }
3169 bool isStartOfDay = parsed.startOfDay;
3170
3171 // Step 4. (ParseISODateTime, steps 19-22.)
3172 bool isUTC;
3173 bool hasOffset;
3174 int64_t timeZoneOffset;
3175 Rooted<ParsedTimeZone> timeZoneAnnotation(cx);
3176 if (parsed.timeZone.hasAnnotation()) {
3177 // Case 1: 19700101Z[+02:00]
3178 // { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: "+02:00" }
3179 //
3180 // Case 2: 19700101+00:00[+02:00]
3181 // { [[Z]]: false, [[OffsetString]]: "+00:00", [[Name]]: "+02:00" }
3182 //
3183 // Case 3: 19700101[+02:00]
3184 // { [[Z]]: false, [[OffsetString]]: undefined, [[Name]]: "+02:00" }
3185 //
3186 // Case 4: 19700101Z[Europe/Berlin]
3187 // { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: "Europe/Berlin" }
3188 //
3189 // Case 5: 19700101+00:00[Europe/Berlin]
3190 // { [[Z]]: false, [[OffsetString]]: "+00:00", [[Name]]: "Europe/Berlin" }
3191 //
3192 // Case 6: 19700101[Europe/Berlin]
3193 // { [[Z]]: false, [[OffsetString]]: undefined, [[Name]]: "Europe/Berlin" }
3194
3195 const auto& annotation = parsed.timeZone.annotation;
3196 if (!ParseTimeZoneAnnotation(cx, annotation, linear, &timeZoneAnnotation)) {
3197 return false;
3198 }
3199
3200 if (parsed.timeZone.isUTC()) {
3201 isUTC = true;
3202 hasOffset = false;
3203 timeZoneOffset = 0;
3204 } else if (parsed.timeZone.hasOffset()) {
3205 isUTC = false;
3206 hasOffset = true;
3207 timeZoneOffset = ParseDateTimeUTCOffset(parsed.timeZone.offset);
3208 } else {
3209 isUTC = false;
3210 hasOffset = false;
3211 timeZoneOffset = 0;
3212 }
3213 } else {
3214 // GetTemporalRelativeToOption ignores any other time zone information when
3215 // no bracketed time zone annotation is present.
3216
3217 isUTC = false;
3218 hasOffset = false;
3219 timeZoneOffset = 0;
3220 timeZoneAnnotation.set(ParsedTimeZone{});
3221 }
3222
3223 // Step 4. (ParseISODateTime, steps 23-24.)
3224 JSLinearString* calendar = nullptr;
3225 if (parsed.calendar.present()) {
3226 calendar = ToString(cx, linear, parsed.calendar);
3227 if (!calendar) {
3228 return false;
3229 }
3230 }
3231
3232 // Step 4. (Return)
3233 result.set(ParsedZonedDateTime{
3234 dateTime,
3235 calendar,
3236 timeZoneAnnotation.get(),
3237 timeZoneOffset,
3238 isUTC,
3239 hasOffset,
3240 isStartOfDay,
3241 });
3242 return true;
3243 }
3244
3245 void js::temporal::ParsedTimeZone::trace(JSTracer* trc) {
3246 TraceNullableRoot(trc, &name, "ParsedTimeZone::name");
3247 }
3248
3249 void js::temporal::ParsedZonedDateTime::trace(JSTracer* trc) {
3250 TraceNullableRoot(trc, &calendar, "ParsedZonedDateTime::calendar");
3251 timeZoneAnnotation.trace(trc);
3252 }