Debian Codegraph @

intl/components/src/calendar/ICU4XCalendar.cpp

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #include "mozilla/intl/calendar/ICU4XCalendar.h"
6
7 #include "mozilla/Assertions.h"
8 #include "mozilla/TextUtils.h"
9 #include "mozilla/intl/ICU4XGeckoDataProvider.h"
10
11 #include <cstring>
12 #include <mutex>
13 #include <stdint.h>
14 #include <type_traits>
15
16 #include "unicode/timezone.h"
17
18 #include "diplomat_runtime.h"
19 #include "ICU4XDataProvider.h"
20 #include "ICU4XError.h"
21
22 namespace mozilla::intl::calendar {
23
24 // Copied from js/src/util/Text.h
25 template <typename CharT>
26 static constexpr uint8_t AsciiDigitToNumber(CharT c) {
27 using UnsignedCharT = std::make_unsigned_t<CharT>;
28 auto uc = static_cast<UnsignedCharT>(c);
29 return uc - '0';
30 }
31
32 static UniqueICU4XCalendar CreateICU4XCalendar(
33 capi::ICU4XAnyCalendarKind kind) {
34 auto result = capi::ICU4XCalendar_create_for_kind(GetDataProvider(), kind);
35 if (!result.is_ok) {
36 return nullptr;
37 }
38 return UniqueICU4XCalendar{result.ok};
39 }
40
41 static UniqueICU4XDate CreateICU4XDate(const ISODate& date,
42 const capi::ICU4XCalendar* calendar) {
43 auto result = capi::ICU4XDate_create_from_iso_in_calendar(
44 date.year, date.month, date.day, calendar);
45 if (!result.is_ok) {
46 return nullptr;
47 }
48 return UniqueICU4XDate{result.ok};
49 }
50
51 static UniqueICU4XDate CreateDateFromCodes(const capi::ICU4XCalendar* calendar,
52 std::string_view era,
53 int32_t eraYear, MonthCode monthCode,
54 int32_t day) {
55 auto monthCodeView = std::string_view{monthCode};
56 auto date = capi::ICU4XDate_create_from_codes_in_calendar(
57 era.data(), era.length(), eraYear, monthCodeView.data(),
58 monthCodeView.length(), day, calendar);
59 if (date.is_ok) {
60 return UniqueICU4XDate{date.ok};
61 }
62 return nullptr;
63 }
64
65 // Copied from js/src/builtin/temporal/Calendar.cpp
66 static UniqueICU4XDate CreateDateFrom(const capi::ICU4XCalendar* calendar,
67 std::string_view era, int32_t eraYear,
68 int32_t month, int32_t day) {
69 MOZ_ASSERT(1 <= month && month <= 13);
70
71 // Create date with month number replaced by month-code.
72 auto monthCode = MonthCode{std::min(month, 12)};
73 auto date = CreateDateFromCodes(calendar, era, eraYear, monthCode, day);
74 if (!date) {
75 return nullptr;
76 }
77
78 // If the ordinal month of |date| matches the input month, no additional
79 // changes are necessary and we can directly return |date|.
80 int32_t ordinal = capi::ICU4XDate_ordinal_month(date.get());
81 if (ordinal == month) {
82 return date;
83 }
84
85 // Otherwise we need to handle three cases:
86 // 1. The input year contains a leap month and we need to adjust the
87 // month-code.
88 // 2. The thirteenth month of a year without leap months was requested.
89 // 3. The thirteenth month of a year with leap months was requested.
90 if (ordinal > month) {
91 MOZ_ASSERT(1 < month && month <= 12);
92
93 // This case can only happen in leap years.
94 MOZ_ASSERT(capi::ICU4XDate_months_in_year(date.get()) == 13);
95
96 // Leap months can occur after any month in the Chinese calendar.
97 //
98 // Example when the fourth month is a leap month between M03 and M04.
99 //
100 // Month code: M01 M02 M03 M03L M04 M05 M06 ...
101 // Ordinal month: 1 2 3 4 5 6 7
102
103 // The month can be off by exactly one.
104 MOZ_ASSERT((ordinal - month) == 1);
105
106 // First try the case when the previous month isn't a leap month. This
107 // case can only occur when |month > 2|, because otherwise we know that
108 // "M01L" is the correct answer.
109 if (month > 2) {
110 auto previousMonthCode = MonthCode{month - 1};
111 date =
112 CreateDateFromCodes(calendar, era, eraYear, previousMonthCode, day);
113 if (!date) {
114 return nullptr;
115 }
116 int32_t ordinal = capi::ICU4XDate_ordinal_month(date.get());
117 if (ordinal == month) {
118 return date;
119 }
120 }
121
122 // Fall-through when the previous month is a leap month.
123 } else {
124 MOZ_ASSERT(month == 13);
125 MOZ_ASSERT(ordinal == 12);
126
127 // Years with leap months contain thirteen months.
128 if (capi::ICU4XDate_months_in_year(date.get()) != 13) {
129 return nullptr;
130 }
131
132 // Fall-through to return leap month "M12L" at the end of the year.
133 }
134
135 // Finally handle the case when the previous month is a leap month.
136 auto leapMonthCode = MonthCode{month - 1, /* isLeapMonth= */ true};
137 return CreateDateFromCodes(calendar, era, eraYear, leapMonthCode, day);
138 }
139
140 static ISODate ToISODate(const capi::ICU4XDate* date) {
141 UniqueICU4XIsoDate isoDate{capi::ICU4XDate_to_iso(date)};
142
143 int32_t isoYear = capi::ICU4XIsoDate_year(isoDate.get());
144 int32_t isoMonth = capi::ICU4XIsoDate_month(isoDate.get());
145 int32_t isoDay = capi::ICU4XIsoDate_day_of_month(isoDate.get());
146
147 return {isoYear, isoMonth, isoDay};
148 }
149
150 ////////////////////////////////////////////////////////////////////////////////
151
152 ICU4XCalendar::ICU4XCalendar(capi::ICU4XAnyCalendarKind kind,
153 const icu::Locale& locale, UErrorCode& success)
154 : icu::Calendar(icu::TimeZone::forLocaleOrDefault(locale), locale, success),
155 kind_(kind) {}
156
157 ICU4XCalendar::ICU4XCalendar(capi::ICU4XAnyCalendarKind kind,
158 const icu::TimeZone& timeZone,
159 const icu::Locale& locale, UErrorCode& success)
160 : icu::Calendar(timeZone, locale, success), kind_(kind) {}
161
162 ICU4XCalendar::ICU4XCalendar(const ICU4XCalendar& other)
163 : icu::Calendar(other), kind_(other.kind_) {}
164
165 ICU4XCalendar::~ICU4XCalendar() = default;
166
167 /**
168 * Get or create the underlying ICU4X calendar.
169 */
170 capi::ICU4XCalendar* ICU4XCalendar::getICU4XCalendar(UErrorCode& status) const {
171 if (U_FAILURE(status)) {
172 return nullptr;
173 }
174 if (!calendar_) {
175 auto result = CreateICU4XCalendar(kind_);
176 if (!result) {
177 status = U_INTERNAL_PROGRAM_ERROR;
178 return nullptr;
179 }
180 calendar_ = std::move(result);
181 }
182 return calendar_.get();
183 }
184
185 /**
186 * Get or create the fallback ICU4C calendar. Used for dates outside the range
187 * supported by ICU4X.
188 */
189 icu::Calendar* ICU4XCalendar::getFallbackCalendar(UErrorCode& status) const {
190 if (U_FAILURE(status)) {
191 return nullptr;
192 }
193 if (!fallback_) {
194 icu::Locale locale = getLocale(ULOC_ACTUAL_LOCALE, status);
195 locale.setKeywordValue("calendar", getType(), status);
196 fallback_.reset(
197 icu::Calendar::createInstance(getTimeZone(), locale, status));
198 }
199 return fallback_.get();
200 }
201
202 UniqueICU4XDate ICU4XCalendar::createICU4XDate(const ISODate& date,
203 UErrorCode& status) const {
204 MOZ_ASSERT(U_SUCCESS(status));
205
206 auto* calendar = getICU4XCalendar(status);
207 if (U_FAILURE(status)) {
208 return nullptr;
209 }
210
211 auto dt = CreateICU4XDate(date, calendar);
212 if (!dt) {
213 status = U_INTERNAL_PROGRAM_ERROR;
214 }
215 return dt;
216 }
217
218 UniqueICU4XDate ICU4XCalendar::createICU4XDate(const CalendarDate& date,
219 UErrorCode& status) const {
220 MOZ_ASSERT(U_SUCCESS(status));
221
222 auto* calendar = getICU4XCalendar(status);
223 if (U_FAILURE(status)) {
224 return nullptr;
225 }
226
227 auto era = eraName(date.year);
228
229 auto dt =
230 CreateDateFromCodes(calendar, era, date.year, date.monthCode, date.day);
231 if (!dt) {
232 status = U_INTERNAL_PROGRAM_ERROR;
233 }
234 return dt;
235 }
236
237 MonthCode ICU4XCalendar::monthCodeFrom(const capi::ICU4XDate* date,
238 UErrorCode& status) {
239 MOZ_ASSERT(U_SUCCESS(status));
240
241 // Storage for the largest valid month code and the terminating NUL-character.
242 char buf[4 + 1] = {};
243 auto writable = capi::diplomat_simple_writeable(buf, std::size(buf));
244
245 if (!capi::ICU4XDate_month_code(date, &writable).is_ok) {
246 status = U_INTERNAL_PROGRAM_ERROR;
247 return {};
248 }
249
250 auto view = std::string_view{writable.buf, writable.len};
251
252 MOZ_ASSERT(view.length() >= 3);
253 MOZ_ASSERT(view[0] == 'M');
254 MOZ_ASSERT(mozilla::IsAsciiDigit(view[1]));
255 MOZ_ASSERT(mozilla::IsAsciiDigit(view[2]));
256 MOZ_ASSERT_IF(view.length() > 3, view[3] == 'L');
257
258 int32_t ordinal =
259 AsciiDigitToNumber(view[1]) * 10 + AsciiDigitToNumber(view[2]);
260 bool isLeapMonth = view.length() > 3;
261
262 return MonthCode{ordinal, isLeapMonth};
263 }
264
265 ////////////////////////////////////////////
266 // icu::Calendar implementation overrides //
267 ////////////////////////////////////////////
268
269 const char* ICU4XCalendar::getTemporalMonthCode(UErrorCode& status) const {
270 int32_t month = get(UCAL_MONTH, status);
271 int32_t isLeapMonth = get(UCAL_IS_LEAP_MONTH, status);
272 if (U_FAILURE(status)) {
273 return nullptr;
274 }
275
276 static const char* MonthCodes[] = {
277 // Non-leap months.
278 "M01",
279 "M02",
280 "M03",
281 "M04",
282 "M05",
283 "M06",
284 "M07",
285 "M08",
286 "M09",
287 "M10",
288 "M11",
289 "M12",
290 "M13",
291
292 // Leap months. (Note: There's no thirteenth leap month.)
293 "M01L",
294 "M02L",
295 "M03L",
296 "M04L",
297 "M05L",
298 "M06L",
299 "M07L",
300 "M08L",
301 "M09L",
302 "M10L",
303 "M11L",
304 "M12L",
305 };
306
307 size_t index = month + (isLeapMonth ? 12 : 0);
308 if (index >= std::size(MonthCodes)) {
309 status = U_ILLEGAL_ARGUMENT_ERROR;
310 return nullptr;
311 }
312 return MonthCodes[index];
313 }
314
315 void ICU4XCalendar::setTemporalMonthCode(const char* code, UErrorCode& status) {
316 if (U_FAILURE(status)) {
317 return;
318 }
319
320 size_t len = std::strlen(code);
321 if (len < 3 || len > 4 || code[0] != 'M' || !IsAsciiDigit(code[1]) ||
322 !IsAsciiDigit(code[2]) || (len == 4 && code[3] != 'L')) {
323 status = U_ILLEGAL_ARGUMENT_ERROR;
324 return;
325 }
326
327 int32_t month =
328 AsciiDigitToNumber(code[1]) * 10 + AsciiDigitToNumber(code[2]);
329 bool isLeapMonth = len == 4;
330
331 if (month < 1 || month > 13 || (month == 13 && isLeapMonth)) {
332 status = U_ILLEGAL_ARGUMENT_ERROR;
333 return;
334 }
335
336 // Check if this calendar supports the requested month code.
337 auto monthCode = MonthCode{month, isLeapMonth};
338 if (!hasMonthCode(monthCode)) {
339 status = U_ILLEGAL_ARGUMENT_ERROR;
340 return;
341 }
342
343 set(UCAL_MONTH, monthCode.ordinal() - 1);
344 set(UCAL_IS_LEAP_MONTH, int32_t(monthCode.isLeapMonth()));
345 }
346
347 int32_t ICU4XCalendar::internalGetMonth(int32_t defaultValue,
348 UErrorCode& status) const {
349 if (U_FAILURE(status)) {
350 return 0;
351 }
352 if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
353 return internalGet(UCAL_MONTH, defaultValue);
354 }
355 if (!hasLeapMonths()) {
356 return internalGet(UCAL_ORDINAL_MONTH);
357 }
358 return internalGetMonth(status);
359 }
360
361 /**
362 * Return the current month, possibly by computing it from |UCAL_ORDINAL_MONTH|.
363 */
364 int32_t ICU4XCalendar::internalGetMonth(UErrorCode& status) const {
365 if (U_FAILURE(status)) {
366 return 0;
367 }
368 if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
369 return internalGet(UCAL_MONTH);
370 }
371 if (!hasLeapMonths()) {
372 return internalGet(UCAL_ORDINAL_MONTH);
373 }
374
375 int32_t extendedYear = internalGet(UCAL_EXTENDED_YEAR);
376 int32_t ordinalMonth = internalGet(UCAL_ORDINAL_MONTH);
377
378 int32_t month;
379 int32_t isLeapMonth;
380 if (requiresFallbackForExtendedYear(extendedYear)) {
381 // Use the fallback calendar for years outside the range supported by ICU4X.
382 auto* fallback = getFallbackCalendar(status);
383 if (U_FAILURE(status)) {
384 return 0;
385 }
386 fallback->clear();
387 fallback->set(UCAL_EXTENDED_YEAR, extendedYear);
388 fallback->set(UCAL_ORDINAL_MONTH, ordinalMonth);
389 fallback->set(UCAL_DAY_OF_MONTH, 1);
390
391 month = fallback->get(UCAL_MONTH, status);
392 isLeapMonth = fallback->get(UCAL_IS_LEAP_MONTH, status);
393 if (U_FAILURE(status)) {
394 return 0;
395 }
396 } else {
397 auto* cal = getICU4XCalendar(status);
398 if (U_FAILURE(status)) {
399 return 0;
400 }
401
402 UniqueICU4XDate date = CreateDateFrom(cal, eraName(extendedYear),
403 extendedYear, ordinalMonth + 1, 1);
404 if (!date) {
405 status = U_INTERNAL_PROGRAM_ERROR;
406 return 0;
407 }
408
409 MonthCode monthCode = monthCodeFrom(date.get(), status);
410 if (U_FAILURE(status)) {
411 return 0;
412 }
413
414 month = monthCode.ordinal() - 1;
415 isLeapMonth = monthCode.isLeapMonth();
416 }
417
418 auto* nonConstThis = const_cast<ICU4XCalendar*>(this);
419 nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, isLeapMonth);
420 nonConstThis->internalSet(UCAL_MONTH, month);
421
422 return month;
423 }
424
425 void ICU4XCalendar::add(UCalendarDateFields field, int32_t amount,
426 UErrorCode& status) {
427 switch (field) {
428 case UCAL_MONTH:
429 case UCAL_ORDINAL_MONTH:
430 if (amount != 0) {
431 // Our implementation doesn't yet support this action.
432 status = U_ILLEGAL_ARGUMENT_ERROR;
433 break;
434 }
435 break;
436 default:
437 Calendar::add(field, amount, status);
438 break;
439 }
440 }
441
442 void ICU4XCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) {
443 add(static_cast<UCalendarDateFields>(field), amount, status);
444 }
445
446 void ICU4XCalendar::roll(UCalendarDateFields field, int32_t amount,
447 UErrorCode& status) {
448 switch (field) {
449 case UCAL_MONTH:
450 case UCAL_ORDINAL_MONTH:
451 if (amount != 0) {
452 // Our implementation doesn't yet support this action.
453 status = U_ILLEGAL_ARGUMENT_ERROR;
454 break;
455 }
456 break;
457 default:
458 Calendar::roll(field, amount, status);
459 break;
460 }
461 }
462
463 void ICU4XCalendar::roll(EDateFields field, int32_t amount,
464 UErrorCode& status) {
465 roll(static_cast<UCalendarDateFields>(field), amount, status);
466 }
467
468 int32_t ICU4XCalendar::handleGetExtendedYear(UErrorCode& status) {
469 if (U_FAILURE(status)) {
470 return 0;
471 }
472 if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
473 return internalGet(UCAL_EXTENDED_YEAR, 1);
474 }
475
476 // We don't yet support the case when UCAL_YEAR is newer.
477 status = U_UNSUPPORTED_ERROR;
478 return 0;
479 }
480
481 int32_t ICU4XCalendar::handleGetYearLength(int32_t extendedYear,
482 UErrorCode& status) const {
483 // Use the (slower) default implementation for years outside the range
484 // supported by ICU4X.
485 if (requiresFallbackForExtendedYear(extendedYear)) {
486 return icu::Calendar::handleGetYearLength(extendedYear, status);
487 }
488
489 auto* cal = getICU4XCalendar(status);
490 if (U_FAILURE(status)) {
491 return 0;
492 }
493
494 UniqueICU4XDate date =
495 CreateDateFrom(cal, eraName(extendedYear), extendedYear, 1, 1);
496 if (!date) {
497 status = U_INTERNAL_PROGRAM_ERROR;
498 return 0;
499 }
500 return capi::ICU4XDate_days_in_year(date.get());
501 }
502
503 /**
504 * Return the number of days in a month.
505 */
506 int32_t ICU4XCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month,
507 UErrorCode& status) const {
508 if (U_FAILURE(status)) {
509 return 0;
510 }
511
512 // ICU4C supports wrap around. We don't support this case.
513 if (month < 0 || month > 11) {
514 status = U_ILLEGAL_ARGUMENT_ERROR;
515 return 0;
516 }
517
518 // Use the fallback calendar for years outside the range supported by ICU4X.
519 if (requiresFallbackForExtendedYear(extendedYear)) {
520 auto* fallback = getFallbackCalendar(status);
521 if (U_FAILURE(status)) {
522 return 0;
523 }
524 fallback->clear();
525 fallback->set(UCAL_EXTENDED_YEAR, extendedYear);
526 fallback->set(UCAL_MONTH, month);
527 fallback->set(UCAL_DAY_OF_MONTH, 1);
528
529 return fallback->getActualMaximum(UCAL_DAY_OF_MONTH, status);
530 }
531
532 auto* cal = getICU4XCalendar(status);
533 if (U_FAILURE(status)) {
534 return 0;
535 }
536
537 bool isLeapMonth = internalGet(UCAL_IS_LEAP_MONTH) != 0;
538 auto monthCode = MonthCode{month + 1, isLeapMonth};
539 UniqueICU4XDate date = CreateDateFromCodes(cal, eraName(extendedYear),
540 extendedYear, monthCode, 1);
541 if (!date) {
542 status = U_INTERNAL_PROGRAM_ERROR;
543 return 0;
544 }
545
546 return capi::ICU4XDate_days_in_month(date.get());
547 }
548
549 /**
550 * Return the start of the month as a Julian date.
551 */
552 int64_t ICU4XCalendar::handleComputeMonthStart(int32_t extendedYear,
553 int32_t month, UBool useMonth,
554 UErrorCode& status) const {
555 if (U_FAILURE(status)) {
556 return 0;
557 }
558
559 // ICU4C supports wrap around. We don't support this case.
560 if (month < 0 || month > 11) {
561 status = U_ILLEGAL_ARGUMENT_ERROR;
562 return 0;
563 }
564
565 // Use the fallback calendar for years outside the range supported by ICU4X.
566 if (requiresFallbackForExtendedYear(extendedYear)) {
567 auto* fallback = getFallbackCalendar(status);
568 if (U_FAILURE(status)) {
569 return 0;
570 }
571 fallback->clear();
572 fallback->set(UCAL_EXTENDED_YEAR, extendedYear);
573 if (useMonth) {
574 fallback->set(UCAL_MONTH, month);
575 fallback->set(UCAL_IS_LEAP_MONTH, internalGet(UCAL_IS_LEAP_MONTH));
576 } else {
577 fallback->set(UCAL_ORDINAL_MONTH, month);
578 }
579 fallback->set(UCAL_DAY_OF_MONTH, 1);
580
581 int32_t newMoon = fallback->get(UCAL_JULIAN_DAY, status);
582 if (U_FAILURE(status)) {
583 return 0;
584 }
585 return newMoon - 1;
586 }
587
588 auto* cal = getICU4XCalendar(status);
589 if (U_FAILURE(status)) {
590 return 0;
591 }
592
593 UniqueICU4XDate date{};
594 if (useMonth) {
595 bool isLeapMonth = internalGet(UCAL_IS_LEAP_MONTH) != 0;
596 auto monthCode = MonthCode{month + 1, isLeapMonth};
597 date = CreateDateFromCodes(cal, eraName(extendedYear), extendedYear,
598 monthCode, 1);
599 } else {
600 date =
601 CreateDateFrom(cal, eraName(extendedYear), extendedYear, month + 1, 1);
602 }
603 if (!date) {
604 status = U_INTERNAL_PROGRAM_ERROR;
605 return 0;
606 }
607
608 auto isoDate = ToISODate(date.get());
609 int32_t newMoon = MakeDay(isoDate);
610
611 return (newMoon - 1) + kEpochStartAsJulianDay;
612 }
613
614 /**
615 * Default implementation of handleComputeFields when using the fallback
616 * calendar.
617 */
618 void ICU4XCalendar::handleComputeFieldsFromFallback(int32_t julianDay,
619 UErrorCode& status) {
620 auto* fallback = getFallbackCalendar(status);
621 if (U_FAILURE(status)) {
622 return;
623 }
624 fallback->clear();
625 fallback->set(UCAL_JULIAN_DAY, julianDay);
626
627 internalSet(UCAL_ERA, fallback->get(UCAL_ERA, status));
628 internalSet(UCAL_YEAR, fallback->get(UCAL_YEAR, status));
629 internalSet(UCAL_EXTENDED_YEAR, fallback->get(UCAL_EXTENDED_YEAR, status));
630 internalSet(UCAL_MONTH, fallback->get(UCAL_MONTH, status));
631 internalSet(UCAL_ORDINAL_MONTH, fallback->get(UCAL_ORDINAL_MONTH, status));
632 internalSet(UCAL_IS_LEAP_MONTH, fallback->get(UCAL_IS_LEAP_MONTH, status));
633 internalSet(UCAL_DAY_OF_MONTH, fallback->get(UCAL_DAY_OF_MONTH, status));
634 internalSet(UCAL_DAY_OF_YEAR, fallback->get(UCAL_DAY_OF_YEAR, status));
635 }
636
637 } // namespace mozilla::intl::calendar