Debian Codegraph @

js/src/builtin/temporal/Calendar.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/Calendar.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/Attributes.h"
11 #include "mozilla/Casting.h"
12 #include "mozilla/CheckedInt.h"
13 #include "mozilla/EnumSet.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/intl/ICU4XGeckoDataProvider.h"
16 #include "mozilla/intl/Locale.h"
17 #include "mozilla/MathAlgorithms.h"
18 #include "mozilla/Maybe.h"
19 #include "mozilla/Result.h"
20 #include "mozilla/ResultVariant.h"
21 #include "mozilla/Span.h"
22 #include "mozilla/TextUtils.h"
23 #include "mozilla/UniquePtr.h"
24
25 #include <algorithm>
26 #include <array>
27 #include <cmath>
28 #include <initializer_list>
29 #include <iterator>
30 #include <stddef.h>
31 #include <stdint.h>
32 #include <utility>
33
34 #include "diplomat_runtime.h"
35 #include "ICU4XAnyCalendarKind.h"
36 #include "ICU4XCalendar.h"
37 #include "ICU4XDate.h"
38 #include "ICU4XError.h"
39 #include "ICU4XIsoDate.h"
40 #include "ICU4XIsoWeekday.h"
41 #include "ICU4XWeekCalculator.h"
42 #include "ICU4XWeekRelativeUnit.h"
43
44 #include "jsnum.h"
45 #include "jstypes.h"
46 #include "NamespaceImports.h"
47
48 #include "builtin/temporal/CalendarFields.h"
49 #include "builtin/temporal/Crash.h"
50 #include "builtin/temporal/Duration.h"
51 #include "builtin/temporal/Era.h"
52 #include "builtin/temporal/MonthCode.h"
53 #include "builtin/temporal/PlainDate.h"
54 #include "builtin/temporal/PlainDateTime.h"
55 #include "builtin/temporal/PlainMonthDay.h"
56 #include "builtin/temporal/PlainTime.h"
57 #include "builtin/temporal/PlainYearMonth.h"
58 #include "builtin/temporal/Temporal.h"
59 #include "builtin/temporal/TemporalParser.h"
60 #include "builtin/temporal/TemporalRoundingMode.h"
61 #include "builtin/temporal/TemporalTypes.h"
62 #include "builtin/temporal/TemporalUnit.h"
63 #include "builtin/temporal/ZonedDateTime.h"
64 #include "gc/Barrier.h"
65 #include "gc/GCEnum.h"
66 #include "js/AllocPolicy.h"
67 #include "js/ErrorReport.h"
68 #include "js/friend/ErrorMessages.h"
69 #include "js/Printer.h"
70 #include "js/RootingAPI.h"
71 #include "js/TracingAPI.h"
72 #include "js/Value.h"
73 #include "js/Vector.h"
74 #include "util/Text.h"
75 #include "vm/BytecodeUtil.h"
76 #include "vm/Compartment.h"
77 #include "vm/JSAtomState.h"
78 #include "vm/JSContext.h"
79 #include "vm/StringType.h"
80
81 #include "vm/Compartment-inl.h"
82 #include "vm/JSContext-inl.h"
83 #include "vm/JSObject-inl.h"
84 #include "vm/ObjectOperations-inl.h"
85
86 using namespace js;
87 using namespace js::temporal;
88
89 void js::temporal::CalendarValue::trace(JSTracer* trc) {
90 TraceRoot(trc, &value_, "CalendarValue::value");
91 }
92
93 bool js::temporal::WrapCalendarValue(JSContext* cx,
94 MutableHandle<JS::Value> calendar) {
95 MOZ_ASSERT(calendar.isInt32());
96 return cx->compartment()->wrap(cx, calendar);
97 }
98
99 /**
100 * IsISOLeapYear ( year )
101 */
102 static constexpr bool IsISOLeapYear(int32_t year) {
103 // Steps 1-5.
104 return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));
105 }
106
107 /**
108 * ISODaysInYear ( year )
109 */
110 static int32_t ISODaysInYear(int32_t year) {
111 // Steps 1-3.
112 return IsISOLeapYear(year) ? 366 : 365;
113 }
114
115 /**
116 * ISODaysInMonth ( year, month )
117 */
118 static constexpr int32_t ISODaysInMonth(int32_t year, int32_t month) {
119 MOZ_ASSERT(1 <= month && month <= 12);
120
121 constexpr uint8_t daysInMonth[2][13] = {
122 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
123 {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
124
125 // Steps 1-4.
126 return daysInMonth[IsISOLeapYear(year)][month];
127 }
128
129 /**
130 * ISODaysInMonth ( year, month )
131 */
132 int32_t js::temporal::ISODaysInMonth(int32_t year, int32_t month) {
133 return ::ISODaysInMonth(year, month);
134 }
135
136 /**
137 * 21.4.1.6 Week Day
138 *
139 * Compute the week day from |day| without first expanding |day| into a full
140 * date through |MakeDate(day, 0)|:
141 *
142 * WeekDay(MakeDate(day, 0))
143 * = WeekDay(day × msPerDay + 0)
144 * = WeekDay(day × msPerDay)
145 * = 𝔽(ℝ(Day(day × msPerDay) + 4𝔽) modulo 7)
146 * = 𝔽(ℝ(𝔽(floor(ℝ((day × msPerDay) / msPerDay))) + 4𝔽) modulo 7)
147 * = 𝔽(ℝ(𝔽(floor(ℝ(day))) + 4𝔽) modulo 7)
148 * = 𝔽(ℝ(𝔽(day) + 4𝔽) modulo 7)
149 */
150 static int32_t WeekDay(int32_t day) {
151 int32_t result = (day + 4) % 7;
152 if (result < 0) {
153 result += 7;
154 }
155 return result;
156 }
157
158 /**
159 * ISODayOfWeek ( isoDate )
160 */
161 static int32_t ISODayOfWeek(const ISODate& isoDate) {
162 MOZ_ASSERT(ISODateWithinLimits(isoDate));
163
164 // Step 1.
165 int32_t day = MakeDay(isoDate);
166
167 // Step 2.
168 int32_t dayOfWeek = WeekDay(day);
169
170 // Steps 3-4.
171 return dayOfWeek != 0 ? dayOfWeek : 7;
172 }
173
174 static constexpr auto FirstDayOfMonth(int32_t year) {
175 // The following array contains the day of year for the first day of each
176 // month, where index 0 is January, and day 0 is January 1.
177 std::array<int32_t, 13> days = {};
178 for (int32_t month = 1; month <= 12; ++month) {
179 days[month] = days[month - 1] + ::ISODaysInMonth(year, month);
180 }
181 return days;
182 }
183
184 /**
185 * ISODayOfYear ( isoDate )
186 */
187 static int32_t ISODayOfYear(const ISODate& isoDate) {
188 MOZ_ASSERT(ISODateWithinLimits(isoDate));
189
190 const auto& [year, month, day] = isoDate;
191
192 // First day of month arrays for non-leap and leap years.
193 constexpr decltype(FirstDayOfMonth(0)) firstDayOfMonth[2] = {
194 FirstDayOfMonth(1), FirstDayOfMonth(0)};
195
196 // Steps 1-2.
197 //
198 // Instead of first computing the date and then using DayWithinYear to map the
199 // date to the day within the year, directly lookup the first day of the month
200 // and then add the additional days.
201 return firstDayOfMonth[IsISOLeapYear(year)][month - 1] + day;
202 }
203
204 static int32_t FloorDiv(int32_t dividend, int32_t divisor) {
205 MOZ_ASSERT(divisor > 0);
206
207 int32_t quotient = dividend / divisor;
208 int32_t remainder = dividend % divisor;
209 if (remainder < 0) {
210 quotient -= 1;
211 }
212 return quotient;
213 }
214
215 /**
216 * 21.4.1.3 Year Number, DayFromYear
217 */
218 static int32_t DayFromYear(int32_t year) {
219 return 365 * (year - 1970) + FloorDiv(year - 1969, 4) -
220 FloorDiv(year - 1901, 100) + FloorDiv(year - 1601, 400);
221 }
222
223 /**
224 * 21.4.1.11 MakeTime ( hour, min, sec, ms )
225 */
226 static int64_t MakeTime(const Time& time) {
227 MOZ_ASSERT(IsValidTime(time));
228
229 // Step 1 (Not applicable).
230
231 // Step 2.
232 int64_t h = time.hour;
233
234 // Step 3.
235 int64_t m = time.minute;
236
237 // Step 4.
238 int64_t s = time.second;
239
240 // Step 5.
241 int64_t milli = time.millisecond;
242
243 // Steps 6-7.
244 return h * ToMilliseconds(TemporalUnit::Hour) +
245 m * ToMilliseconds(TemporalUnit::Minute) +
246 s * ToMilliseconds(TemporalUnit::Second) + milli;
247 }
248
249 /**
250 * 21.4.1.12 MakeDay ( year, month, date )
251 */
252 int32_t js::temporal::MakeDay(const ISODate& date) {
253 MOZ_ASSERT(ISODateWithinLimits(date));
254
255 return DayFromYear(date.year) + ISODayOfYear(date) - 1;
256 }
257
258 /**
259 * 21.4.1.13 MakeDate ( day, time )
260 */
261 int64_t js::temporal::MakeDate(const ISODateTime& dateTime) {
262 MOZ_ASSERT(ISODateTimeWithinLimits(dateTime));
263
264 // Step 1 (Not applicable).
265
266 // Steps 2-3.
267 int64_t tv = MakeDay(dateTime.date) * ToMilliseconds(TemporalUnit::Day) +
268 MakeTime(dateTime.time);
269
270 // Step 4.
271 return tv;
272 }
273
274 struct YearWeek final {
275 int32_t year = 0;
276 int32_t week = 0;
277 };
278
279 /**
280 * ISOWeekOfYear ( isoDate )
281 */
282 static YearWeek ISOWeekOfYear(const ISODate& isoDate) {
283 MOZ_ASSERT(ISODateWithinLimits(isoDate));
284
285 // Step 1.
286 int32_t year = isoDate.year;
287
288 // Step 2-7. (Not applicable in our implementation.)
289
290 // Steps 8-9.
291 int32_t dayOfYear = ISODayOfYear(isoDate);
292 int32_t dayOfWeek = ISODayOfWeek(isoDate);
293
294 // Step 10.
295 int32_t week = (10 + dayOfYear - dayOfWeek) / 7;
296 MOZ_ASSERT(0 <= week && week <= 53);
297
298 // An ISO year has 53 weeks if the year starts on a Thursday or if it's a
299 // leap year which starts on a Wednesday.
300 auto isLongYear = [](int32_t year) {
301 int32_t startOfYear = ISODayOfWeek({year, 1, 1});
302 return startOfYear == 4 || (startOfYear == 3 && IsISOLeapYear(year));
303 };
304
305 // Step 11.
306 //
307 // Part of last year's last week, which is either week 52 or week 53.
308 if (week == 0) {
309 return {year - 1, 52 + int32_t(isLongYear(year - 1))};
310 }
311
312 // Step 12.
313 //
314 // Part of next year's first week if the current year isn't a long year.
315 if (week == 53 && !isLongYear(year)) {
316 return {year + 1, 1};
317 }
318
319 // Step 13.
320 return {year, week};
321 }
322
323 /**
324 * ToTemporalCalendarIdentifier ( calendarSlotValue )
325 */
326 std::string_view js::temporal::CalendarIdentifier(CalendarId calendarId) {
327 switch (calendarId) {
328 case CalendarId::ISO8601:
329 return "iso8601";
330 case CalendarId::Buddhist:
331 return "buddhist";
332 case CalendarId::Chinese:
333 return "chinese";
334 case CalendarId::Coptic:
335 return "coptic";
336 case CalendarId::Dangi:
337 return "dangi";
338 case CalendarId::Ethiopian:
339 return "ethiopic";
340 case CalendarId::EthiopianAmeteAlem:
341 return "ethioaa";
342 case CalendarId::Gregorian:
343 return "gregory";
344 case CalendarId::Hebrew:
345 return "hebrew";
346 case CalendarId::Indian:
347 return "indian";
348 case CalendarId::Islamic:
349 return "islamic";
350 case CalendarId::IslamicCivil:
351 return "islamic-civil";
352 case CalendarId::IslamicRGSA:
353 return "islamic-rgsa";
354 case CalendarId::IslamicTabular:
355 return "islamic-tbla";
356 case CalendarId::IslamicUmmAlQura:
357 return "islamic-umalqura";
358 case CalendarId::Japanese:
359 return "japanese";
360 case CalendarId::Persian:
361 return "persian";
362 case CalendarId::ROC:
363 return "roc";
364 }
365 MOZ_CRASH("invalid calendar id");
366 }
367
368 class MOZ_STACK_CLASS AsciiLowerCaseChars final {
369 static constexpr size_t InlineCapacity = 24;
370
371 Vector<char, InlineCapacity> chars_;
372
373 public:
374 explicit AsciiLowerCaseChars(JSContext* cx) : chars_(cx) {}
375
376 operator mozilla::Span<const char>() const {
377 return mozilla::Span<const char>{chars_};
378 }
379
380 [[nodiscard]] bool init(JSLinearString* str) {
381 MOZ_ASSERT(StringIsAscii(str));
382
383 if (!chars_.resize(str->length())) {
384 return false;
385 }
386
387 CopyChars(reinterpret_cast<JS::Latin1Char*>(chars_.begin()), *str);
388
389 mozilla::intl::AsciiToLowerCase(chars_.begin(), chars_.length(),
390 chars_.begin());
391
392 return true;
393 }
394 };
395
396 /**
397 * CanonicalizeCalendar ( id )
398 */
399 bool js::temporal::CanonicalizeCalendar(JSContext* cx, Handle<JSString*> id,
400 MutableHandle<CalendarValue> result) {
401 Rooted<JSLinearString*> linear(cx, id->ensureLinear(cx));
402 if (!linear) {
403 return false;
404 }
405
406 // Steps 1-3.
407 do {
408 if (!StringIsAscii(linear) || linear->empty()) {
409 break;
410 }
411
412 AsciiLowerCaseChars lowerCaseChars(cx);
413 if (!lowerCaseChars.init(linear)) {
414 return false;
415 }
416 mozilla::Span<const char> id = lowerCaseChars;
417
418 // Reject invalid types before trying to resolve aliases.
419 if (mozilla::intl::LocaleParser::CanParseUnicodeExtensionType(id).isErr()) {
420 break;
421 }
422
423 // Resolve calendar aliases.
424 static constexpr auto key = mozilla::MakeStringSpan("ca");
425 if (const char* replacement =
426 mozilla::intl::Locale::ReplaceUnicodeExtensionType(key, id)) {
427 id = mozilla::MakeStringSpan(replacement);
428 }
429
430 // Step 1.
431 static constexpr auto& calendars = AvailableCalendars();
432
433 // Steps 2-3.
434 for (auto identifier : calendars) {
435 if (id == mozilla::Span{CalendarIdentifier(identifier)}) {
436 result.set(CalendarValue(identifier));
437 return true;
438 }
439 }
440 } while (false);
441
442 if (auto chars = QuoteString(cx, linear)) {
443 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
444 JSMSG_TEMPORAL_CALENDAR_INVALID_ID, chars.get());
445 }
446 return false;
447 }
448
449 template <typename T, typename... Ts>
450 static bool ToTemporalCalendar(JSContext* cx, Handle<JSObject*> object,
451 MutableHandle<CalendarValue> result) {
452 if (auto* unwrapped = object->maybeUnwrapIf<T>()) {
453 result.set(unwrapped->calendar());
454 return result.wrap(cx);
455 }
456
457 if constexpr (sizeof...(Ts) > 0) {
458 return ToTemporalCalendar<Ts...>(cx, object, result);
459 }
460
461 result.set(CalendarValue());
462 return true;
463 }
464
465 /**
466 * ToTemporalCalendarSlotValue ( temporalCalendarLike )
467 */
468 bool js::temporal::ToTemporalCalendar(JSContext* cx,
469 Handle<Value> temporalCalendarLike,
470 MutableHandle<CalendarValue> result) {
471 // Step 1.
472 if (temporalCalendarLike.isObject()) {
473 Rooted<JSObject*> obj(cx, &temporalCalendarLike.toObject());
474
475 // Step 1.a.
476 Rooted<CalendarValue> calendar(cx);
477 if (!::ToTemporalCalendar<PlainDateObject, PlainDateTimeObject,
478 PlainMonthDayObject, PlainYearMonthObject,
479 ZonedDateTimeObject>(cx, obj, &calendar)) {
480 return false;
481 }
482 if (calendar) {
483 result.set(calendar);
484 return true;
485 }
486 }
487
488 // Step 2.
489 if (!temporalCalendarLike.isString()) {
490 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_IGNORE_STACK,
491 temporalCalendarLike, nullptr, "not a string");
492 return false;
493 }
494 Rooted<JSString*> str(cx, temporalCalendarLike.toString());
495
496 // Step 3.
497 Rooted<JSLinearString*> id(cx, ParseTemporalCalendarString(cx, str));
498 if (!id) {
499 return false;
500 }
501
502 // Step 4.
503 return CanonicalizeCalendar(cx, id, result);
504 }
505
506 /**
507 * GetTemporalCalendarSlotValueWithISODefault ( item )
508 */
509 bool js::temporal::GetTemporalCalendarWithISODefault(
510 JSContext* cx, Handle<JSObject*> item,
511 MutableHandle<CalendarValue> result) {
512 // Step 1.
513 Rooted<CalendarValue> calendar(cx);
514 if (!::ToTemporalCalendar<PlainDateObject, PlainDateTimeObject,
515 PlainMonthDayObject, PlainYearMonthObject,
516 ZonedDateTimeObject>(cx, item, &calendar)) {
517 return false;
518 }
519 if (calendar) {
520 result.set(calendar);
521 return true;
522 }
523
524 // Step 2.
525 Rooted<Value> calendarValue(cx);
526 if (!GetProperty(cx, item, item, cx->names().calendar, &calendarValue)) {
527 return false;
528 }
529
530 // Step 3.
531 if (calendarValue.isUndefined()) {
532 result.set(CalendarValue(CalendarId::ISO8601));
533 return true;
534 }
535
536 // Step 4.
537 return ToTemporalCalendar(cx, calendarValue, result);
538 }
539
540 static inline bool DayOfMonthCanBeZero(CalendarId calendarId) {
541 // Workaround when day-of-month returns zero.
542 //
543 // See <https://github.com/unicode-org/icu4x/issues/5069>.
544 static constexpr mozilla::EnumSet<CalendarId> calendars{
545 CalendarId::Islamic,
546 CalendarId::IslamicRGSA,
547 CalendarId::IslamicUmmAlQura,
548 };
549 return calendars.contains(calendarId);
550 }
551
552 static inline int32_t OrdinalMonth(CalendarId calendarId,
553 const capi::ICU4XDate* date) {
554 int32_t month = capi::ICU4XDate_ordinal_month(date);
555 MOZ_ASSERT(month > 0);
556
557 if (DayOfMonthCanBeZero(calendarId)) {
558 // If |dayOfMonth| is zero, interpret as last day of previous month.
559 int32_t dayOfMonth = capi::ICU4XDate_day_of_month(date);
560 if (dayOfMonth == 0) {
561 MOZ_ASSERT(month > 1);
562 month -= 1;
563 }
564 }
565
566 return month;
567 }
568
569 static inline int32_t DayOfMonth(CalendarId calendarId,
570 const capi::ICU4XDate* date) {
571 int32_t dayOfMonth = capi::ICU4XDate_day_of_month(date);
572
573 if (DayOfMonthCanBeZero(calendarId)) {
574 // If |dayOfMonth| is zero, interpret as last day of previous month.
575 if (dayOfMonth == 0) {
576 MOZ_ASSERT(CalendarDaysInMonth(calendarId).second == 30);
577 dayOfMonth = 30;
578 }
579 }
580
581 MOZ_ASSERT(dayOfMonth > 0);
582 return dayOfMonth;
583 }
584
585 static inline int32_t DayOfYear(const capi::ICU4XDate* date) {
586 int32_t dayOfYear = capi::ICU4XDate_day_of_year(date);
587 MOZ_ASSERT(dayOfYear > 0);
588 return dayOfYear;
589 }
590
591 static inline int32_t DaysInMonth(const capi::ICU4XDate* date) {
592 int32_t daysInMonth = capi::ICU4XDate_days_in_month(date);
593 MOZ_ASSERT(daysInMonth > 0);
594 return daysInMonth;
595 }
596
597 static inline int32_t DaysInYear(const capi::ICU4XDate* date) {
598 int32_t daysInYear = capi::ICU4XDate_days_in_year(date);
599 MOZ_ASSERT(daysInYear > 0);
600 return daysInYear;
601 }
602
603 static inline int32_t MonthsInYear(const capi::ICU4XDate* date) {
604 int32_t monthsInYear = capi::ICU4XDate_months_in_year(date);
605 MOZ_ASSERT(monthsInYear > 0);
606 return monthsInYear;
607 }
608
609 static auto ToAnyCalendarKind(CalendarId id) {
610 switch (id) {
611 case CalendarId::ISO8601:
612 return capi::ICU4XAnyCalendarKind_Iso;
613 case CalendarId::Buddhist:
614 return capi::ICU4XAnyCalendarKind_Buddhist;
615 case CalendarId::Chinese:
616 return capi::ICU4XAnyCalendarKind_Chinese;
617 case CalendarId::Coptic:
618 return capi::ICU4XAnyCalendarKind_Coptic;
619 case CalendarId::Dangi:
620 return capi::ICU4XAnyCalendarKind_Dangi;
621 case CalendarId::Ethiopian:
622 return capi::ICU4XAnyCalendarKind_Ethiopian;
623 case CalendarId::EthiopianAmeteAlem:
624 return capi::ICU4XAnyCalendarKind_EthiopianAmeteAlem;
625 case CalendarId::Gregorian:
626 return capi::ICU4XAnyCalendarKind_Gregorian;
627 case CalendarId::Hebrew:
628 return capi::ICU4XAnyCalendarKind_Hebrew;
629 case CalendarId::Indian:
630 return capi::ICU4XAnyCalendarKind_Indian;
631 case CalendarId::IslamicCivil:
632 return capi::ICU4XAnyCalendarKind_IslamicCivil;
633 case CalendarId::Islamic:
634 return capi::ICU4XAnyCalendarKind_IslamicObservational;
635 case CalendarId::IslamicRGSA:
636 // ICU4X doesn't support a separate islamic-rgsa calendar, so we use the
637 // observational calendar instead. This also matches ICU4C.
638 return capi::ICU4XAnyCalendarKind_IslamicObservational;
639 case CalendarId::IslamicTabular:
640 return capi::ICU4XAnyCalendarKind_IslamicTabular;
641 case CalendarId::IslamicUmmAlQura:
642 return capi::ICU4XAnyCalendarKind_IslamicUmmAlQura;
643 case CalendarId::Japanese:
644 return capi::ICU4XAnyCalendarKind_Japanese;
645 case CalendarId::Persian:
646 return capi::ICU4XAnyCalendarKind_Persian;
647 case CalendarId::ROC:
648 return capi::ICU4XAnyCalendarKind_Roc;
649 }
650 MOZ_CRASH("invalid calendar id");
651 }
652
653 class ICU4XCalendarDeleter {
654 public:
655 void operator()(capi::ICU4XCalendar* ptr) {
656 capi::ICU4XCalendar_destroy(ptr);
657 }
658 };
659
660 using UniqueICU4XCalendar =
661 mozilla::UniquePtr<capi::ICU4XCalendar, ICU4XCalendarDeleter>;
662
663 static UniqueICU4XCalendar CreateICU4XCalendar(JSContext* cx, CalendarId id) {
664 auto result = capi::ICU4XCalendar_create_for_kind(
665 mozilla::intl::GetDataProvider(), ToAnyCalendarKind(id));
666 if (!result.is_ok) {
667 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
668 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
669 return nullptr;
670 }
671 return UniqueICU4XCalendar{result.ok};
672 }
673
674 static uint32_t MaximumISOYear(CalendarId calendarId) {
675 switch (calendarId) {
676 case CalendarId::ISO8601:
677 case CalendarId::Buddhist:
678 case CalendarId::Coptic:
679 case CalendarId::Ethiopian:
680 case CalendarId::EthiopianAmeteAlem:
681 case CalendarId::Gregorian:
682 case CalendarId::Hebrew:
683 case CalendarId::Indian:
684 case CalendarId::IslamicCivil:
685 case CalendarId::IslamicTabular:
686 case CalendarId::Japanese:
687 case CalendarId::Persian:
688 case CalendarId::ROC: {
689 // Passing values near INT32_{MIN,MAX} triggers ICU4X assertions, so we
690 // have to handle large input years early.
691 return 300'000;
692 }
693
694 case CalendarId::Chinese:
695 case CalendarId::Dangi: {
696 // Lower limit for these calendars to avoid running into ICU4X assertions.
697 //
698 // https://github.com/unicode-org/icu4x/issues/4917
699 return 10'000;
700 }
701
702 case CalendarId::Islamic:
703 case CalendarId::IslamicRGSA:
704 case CalendarId::IslamicUmmAlQura: {
705 // Lower limit for these calendars to avoid running into ICU4X assertions.
706 //
707 // https://github.com/unicode-org/icu4x/issues/4917
708 return 5'000;
709 }
710 }
711 MOZ_CRASH("invalid calendar");
712 }
713
714 static uint32_t MaximumCalendarYear(CalendarId calendarId) {
715 switch (calendarId) {
716 case CalendarId::ISO8601:
717 case CalendarId::Buddhist:
718 case CalendarId::Coptic:
719 case CalendarId::Ethiopian:
720 case CalendarId::EthiopianAmeteAlem:
721 case CalendarId::Gregorian:
722 case CalendarId::Hebrew:
723 case CalendarId::Indian:
724 case CalendarId::IslamicCivil:
725 case CalendarId::IslamicTabular:
726 case CalendarId::Japanese:
727 case CalendarId::Persian:
728 case CalendarId::ROC: {
729 // Passing values near INT32_{MIN,MAX} triggers ICU4X assertions, so we
730 // have to handle large input years early.
731 return 300'000;
732 }
733
734 case CalendarId::Chinese:
735 case CalendarId::Dangi: {
736 // Lower limit for these calendars to avoid running into ICU4X assertions.
737 //
738 // https://github.com/unicode-org/icu4x/issues/4917
739 return 10'000;
740 }
741
742 case CalendarId::Islamic:
743 case CalendarId::IslamicRGSA:
744 case CalendarId::IslamicUmmAlQura: {
745 // Lower limit for these calendars to avoid running into ICU4X assertions.
746 //
747 // https://github.com/unicode-org/icu4x/issues/4917
748 return 5'000;
749 }
750 }
751 MOZ_CRASH("invalid calendar");
752 }
753
754 static void ReportCalendarFieldOverflow(JSContext* cx, const char* name,
755 double num) {
756 ToCStringBuf numCbuf;
757 const char* numStr = NumberToCString(&numCbuf, num);
758
759 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
760 JSMSG_TEMPORAL_CALENDAR_OVERFLOW_FIELD, name,
761 numStr);
762 }
763
764 class ICU4XDateDeleter {
765 public:
766 void operator()(capi::ICU4XDate* ptr) { capi::ICU4XDate_destroy(ptr); }
767 };
768
769 using UniqueICU4XDate = mozilla::UniquePtr<capi::ICU4XDate, ICU4XDateDeleter>;
770
771 static UniqueICU4XDate CreateICU4XDate(JSContext* cx, const ISODate& date,
772 CalendarId calendarId,
773 const capi::ICU4XCalendar* calendar) {
774 if (mozilla::Abs(date.year) > MaximumISOYear(calendarId)) {
775 ReportCalendarFieldOverflow(cx, "year", date.year);
776 return nullptr;
777 }
778
779 auto result = capi::ICU4XDate_create_from_iso_in_calendar(
780 date.year, date.month, date.day, calendar);
781 if (!result.is_ok) {
782 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
783 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
784 return nullptr;
785 }
786 return UniqueICU4XDate{result.ok};
787 }
788
789 class ICU4XIsoDateDeleter {
790 public:
791 void operator()(capi::ICU4XIsoDate* ptr) { capi::ICU4XIsoDate_destroy(ptr); }
792 };
793
794 using UniqueICU4XIsoDate =
795 mozilla::UniquePtr<capi::ICU4XIsoDate, ICU4XIsoDateDeleter>;
796
797 class ICU4XWeekCalculatorDeleter {
798 public:
799 void operator()(capi::ICU4XWeekCalculator* ptr) {
800 capi::ICU4XWeekCalculator_destroy(ptr);
801 }
802 };
803
804 using UniqueICU4XWeekCalculator =
805 mozilla::UniquePtr<capi::ICU4XWeekCalculator, ICU4XWeekCalculatorDeleter>;
806
807 static UniqueICU4XWeekCalculator CreateICU4WeekCalculator(JSContext* cx,
808 CalendarId calendar) {
809 MOZ_ASSERT(calendar == CalendarId::Gregorian);
810
811 auto firstWeekday = capi::ICU4XIsoWeekday_Monday;
812 uint8_t minWeekDays = 1;
813
814 auto* result =
815 capi::ICU4XWeekCalculator_create_from_first_day_of_week_and_min_week_days(
816 firstWeekday, minWeekDays);
817 return UniqueICU4XWeekCalculator{result};
818 }
819
820 // Define IMPLEMENTS_DR2126 if DR2126 is implemented.
821 //
822 // https://cplusplus.github.io/CWG/issues/2126.html
823 #if defined(__clang__)
824 # if (__clang_major__ >= 12)
825 # define IMPLEMENTS_DR2126
826 # endif
827 #else
828 # define IMPLEMENTS_DR2126
829 #endif
830
831 #ifdef IMPLEMENTS_DR2126
832 static constexpr size_t EraNameMaxLength() {
833 size_t length = 0;
834 for (auto calendar : AvailableCalendars()) {
835 for (auto era : CalendarEras(calendar)) {
836 for (auto name : CalendarEraNames(calendar, era)) {
837 length = std::max(length, name.length());
838 }
839 }
840 }
841 return length;
842 }
843 #endif
844
845 static mozilla::Maybe<EraCode> EraForString(CalendarId calendar,
846 JSLinearString* string) {
847 MOZ_ASSERT(CalendarEraRelevant(calendar));
848
849 // Note: Assigning MaxLength to EraNameMaxLength() breaks the CDT indexer.
850 constexpr size_t MaxLength = 24;
851 #ifdef IMPLEMENTS_DR2126
852 static_assert(MaxLength >= EraNameMaxLength(),
853 "Storage size is at least as large as the largest known era");
854 #endif
855
856 if (string->length() > MaxLength || !StringIsAscii(string)) {
857 return mozilla::Nothing();
858 }
859
860 char chars[MaxLength] = {};
861 CopyChars(reinterpret_cast<JS::Latin1Char*>(chars), *string);
862
863 auto stringView = std::string_view{chars, string->length()};
864
865 for (auto era : CalendarEras(calendar)) {
866 for (auto name : CalendarEraNames(calendar, era)) {
867 if (name == stringView) {
868 return mozilla::Some(era);
869 }
870 }
871 }
872 return mozilla::Nothing();
873 }
874
875 static constexpr std::string_view IcuEraName(CalendarId calendar, EraCode era) {
876 switch (calendar) {
877 // https://docs.rs/icu/latest/icu/calendar/iso/struct.Iso.html#era-codes
878 case CalendarId::ISO8601: {
879 MOZ_ASSERT(era == EraCode::Standard);
880 return "default";
881 }
882
883 // https://docs.rs/icu/latest/icu/calendar/buddhist/struct.Buddhist.html#era-codes
884 case CalendarId::Buddhist: {
885 MOZ_ASSERT(era == EraCode::Standard);
886 return "be";
887 }
888
889 // https://docs.rs/icu/latest/icu/calendar/chinese/struct.Chinese.html#year-and-era-codes
890 case CalendarId::Chinese: {
891 MOZ_ASSERT(era == EraCode::Standard);
892 return "chinese";
893 }
894
895 // https://docs.rs/icu/latest/icu/calendar/coptic/struct.Coptic.html#era-codes
896 case CalendarId::Coptic: {
897 MOZ_ASSERT(era == EraCode::Standard || era == EraCode::Inverse);
898 return era == EraCode::Standard ? "ad" : "bd";
899 }
900
901 // https://docs.rs/icu/latest/icu/calendar/dangi/struct.Dangi.html#era-codes
902 case CalendarId::Dangi: {
903 MOZ_ASSERT(era == EraCode::Standard);
904 return "dangi";
905 }
906
907 // https://docs.rs/icu/latest/icu/calendar/ethiopian/struct.Ethiopian.html#era-codes
908 case CalendarId::Ethiopian: {
909 MOZ_ASSERT(era == EraCode::Standard || era == EraCode::Inverse);
910 return era == EraCode::Standard ? "incar" : "pre-incar";
911 }
912
913 // https://docs.rs/icu/latest/icu/calendar/ethiopian/struct.Ethiopian.html#era-codes
914 case CalendarId::EthiopianAmeteAlem: {
915 MOZ_ASSERT(era == EraCode::Standard);
916 return "mundi";
917 }
918
919 // https://docs.rs/icu/latest/icu/calendar/gregorian/struct.Gregorian.html#era-codes
920 case CalendarId::Gregorian: {
921 MOZ_ASSERT(era == EraCode::Standard || era == EraCode::Inverse);
922 return era == EraCode::Standard ? "ce" : "bce";
923 }
924
925 // https://docs.rs/icu/latest/icu/calendar/hebrew/struct.Hebrew.html
926 case CalendarId::Hebrew: {
927 MOZ_ASSERT(era == EraCode::Standard);
928 return "am";
929 }
930
931 // https://docs.rs/icu/latest/icu/calendar/indian/struct.Indian.html#era-codes
932 case CalendarId::Indian: {
933 MOZ_ASSERT(era == EraCode::Standard);
934 return "saka";
935 }
936
937 // https://docs.rs/icu/latest/icu/calendar/islamic/struct.IslamicCivil.html#era-codes
938 // https://docs.rs/icu/latest/icu/calendar/islamic/struct.IslamicObservational.html#era-codes
939 // https://docs.rs/icu/latest/icu/calendar/islamic/struct.IslamicTabular.html#era-codes
940 // https://docs.rs/icu/latest/icu/calendar/islamic/struct.IslamicUmmAlQura.html#era-codes
941 // https://docs.rs/icu/latest/icu/calendar/persian/struct.Persian.html#era-codes
942 case CalendarId::Islamic:
943 case CalendarId::IslamicCivil:
944 case CalendarId::IslamicRGSA:
945 case CalendarId::IslamicTabular:
946 case CalendarId::IslamicUmmAlQura:
947 case CalendarId::Persian: {
948 MOZ_ASSERT(era == EraCode::Standard);
949 return "ah";
950 }
951
952 // https://docs.rs/icu/latest/icu/calendar/japanese/struct.Japanese.html#era-codes
953 case CalendarId::Japanese: {
954 switch (era) {
955 case EraCode::Standard:
956 return "ce";
957 case EraCode::Inverse:
958 return "bce";
959 case EraCode::Meiji:
960 return "meiji";
961 case EraCode::Taisho:
962 return "taisho";
963 case EraCode::Showa:
964 return "showa";
965 case EraCode::Heisei:
966 return "heisei";
967 case EraCode::Reiwa:
968 return "reiwa";
969 }
970 break;
971 }
972
973 // https://docs.rs/icu/latest/icu/calendar/roc/struct.Roc.html#era-codes
974 case CalendarId::ROC: {
975 MOZ_ASSERT(era == EraCode::Standard || era == EraCode::Inverse);
976 return era == EraCode::Standard ? "roc" : "roc-inverse";
977 }
978 }
979 JS_CONSTEXPR_CRASH("invalid era");
980 }
981
982 enum class CalendarError {
983 // Catch-all kind for all other error types.
984 Generic,
985
986 // https://docs.rs/icu/latest/icu/calendar/enum.Error.html#variant.Overflow
987 Overflow,
988
989 // https://docs.rs/icu/latest/icu/calendar/enum.Error.html#variant.Underflow
990 Underflow,
991
992 // https://docs.rs/icu/latest/icu/calendar/enum.Error.html#variant.OutOfRange
993 OutOfRange,
994
995 // https://docs.rs/icu/latest/icu/calendar/enum.Error.html#variant.UnknownEra
996 UnknownEra,
997
998 // https://docs.rs/icu/latest/icu/calendar/enum.Error.html#variant.UnknownMonthCode
999 UnknownMonthCode,
1000 };
1001
1002 #ifdef DEBUG
1003 static auto CalendarErasAsEnumSet(CalendarId calendarId) {
1004 // `mozilla::EnumSet<EraCode>(CalendarEras(calendarId))` doesn't work in old
1005 // GCC versions, so add all era codes manually to the enum set.
1006 mozilla::EnumSet<EraCode> eras{};
1007 for (auto era : CalendarEras(calendarId)) {
1008 eras += era;
1009 }
1010 return eras;
1011 }
1012 #endif
1013
1014 static mozilla::Result<UniqueICU4XDate, CalendarError> CreateDateFromCodes(
1015 CalendarId calendarId, const capi::ICU4XCalendar* calendar, EraYear eraYear,
1016 MonthCode monthCode, int32_t day) {
1017 MOZ_ASSERT(calendarId != CalendarId::ISO8601);
1018 MOZ_ASSERT(capi::ICU4XCalendar_kind(calendar) ==
1019 ToAnyCalendarKind(calendarId));
1020 MOZ_ASSERT(CalendarErasAsEnumSet(calendarId).contains(eraYear.era));
1021 MOZ_ASSERT_IF(CalendarEraRelevant(calendarId), eraYear.year > 0);
1022 MOZ_ASSERT(mozilla::Abs(eraYear.year) <= MaximumCalendarYear(calendarId));
1023 MOZ_ASSERT(CalendarMonthCodes(calendarId).contains(monthCode));
1024 MOZ_ASSERT(day > 0);
1025 MOZ_ASSERT(day <= CalendarDaysInMonth(calendarId).second);
1026
1027 auto era = IcuEraName(calendarId, eraYear.era);
1028 auto monthCodeView = std::string_view{monthCode};
1029 auto date = capi::ICU4XDate_create_from_codes_in_calendar(
1030 era.data(), era.length(), eraYear.year, monthCodeView.data(),
1031 monthCodeView.length(), day, calendar);
1032 if (date.is_ok) {
1033 return UniqueICU4XDate{date.ok};
1034 }
1035
1036 // Map possible calendar errors.
1037 //
1038 // Calendar error codes which can't happen for `create_from_codes_in_calendar`
1039 // are mapped to `CalendarError::Generic`.
1040 switch (date.err) {
1041 case capi::ICU4XError_CalendarOverflowError:
1042 return mozilla::Err(CalendarError::Overflow);
1043 case capi::ICU4XError_CalendarUnderflowError:
1044 return mozilla::Err(CalendarError::Underflow);
1045 case capi::ICU4XError_CalendarOutOfRangeError:
1046 return mozilla::Err(CalendarError::OutOfRange);
1047 case capi::ICU4XError_CalendarUnknownEraError:
1048 return mozilla::Err(CalendarError::UnknownEra);
1049 case capi::ICU4XError_CalendarUnknownMonthCodeError:
1050 return mozilla::Err(CalendarError::UnknownMonthCode);
1051 default:
1052 return mozilla::Err(CalendarError::Generic);
1053 }
1054 }
1055
1056 /**
1057 * Return the first year (gannen) of a Japanese era.
1058 */
1059 static bool FirstYearOfJapaneseEra(JSContext* cx, CalendarId calendarId,
1060 const capi::ICU4XCalendar* calendar,
1061 EraCode era, int32_t* result) {
1062 MOZ_ASSERT(calendarId == CalendarId::Japanese);
1063 MOZ_ASSERT(!CalendarEraStartsAtYearBoundary(calendarId, era));
1064
1065 // All supported Japanese eras last at least one year, so December 31 is
1066 // guaranteed to be in the first year of the era.
1067 auto dateResult =
1068 CreateDateFromCodes(calendarId, calendar, {era, 1}, MonthCode{12}, 31);
1069 if (dateResult.isErr()) {
1070 MOZ_ASSERT(dateResult.inspectErr() == CalendarError::Generic,
1071 "unexpected non-generic calendar error");
1072
1073 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1074 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
1075 return false;
1076 }
1077
1078 auto date = dateResult.unwrap();
1079 UniqueICU4XIsoDate isoDate{capi::ICU4XDate_to_iso(date.get())};
1080
1081 int32_t isoYear = capi::ICU4XIsoDate_year(isoDate.get());
1082 MOZ_ASSERT(isoYear > 0, "unexpected era start before 1 CE");
1083
1084 *result = isoYear;
1085 return true;
1086 }
1087
1088 /**
1089 * Return the equivalent common era year for a Japanese era year.
1090 */
1091 static bool JapaneseEraYearToCommonEraYear(JSContext* cx, CalendarId calendarId,
1092 const capi::ICU4XCalendar* calendar,
1093 EraYear eraYear, EraYear* result) {
1094 int32_t firstYearOfEra;
1095 if (!FirstYearOfJapaneseEra(cx, calendarId, calendar, eraYear.era,
1096 &firstYearOfEra)) {
1097 return false;
1098 }
1099
1100 // Map non-positive era years to years before the first era year:
1101 //
1102 // 1 Reiwa = 2019 CE
1103 // 0 Reiwa -> 2018 CE
1104 // -1 Reiwa -> 2017 CE
1105 // etc.
1106 //
1107 // Map too large era years to the next era:
1108 //
1109 // Heisei 31 = 2019 CE
1110 // Heisei 32 -> 2020 CE
1111 // ...
1112
1113 int32_t year = (firstYearOfEra - 1) + eraYear.year;
1114 if (year > 0) {
1115 *result = {EraCode::Standard, year};
1116 return true;
1117 }
1118 *result = {EraCode::Inverse, int32_t(mozilla::Abs(year) + 1)};
1119 return true;
1120 }
1121
1122 static UniqueICU4XDate CreateDateFromCodes(JSContext* cx, CalendarId calendarId,
1123 const capi::ICU4XCalendar* calendar,
1124 EraYear eraYear, MonthCode monthCode,
1125 int32_t day,
1126 TemporalOverflow overflow) {
1127 MOZ_ASSERT(CalendarMonthCodes(calendarId).contains(monthCode));
1128 MOZ_ASSERT(day > 0);
1129 MOZ_ASSERT(day <= CalendarDaysInMonth(calendarId).second);
1130
1131 // Constrain day to the maximum possible day for the input month.
1132 //
1133 // Special cases like February 29 in leap years of the Gregorian calendar are
1134 // handled below.
1135 int32_t daysInMonth = CalendarDaysInMonth(calendarId, monthCode).second;
1136 if (overflow == TemporalOverflow::Constrain) {
1137 day = std::min(day, daysInMonth);
1138 } else {
1139 MOZ_ASSERT(overflow == TemporalOverflow::Reject);
1140
1141 if (day > daysInMonth) {
1142 ReportCalendarFieldOverflow(cx, "day", day);
1143 return nullptr;
1144 }
1145 }
1146
1147 // ICU4X doesn't support large dates, so we have to handle this case early.
1148 if (mozilla::Abs(eraYear.year) > MaximumCalendarYear(calendarId)) {
1149 ReportCalendarFieldOverflow(cx, "year", eraYear.year);
1150 return nullptr;
1151 }
1152
1153 auto result =
1154 CreateDateFromCodes(calendarId, calendar, eraYear, monthCode, day);
1155 if (result.isOk()) {
1156 return result.unwrap();
1157 }
1158
1159 switch (result.inspectErr()) {
1160 case CalendarError::UnknownMonthCode: {
1161 // We've asserted above that |monthCode| is valid for this calendar, so
1162 // any unknown month code must be for a leap month which doesn't happen in
1163 // the current year.
1164 MOZ_ASSERT(CalendarHasLeapMonths(calendarId));
1165 MOZ_ASSERT(monthCode.isLeapMonth());
1166
1167 if (overflow == TemporalOverflow::Reject) {
1168 // Ensure the month code is null-terminated.
1169 char code[5] = {};
1170 auto monthCodeView = std::string_view{monthCode};
1171 monthCodeView.copy(code, monthCodeView.length());
1172
1173 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1174 JSMSG_TEMPORAL_CALENDAR_INVALID_MONTHCODE,
1175 code);
1176 return nullptr;
1177 }
1178
1179 // Retry as non-leap month when we're allowed to constrain.
1180 //
1181 // CalendarDateToISO ( calendar, fields, overflow )
1182 //
1183 // If the month is a leap month that doesn't exist in the year, pick
1184 // another date according to the cultural conventions of that calendar's
1185 // users. Usually this will result in the same day in the month before or
1186 // after where that month would normally fall in a leap year.
1187 //
1188 // Hebrew calendar:
1189 // Replace Adar I (M05L) with Adar (M06).
1190 //
1191 // Chinese/Dangi calendar:
1192 // Pick the next month, for example M03L -> M04, except for M12L, because
1193 // we don't want to switch over to the next year.
1194
1195 // TODO: Temporal spec polyfill replaces M03L with M03 for Chinese/Dangi.
1196 // No idea what are the "cultural conventions" for these two calendars...
1197 //
1198 // https://github.com/tc39/proposal-intl-era-monthcode/issues/32
1199
1200 int32_t nonLeapMonth = std::min(monthCode.ordinal() + 1, 12);
1201 auto nonLeapMonthCode = MonthCode{nonLeapMonth};
1202 return CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1203 nonLeapMonthCode, day, overflow);
1204 }
1205
1206 case CalendarError::Overflow: {
1207 // ICU4X throws an overflow error when:
1208 // 1. month > monthsInYear(year), or
1209 // 2. days > daysInMonthOf(year, month).
1210 //
1211 // Case 1 can't happen for month-codes, so it doesn't apply here.
1212 // Case 2 can only happen when |day| is larger than the minimum number
1213 // of days in the month.
1214 MOZ_ASSERT(day > CalendarDaysInMonth(calendarId, monthCode).first);
1215
1216 if (overflow == TemporalOverflow::Reject) {
1217 ReportCalendarFieldOverflow(cx, "day", day);
1218 return nullptr;
1219 }
1220
1221 auto firstDayOfMonth = CreateDateFromCodes(
1222 cx, calendarId, calendar, eraYear, monthCode, 1, overflow);
1223 if (!firstDayOfMonth) {
1224 return nullptr;
1225 }
1226
1227 int32_t daysInMonth = DaysInMonth(firstDayOfMonth.get());
1228 MOZ_ASSERT(day > daysInMonth);
1229 return CreateDateFromCodes(cx, calendarId, calendar, eraYear, monthCode,
1230 daysInMonth, overflow);
1231 }
1232
1233 case CalendarError::OutOfRange: {
1234 // ICU4X throws an out-of-range error if:
1235 // 1. Non-positive era years are given.
1236 // 2. Dates are before/after the requested named Japanese era.
1237 //
1238 // Case 1 doesn't happen for us, because we always pass strictly positive
1239 // era years, so this error must be for case 2.
1240 MOZ_ASSERT(calendarId == CalendarId::Japanese);
1241 MOZ_ASSERT(!CalendarEraStartsAtYearBoundary(calendarId, eraYear.era));
1242
1243 EraYear commonEraYear;
1244 if (!JapaneseEraYearToCommonEraYear(cx, calendarId, calendar, eraYear,
1245 &commonEraYear)) {
1246 return nullptr;
1247 }
1248 return CreateDateFromCodes(cx, calendarId, calendar, commonEraYear,
1249 monthCode, day, overflow);
1250 }
1251
1252 case CalendarError::Underflow:
1253 case CalendarError::UnknownEra:
1254 MOZ_ASSERT(false, "unexpected calendar error");
1255 break;
1256
1257 case CalendarError::Generic:
1258 break;
1259 }
1260
1261 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1262 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
1263 return nullptr;
1264 }
1265
1266 static UniqueICU4XDate CreateDateFrom(JSContext* cx, CalendarId calendarId,
1267 const capi::ICU4XCalendar* calendar,
1268 EraYear eraYear, int32_t month,
1269 int32_t day, TemporalOverflow overflow) {
1270 MOZ_ASSERT(calendarId != CalendarId::ISO8601);
1271 MOZ_ASSERT(month > 0);
1272 MOZ_ASSERT(day > 0);
1273 MOZ_ASSERT(month <= CalendarMonthsPerYear(calendarId));
1274 MOZ_ASSERT(day <= CalendarDaysInMonth(calendarId).second);
1275
1276 switch (calendarId) {
1277 case CalendarId::ISO8601:
1278 case CalendarId::Buddhist:
1279 case CalendarId::Coptic:
1280 case CalendarId::Ethiopian:
1281 case CalendarId::EthiopianAmeteAlem:
1282 case CalendarId::Gregorian:
1283 case CalendarId::Indian:
1284 case CalendarId::Islamic:
1285 case CalendarId::IslamicCivil:
1286 case CalendarId::IslamicRGSA:
1287 case CalendarId::IslamicTabular:
1288 case CalendarId::IslamicUmmAlQura:
1289 case CalendarId::Japanese:
1290 case CalendarId::Persian:
1291 case CalendarId::ROC: {
1292 MOZ_ASSERT(!CalendarHasLeapMonths(calendarId));
1293
1294 // Use the month-code corresponding to the ordinal month number for
1295 // calendar systems without leap months.
1296 auto date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1297 MonthCode{month}, day, overflow);
1298 if (!date) {
1299 return nullptr;
1300 }
1301 MOZ_ASSERT_IF(CalendarEraStartsAtYearBoundary(calendarId),
1302 OrdinalMonth(calendarId, date.get()) == month);
1303 return date;
1304 }
1305
1306 case CalendarId::Dangi:
1307 case CalendarId::Chinese: {
1308 static_assert(CalendarHasLeapMonths(CalendarId::Chinese));
1309 static_assert(CalendarMonthsPerYear(CalendarId::Chinese) == 13);
1310 static_assert(CalendarHasLeapMonths(CalendarId::Dangi));
1311 static_assert(CalendarMonthsPerYear(CalendarId::Dangi) == 13);
1312
1313 MOZ_ASSERT(1 <= month && month <= 13);
1314
1315 // Create date with month number replaced by month-code.
1316 auto monthCode = MonthCode{std::min(month, 12)};
1317 auto date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1318 monthCode, day, overflow);
1319 if (!date) {
1320 return nullptr;
1321 }
1322
1323 // If the ordinal month of |date| matches the input month, no additional
1324 // changes are necessary and we can directly return |date|.
1325 int32_t ordinal = OrdinalMonth(calendarId, date.get());
1326 if (ordinal == month) {
1327 return date;
1328 }
1329
1330 // Otherwise we need to handle three cases:
1331 // 1. The input year contains a leap month and we need to adjust the
1332 // month-code.
1333 // 2. The thirteenth month of a year without leap months was requested.
1334 // 3. The thirteenth month of a year with leap months was requested.
1335 if (ordinal > month) {
1336 MOZ_ASSERT(1 < month && month <= 12);
1337
1338 // This case can only happen in leap years.
1339 MOZ_ASSERT(MonthsInYear(date.get()) == 13);
1340
1341 // Leap months can occur after any month in the Chinese calendar.
1342 //
1343 // Example when the fourth month is a leap month between M03 and M04.
1344 //
1345 // Month code: M01 M02 M03 M03L M04 M05 M06 ...
1346 // Ordinal month: 1 2 3 4 5 6 7
1347
1348 // The month can be off by exactly one.
1349 MOZ_ASSERT((ordinal - month) == 1);
1350
1351 // First try the case when the previous month isn't a leap month. This
1352 // case can only occur when |month > 2|, because otherwise we know that
1353 // "M01L" is the correct answer.
1354 if (month > 2) {
1355 auto previousMonthCode = MonthCode{month - 1};
1356 date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1357 previousMonthCode, day, overflow);
1358 if (!date) {
1359 return nullptr;
1360 }
1361
1362 int32_t ordinal = OrdinalMonth(calendarId, date.get());
1363 if (ordinal == month) {
1364 return date;
1365 }
1366 }
1367
1368 // Fall-through when the previous month is a leap month.
1369 } else {
1370 MOZ_ASSERT(month == 13);
1371 MOZ_ASSERT(ordinal == 12);
1372
1373 // Years with leap months contain thirteen months.
1374 if (MonthsInYear(date.get()) != 13) {
1375 if (overflow == TemporalOverflow::Reject) {
1376 ReportCalendarFieldOverflow(cx, "month", month);
1377 return nullptr;
1378 }
1379 return date;
1380 }
1381
1382 // Fall-through to return leap month "M12L" at the end of the year.
1383 }
1384
1385 // Finally handle the case when the previous month is a leap month.
1386 auto leapMonthCode = MonthCode{month - 1, /* isLeapMonth= */ true};
1387 date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1388 leapMonthCode, day, overflow);
1389 if (!date) {
1390 return nullptr;
1391 }
1392 MOZ_ASSERT(OrdinalMonth(calendarId, date.get()) == month,
1393 "unexpected ordinal month");
1394 return date;
1395 }
1396
1397 case CalendarId::Hebrew: {
1398 static_assert(CalendarHasLeapMonths(CalendarId::Hebrew));
1399 static_assert(CalendarMonthsPerYear(CalendarId::Hebrew) == 13);
1400
1401 MOZ_ASSERT(1 <= month && month <= 13);
1402
1403 // Create date with month number replaced by month-code.
1404 auto monthCode = MonthCode{std::min(month, 12)};
1405 auto date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1406 monthCode, day, overflow);
1407 if (!date) {
1408 return nullptr;
1409 }
1410
1411 // If the ordinal month of |date| matches the input month, no additional
1412 // changes are necessary and we can directly return |date|.
1413 int32_t ordinal = OrdinalMonth(calendarId, date.get());
1414 if (ordinal == month) {
1415 return date;
1416 }
1417
1418 // Otherwise we need to handle two cases:
1419 // 1. The input year contains a leap month and we need to adjust the
1420 // month-code.
1421 // 2. The thirteenth month of a year without leap months was requested.
1422 if (ordinal > month) {
1423 MOZ_ASSERT(1 < month && month <= 12);
1424
1425 // This case can only happen in leap years.
1426 MOZ_ASSERT(MonthsInYear(date.get()) == 13);
1427
1428 // Leap months can occur between M05 and M06 in the Hebrew calendar.
1429 //
1430 // Month code: M01 M02 M03 M04 M05 M05L M06 ...
1431 // Ordinal month: 1 2 3 4 5 6 7
1432
1433 // The month can be off by exactly one.
1434 MOZ_ASSERT((ordinal - month) == 1);
1435 } else {
1436 MOZ_ASSERT(month == 13);
1437 MOZ_ASSERT(ordinal == 12);
1438
1439 if (overflow == TemporalOverflow::Reject) {
1440 ReportCalendarFieldOverflow(cx, "month", month);
1441 return nullptr;
1442 }
1443 return date;
1444 }
1445
1446 // The previous month is the leap month Adar I iff |month| is six.
1447 bool isLeapMonth = month == 6;
1448 auto previousMonthCode = MonthCode{month - 1, isLeapMonth};
1449 date = CreateDateFromCodes(cx, calendarId, calendar, eraYear,
1450 previousMonthCode, day, overflow);
1451 if (!date) {
1452 return nullptr;
1453 }
1454 MOZ_ASSERT(OrdinalMonth(calendarId, date.get()) == month,
1455 "unexpected ordinal month");
1456 return date;
1457 }
1458 }
1459 MOZ_CRASH("invalid calendar id");
1460 }
1461
1462 #ifdef IMPLEMENTS_DR2126
1463 static constexpr size_t ICUEraNameMaxLength() {
1464 size_t length = 0;
1465 for (auto calendar : AvailableCalendars()) {
1466 for (auto era : CalendarEras(calendar)) {
1467 auto name = IcuEraName(calendar, era);
1468 length = std::max(length, name.length());
1469 }
1470 }
1471 return length;
1472 }
1473 #endif
1474
1475 /**
1476 * Retrieve the era code from |date| and then map the returned ICU4X era code to
1477 * the corresponding |EraCode| member.
1478 */
1479 static bool CalendarDateEra(JSContext* cx, CalendarId calendar,
1480 const capi::ICU4XDate* date, EraCode* result) {
1481 MOZ_ASSERT(calendar != CalendarId::ISO8601);
1482
1483 // Note: Assigning MaxLength to ICUEraNameMaxLength() breaks the CDT indexer.
1484 constexpr size_t MaxLength = 15;
1485 #ifdef IMPLEMENTS_DR2126
1486
1487 // Disable tautological-value-range-compare to avoid a bogus Clang warning.
1488 // See bug 1956918 and bug 1936626.
1489 # ifdef __clang__
1490 # pragma clang diagnostic push
1491 # pragma clang diagnostic ignored "-Wtautological-value-range-compare"
1492 # endif
1493
1494 static_assert(MaxLength >= ICUEraNameMaxLength(),
1495 "Storage size is at least as large as the largest known era");
1496
1497 # ifdef __clang__
1498 # pragma clang diagnostic pop
1499 # endif
1500
1501 #endif
1502
1503 // Storage for the largest known era string and the terminating NUL-character.
1504 char buf[MaxLength + 1] = {};
1505 auto writable = capi::diplomat_simple_writeable(buf, std::size(buf));
1506
1507 if (!capi::ICU4XDate_era(date, &writable).is_ok) {
1508 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1509 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
1510 return false;
1511 }
1512 MOZ_ASSERT(writable.buf == buf, "unexpected buffer relocation");
1513
1514 auto dateEra = std::string_view{writable.buf, writable.len};
1515
1516 // Map to era name to era code.
1517 for (auto era : CalendarEras(calendar)) {
1518 if (IcuEraName(calendar, era) == dateEra) {
1519 *result = era;
1520 return true;
1521 }
1522 }
1523
1524 // Invalid/Unknown era name.
1525 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1526 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
1527 return false;
1528 }
1529
1530 /**
1531 * Return the extended (non-era) year from |date|.
1532 */
1533 static bool CalendarDateYear(JSContext* cx, CalendarId calendar,
1534 const capi::ICU4XDate* date, int32_t* result) {
1535 MOZ_ASSERT(calendar != CalendarId::ISO8601);
1536
1537 // FIXME: ICU4X doesn't yet support CalendarDateYear, so we need to manually
1538 // adjust the era year to determine the non-era year.
1539 //
1540 // https://github.com/unicode-org/icu4x/issues/3962
1541
1542 if (!CalendarEraRelevant(calendar)) {
1543 int32_t year = capi::ICU4XDate_year_in_era(date);
1544 *result = year;
1545 return true;
1546 }
1547
1548 if (calendar != CalendarId::Japanese) {
1549 MOZ_ASSERT(CalendarEras(calendar).size() == 2);
1550
1551 int32_t year = capi::ICU4XDate_year_in_era(date);
1552 MOZ_ASSERT(year > 0, "era years are strictly positive in ICU4X");
1553
1554 EraCode era;
1555 if (!CalendarDateEra(cx, calendar, date, &era)) {
1556 return false;
1557 }
1558
1559 // Map from era year to extended year.
1560 //
1561 // For example in the Gregorian calendar:
1562 //
1563 // ----------------------------
1564 // | Era Year | Extended Year |
1565 // | 2 CE | 2 |
1566 // | 1 CE | 1 |
1567 // | 1 BCE | 0 |
1568 // | 2 BCE | -1 |
1569 // ----------------------------
1570 if (era == EraCode::Inverse) {
1571 year = -(year - 1);
1572 } else {
1573 MOZ_ASSERT(era == EraCode::Standard);
1574 }
1575
1576 *result = year;
1577 return true;
1578 }
1579
1580 // Japanese uses a proleptic Gregorian calendar, so we can use the ISO year.
1581 UniqueICU4XIsoDate isoDate{capi::ICU4XDate_to_iso(date)};
1582 int32_t isoYear = capi::ICU4XIsoDate_year(isoDate.get());
1583
1584 *result = isoYear;
1585 return true;
1586 }
1587
1588 /**
1589 * Retrieve the month code from |date| and then map the returned ICU4X month
1590 * code to the corresponding |MonthCode| member.
1591 */
1592 static bool CalendarDateMonthCode(JSContext* cx, CalendarId calendar,
1593 const capi::ICU4XDate* date,
1594 MonthCode* result) {
1595 MOZ_ASSERT(calendar != CalendarId::ISO8601);
1596
1597 // Valid month codes are "M01".."M13" and "M01L".."M12L".
1598 constexpr size_t MaxLength =
1599 std::string_view{MonthCode::maxLeapMonth()}.length();
1600 static_assert(
1601 MaxLength > std::string_view{MonthCode::maxNonLeapMonth()}.length(),
1602 "string representation of max-leap month is larger");
1603
1604 // Storage for the largest valid month code and the terminating NUL-character.
1605 char buf[MaxLength + 1] = {};
1606 auto writable = capi::diplomat_simple_writeable(buf, std::size(buf));
1607
1608 if (!capi::ICU4XDate_month_code(date, &writable).is_ok) {
1609 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1610 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
1611 return false;
1612 }
1613 MOZ_ASSERT(writable.buf == buf, "unexpected buffer relocation");
1614
1615 auto view = std::string_view{writable.buf, writable.len};
1616
1617 MOZ_ASSERT(view.length() >= 3);
1618 MOZ_ASSERT(view[0] == 'M');
1619 MOZ_ASSERT(mozilla::IsAsciiDigit(view[1]));
1620 MOZ_ASSERT(mozilla::IsAsciiDigit(view[2]));
1621 MOZ_ASSERT_IF(view.length() > 3, view[3] == 'L');
1622
1623 int32_t ordinal =
1624 AsciiDigitToNumber(view[1]) * 10 + AsciiDigitToNumber(view[2]);
1625 bool isLeapMonth = view.length() > 3;
1626 auto monthCode = MonthCode{ordinal, isLeapMonth};
1627
1628 static constexpr auto IrregularAdarII =
1629 MonthCode{6, /* isLeapMonth = */ true};
1630 static constexpr auto RegularAdarII = MonthCode{6};
1631
1632 // Handle the irregular month code "M06L" for Adar II in leap years.
1633 //
1634 // https://docs.rs/icu/latest/icu/calendar/hebrew/struct.Hebrew.html#month-codes
1635 if (calendar == CalendarId::Hebrew && monthCode == IrregularAdarII) {
1636 monthCode = RegularAdarII;
1637 }
1638
1639 if (DayOfMonthCanBeZero(calendar)) {
1640 // If |dayOfMonth| is zero, interpret as last day of previous month.
1641 int32_t dayOfMonth = capi::ICU4XDate_day_of_month(date);
1642 if (dayOfMonth == 0) {
1643 MOZ_ASSERT(ordinal > 1 && !isLeapMonth);
1644 monthCode = MonthCode{ordinal - 1};
1645 }
1646 }
1647
1648 // The month code must be valid for this calendar.
1649 MOZ_ASSERT(CalendarMonthCodes(calendar).contains(monthCode));
1650
1651 *result = monthCode;
1652 return true;
1653 }
1654
1655 class MonthCodeString {
1656 // Zero-terminated month code string.
1657 char str_[4 + 1];
1658
1659 public:
1660 explicit MonthCodeString(MonthCodeField field) {
1661 str_[0] = 'M';
1662 str_[1] = char('0' + (field.ordinal() / 10));
1663 str_[2] = char('0' + (field.ordinal() % 10));
1664 str_[3] = field.isLeapMonth() ? 'L' : '\0';
1665 str_[4] = '\0';
1666 }
1667
1668 const char* toCString() const { return str_; }
1669 };
1670
1671 /**
1672 * CalendarResolveFields ( calendar, fields, type )
1673 */
1674 static bool ISOCalendarResolveMonth(JSContext* cx,
1675 Handle<CalendarFields> fields,
1676 double* result) {
1677 double month = fields.month();
1678 MOZ_ASSERT_IF(fields.has(CalendarField::Month),
1679 IsInteger(month) && month > 0);
1680
1681 // CalendarResolveFields, steps 1.e.
1682 if (!fields.has(CalendarField::MonthCode)) {
1683 MOZ_ASSERT(fields.has(CalendarField::Month));
1684
1685 *result = month;
1686 return true;
1687 }
1688
1689 auto monthCode = fields.monthCode();
1690
1691 // CalendarResolveFields, steps 1.f-k.
1692 int32_t ordinal = monthCode.ordinal();
1693 if (ordinal < 1 || ordinal > 12 || monthCode.isLeapMonth()) {
1694 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1695 JSMSG_TEMPORAL_CALENDAR_INVALID_MONTHCODE,
1696 MonthCodeString{monthCode}.toCString());
1697 return false;
1698 }
1699
1700 // CalendarResolveFields, steps 1.l-m.
1701 if (fields.has(CalendarField::Month) && month != ordinal) {
1702 ToCStringBuf cbuf;
1703 const char* monthStr = NumberToCString(&cbuf, month);
1704
1705 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1706 JSMSG_TEMPORAL_CALENDAR_INCOMPATIBLE_MONTHCODE,
1707 MonthCodeString{monthCode}.toCString(), monthStr);
1708 return false;
1709 }
1710
1711 // CalendarResolveFields, steps 1.n.
1712 *result = ordinal;
1713 return true;
1714 }
1715
1716 struct EraYears {
1717 // Year starting from the calendar epoch.
1718 mozilla::Maybe<EraYear> fromEpoch;
1719
1720 // Year starting from a specific calendar era.
1721 mozilla::Maybe<EraYear> fromEra;
1722 };
1723
1724 static bool CalendarEraYear(JSContext* cx, CalendarId calendarId,
1725 EraYear eraYear, EraYear* result) {
1726 MOZ_ASSERT(CalendarEraRelevant(calendarId));
1727 MOZ_ASSERT(mozilla::Abs(eraYear.year) <= MaximumCalendarYear(calendarId));
1728
1729 if (eraYear.year > 0) {
1730 *result = eraYear;
1731 return true;
1732 }
1733
1734 switch (eraYear.era) {
1735 case EraCode::Standard: {
1736 // Map non-positive era years as follows:
1737 //
1738 // 0 CE -> 1 BCE
1739 // -1 CE -> 2 BCE
1740 // etc.
1741 *result = {EraCode::Inverse, int32_t(mozilla::Abs(eraYear.year) + 1)};
1742 return true;
1743 }
1744
1745 case EraCode::Inverse: {
1746 // Map non-positive era years as follows:
1747 //
1748 // 0 BCE -> 1 CE
1749 // -1 BCE -> 2 CE
1750 // etc.
1751 *result = {EraCode::Standard, int32_t(mozilla::Abs(eraYear.year) + 1)};
1752 return true;
1753 }
1754
1755 case EraCode::Meiji:
1756 case EraCode::Taisho:
1757 case EraCode::Showa:
1758 case EraCode::Heisei:
1759 case EraCode::Reiwa: {
1760 MOZ_ASSERT(calendarId == CalendarId::Japanese);
1761
1762 auto cal = CreateICU4XCalendar(cx, calendarId);
1763 if (!cal) {
1764 return false;
1765 }
1766 return JapaneseEraYearToCommonEraYear(cx, calendarId, cal.get(), eraYear,
1767 result);
1768 }
1769 }
1770 MOZ_CRASH("invalid era id");
1771 }
1772
1773 /**
1774 * CalendarResolveFields ( calendar, fields, type )
1775 * CalendarDateToISO ( calendar, fields, overflow )
1776 * CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow )
1777 *
1778 * Extract `year` and `eraYear` from |fields| and perform some initial
1779 * validation to ensure the values are valid for the requested calendar.
1780 */
1781 static bool CalendarFieldYear(JSContext* cx, CalendarId calendar,
1782 Handle<CalendarFields> fields, EraYears* result) {
1783 MOZ_ASSERT(fields.has(CalendarField::Year) ||
1784 fields.has(CalendarField::EraYear));
1785
1786 // |eraYear| is to be ignored when not relevant for |calendar| per
1787 // CalendarResolveFields.
1788 bool hasRelevantEra =
1789 fields.has(CalendarField::Era) && CalendarEraRelevant(calendar);
1790 MOZ_ASSERT_IF(fields.has(CalendarField::Era), CalendarEraRelevant(calendar));
1791
1792 // Case 1: |year| field is present.
1793 mozilla::Maybe<EraYear> fromEpoch;
1794 if (fields.has(CalendarField::Year)) {
1795 double year = fields.year();
1796 MOZ_ASSERT(IsInteger(year));
1797
1798 int32_t intYear;
1799 if (!mozilla::NumberEqualsInt32(year, &intYear) ||
1800 mozilla::Abs(intYear) > MaximumCalendarYear(calendar)) {
1801 ReportCalendarFieldOverflow(cx, "year", year);
1802 return false;
1803 }
1804
1805 fromEpoch = mozilla::Some(CalendarEraYear(calendar, intYear));
1806 } else {
1807 MOZ_ASSERT(hasRelevantEra);
1808 }
1809
1810 // Case 2: |era| and |eraYear| fields are present and relevant for |calendar|.
1811 mozilla::Maybe<EraYear> fromEra;
1812 if (hasRelevantEra) {
1813 MOZ_ASSERT(fields.has(CalendarField::Era));
1814 MOZ_ASSERT(fields.has(CalendarField::EraYear));
1815
1816 auto era = fields.era();
1817 MOZ_ASSERT(era);
1818
1819 double eraYear = fields.eraYear();
1820 MOZ_ASSERT(IsInteger(eraYear));
1821
1822 auto* linearEra = era->ensureLinear(cx);
1823 if (!linearEra) {
1824 return false;
1825 }
1826
1827 // Ensure the requested era is valid for |calendar|.
1828 auto eraCode = EraForString(calendar, linearEra);
1829 if (!eraCode) {
1830 if (auto code = QuoteString(cx, era)) {
1831 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1832 JSMSG_TEMPORAL_CALENDAR_INVALID_ERA,
1833 code.get());
1834 }
1835 return false;
1836 }
1837
1838 int32_t intEraYear;
1839 if (!mozilla::NumberEqualsInt32(eraYear, &intEraYear) ||
1840 mozilla::Abs(intEraYear) > MaximumCalendarYear(calendar)) {
1841 ReportCalendarFieldOverflow(cx, "eraYear", eraYear);
1842 return false;
1843 }
1844
1845 EraYear eraAndYear;
1846 if (!CalendarEraYear(cx, calendar, {*eraCode, intEraYear}, &eraAndYear)) {
1847 return false;
1848 }
1849 fromEra = mozilla::Some(eraAndYear);
1850 }
1851
1852 *result = {fromEpoch, fromEra};
1853 return true;
1854 }
1855
1856 struct Month {
1857 // Month code.
1858 MonthCode code;
1859
1860 // Ordinal month number.
1861 int32_t ordinal = 0;
1862 };
1863
1864 /**
1865 * CalendarResolveFields ( calendar, fields, type )
1866 * CalendarDateToISO ( calendar, fields, overflow )
1867 * CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow )
1868 *
1869 * Extract `month` and `monthCode` from |fields| and perform some initial
1870 * validation to ensure the values are valid for the requested calendar.
1871 */
1872 static bool CalendarFieldMonth(JSContext* cx, CalendarId calendar,
1873 Handle<CalendarFields> fields,
1874 TemporalOverflow overflow, Month* result) {
1875 MOZ_ASSERT(fields.has(CalendarField::Month) ||
1876 fields.has(CalendarField::MonthCode));
1877
1878 // Case 1: |month| field is present.
1879 int32_t intMonth = 0;
1880 if (fields.has(CalendarField::Month)) {
1881 double month = fields.month();
1882 MOZ_ASSERT(IsInteger(month) && month > 0);
1883
1884 if (!mozilla::NumberEqualsInt32(month, &intMonth)) {
1885 intMonth = 0;
1886 }
1887
1888 const int32_t monthsPerYear = CalendarMonthsPerYear(calendar);
1889 if (intMonth < 1 || intMonth > monthsPerYear) {
1890 if (overflow == TemporalOverflow::Reject) {
1891 ReportCalendarFieldOverflow(cx, "month", month);
1892 return false;
1893 }
1894 MOZ_ASSERT(overflow == TemporalOverflow::Constrain);
1895
1896 intMonth = monthsPerYear;
1897 }
1898
1899 MOZ_ASSERT(intMonth > 0);
1900 }
1901
1902 // Case 2: |monthCode| field is present.
1903 MonthCode fromMonthCode;
1904 if (fields.has(CalendarField::MonthCode)) {
1905 auto monthCode = fields.monthCode();
1906 int32_t ordinal = monthCode.ordinal();
1907 bool isLeapMonth = monthCode.isLeapMonth();
1908
1909 constexpr int32_t minMonth = MonthCode{1}.ordinal();
1910 constexpr int32_t maxNonLeapMonth = MonthCode::maxNonLeapMonth().ordinal();
1911 constexpr int32_t maxLeapMonth = MonthCode::maxLeapMonth().ordinal();
1912
1913 // Minimum month number is 1. Maximum month is 12 (or 13 when the calendar
1914 // uses epagomenal months).
1915 const int32_t maxMonth = isLeapMonth ? maxLeapMonth : maxNonLeapMonth;
1916 if (minMonth <= ordinal && ordinal <= maxMonth) {
1917 fromMonthCode = MonthCode{ordinal, isLeapMonth};
1918 }
1919
1920 // Ensure the month code is valid for this calendar.
1921 const auto& monthCodes = CalendarMonthCodes(calendar);
1922 if (!monthCodes.contains(fromMonthCode)) {
1923 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1924 JSMSG_TEMPORAL_CALENDAR_INVALID_MONTHCODE,
1925 MonthCodeString{monthCode}.toCString());
1926 return false;
1927 }
1928 }
1929
1930 *result = {fromMonthCode, intMonth};
1931 return true;
1932 }
1933
1934 /**
1935 * CalendarResolveFields ( calendar, fields, type )
1936 * CalendarDateToISO ( calendar, fields, overflow )
1937 * CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow )
1938 *
1939 * Extract `day` from |fields| and perform some initial validation to ensure the
1940 * value is valid for the requested calendar.
1941 */
1942 static bool CalendarFieldDay(JSContext* cx, CalendarId calendar,
1943 Handle<CalendarFields> fields,
1944 TemporalOverflow overflow, int32_t* result) {
1945 MOZ_ASSERT(fields.has(CalendarField::Day));
1946
1947 double day = fields.day();
1948 MOZ_ASSERT(IsInteger(day) && day > 0);
1949
1950 int32_t intDay;
1951 if (!mozilla::NumberEqualsInt32(day, &intDay)) {
1952 intDay = 0;
1953 }
1954
1955 // Constrain to a valid day value in this calendar.
1956 int32_t daysPerMonth = CalendarDaysInMonth(calendar).second;
1957 if (intDay < 1 || intDay > daysPerMonth) {
1958 if (overflow == TemporalOverflow::Reject) {
1959 ReportCalendarFieldOverflow(cx, "day", day);
1960 return false;
1961 }
1962 MOZ_ASSERT(overflow == TemporalOverflow::Constrain);
1963
1964 intDay = daysPerMonth;
1965 }
1966
1967 *result = intDay;
1968 return true;
1969 }
1970
1971 /**
1972 * CalendarResolveFields ( calendar, fields, type )
1973 *
1974 * > The operation throws a TypeError exception if the properties of fields are
1975 * > internally inconsistent within the calendar [...]. For example:
1976 * >
1977 * > [...] The values for "era" and "eraYear" do not together identify the same
1978 * > year as the value for "year".
1979 */
1980 static bool CalendarFieldEraYearMatchesYear(JSContext* cx, CalendarId calendar,
1981 Handle<CalendarFields> fields,
1982 const capi::ICU4XDate* date) {
1983 MOZ_ASSERT(fields.has(CalendarField::EraYear));
1984 MOZ_ASSERT(fields.has(CalendarField::Year));
1985
1986 double year = fields.year();
1987 MOZ_ASSERT(IsInteger(year));
1988
1989 int32_t intYear;
1990 MOZ_ALWAYS_TRUE(mozilla::NumberEqualsInt32(year, &intYear));
1991
1992 int32_t yearFromEraYear;
1993 if (!CalendarDateYear(cx, calendar, date, &yearFromEraYear)) {
1994 return false;
1995 }
1996
1997 // The user requested year must match the actual (extended/epoch) year.
1998 if (intYear != yearFromEraYear) {
1999 ToCStringBuf yearCbuf;
2000 const char* yearStr = NumberToCString(&yearCbuf, intYear);
2001
2002 ToCStringBuf fromEraCbuf;
2003 const char* fromEraStr = NumberToCString(&fromEraCbuf, yearFromEraYear);
2004
2005 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2006 JSMSG_TEMPORAL_CALENDAR_INCOMPATIBLE_YEAR,
2007 yearStr, fromEraStr);
2008 return false;
2009 }
2010 return true;
2011 }
2012
2013 /**
2014 * CalendarResolveFields ( calendar, fields, type )
2015 *
2016 * > The operation throws a TypeError exception if the properties of fields are
2017 * > internally inconsistent within the calendar [...]. For example:
2018 * >
2019 * > If "month" and "monthCode" in the calendar [...] do not identify the same
2020 * > month.
2021 */
2022 static bool CalendarFieldMonthCodeMatchesMonth(JSContext* cx,
2023 CalendarId calendarId,
2024 Handle<CalendarFields> fields,
2025 const capi::ICU4XDate* date,
2026 int32_t month) {
2027 int32_t ordinal = OrdinalMonth(calendarId, date);
2028
2029 // The user requested month must match the actual ordinal month.
2030 if (month != ordinal) {
2031 ToCStringBuf cbuf;
2032 const char* monthStr = NumberToCString(&cbuf, fields.month());
2033
2034 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
2035 JSMSG_TEMPORAL_CALENDAR_INCOMPATIBLE_MONTHCODE,
2036 MonthCodeString{fields.monthCode()}.toCString(),
2037 monthStr);
2038 return false;
2039 }
2040 return true;
2041 }
2042
2043 static ISODate ToISODate(const capi::ICU4XDate* date) {
2044 UniqueICU4XIsoDate isoDate{capi::ICU4XDate_to_iso(date)};
2045
2046 int32_t isoYear = capi::ICU4XIsoDate_year(isoDate.get());
2047
2048 int32_t isoMonth = capi::ICU4XIsoDate_month(isoDate.get());
2049 MOZ_ASSERT(1 <= isoMonth && isoMonth <= 12);
2050
2051 int32_t isoDay = capi::ICU4XIsoDate_day_of_month(isoDate.get());
2052
2053 // TODO: Workaround for <https://github.com/unicode-org/icu4x/issues/5070>.
2054 if (isoDay == 0) {
2055 MOZ_ASSERT(capi::ICU4XCalendar_kind(capi::ICU4XDate_calendar(date)) ==
2056 capi::ICU4XAnyCalendarKind_Indian);
2057 isoDay = 31;
2058 isoMonth = 12;
2059 isoYear -= 1;
2060 }
2061
2062 MOZ_ASSERT(1 <= isoDay && isoDay <= ::ISODaysInMonth(isoYear, isoMonth));
2063
2064 return {isoYear, isoMonth, isoDay};
2065 }
2066
2067 static UniqueICU4XDate CreateDateFrom(JSContext* cx, CalendarId calendar,
2068 const capi::ICU4XCalendar* cal,
2069 const EraYears& eraYears,
2070 const Month& month, int32_t day,
2071 Handle<CalendarFields> fields,
2072 TemporalOverflow overflow) {
2073 // Use |eraYear| if present, so we can more easily check for consistent
2074 // |year| and |eraYear| fields.
2075 auto eraYear = eraYears.fromEra ? *eraYears.fromEra : *eraYears.fromEpoch;
2076
2077 UniqueICU4XDate date;
2078 if (month.code != MonthCode{}) {
2079 date = CreateDateFromCodes(cx, calendar, cal, eraYear, month.code, day,
2080 overflow);
2081 } else {
2082 date = CreateDateFrom(cx, calendar, cal, eraYear, month.ordinal, day,
2083 overflow);
2084 }
2085 if (!date) {
2086 return nullptr;
2087 }
2088
2089 // |year| and |eraYear| must be consistent.
2090 if (eraYears.fromEpoch && eraYears.fromEra) {
2091 if (!CalendarFieldEraYearMatchesYear(cx, calendar, fields, date.get())) {
2092 return nullptr;
2093 }
2094 }
2095
2096 // |month| and |monthCode| must be consistent.
2097 if (month.code != MonthCode{} && month.ordinal > 0) {
2098 if (!CalendarFieldMonthCodeMatchesMonth(cx, calendar, fields, date.get(),
2099 month.ordinal)) {
2100 return nullptr;
2101 }
2102 }
2103
2104 return date;
2105 }
2106
2107 /**
2108 * RegulateISODate ( year, month, day, overflow )
2109 */
2110 static bool RegulateISODate(JSContext* cx, int32_t year, double month,
2111 double day, TemporalOverflow overflow,
2112 ISODate* result) {
2113 MOZ_ASSERT(IsInteger(month));
2114 MOZ_ASSERT(IsInteger(day));
2115
2116 // Step 1.
2117 if (overflow == TemporalOverflow::Constrain) {
2118 // Step 1.a.
2119 int32_t m = int32_t(std::clamp(month, 1.0, 12.0));
2120
2121 // Step 1.b.
2122 double daysInMonth = double(::ISODaysInMonth(year, m));
2123
2124 // Step 1.c.
2125 int32_t d = int32_t(std::clamp(day, 1.0, daysInMonth));
2126
2127 // Step 3. (Inlined call to CreateISODateRecord.)
2128 *result = {year, m, d};
2129 return true;
2130 }
2131
2132 // Step 2.a.
2133 MOZ_ASSERT(overflow == TemporalOverflow::Reject);
2134
2135 // Step 2.b.
2136 if (!ThrowIfInvalidISODate(cx, year, month, day)) {
2137 return false;
2138 }
2139
2140 // Step 3. (Inlined call to CreateISODateRecord.)
2141 *result = {year, int32_t(month), int32_t(day)};
2142 return true;
2143 }
2144
2145 /**
2146 * CalendarDateToISO ( calendar, fields, overflow )
2147 */
2148 static bool CalendarDateToISO(JSContext* cx, CalendarId calendar,
2149 Handle<CalendarFields> fields,
2150 TemporalOverflow overflow, ISODate* result) {
2151 // Step 1.
2152 if (calendar == CalendarId::ISO8601) {
2153 // Step 1.a.
2154 MOZ_ASSERT(fields.has(CalendarField::Year));
2155 MOZ_ASSERT(fields.has(CalendarField::Month) ||
2156 fields.has(CalendarField::MonthCode));
2157 MOZ_ASSERT(fields.has(CalendarField::Day));
2158
2159 // Remaining steps from CalendarResolveFields to resolve the month.
2160 double month;
2161 if (!ISOCalendarResolveMonth(cx, fields, &month)) {
2162 return false;
2163 }
2164
2165 int32_t intYear;
2166 if (!mozilla::NumberEqualsInt32(fields.year(), &intYear)) {
2167 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2168 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
2169 return false;
2170 }
2171
2172 // Step 1.b.
2173 return RegulateISODate(cx, intYear, month, fields.day(), overflow, result);
2174 }
2175
2176 // Step 2.
2177
2178 EraYears eraYears;
2179 if (!CalendarFieldYear(cx, calendar, fields, &eraYears)) {
2180 return false;
2181 }
2182
2183 Month month;
2184 if (!CalendarFieldMonth(cx, calendar, fields, overflow, &month)) {
2185 return false;
2186 }
2187
2188 int32_t day;
2189 if (!CalendarFieldDay(cx, calendar, fields, overflow, &day)) {
2190 return false;
2191 }
2192
2193 auto cal = CreateICU4XCalendar(cx, calendar);
2194 if (!cal) {
2195 return false;
2196 }
2197
2198 auto date = CreateDateFrom(cx, calendar, cal.get(), eraYears, month, day,
2199 fields, overflow);
2200 if (!date) {
2201 return false;
2202 }
2203
2204 *result = ToISODate(date.get());
2205 return true;
2206 }
2207
2208 /**
2209 * CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow )
2210 */
2211 static bool CalendarMonthDayToISOReferenceDate(JSContext* cx,
2212 CalendarId calendar,
2213 Handle<CalendarFields> fields,
2214 TemporalOverflow overflow,
2215 ISODate* result) {
2216 // Step 1.
2217 if (calendar == CalendarId::ISO8601) {
2218 // Step 1.a.
2219 MOZ_ASSERT(fields.has(CalendarField::Month) ||
2220 fields.has(CalendarField::MonthCode));
2221 MOZ_ASSERT(fields.has(CalendarField::Day));
2222
2223 // Remaining steps from CalendarResolveFields to resolve the month.
2224 double month;
2225 if (!ISOCalendarResolveMonth(cx, fields, &month)) {
2226 return false;
2227 }
2228
2229 // Step 1.b.
2230 int32_t referenceISOYear = 1972;
2231
2232 // Step 1.c.
2233 double year =
2234 !fields.has(CalendarField::Year) ? referenceISOYear : fields.year();
2235
2236 int32_t intYear;
2237 if (!mozilla::NumberEqualsInt32(year, &intYear)) {
2238 // Calendar cycles repeat every 400 years in the Gregorian calendar.
2239 intYear = int32_t(std::fmod(year, 400));
2240 }
2241
2242 // Step 1.d.
2243 ISODate regulated;
2244 if (!RegulateISODate(cx, intYear, month, fields.day(), overflow,
2245 &regulated)) {
2246 return false;
2247 }
2248
2249 // Step 1.e.
2250 *result = {referenceISOYear, regulated.month, regulated.day};
2251 return true;
2252 }
2253
2254 // Step 2.
2255
2256 EraYears eraYears;
2257 if (fields.has(CalendarField::Year) || fields.has(CalendarField::EraYear)) {
2258 if (!CalendarFieldYear(cx, calendar, fields, &eraYears)) {
2259 return false;
2260 }
2261 } else {
2262 MOZ_ASSERT(fields.has(CalendarField::MonthCode));
2263 }
2264
2265 Month month;
2266 if (!CalendarFieldMonth(cx, calendar, fields, overflow, &month)) {
2267 return false;
2268 }
2269
2270 int32_t day;
2271 if (!CalendarFieldDay(cx, calendar, fields, overflow, &day)) {
2272 return false;
2273 }
2274
2275 auto cal = CreateICU4XCalendar(cx, calendar);
2276 if (!cal) {
2277 return false;
2278 }
2279
2280 // We first have to compute the month-code if it wasn't provided to us.
2281 auto monthCode = month.code;
2282 if (fields.has(CalendarField::Year) || fields.has(CalendarField::EraYear)) {
2283 auto date = CreateDateFrom(cx, calendar, cal.get(), eraYears, month, day,
2284 fields, overflow);
2285 if (!date) {
2286 return false;
2287 }
2288
2289 // This operation throws a RangeError if the ISO 8601 year corresponding to
2290 // `fields.[[Year]]` is outside the valid limits.
2291 auto isoDate = ToISODate(date.get());
2292 if (!ISODateWithinLimits(isoDate)) {
2293 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2294 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
2295 return false;
2296 }
2297
2298 if (!fields.has(CalendarField::MonthCode)) {
2299 if (!CalendarDateMonthCode(cx, calendar, date.get(), &monthCode)) {
2300 return false;
2301 }
2302 }
2303 MOZ_ASSERT(monthCode != MonthCode{});
2304
2305 if (overflow == TemporalOverflow::Constrain) {
2306 // Call into ICU4X if `day` exceeds the minimum number of days.
2307 int32_t minDaysInMonth = CalendarDaysInMonth(calendar, monthCode).first;
2308 if (day > minDaysInMonth) {
2309 day = DayOfMonth(calendar, date.get());
2310 }
2311 } else {
2312 MOZ_ASSERT(overflow == TemporalOverflow::Reject);
2313 MOZ_ASSERT(day == DayOfMonth(calendar, date.get()));
2314 }
2315 } else {
2316 MOZ_ASSERT(monthCode != MonthCode{});
2317
2318 // Constrain `day` to maximum possible day of the input month.
2319 int32_t maxDaysInMonth = CalendarDaysInMonth(calendar, monthCode).second;
2320 if (overflow == TemporalOverflow::Constrain) {
2321 day = std::min(day, maxDaysInMonth);
2322 } else {
2323 MOZ_ASSERT(overflow == TemporalOverflow::Reject);
2324
2325 if (day > maxDaysInMonth) {
2326 ReportCalendarFieldOverflow(cx, "day", day);
2327 return false;
2328 }
2329 }
2330 }
2331
2332 // Try years starting from 31 December, 1972.
2333 constexpr auto isoReferenceDate = ISODate{1972, 12, 31};
2334
2335 auto fromIsoDate = CreateICU4XDate(cx, isoReferenceDate, calendar, cal.get());
2336 if (!fromIsoDate) {
2337 return false;
2338 }
2339
2340 // Find the calendar year for the ISO reference date.
2341 int32_t calendarYear;
2342 if (!CalendarDateYear(cx, calendar, fromIsoDate.get(), &calendarYear)) {
2343 return false;
2344 }
2345
2346 // 10'000 is sufficient to find all possible month-days, even for rare cases
2347 // like `{calendar: "chinese", monthCode: "M09L", day: 30}`.
2348 constexpr size_t maxIterations = 10'000;
2349
2350 UniqueICU4XDate date;
2351 for (size_t i = 0; i < maxIterations; i++) {
2352 // This loop can run for a long time.
2353 if (!CheckForInterrupt(cx)) {
2354 return false;
2355 }
2356
2357 auto candidateYear = CalendarEraYear(calendar, calendarYear);
2358
2359 auto result =
2360 CreateDateFromCodes(calendar, cal.get(), candidateYear, monthCode, day);
2361 if (result.isOk()) {
2362 // Make sure the resolved date is before December 31, 1972.
2363 auto isoDate = ToISODate(result.inspect().get());
2364 if (isoDate.year > isoReferenceDate.year) {
2365 calendarYear -= 1;
2366 continue;
2367 }
2368
2369 date = result.unwrap();
2370 break;
2371 }
2372
2373 switch (result.inspectErr()) {
2374 case CalendarError::UnknownMonthCode: {
2375 MOZ_ASSERT(CalendarHasLeapMonths(calendar));
2376 MOZ_ASSERT(monthCode.isLeapMonth());
2377
2378 // Try the next candidate year if the requested leap month doesn't
2379 // occur in the current year.
2380 calendarYear -= 1;
2381 continue;
2382 }
2383
2384 case CalendarError::Overflow: {
2385 // ICU4X throws an overflow error when:
2386 // 1. month > monthsInYear(year), or
2387 // 2. days > daysInMonthOf(year, month).
2388 //
2389 // Case 1 can't happen for month-codes, so it doesn't apply here.
2390 // Case 2 can only happen when |day| is larger than the minimum number
2391 // of days in the month.
2392 MOZ_ASSERT(day > CalendarDaysInMonth(calendar, monthCode).first);
2393
2394 // Try next candidate year to find an earlier year which can fulfill
2395 // the input request.
2396 calendarYear -= 1;
2397 continue;
2398 }
2399
2400 case CalendarError::OutOfRange:
2401 case CalendarError::Underflow:
2402 case CalendarError::UnknownEra:
2403 MOZ_ASSERT(false, "unexpected calendar error");
2404 break;
2405
2406 case CalendarError::Generic:
2407 break;
2408 }
2409
2410 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2411 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
2412 return false;
2413 }
2414
2415 // We shouldn't end up here with |maxIterations == 10'000|, but just in case
2416 // still handle this case and report an error.
2417 if (!date) {
2418 ReportCalendarFieldOverflow(cx, "day", day);
2419 return false;
2420 }
2421
2422 // |month| and |monthCode| must be consistent.
2423 if (month.code != MonthCode{} && month.ordinal > 0) {
2424 if (!CalendarFieldMonthCodeMatchesMonth(cx, calendar, fields, date.get(),
2425 month.ordinal)) {
2426 return false;
2427 }
2428 }
2429
2430 *result = ToISODate(date.get());
2431 return true;
2432 }
2433
2434 enum class FieldType { Date, YearMonth, MonthDay };
2435
2436 /**
2437 * CalendarResolveFields ( calendar, fields, type )
2438 */
2439 static bool CalendarResolveFields(JSContext* cx, CalendarId calendar,
2440 Handle<CalendarFields> fields,
2441 FieldType type) {
2442 // Step 1.
2443 if (calendar == CalendarId::ISO8601) {
2444 // Steps 1.a-e.
2445 const char* missingField = nullptr;
2446 if ((type == FieldType::Date || type == FieldType::YearMonth) &&
2447 !fields.has(CalendarField::Year)) {
2448 missingField = "year";
2449 } else if ((type == FieldType::Date || type == FieldType::MonthDay) &&
2450 !fields.has(CalendarField::Day)) {
2451 missingField = "day";
2452 } else if (!fields.has(CalendarField::MonthCode) &&
2453 !fields.has(CalendarField::Month)) {
2454 missingField = "month";
2455 }
2456
2457 if (missingField) {
2458 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2459 JSMSG_TEMPORAL_CALENDAR_MISSING_FIELD,
2460 missingField);
2461 return false;
2462 }
2463
2464 // Steps 1.f-n. (Handled in ISOCalendarResolveMonth.)
2465
2466 return true;
2467 }
2468
2469 // Step 2.
2470
2471 // Date and Month-Day require |day| to be present.
2472 bool requireDay = type == FieldType::Date || type == FieldType::MonthDay;
2473
2474 // Date and Year-Month require |year| (or |eraYear|) to be present.
2475 // Month-Day requires |year| (or |eraYear|) if |monthCode| is absent.
2476 bool requireYear = type == FieldType::Date || type == FieldType::YearMonth ||
2477 !fields.has(CalendarField::MonthCode);
2478
2479 // Determine if any calendar fields are missing.
2480 const char* missingField = nullptr;
2481 if (!fields.has(CalendarField::MonthCode) &&
2482 !fields.has(CalendarField::Month)) {
2483 // |monthCode| or |month| must be present.
2484 missingField = "monthCode";
2485 } else if (requireDay && !fields.has(CalendarField::Day)) {
2486 missingField = "day";
2487 } else if (!CalendarEraRelevant(calendar)) {
2488 if (requireYear && !fields.has(CalendarField::Year)) {
2489 missingField = "year";
2490 }
2491 } else {
2492 if (fields.has(CalendarField::Era) != fields.has(CalendarField::EraYear)) {
2493 // |era| and |eraYear| must either both be present or both absent.
2494 missingField = fields.has(CalendarField::Era) ? "eraYear" : "era";
2495 } else if (requireYear && !fields.has(CalendarField::EraYear) &&
2496 !fields.has(CalendarField::Year)) {
2497 missingField = "eraYear";
2498 }
2499 }
2500
2501 if (missingField) {
2502 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2503 JSMSG_TEMPORAL_CALENDAR_MISSING_FIELD,
2504 missingField);
2505 return false;
2506 }
2507
2508 return true;
2509 }
2510
2511 /**
2512 * CalendarISOToDate ( calendar, isoDate )
2513 *
2514 * Return the Calendar Date Record's [[Era]] field.
2515 */
2516 bool js::temporal::CalendarEra(JSContext* cx, Handle<CalendarValue> calendar,
2517 const ISODate& date,
2518 MutableHandle<Value> result) {
2519 auto calendarId = calendar.identifier();
2520
2521 // Step 1.
2522 if (calendarId == CalendarId::ISO8601) {
2523 result.setUndefined();
2524 return true;
2525 }
2526
2527 // Step 2.
2528 if (!CalendarEraRelevant(calendarId)) {
2529 result.setUndefined();
2530 return true;
2531 }
2532
2533 auto cal = CreateICU4XCalendar(cx, calendarId);
2534 if (!cal) {
2535 return false;
2536 }
2537
2538 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2539 if (!dt) {
2540 return false;
2541 }
2542
2543 EraCode era;
2544 if (!CalendarDateEra(cx, calendarId, dt.get(), &era)) {
2545 return false;
2546 }
2547
2548 auto* str = NewStringCopy<CanGC>(cx, CalendarEraName(calendarId, era));
2549 if (!str) {
2550 return false;
2551 }
2552
2553 result.setString(str);
2554 return true;
2555 }
2556
2557 /**
2558 * CalendarISOToDate ( calendar, isoDate )
2559 *
2560 * Return the Calendar Date Record's [[EraYear]] field.
2561 */
2562 bool js::temporal::CalendarEraYear(JSContext* cx,
2563 Handle<CalendarValue> calendar,
2564 const ISODate& date,
2565 MutableHandle<Value> result) {
2566 auto calendarId = calendar.identifier();
2567
2568 // Step 1.
2569 if (calendarId == CalendarId::ISO8601) {
2570 result.setUndefined();
2571 return true;
2572 }
2573
2574 // Step 2.
2575 if (!CalendarEraRelevant(calendarId)) {
2576 result.setUndefined();
2577 return true;
2578 }
2579
2580 auto cal = CreateICU4XCalendar(cx, calendarId);
2581 if (!cal) {
2582 return false;
2583 }
2584
2585 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2586 if (!dt) {
2587 return false;
2588 }
2589
2590 int32_t year = capi::ICU4XDate_year_in_era(dt.get());
2591 result.setInt32(year);
2592 return true;
2593 }
2594
2595 /**
2596 * CalendarISOToDate ( calendar, isoDate )
2597 *
2598 * Return the Calendar Date Record's [[Year]] field.
2599 */
2600 bool js::temporal::CalendarYear(JSContext* cx, Handle<CalendarValue> calendar,
2601 const ISODate& date,
2602 MutableHandle<Value> result) {
2603 auto calendarId = calendar.identifier();
2604
2605 // Step 1.
2606 if (calendarId == CalendarId::ISO8601) {
2607 result.setInt32(date.year);
2608 return true;
2609 }
2610
2611 // Step 2.
2612 auto cal = CreateICU4XCalendar(cx, calendarId);
2613 if (!cal) {
2614 return false;
2615 }
2616
2617 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2618 if (!dt) {
2619 return false;
2620 }
2621
2622 int32_t year;
2623 if (!CalendarDateYear(cx, calendarId, dt.get(), &year)) {
2624 return false;
2625 }
2626
2627 result.setInt32(year);
2628 return true;
2629 }
2630
2631 /**
2632 * CalendarISOToDate ( calendar, isoDate )
2633 *
2634 * Return the Calendar Date Record's [[Month]] field.
2635 */
2636 bool js::temporal::CalendarMonth(JSContext* cx, Handle<CalendarValue> calendar,
2637 const ISODate& date,
2638 MutableHandle<Value> result) {
2639 auto calendarId = calendar.identifier();
2640
2641 // Step 1.
2642 if (calendarId == CalendarId::ISO8601) {
2643 result.setInt32(date.month);
2644 return true;
2645 }
2646
2647 // Step 2.
2648 auto cal = CreateICU4XCalendar(cx, calendarId);
2649 if (!cal) {
2650 return false;
2651 }
2652
2653 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2654 if (!dt) {
2655 return false;
2656 }
2657
2658 int32_t month = OrdinalMonth(calendarId, dt.get());
2659 result.setInt32(month);
2660 return true;
2661 }
2662
2663 /**
2664 * CalendarISOToDate ( calendar, isoDate )
2665 *
2666 * Return the Calendar Date Record's [[MonthCode]] field.
2667 */
2668 bool js::temporal::CalendarMonthCode(JSContext* cx,
2669 Handle<CalendarValue> calendar,
2670 const ISODate& date,
2671 MutableHandle<Value> result) {
2672 auto calendarId = calendar.identifier();
2673
2674 // Step 1.
2675 if (calendarId == CalendarId::ISO8601) {
2676 // Steps 1.a-b.
2677 auto monthCode = MonthCode{date.month};
2678 JSString* str = NewStringCopy<CanGC>(cx, std::string_view{monthCode});
2679 if (!str) {
2680 return false;
2681 }
2682
2683 result.setString(str);
2684 return true;
2685 }
2686
2687 // Step 2.
2688 auto cal = CreateICU4XCalendar(cx, calendarId);
2689 if (!cal) {
2690 return false;
2691 }
2692
2693 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2694 if (!dt) {
2695 return false;
2696 }
2697
2698 MonthCode monthCode;
2699 if (!CalendarDateMonthCode(cx, calendarId, dt.get(), &monthCode)) {
2700 return false;
2701 }
2702
2703 auto* str = NewStringCopy<CanGC>(cx, std::string_view{monthCode});
2704 if (!str) {
2705 return false;
2706 }
2707
2708 result.setString(str);
2709 return true;
2710 }
2711
2712 /**
2713 * CalendarISOToDate ( calendar, isoDate )
2714 *
2715 * Return the Calendar Date Record's [[Day]] field.
2716 */
2717 bool js::temporal::CalendarDay(JSContext* cx, Handle<CalendarValue> calendar,
2718 const ISODate& date,
2719 MutableHandle<Value> result) {
2720 auto calendarId = calendar.identifier();
2721
2722 // Step 1.
2723 if (calendarId == CalendarId::ISO8601) {
2724 result.setInt32(date.day);
2725 return true;
2726 }
2727
2728 // Step 2.
2729 auto cal = CreateICU4XCalendar(cx, calendarId);
2730 if (!cal) {
2731 return false;
2732 }
2733
2734 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2735 if (!dt) {
2736 return false;
2737 }
2738
2739 int32_t day = DayOfMonth(calendarId, dt.get());
2740 result.setInt32(day);
2741 return true;
2742 }
2743
2744 /**
2745 * CalendarISOToDate ( calendar, isoDate )
2746 *
2747 * Return the Calendar Date Record's [[DayOfWeek]] field.
2748 */
2749 bool js::temporal::CalendarDayOfWeek(JSContext* cx,
2750 Handle<CalendarValue> calendar,
2751 const ISODate& date,
2752 MutableHandle<Value> result) {
2753 auto calendarId = calendar.identifier();
2754
2755 // Step 1.
2756 if (calendarId == CalendarId::ISO8601) {
2757 result.setInt32(ISODayOfWeek(date));
2758 return true;
2759 }
2760
2761 // Step 2.
2762 auto cal = CreateICU4XCalendar(cx, calendarId);
2763 if (!cal) {
2764 return false;
2765 }
2766
2767 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2768 if (!dt) {
2769 return false;
2770 }
2771
2772 // Week day codes are correctly ordered.
2773 static_assert(capi::ICU4XIsoWeekday_Monday == 1);
2774 static_assert(capi::ICU4XIsoWeekday_Tuesday == 2);
2775 static_assert(capi::ICU4XIsoWeekday_Wednesday == 3);
2776 static_assert(capi::ICU4XIsoWeekday_Thursday == 4);
2777 static_assert(capi::ICU4XIsoWeekday_Friday == 5);
2778 static_assert(capi::ICU4XIsoWeekday_Saturday == 6);
2779 static_assert(capi::ICU4XIsoWeekday_Sunday == 7);
2780
2781 capi::ICU4XIsoWeekday day = capi::ICU4XDate_day_of_week(dt.get());
2782 result.setInt32(static_cast<int32_t>(day));
2783 return true;
2784 }
2785
2786 /**
2787 * CalendarISOToDate ( calendar, isoDate )
2788 *
2789 * Return the Calendar Date Record's [[DayOfYear]] field.
2790 */
2791 bool js::temporal::CalendarDayOfYear(JSContext* cx,
2792 Handle<CalendarValue> calendar,
2793 const ISODate& date,
2794 MutableHandle<Value> result) {
2795 auto calendarId = calendar.identifier();
2796
2797 // Step 1.
2798 if (calendarId == CalendarId::ISO8601) {
2799 result.setInt32(ISODayOfYear(date));
2800 return true;
2801 }
2802
2803 // Step 2.
2804 auto cal = CreateICU4XCalendar(cx, calendarId);
2805 if (!cal) {
2806 return false;
2807 }
2808
2809 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2810 if (!dt) {
2811 return false;
2812 }
2813
2814 // Workaround for https://github.com/unicode-org/icu4x/issues/5655
2815 if (calendarId == CalendarId::Japanese) {
2816 // Use the extended year instead of the era year to correctly handle the
2817 // case when the era changes in the current year. This can happen in the
2818 // Japanese calendar.
2819 int32_t year;
2820 if (!CalendarDateYear(cx, calendarId, dt.get(), &year)) {
2821 return false;
2822 }
2823 auto eraYear = CalendarEraYear(calendarId, year);
2824
2825 int32_t dayOfYear = DayOfMonth(calendarId, dt.get());
2826 int32_t month = OrdinalMonth(calendarId, dt.get());
2827
2828 // Add the number of days of all preceding months to compute the overall day
2829 // of the year.
2830 while (month > 1) {
2831 auto previousMonth = CreateDateFrom(cx, calendarId, cal.get(), eraYear,
2832 --month, 1, TemporalOverflow::Reject);
2833 if (!previousMonth) {
2834 return false;
2835 }
2836
2837 dayOfYear += DaysInMonth(previousMonth.get());
2838 }
2839
2840 MOZ_ASSERT(dayOfYear <= DaysInYear(dt.get()));
2841
2842 result.setInt32(dayOfYear);
2843 return true;
2844 }
2845
2846 int32_t day = DayOfYear(dt.get());
2847 result.setInt32(day);
2848 return true;
2849 }
2850
2851 /**
2852 * CalendarISOToDate ( calendar, isoDate )
2853 *
2854 * Return the Calendar Date Record's [[WeekOfYear]].[[Week]] field.
2855 */
2856 bool js::temporal::CalendarWeekOfYear(JSContext* cx,
2857 Handle<CalendarValue> calendar,
2858 const ISODate& date,
2859 MutableHandle<Value> result) {
2860 auto calendarId = calendar.identifier();
2861
2862 // Step 1.
2863 if (calendarId == CalendarId::ISO8601) {
2864 result.setInt32(ISOWeekOfYear(date).week);
2865 return true;
2866 }
2867
2868 // Step 2.
2869
2870 // Non-Gregorian calendars don't get week-of-year support for now.
2871 //
2872 // https://github.com/tc39/proposal-intl-era-monthcode/issues/15
2873 if (calendarId != CalendarId::Gregorian) {
2874 result.setUndefined();
2875 return true;
2876 }
2877
2878 auto cal = CreateICU4XCalendar(cx, calendarId);
2879 if (!cal) {
2880 return false;
2881 }
2882
2883 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2884 if (!dt) {
2885 return false;
2886 }
2887
2888 auto weekCal = CreateICU4WeekCalculator(cx, calendarId);
2889 if (!weekCal) {
2890 return false;
2891 }
2892
2893 auto week = capi::ICU4XDate_week_of_year(dt.get(), weekCal.get());
2894 if (!week.is_ok) {
2895 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2896 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
2897 return false;
2898 }
2899
2900 result.setInt32(week.ok.week);
2901 return true;
2902 }
2903
2904 /**
2905 * CalendarISOToDate ( calendar, isoDate )
2906 *
2907 * Return the Calendar Date Record's [[WeekOfYear]].[[Year]] field.
2908 */
2909 bool js::temporal::CalendarYearOfWeek(JSContext* cx,
2910 Handle<CalendarValue> calendar,
2911 const ISODate& date,
2912 MutableHandle<Value> result) {
2913 auto calendarId = calendar.identifier();
2914
2915 // Step 1.
2916 if (calendarId == CalendarId::ISO8601) {
2917 result.setInt32(ISOWeekOfYear(date).year);
2918 return true;
2919 }
2920
2921 // Step 2.
2922
2923 // Non-Gregorian calendars don't get week-of-year support for now.
2924 //
2925 // https://github.com/tc39/proposal-intl-era-monthcode/issues/15
2926 if (calendarId != CalendarId::Gregorian) {
2927 result.setUndefined();
2928 return true;
2929 }
2930
2931 auto cal = CreateICU4XCalendar(cx, calendarId);
2932 if (!cal) {
2933 return false;
2934 }
2935
2936 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
2937 if (!dt) {
2938 return false;
2939 }
2940
2941 auto weekCal = CreateICU4WeekCalculator(cx, calendarId);
2942 if (!weekCal) {
2943 return false;
2944 }
2945
2946 auto week = capi::ICU4XDate_week_of_year(dt.get(), weekCal.get());
2947 if (!week.is_ok) {
2948 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2949 JSMSG_TEMPORAL_CALENDAR_INTERNAL_ERROR);
2950 return false;
2951 }
2952
2953 int32_t relative = 0;
2954 switch (week.ok.unit) {
2955 case capi::ICU4XWeekRelativeUnit_Previous:
2956 relative = -1;
2957 break;
2958 case capi::ICU4XWeekRelativeUnit_Current:
2959 relative = 0;
2960 break;
2961 case capi::ICU4XWeekRelativeUnit_Next:
2962 relative = 1;
2963 break;
2964 }
2965
2966 int32_t calendarYear;
2967 if (!CalendarDateYear(cx, calendarId, dt.get(), &calendarYear)) {
2968 return false;
2969 }
2970
2971 result.setInt32(calendarYear + relative);
2972 return true;
2973 }
2974
2975 /**
2976 * CalendarISOToDate ( calendar, isoDate )
2977 *
2978 * Return the Calendar Date Record's [[DaysInWeek]] field.
2979 */
2980 bool js::temporal::CalendarDaysInWeek(JSContext* cx,
2981 Handle<CalendarValue> calendar,
2982 const ISODate& date,
2983 MutableHandle<Value> result) {
2984 // All supported ICU4X calendars use a 7-day week and so does the ISO 8601
2985 // calendar.
2986 //
2987 // This function isn't supported through the ICU4X FFI, so we have to
2988 // hardcode the result.
2989
2990 // Step 1-2.
2991 result.setInt32(7);
2992 return true;
2993 }
2994
2995 /**
2996 * CalendarISOToDate ( calendar, isoDate )
2997 *
2998 * Return the Calendar Date Record's [[DaysInMonth]] field.
2999 */
3000 bool js::temporal::CalendarDaysInMonth(JSContext* cx,
3001 Handle<CalendarValue> calendar,
3002 const ISODate& date,
3003 MutableHandle<Value> result) {
3004 auto calendarId = calendar.identifier();
3005
3006 // Step 1.
3007 if (calendarId == CalendarId::ISO8601) {
3008 result.setInt32(::ISODaysInMonth(date.year, date.month));
3009 return true;
3010 }
3011
3012 // Step 2.
3013 auto cal = CreateICU4XCalendar(cx, calendarId);
3014 if (!cal) {
3015 return false;
3016 }
3017
3018 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
3019 if (!dt) {
3020 return false;
3021 }
3022
3023 int32_t days = DaysInMonth(dt.get());
3024 result.setInt32(days);
3025 return true;
3026 }
3027
3028 /**
3029 * CalendarISOToDate ( calendar, isoDate )
3030 *
3031 * Return the Calendar Date Record's [[DaysInYear]] field.
3032 */
3033 bool js::temporal::CalendarDaysInYear(JSContext* cx,
3034 Handle<CalendarValue> calendar,
3035 const ISODate& date,
3036 MutableHandle<Value> result) {
3037 auto calendarId = calendar.identifier();
3038
3039 // Step 1.
3040 if (calendarId == CalendarId::ISO8601) {
3041 result.setInt32(ISODaysInYear(date.year));
3042 return true;
3043 }
3044
3045 // Step 2.
3046 auto cal = CreateICU4XCalendar(cx, calendarId);
3047 if (!cal) {
3048 return false;
3049 }
3050
3051 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
3052 if (!dt) {
3053 return false;
3054 }
3055
3056 int32_t days = DaysInYear(dt.get());
3057 result.setInt32(days);
3058 return true;
3059 }
3060
3061 /**
3062 * CalendarISOToDate ( calendar, isoDate )
3063 *
3064 * Return the Calendar Date Record's [[MonthsInYear]] field.
3065 */
3066 bool js::temporal::CalendarMonthsInYear(JSContext* cx,
3067 Handle<CalendarValue> calendar,
3068 const ISODate& date,
3069 MutableHandle<Value> result) {
3070 auto calendarId = calendar.identifier();
3071
3072 // Step 1.
3073 if (calendarId == CalendarId::ISO8601) {
3074 result.setInt32(12);
3075 return true;
3076 }
3077
3078 // Step 2
3079 auto cal = CreateICU4XCalendar(cx, calendarId);
3080 if (!cal) {
3081 return false;
3082 }
3083
3084 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
3085 if (!dt) {
3086 return false;
3087 }
3088
3089 int32_t months = MonthsInYear(dt.get());
3090 result.setInt32(months);
3091 return true;
3092 }
3093
3094 /**
3095 * CalendarISOToDate ( calendar, isoDate )
3096 *
3097 * Return the Calendar Date Record's [[InLeapYear]] field.
3098 */
3099 bool js::temporal::CalendarInLeapYear(JSContext* cx,
3100 Handle<CalendarValue> calendar,
3101 const ISODate& date,
3102 MutableHandle<Value> result) {
3103 auto calendarId = calendar.identifier();
3104
3105 // Step 1.
3106 if (calendarId == CalendarId::ISO8601) {
3107 result.setBoolean(IsISOLeapYear(date.year));
3108 return true;
3109 }
3110
3111 // Step 2.
3112
3113 // FIXME: Not supported in ICU4X.
3114 //
3115 // https://github.com/unicode-org/icu4x/issues/5654
3116
3117 auto cal = CreateICU4XCalendar(cx, calendarId);
3118 if (!cal) {
3119 return false;
3120 }
3121
3122 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
3123 if (!dt) {
3124 return false;
3125 }
3126
3127 bool inLeapYear = false;
3128 switch (calendarId) {
3129 case CalendarId::ISO8601:
3130 case CalendarId::Buddhist:
3131 case CalendarId::Gregorian:
3132 case CalendarId::Japanese:
3133 case CalendarId::Coptic:
3134 case CalendarId::Ethiopian:
3135 case CalendarId::EthiopianAmeteAlem:
3136 case CalendarId::Indian:
3137 case CalendarId::Persian:
3138 case CalendarId::ROC: {
3139 MOZ_ASSERT(!CalendarHasLeapMonths(calendarId));
3140
3141 // Solar calendars have either 365 or 366 days per year.
3142 int32_t days = DaysInYear(dt.get());
3143 MOZ_ASSERT(days == 365 || days == 366);
3144
3145 // Leap years have 366 days.
3146 inLeapYear = days == 366;
3147 break;
3148 }
3149
3150 case CalendarId::Islamic:
3151 case CalendarId::IslamicCivil:
3152 case CalendarId::IslamicRGSA:
3153 case CalendarId::IslamicTabular:
3154 case CalendarId::IslamicUmmAlQura: {
3155 MOZ_ASSERT(!CalendarHasLeapMonths(calendarId));
3156
3157 // Lunar Islamic calendars have either 354 or 355 days per year.
3158 //
3159 // Allow 353 days to workaround
3160 // <https://github.com/unicode-org/icu4x/issues/4930>.
3161 int32_t days = DaysInYear(dt.get());
3162 MOZ_ASSERT(days == 353 || days == 354 || days == 355);
3163
3164 // Leap years have 355 days.
3165 inLeapYear = days == 355;
3166 break;
3167 }
3168
3169 case CalendarId::Chinese:
3170 case CalendarId::Dangi:
3171 case CalendarId::Hebrew: {
3172 MOZ_ASSERT(CalendarHasLeapMonths(calendarId));
3173
3174 // Calendars with separate leap months have either 12 or 13 months per
3175 // year.
3176 int32_t months = MonthsInYear(dt.get());
3177 MOZ_ASSERT(months == 12 || months == 13);
3178
3179 // Leap years have 13 months.
3180 inLeapYear = months == 13;
3181 break;
3182 }
3183 }
3184
3185 result.setBoolean(inLeapYear);
3186 return true;
3187 }
3188
3189 enum class DateFieldType { Date, YearMonth, MonthDay };
3190
3191 /**
3192 * ISODateToFields ( calendar, isoDate, type )
3193 */
3194 static bool ISODateToFields(JSContext* cx, Handle<CalendarValue> calendar,
3195 const ISODate& date, DateFieldType type,
3196 MutableHandle<CalendarFields> result) {
3197 auto calendarId = calendar.identifier();
3198
3199 // Step 1.
3200 result.set(CalendarFields{});
3201
3202 // Steps 2-6. (Optimization for the ISO 8601 calendar.)
3203 if (calendarId == CalendarId::ISO8601) {
3204 // Step 2. (Not applicable in our implementation.)
3205
3206 // Step 3.
3207 result.setMonthCode(MonthCode{date.month});
3208
3209 // Step 4.
3210 if (type == DateFieldType::MonthDay || type == DateFieldType::Date) {
3211 result.setDay(date.day);
3212 }
3213
3214 // Step 5.
3215 if (type == DateFieldType::YearMonth || type == DateFieldType::Date) {
3216 result.setYear(date.year);
3217 }
3218
3219 // Step 6.
3220 return true;
3221 }
3222
3223 // Step 2.
3224 auto cal = CreateICU4XCalendar(cx, calendarId);
3225 if (!cal) {
3226 return false;
3227 }
3228
3229 auto dt = CreateICU4XDate(cx, date, calendarId, cal.get());
3230 if (!dt) {
3231 return false;
3232 }
3233
3234 // Step 3.
3235 MonthCode monthCode;
3236 if (!CalendarDateMonthCode(cx, calendarId, dt.get(), &monthCode)) {
3237 return false;
3238 }
3239 result.setMonthCode(monthCode);
3240
3241 // Step 4.
3242 if (type == DateFieldType::MonthDay || type == DateFieldType::Date) {
3243 int32_t day = DayOfMonth(calendarId, dt.get());
3244 result.setDay(day);
3245 }
3246
3247 // Step 5.
3248 if (type == DateFieldType::YearMonth || type == DateFieldType::Date) {
3249 int32_t year;
3250 if (!CalendarDateYear(cx, calendarId, dt.get(), &year)) {
3251 return false;
3252 }
3253 result.setYear(year);
3254 }
3255
3256 // Step 6.
3257 return true;
3258 }
3259
3260 /**
3261 * ISODateToFields ( calendar, isoDate, type )
3262 */
3263 bool js::temporal::ISODateToFields(JSContext* cx, Handle<PlainDate> date,
3264 MutableHandle<CalendarFields> result) {
3265 return ISODateToFields(cx, date.calendar(), date, DateFieldType::Date,
3266 result);
3267 }
3268
3269 /**
3270 * ISODateToFields ( calendar, isoDate, type )
3271 */
3272 bool js::temporal::ISODateToFields(JSContext* cx,
3273 Handle<PlainDateTime> dateTime,
3274 MutableHandle<CalendarFields> result) {
3275 return ISODateToFields(cx, dateTime.calendar(), dateTime.date(),
3276 DateFieldType::Date, result);
3277 }
3278
3279 /**
3280 * ISODateToFields ( calendar, isoDate, type )
3281 */
3282 bool js::temporal::ISODateToFields(JSContext* cx,
3283 Handle<PlainMonthDay> monthDay,
3284 MutableHandle<CalendarFields> result) {
3285 return ISODateToFields(cx, monthDay.calendar(), monthDay.date(),
3286 DateFieldType::MonthDay, result);
3287 }
3288
3289 /**
3290 * ISODateToFields ( calendar, isoDate, type )
3291 */
3292 bool js::temporal::ISODateToFields(JSContext* cx,
3293 Handle<PlainYearMonth> yearMonth,
3294 MutableHandle<CalendarFields> result) {
3295 return ISODateToFields(cx, yearMonth.calendar(), yearMonth.date(),
3296 DateFieldType::YearMonth, result);
3297 }
3298
3299 /**
3300 * CalendarDateFromFields ( calendar, fields, overflow )
3301 */
3302 bool js::temporal::CalendarDateFromFields(JSContext* cx,
3303 Handle<CalendarValue> calendar,
3304 Handle<CalendarFields> fields,
3305 TemporalOverflow overflow,
3306 MutableHandle<PlainDate> result) {
3307 auto calendarId = calendar.identifier();
3308
3309 // Step 1.
3310 if (!CalendarResolveFields(cx, calendarId, fields, FieldType::Date)) {
3311 return false;
3312 }
3313
3314 // Step 2.
3315 ISODate date;
3316 if (!CalendarDateToISO(cx, calendarId, fields, overflow, &date)) {
3317 return false;
3318 }
3319
3320 // Steps 3-4.
3321 return CreateTemporalDate(cx, date, calendar, result);
3322 }
3323
3324 /**
3325 * CalendarYearMonthFromFields ( calendar, fields, overflow )
3326 */
3327 bool js::temporal::CalendarYearMonthFromFields(
3328 JSContext* cx, Handle<CalendarValue> calendar,
3329 Handle<CalendarFields> fields, TemporalOverflow overflow,
3330 MutableHandle<PlainYearMonth> result) {
3331 auto calendarId = calendar.identifier();
3332
3333 // Step 1.
3334 if (!CalendarResolveFields(cx, calendarId, fields, FieldType::YearMonth)) {
3335 return false;
3336 }
3337
3338 // Step 2.
3339 int32_t firstDayIndex = 1;
3340
3341 // Step 3.
3342 Rooted<CalendarFields> resolvedFields(cx, CalendarFields{fields});
3343 resolvedFields.setDay(firstDayIndex);
3344
3345 // Step 4.
3346 ISODate date;
3347 if (!CalendarDateToISO(cx, calendarId, resolvedFields, overflow, &date)) {
3348 return false;
3349 }
3350
3351 // Steps 5-6.
3352 return CreateTemporalYearMonth(cx, date, calendar, result);
3353 }
3354
3355 /**
3356 * CalendarMonthDayFromFields ( calendar, fields, overflow )
3357 */
3358 bool js::temporal::CalendarMonthDayFromFields(
3359 JSContext* cx, Handle<CalendarValue> calendar,
3360 Handle<CalendarFields> fields, TemporalOverflow overflow,
3361 MutableHandle<PlainMonthDay> result) {
3362 auto calendarId = calendar.identifier();
3363
3364 // Step 1.
3365 if (!CalendarResolveFields(cx, calendarId, fields, FieldType::MonthDay)) {
3366 return false;
3367 }
3368
3369 // Step 2.
3370 ISODate date;
3371 if (!CalendarMonthDayToISOReferenceDate(cx, calendarId, fields, overflow,
3372 &date)) {
3373 return false;
3374 }
3375
3376 // Step 3-4.
3377 return CreateTemporalMonthDay(cx, date, calendar, result);
3378 }
3379
3380 /**
3381 * Mathematical Operations, "modulo" notation.
3382 */
3383 static int32_t NonNegativeModulo(int64_t x, int32_t y) {
3384 MOZ_ASSERT(y > 0);
3385
3386 int32_t result = mozilla::AssertedCast<int32_t>(x % y);
3387 return (result < 0) ? (result + y) : result;
3388 }
3389
3390 /**
3391 * RegulateISODate ( year, month, day, overflow )
3392 *
3393 * With |overflow = "constrain"|.
3394 */
3395 static ISODate ConstrainISODate(const ISODate& date) {
3396 const auto& [year, month, day] = date;
3397
3398 // Step 1.a.
3399 int32_t m = std::clamp(month, 1, 12);
3400
3401 // Step 1.b.
3402 int32_t daysInMonth = ::ISODaysInMonth(year, m);
3403
3404 // Step 1.c.
3405 int32_t d = std::clamp(day, 1, daysInMonth);
3406
3407 // Step 3.
3408 return {year, m, d};
3409 }
3410
3411 /**
3412 * RegulateISODate ( year, month, day, overflow )
3413 */
3414 static bool RegulateISODate(JSContext* cx, const ISODate& date,
3415 TemporalOverflow overflow, ISODate* result) {
3416 // Step 1.
3417 if (overflow == TemporalOverflow::Constrain) {
3418 // Steps 1.a-c and 3.
3419 *result = ConstrainISODate(date);
3420 return true;
3421 }
3422
3423 // Step 2.a.
3424 MOZ_ASSERT(overflow == TemporalOverflow::Reject);
3425
3426 // Step 2.b.
3427 if (!ThrowIfInvalidISODate(cx, date)) {
3428 return false;
3429 }
3430
3431 // Step 3. (Inlined call to CreateISODateRecord.)
3432 *result = date;
3433 return true;
3434 }
3435
3436 struct BalancedYearMonth final {
3437 int64_t year = 0;
3438 int32_t month = 0;
3439 };
3440
3441 /**
3442 * BalanceISOYearMonth ( year, month )
3443 */
3444 static BalancedYearMonth BalanceISOYearMonth(int64_t year, int64_t month) {
3445 MOZ_ASSERT(std::abs(year) < (int64_t(1) << 33),
3446 "year is the addition of plain-date year with duration years");
3447 MOZ_ASSERT(std::abs(month) < (int64_t(1) << 33),
3448 "month is the addition of plain-date month with duration months");
3449
3450 // Step 1. (Not applicable in our implementation.)
3451
3452 // Step 2.
3453 int64_t balancedYear = year + temporal::FloorDiv(month - 1, 12);
3454
3455 // Step 3.
3456 int32_t balancedMonth = NonNegativeModulo(month - 1, 12) + 1;
3457 MOZ_ASSERT(1 <= balancedMonth && balancedMonth <= 12);
3458
3459 // Step 4.
3460 return {balancedYear, balancedMonth};
3461 }
3462
3463 static BalancedYearMonth BalanceYearMonth(int64_t year, int64_t month,
3464 int32_t monthsPerYear) {
3465 MOZ_ASSERT(std::abs(year) < (int64_t(1) << 33),
3466 "year is the addition of plain-date year with duration years");
3467 MOZ_ASSERT(std::abs(month) < (int64_t(1) << 33),
3468 "month is the addition of plain-date month with duration months");
3469
3470 int64_t balancedYear = year + temporal::FloorDiv(month - 1, monthsPerYear);
3471
3472 int32_t balancedMonth = NonNegativeModulo(month - 1, monthsPerYear) + 1;
3473 MOZ_ASSERT(1 <= balancedMonth && balancedMonth <= monthsPerYear);
3474
3475 return {balancedYear, balancedMonth};
3476 }
3477
3478 /**
3479 * CalendarDateAdd ( calendar, isoDate, duration, overflow )
3480 */
3481 static bool AddISODate(JSContext* cx, const ISODate& isoDate,
3482 const DateDuration& duration, TemporalOverflow overflow,
3483 ISODate* result) {
3484 MOZ_ASSERT(ISODateWithinLimits(isoDate));
3485 MOZ_ASSERT(IsValidDuration(duration));
3486
3487 // Step 1.a.
3488 auto yearMonth = BalanceISOYearMonth(isoDate.year + duration.years,
3489 isoDate.month + duration.months);
3490 MOZ_ASSERT(1 <= yearMonth.month && yearMonth.month <= 12);
3491
3492 auto balancedYear = mozilla::CheckedInt<int32_t>(yearMonth.year);
3493 if (!balancedYear.isValid()) {
3494 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3495 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3496 return false;
3497 }
3498
3499 // Step 1.b.
3500 ISODate regulated;
3501 if (!RegulateISODate(cx, {balancedYear.value(), yearMonth.month, isoDate.day},
3502 overflow, &regulated)) {
3503 return false;
3504 }
3505 if (!ISODateWithinLimits(regulated)) {
3506 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3507 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3508 return false;
3509 }
3510
3511 // Step 1.c.
3512 int64_t days = duration.days + duration.weeks * 7;
3513
3514 // Step 1.d.
3515 ISODate balanced;
3516 if (!BalanceISODate(cx, regulated, days, &balanced)) {
3517 return false;
3518 }
3519 MOZ_ASSERT(IsValidISODate(balanced));
3520
3521 *result = balanced;
3522 return true;
3523 }
3524
3525 struct CalendarDate {
3526 int32_t year = 0;
3527 MonthCode monthCode = {};
3528 int32_t day = 0;
3529 };
3530
3531 /**
3532 * CompareISODate adjusted for calendar dates.
3533 */
3534 static int32_t CompareCalendarDate(const CalendarDate& one,
3535 const CalendarDate& two) {
3536 if (one.year != two.year) {
3537 return one.year < two.year ? -1 : 1;
3538 }
3539 if (one.monthCode != two.monthCode) {
3540 return one.monthCode < two.monthCode ? -1 : 1;
3541 }
3542 if (one.day != two.day) {
3543 return one.day < two.day ? -1 : 1;
3544 }
3545 return 0;
3546 }
3547
3548 static bool ToCalendarDate(JSContext* cx, CalendarId calendarId,
3549 const capi::ICU4XDate* dt, CalendarDate* result) {
3550 int32_t year;
3551 if (!CalendarDateYear(cx, calendarId, dt, &year)) {
3552 return false;
3553 }
3554
3555 MonthCode monthCode;
3556 if (!CalendarDateMonthCode(cx, calendarId, dt, &monthCode)) {
3557 return false;
3558 }
3559
3560 int32_t day = DayOfMonth(calendarId, dt);
3561
3562 *result = {year, monthCode, day};
3563 return true;
3564 }
3565
3566 /**
3567 * Store a calendar date in a |ISODate| struct when leap months don't matter.
3568 */
3569 static bool ToCalendarDate(JSContext* cx, CalendarId calendarId,
3570 const capi::ICU4XDate* dt, ISODate* result) {
3571 MOZ_ASSERT(!CalendarHasLeapMonths(calendarId));
3572
3573 int32_t year;
3574 if (!CalendarDateYear(cx, calendarId, dt, &year)) {
3575 return false;
3576 }
3577
3578 int32_t month = OrdinalMonth(calendarId, dt);
3579 int32_t day = DayOfMonth(calendarId, dt);
3580
3581 *result = {year, month, day};
3582 return true;
3583 }
3584
3585 static bool AddYearMonthDuration(JSContext* cx, CalendarId calendarId,
3586 const ISODate& calendarDate,
3587 const DateDuration& duration,
3588 CalendarDate* result) {
3589 MOZ_ASSERT(!CalendarHasLeapMonths(calendarId));
3590 MOZ_ASSERT(IsValidDuration(duration));
3591
3592 auto [year, month, day] = calendarDate;
3593
3594 // Months per year are fixed, so we can directly compute the final number of
3595 // years.
3596 auto yearMonth =
3597 BalanceYearMonth(year + duration.years, month + duration.months,
3598 CalendarMonthsPerYear(calendarId));
3599
3600 auto balancedYear = mozilla::CheckedInt<int32_t>(yearMonth.year);
3601 if (!balancedYear.isValid()) {
3602 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3603 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3604 return false;
3605 }
3606
3607 *result = {balancedYear.value(), MonthCode{yearMonth.month}, day};
3608 return true;
3609 }
3610
3611 static bool AddYearMonthDuration(JSContext* cx, CalendarId calendarId,
3612 const capi::ICU4XCalendar* calendar,
3613 const CalendarDate& calendarDate,
3614 const DateDuration& duration,
3615 CalendarDate* result) {
3616 MOZ_ASSERT(CalendarHasLeapMonths(calendarId));
3617 MOZ_ASSERT(IsValidDuration(duration));
3618
3619 auto [year, monthCode, day] = calendarDate;
3620
3621 // Add all duration years.
3622 auto durationYear = mozilla::CheckedInt<int32_t>(year) + duration.years;
3623 if (!durationYear.isValid()) {
3624 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3625 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3626 return false;
3627 }
3628 year = durationYear.value();
3629
3630 // Months per year are variable, so we have construct a new date for each
3631 // year to balance the years and months.
3632 int64_t months = duration.months;
3633 if (months != 0) {
3634 auto eraYear = CalendarEraYear(calendarId, year);
3635 auto firstDayOfMonth =
3636 CreateDateFromCodes(cx, calendarId, calendar, eraYear, monthCode, 1,
3637 TemporalOverflow::Constrain);
3638 if (!firstDayOfMonth) {
3639 return false;
3640 }
3641
3642 if (months > 0) {
3643 while (true) {
3644 // Check if adding |months| is still in the current year.
3645 int32_t month = OrdinalMonth(calendarId, firstDayOfMonth.get());
3646 int32_t monthsInYear = MonthsInYear(firstDayOfMonth.get());
3647 if (month + months <= monthsInYear) {
3648 break;
3649 }
3650
3651 // We've crossed a year boundary. Increase |year| and adjust |months|.
3652 year += 1;
3653 months -= (monthsInYear - month + 1);
3654
3655 // Restart the loop with the first month of the next year.
3656 eraYear = CalendarEraYear(calendarId, year);
3657 firstDayOfMonth = CreateDateFrom(cx, calendarId, calendar, eraYear, 1,
3658 1, TemporalOverflow::Constrain);
3659 if (!firstDayOfMonth) {
3660 return false;
3661 }
3662 }
3663 } else {
3664 int32_t monthsPerYear = CalendarMonthsPerYear(calendarId);
3665
3666 while (true) {
3667 // Check if subtracting |months| is still in the current year.
3668 int32_t month = OrdinalMonth(calendarId, firstDayOfMonth.get());
3669 if (month + months >= 1) {
3670 break;
3671 }
3672
3673 // We've crossed a year boundary. Decrease |year| and adjust |months|.
3674 year -= 1;
3675 months += month;
3676
3677 // Restart the loop with the last month of the previous year.
3678 eraYear = CalendarEraYear(calendarId, year);
3679 firstDayOfMonth =
3680 CreateDateFrom(cx, calendarId, calendar, eraYear, monthsPerYear, 1,
3681 TemporalOverflow::Constrain);
3682 if (!firstDayOfMonth) {
3683 return false;
3684 }
3685 }
3686 }
3687
3688 // Compute the actual month to find the correct month code.
3689 int32_t month = OrdinalMonth(calendarId, firstDayOfMonth.get()) + months;
3690 firstDayOfMonth = CreateDateFrom(cx, calendarId, calendar, eraYear, month,
3691 1, TemporalOverflow::Constrain);
3692 if (!firstDayOfMonth) {
3693 return false;
3694 }
3695
3696 if (!CalendarDateMonthCode(cx, calendarId, firstDayOfMonth.get(),
3697 &monthCode)) {
3698 return false;
3699 }
3700 }
3701
3702 *result = {year, monthCode, day};
3703 return true;
3704 }
3705
3706 static bool AddNonISODate(JSContext* cx, CalendarId calendarId,
3707 const ISODate& isoDate, const DateDuration& duration,
3708 TemporalOverflow overflow, ISODate* result) {
3709 MOZ_ASSERT(ISODateWithinLimits(isoDate));
3710 MOZ_ASSERT(IsValidDuration(duration));
3711
3712 auto cal = CreateICU4XCalendar(cx, calendarId);
3713 if (!cal) {
3714 return false;
3715 }
3716
3717 auto dt = CreateICU4XDate(cx, isoDate, calendarId, cal.get());
3718 if (!dt) {
3719 return false;
3720 }
3721
3722 CalendarDate calendarDate;
3723 if (!CalendarHasLeapMonths(calendarId)) {
3724 ISODate date;
3725 if (!ToCalendarDate(cx, calendarId, dt.get(), &date)) {
3726 return false;
3727 }
3728 if (!AddYearMonthDuration(cx, calendarId, date, duration, &calendarDate)) {
3729 return false;
3730 }
3731 } else {
3732 CalendarDate date;
3733 if (!ToCalendarDate(cx, calendarId, dt.get(), &date)) {
3734 return false;
3735 }
3736 if (!AddYearMonthDuration(cx, calendarId, cal.get(), date, duration,
3737 &calendarDate)) {
3738 return false;
3739 }
3740 }
3741
3742 // Regulate according to |overflow|.
3743 auto eraYear = CalendarEraYear(calendarId, calendarDate.year);
3744 auto regulated =
3745 CreateDateFromCodes(cx, calendarId, cal.get(), eraYear,
3746 calendarDate.monthCode, calendarDate.day, overflow);
3747 if (!regulated) {
3748 return false;
3749 }
3750
3751 // Compute the corresponding ISO date.
3752 auto regulatedIso = ToISODate(regulated.get());
3753 if (!ISODateWithinLimits(regulatedIso)) {
3754 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3755 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3756 return false;
3757 }
3758
3759 // Add duration days and weeks.
3760 int64_t days = duration.days + duration.weeks * 7;
3761
3762 // Adding days isn't calendar-specific, so we can use BalanceISODate.
3763 ISODate balancedIso;
3764 if (!BalanceISODate(cx, regulatedIso, days, &balancedIso)) {
3765 return false;
3766 }
3767 MOZ_ASSERT(IsValidISODate(balancedIso));
3768
3769 *result = balancedIso;
3770 return true;
3771 }
3772
3773 static bool AddCalendarDate(JSContext* cx, CalendarId calendarId,
3774 const ISODate& isoDate,
3775 const DateDuration& duration,
3776 TemporalOverflow overflow, ISODate* result) {
3777 // ICU4X doesn't yet provide a public API for CalendarDateAdd.
3778 //
3779 // https://github.com/unicode-org/icu4x/issues/3964
3780
3781 // If neither |years| nor |months| are present, just delegate to the ISO 8601
3782 // calendar version. This works because all supported calendars use a 7-days
3783 // week.
3784 if (duration.years == 0 && duration.months == 0) {
3785 return AddISODate(cx, isoDate, duration, overflow, result);
3786 }
3787
3788 switch (calendarId) {
3789 case CalendarId::ISO8601:
3790 case CalendarId::Buddhist:
3791 case CalendarId::Gregorian:
3792 case CalendarId::Japanese:
3793 case CalendarId::ROC:
3794 // Use the ISO 8601 calendar if the calendar system starts its year at the
3795 // same time as the ISO 8601 calendar and all months exactly match the
3796 // ISO 8601 calendar months.
3797 return AddISODate(cx, isoDate, duration, overflow, result);
3798
3799 case CalendarId::Chinese:
3800 case CalendarId::Coptic:
3801 case CalendarId::Dangi:
3802 case CalendarId::Ethiopian:
3803 case CalendarId::EthiopianAmeteAlem:
3804 case CalendarId::Hebrew:
3805 case CalendarId::Indian:
3806 case CalendarId::Islamic:
3807 case CalendarId::IslamicCivil:
3808 case CalendarId::IslamicRGSA:
3809 case CalendarId::IslamicTabular:
3810 case CalendarId::IslamicUmmAlQura:
3811 case CalendarId::Persian:
3812 return AddNonISODate(cx, calendarId, isoDate, duration, overflow, result);
3813 }
3814 MOZ_CRASH("invalid calendar id");
3815 }
3816
3817 /**
3818 * CalendarDateAdd ( calendar, isoDate, duration, overflow )
3819 */
3820 bool js::temporal::CalendarDateAdd(JSContext* cx,
3821 Handle<CalendarValue> calendar,
3822 const ISODate& isoDate,
3823 const DateDuration& duration,
3824 TemporalOverflow overflow, ISODate* result) {
3825 MOZ_ASSERT(ISODateWithinLimits(isoDate));
3826 MOZ_ASSERT(IsValidDuration(duration));
3827
3828 auto calendarId = calendar.identifier();
3829
3830 // Steps 1-2.
3831 if (calendarId == CalendarId::ISO8601) {
3832 if (!AddISODate(cx, isoDate, duration, overflow, result)) {
3833 return false;
3834 }
3835 } else {
3836 if (!AddCalendarDate(cx, calendarId, isoDate, duration, overflow, result)) {
3837 return false;
3838 }
3839 }
3840
3841 // Step 3.
3842 if (!ISODateWithinLimits(*result)) {
3843 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3844 JSMSG_TEMPORAL_PLAIN_DATE_INVALID);
3845 return false;
3846 }
3847
3848 // Step 4.
3849 return true;
3850 }
3851
3852 /**
3853 * CalendarDateUntil ( calendar, one, two, largestUnit )
3854 */
3855 static DateDuration DifferenceISODate(const ISODate& one, const ISODate& two,
3856 TemporalUnit largestUnit) {
3857 MOZ_ASSERT(IsValidISODate(one));
3858 MOZ_ASSERT(IsValidISODate(two));
3859
3860 // Both inputs are also within the date limits.
3861 MOZ_ASSERT(ISODateWithinLimits(one));
3862 MOZ_ASSERT(ISODateWithinLimits(two));
3863
3864 MOZ_ASSERT(TemporalUnit::Year <= largestUnit &&
3865 largestUnit <= TemporalUnit::Day);
3866
3867 // Step 1.a.
3868 int32_t sign = -CompareISODate(one, two);
3869
3870 // Step 1.b.
3871 if (sign == 0) {
3872 return {};
3873 }
3874
3875 // Step 1.c.
3876 int32_t years = 0;
3877
3878 // Step 1.e. (Reordered)
3879 int32_t months = 0;
3880
3881 // Steps 1.d and 1.f.
3882 if (largestUnit == TemporalUnit::Year || largestUnit == TemporalUnit::Month) {
3883 years = two.year - one.year;
3884 months = two.month - one.month;
3885
3886 auto intermediate = ISODate{one.year + years, one.month, one.day};
3887 if (CompareISODate(intermediate, two) * sign > 0) {
3888 years -= sign;
3889 months += 12 * sign;
3890 }
3891
3892 intermediate = ISODate{one.year + years, one.month + months, one.day};
3893 if (intermediate.month > 12) {
3894 intermediate.month -= 12;
3895 intermediate.year += 1;
3896 } else if (intermediate.month < 1) {
3897 intermediate.month += 12;
3898 intermediate.year -= 1;
3899 }
3900 if (CompareISODate(intermediate, two) * sign > 0) {
3901 months -= sign;
3902 }
3903
3904 if (largestUnit == TemporalUnit::Month) {
3905 months += years * 12;
3906 years = 0;
3907 }
3908 }
3909
3910 // Step 1.g.
3911 auto intermediate = BalanceISOYearMonth(one.year + years, one.month + months);
3912
3913 // Step 1.h.
3914 auto constrained = ConstrainISODate(
3915 ISODate{int32_t(intermediate.year), intermediate.month, one.day});
3916
3917 // Step 1.i.
3918 int64_t weeks = 0;
3919
3920 // Steps 1.k-n.
3921 int64_t days = MakeDay(two) - MakeDay(constrained);
3922
3923 // Step 1.j. (Reordered)
3924 if (largestUnit == TemporalUnit::Week) {
3925 weeks = days / 7;
3926 days %= 7;
3927 }
3928
3929 // Step 1.o.
3930 auto result = DateDuration{
3931 int64_t(years),
3932 int64_t(months),
3933 int64_t(weeks),
3934 int64_t(days),
3935 };
3936 MOZ_ASSERT(IsValidDuration(result));
3937 return result;
3938 }
3939
3940 static bool DifferenceNonISODate(JSContext* cx, CalendarId calendarId,
3941 const ISODate& one, const ISODate& two,
3942 TemporalUnit largestUnit,
3943 DateDuration* result) {
3944 // Both inputs are also within the date limits.
3945 MOZ_ASSERT(ISODateWithinLimits(one));
3946 MOZ_ASSERT(ISODateWithinLimits(two));
3947
3948 MOZ_ASSERT(TemporalUnit::Year <= largestUnit &&
3949 largestUnit <= TemporalUnit::Month);
3950
3951 if (one == two) {
3952 *result = {};
3953 return true;
3954 }
3955
3956 auto cal = CreateICU4XCalendar(cx, calendarId);
3957 if (!cal) {
3958 return false;
3959 }
3960
3961 auto dtOne = CreateICU4XDate(cx, one, calendarId, cal.get());
3962 if (!dtOne) {
3963 return false;
3964 }
3965
3966 auto dtTwo = CreateICU4XDate(cx, two, calendarId, cal.get());
3967 if (!dtTwo) {
3968 return false;
3969 }
3970
3971 int32_t years = 0;
3972 int32_t months = 0;
3973
3974 ISODate constrainedIso;
3975 if (!CalendarHasLeapMonths(calendarId)) {
3976 // If the months per year are fixed, we can use a modified DifferenceISODate
3977 // implementation to compute the date duration.
3978 int32_t monthsPerYear = CalendarMonthsPerYear(calendarId);
3979
3980 ISODate oneDate;
3981 if (!ToCalendarDate(cx, calendarId, dtOne.get(), &oneDate)) {
3982 return false;
3983 }
3984
3985 ISODate twoDate;
3986 if (!ToCalendarDate(cx, calendarId, dtTwo.get(), &twoDate)) {
3987 return false;
3988 }
3989
3990 int32_t sign = -CompareISODate(oneDate, twoDate);
3991 MOZ_ASSERT(sign != 0);
3992
3993 years = twoDate.year - oneDate.year;
3994 months = twoDate.month - oneDate.month;
3995
3996 // If |oneDate + years| surpasses |twoDate|, reduce |years| by one and add
3997 // |monthsPerYear| to |months|. The next step will balance the intermediate
3998 // result.
3999 auto intermediate =
4000 ISODate{oneDate.year + years, oneDate.month, oneDate.day};
4001 if (CompareISODate(intermediate, twoDate) * sign > 0) {
4002 years -= sign;
4003 months += monthsPerYear * sign;
4004 }
4005
4006 // Add both |years| and |months| and then balance the intermediate result to
4007 // ensure its month is within the valid bounds.
4008 intermediate =
4009 ISODate{oneDate.year + years, oneDate.month + months, oneDate.day};
4010 if (intermediate.month > monthsPerYear) {
4011 intermediate.month -= monthsPerYear;
4012 intermediate.year += 1;
4013 } else if (intermediate.month < 1) {
4014 intermediate.month += monthsPerYear;
4015 intermediate.year -= 1;
4016 }
4017
4018 // If |intermediate| surpasses |twoDate|, reduce |month| by one.
4019 if (CompareISODate(intermediate, twoDate) * sign > 0) {
4020 months -= sign;
4021 }
4022
4023 // Convert years to months if necessary.
4024 if (largestUnit == TemporalUnit::Month) {
4025 months += years * monthsPerYear;
4026 years = 0;
4027 }
4028
4029 // Constrain to a proper date.
4030 auto balanced = BalanceYearMonth(oneDate.year + years,
4031 oneDate.month + months, monthsPerYear);
4032
4033 auto eraYear = CalendarEraYear(calendarId, balanced.year);
4034 auto constrained =
4035 CreateDateFrom(cx, calendarId, cal.get(), eraYear, balanced.month,
4036 oneDate.day, TemporalOverflow::Constrain);
4037 if (!constrained) {
4038 return false;
4039 }
4040 constrainedIso = ToISODate(constrained.get());
4041
4042 MOZ_ASSERT(CompareISODate(constrainedIso, two) * sign <= 0,
4043 "constrained doesn't surpass two");
4044 } else {
4045 CalendarDate oneDate;
4046 if (!ToCalendarDate(cx, calendarId, dtOne.get(), &oneDate)) {
4047 return false;
4048 }
4049
4050 CalendarDate twoDate;
4051 if (!ToCalendarDate(cx, calendarId, dtTwo.get(), &twoDate)) {
4052 return false;
4053 }
4054
4055 int32_t sign = -CompareCalendarDate(oneDate, twoDate);
4056 MOZ_ASSERT(sign != 0);
4057
4058 years = twoDate.year - oneDate.year;
4059
4060 // If |oneDate + years| surpasses |twoDate|, reduce |years| by one and add
4061 // |monthsPerYear| to |months|. The next step will balance the intermediate
4062 // result.
4063 auto eraYear = CalendarEraYear(calendarId, oneDate.year + years);
4064 auto constrained = CreateDateFromCodes(cx, calendarId, cal.get(), eraYear,
4065 oneDate.monthCode, oneDate.day,
4066 TemporalOverflow::Constrain);
4067 if (!constrained) {
4068 return false;
4069 }
4070
4071 CalendarDate constrainedDate;
4072 if (!ToCalendarDate(cx, calendarId, constrained.get(), &constrainedDate)) {
4073 return false;
4074 }
4075
4076 if (CompareCalendarDate(constrainedDate, twoDate) * sign > 0) {
4077 years -= sign;
4078 }
4079
4080 // Add as many months as possible without surpassing |twoDate|.
4081 while (true) {
4082 CalendarDate intermediateDate;
4083 if (!AddYearMonthDuration(cx, calendarId, cal.get(), oneDate,
4084 {years, months + sign}, &intermediateDate)) {
4085 return false;
4086 }
4087 if (CompareCalendarDate(intermediateDate, twoDate) * sign > 0) {
4088 break;
4089 }
4090 months += sign;
4091 constrainedDate = intermediateDate;
4092 }
4093 MOZ_ASSERT(std::abs(months) < CalendarMonthsPerYear(calendarId));
4094
4095 // Convert years to months if necessary.
4096 if (largestUnit == TemporalUnit::Month && years != 0) {
4097 auto monthsUntilEndOfYear = [calendarId](const capi::ICU4XDate* date) {
4098 int32_t month = OrdinalMonth(calendarId, date);
4099 int32_t monthsInYear = MonthsInYear(date);
4100 MOZ_ASSERT(1 <= month && month <= monthsInYear);
4101
4102 return monthsInYear - month + 1;
4103 };
4104
4105 auto monthsSinceStartOfYear = [calendarId](const capi::ICU4XDate* date) {
4106 return OrdinalMonth(calendarId, date) - 1;
4107 };
4108
4109 // Add months until end of year resp. since start of year.
4110 if (sign > 0) {
4111 months += monthsUntilEndOfYear(dtOne.get());
4112 } else {
4113 months -= monthsSinceStartOfYear(dtOne.get());
4114 }
4115
4116 // Months in full year.
4117 for (int32_t y = sign; y != years; y += sign) {
4118 auto eraYear = CalendarEraYear(calendarId, oneDate.year + y);
4119 auto dt =
4120 CreateDateFromCodes(cx, calendarId, cal.get(), eraYear,
4121 MonthCode{1}, 1, TemporalOverflow::Constrain);
4122 if (!dt) {
4123 return false;
4124 }
4125 months += MonthsInYear(dt.get()) * sign;
4126 }
4127
4128 // Add months since start of year resp. until end of year.
4129 auto eraYear = CalendarEraYear(calendarId, oneDate.year + years);
4130 auto dt = CreateDateFromCodes(cx, calendarId, cal.get(), eraYear,
4131 oneDate.monthCode, 1,
4132 TemporalOverflow::Constrain);
4133 if (!dt) {
4134 return false;
4135 }
4136 if (sign > 0) {
4137 months += monthsSinceStartOfYear(dt.get());
4138 } else {
4139 months -= monthsUntilEndOfYear(dt.get());
4140 }
4141
4142 years = 0;
4143 }
4144
4145 eraYear = CalendarEraYear(calendarId, constrainedDate.year);
4146 constrained = CreateDateFromCodes(
4147 cx, calendarId, cal.get(), eraYear, constrainedDate.monthCode,
4148 constrainedDate.day, TemporalOverflow::Constrain);
4149 if (!constrained) {
4150 return false;
4151 }
4152 constrainedIso = ToISODate(constrained.get());
4153
4154 MOZ_ASSERT(CompareISODate(constrainedIso, two) * sign <= 0,
4155 "constrained doesn't surpass two");
4156 }
4157
4158 int64_t days = MakeDay(two) - MakeDay(constrainedIso);
4159
4160 *result = DateDuration{
4161 int64_t(years),
4162 int64_t(months),
4163 0,
4164 int64_t(days),
4165 };
4166 MOZ_ASSERT(IsValidDuration(*result));
4167 return true;
4168 }
4169
4170 static bool DifferenceCalendarDate(JSContext* cx, CalendarId calendarId,
4171 const ISODate& one, const ISODate& two,
4172 TemporalUnit largestUnit,
4173 DateDuration* result) {
4174 // ICU4X doesn't yet provide a public API for CalendarDateUntil.
4175 //
4176 // https://github.com/unicode-org/icu4x/issues/3964
4177
4178 // Delegate to the ISO 8601 calendar for "weeks" and "days". This works
4179 // because all supported calendars use a 7-days week.
4180 if (largestUnit >= TemporalUnit::Week) {
4181 *result = DifferenceISODate(one, two, largestUnit);
4182 return true;
4183 }
4184
4185 switch (calendarId) {
4186 case CalendarId::ISO8601:
4187 case CalendarId::Buddhist:
4188 case CalendarId::Gregorian:
4189 case CalendarId::Japanese:
4190 case CalendarId::ROC:
4191 // Use the ISO 8601 calendar if the calendar system starts its year at the
4192 // same time as the ISO 8601 calendar and all months exactly match the
4193 // ISO 8601 calendar months.
4194 *result = DifferenceISODate(one, two, largestUnit);
4195 return true;
4196
4197 case CalendarId::Chinese:
4198 case CalendarId::Coptic:
4199 case CalendarId::Dangi:
4200 case CalendarId::Ethiopian:
4201 case CalendarId::EthiopianAmeteAlem:
4202 case CalendarId::Hebrew:
4203 case CalendarId::Indian:
4204 case CalendarId::Islamic:
4205 case CalendarId::IslamicCivil:
4206 case CalendarId::IslamicRGSA:
4207 case CalendarId::IslamicTabular:
4208 case CalendarId::IslamicUmmAlQura:
4209 case CalendarId::Persian:
4210 return DifferenceNonISODate(cx, calendarId, one, two, largestUnit,
4211 result);
4212 }
4213 MOZ_CRASH("invalid calendar id");
4214 }
4215
4216 /**
4217 * CalendarDateUntil ( calendar, one, two, largestUnit )
4218 */
4219 bool js::temporal::CalendarDateUntil(JSContext* cx,
4220 Handle<CalendarValue> calendar,
4221 const ISODate& one, const ISODate& two,
4222 TemporalUnit largestUnit,
4223 DateDuration* result) {
4224 MOZ_ASSERT(largestUnit <= TemporalUnit::Day);
4225
4226 auto calendarId = calendar.identifier();
4227
4228 // Step 1.
4229 if (calendarId == CalendarId::ISO8601) {
4230 *result = DifferenceISODate(one, two, largestUnit);
4231 return true;
4232 }
4233
4234 // Step 2.
4235 return DifferenceCalendarDate(cx, calendarId, one, two, largestUnit, result);
4236 }