From d31f1c5aaeb9e9a41a6824c24b7e24615029ac88 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 8 Sep 2026 21:15:36 +0000 Subject: [PATCH] [JSC][Temporal] Hijri and Persian years below 1: report the real year and month lengths ICU4C's IslamicCivilCalendar::civilLeapYear() computes (14 + 11 * year) % 30 < 11 and PersianCalendar::isLeapYear() computes (25 * year + 11) % 33 < 8 with the truncating % (the Hijri one always did; the Persian one since ICU 75, where ICU-22633's unicode-org/icu@d43d216feb replaced a ClockMath::floorDivide; both unchanged in ICU 78). For a negative dividend (Hijri year <= -2, Persian year <= -1) the remainder is <= 0, so every such year reads as leap: handleGetYearLength() says 355 or 366 and handleGetMonthLength() gives the last month 30 days. yearStart() and monthStart() floor-divide, so ICU still places the days themselves where icu4x does, and day 30 of a 29-day final month is the same day as the next year's day 1. islamic-umalqura uses the civil rule outside its 1300-1600 AH table, so it is affected for the same years. Through the Temporal calendar bridge, for islamic-civil, islamic-tbla, islamic-umalqura and persian in years below 1, this showed up as: - inLeapYear true, daysInYear 355 or 366 and a 30-day last month for common years, while until() to the next new year measures 354 or 365 days; - {year: -7, month: 12, day: 30} accepted with overflow "reject", and equal to {year: -6, month: 1, day: 1}; - year and month arithmetic off by a month, because ucal_add() pins DAY_OF_MONTH against the same wrong length and lands in the next month: in the Hijri calendars -4-12-30 + P1Y gave -2-01-30 instead of -3-12-29, and persian -1-11-30 + P1M threw a RangeError. For those years the bridge now takes daysInMonth, daysInYear, inLeapYear and the day regulation in from(), with(), add(), subtract(), until() and since() from the tabular leap rules with a floored remainder, as icu4x does. The three Hijri calendars have twelve months every year, so they join the fixed-month arithmetic path that coptic, ethiopic, ethioaa, indian and persian already use (balance the year and month, construct the native fields directly, regulate the day) instead of ucal_add(), which is now used by the lunisolar calendars only. The fixed-solar helpers are renamed fixed-month to match. Years from 1 on, and every other calendar, are unchanged. * JSTests/stress/temporal-tabular-calendars-before-epoch.js: Added. Year and month lengths against the distance to the next year and month for years -70..5, reject and constrain of day 30, year and month arithmetic across common and leap years, ISO dates checked against icu4x, and islamic-umalqura inside its table. * Source/JavaScriptCore/runtime/temporal/core/CalendarICUBridge.cpp: (JSC::TemporalCore::calendarUsesTabularLeapRule): (JSC::TemporalCore::tabularLeapYear): (JSC::TemporalCore::tabularDaysInYear): (JSC::TemporalCore::tabularDaysInMonth): (JSC::TemporalCore::tabularYearBelowOneAtCursor): (JSC::TemporalCore::daysInMonthAtCursor): Added. (JSC::TemporalCore::calendarDaysInMonth): (JSC::TemporalCore::calendarDaysInYear): (JSC::TemporalCore::calendarInLeapYear): (JSC::TemporalCore::nonISOCalendarDateToISO): (JSC::TemporalCore::setMonths): Read the month and year length through the helpers. (JSC::TemporalCore::calendarHasFixedMonths): Renamed from calendarIsNonISOSolar; adds the Hijri calendars. (JSC::TemporalCore::fixedMonthsInYear): (JSC::TemporalCore::balanceFixedMonthYearMonth): (JSC::TemporalCore::verifyAndCorrectFixedMonthDay): (JSC::TemporalCore::setFixedMonthCalendarToYearMonth): (JSC::TemporalCore::fixedMonthDateAdd): Renamed from the fixedSolar spellings. (JSC::TemporalCore::calendarDateAdd): (JSC::TemporalCore::surpassesMonths): Assert that the ucal_add() path is lunisolar. --- ...temporal-tabular-calendars-before-epoch.js | 171 +++++++++++++++++ .../temporal/core/CalendarICUBridge.cpp | 181 +++++++++++++----- 2 files changed, 308 insertions(+), 44 deletions(-) create mode 100644 JSTests/stress/temporal-tabular-calendars-before-epoch.js diff --git a/JSTests/stress/temporal-tabular-calendars-before-epoch.js b/JSTests/stress/temporal-tabular-calendars-before-epoch.js new file mode 100644 index 0000000000000..ba5ee96cb8adf --- /dev/null +++ b/JSTests/stress/temporal-tabular-calendars-before-epoch.js @@ -0,0 +1,171 @@ +//@ requireOptions("--useTemporal=1") + +// islamic-civil / islamic-tbla / islamic-umalqura and persian in years below 1. ICU4C's +// IslamicCivilCalendar::civilLeapYear() and PersianCalendar::isLeapYear() take a truncating `%` of a +// negative dividend there and call every such year leap, while ICU places the days themselves +// correctly. The bridge must report year and month lengths that agree with where the days are +// (and with icu4x): daysInYear is the distance to the next new year, the month lengths add up to +// it, inLeapYear matches it, day 30 of a 29-day final month constrains or rejects instead of +// aliasing the next year's day 1, and year/month arithmetic regulates the day against the real +// month length. + +function shouldBe(actual, expected, label) { + if (actual !== expected) + throw new Error(`${label}: expected ${expected}, got ${actual}`); +} + +function shouldThrow(func, errorType, label) { + try { + func(); + } catch (error) { + if (error instanceof errorType) + return; + throw new Error(`${label}: expected ${errorType.name}, got ${error.constructor.name}`); + } + throw new Error(`${label}: expected ${errorType.name}, but no exception was thrown`); +} + +function fields(date) { + return `${date.year}-${date.monthCode}-${date.day}`; +} + +// icu4x reference: (14 + 11 * year) mod 30 < 11 (TabularAlgorithm::year) and +// (25 * year + 11) mod 33 < 8 (calendrical_calculations persian::is_leap_year), floored. +function tabularLeapYear(calendar, year) { + const mod = (a, n) => ((a % n) + n) % n; + if (calendar === "persian") + return mod(25 * year + 11, 33) < 8; + return mod(14 + 11 * year, 30) < 11; +} + +const hijriCalendars = ["islamic-civil", "islamic-tbla", "islamic-umalqura"]; + +for (const calendar of [...hijriCalendars, "persian"]) { + const isPersian = calendar === "persian"; + const commonYear = isPersian ? 365 : 354; + for (let year = -70; year <= 5; ++year) { + const label = `${calendar} ${year}`; + const first = Temporal.PlainDate.from({ year, month: 1, day: 1, calendar }); + const next = Temporal.PlainDate.from({ year: year + 1, month: 1, day: 1, calendar }); + const leap = tabularLeapYear(calendar, year); + const span = first.until(next, { largestUnit: "days" }).days; + + shouldBe(first.inLeapYear, leap, `${label} inLeapYear`); + shouldBe(first.daysInYear, commonYear + leap, `${label} daysInYear`); + shouldBe(span, first.daysInYear, `${label} days until next 1/1`); + shouldBe(first.monthsInYear, 12, `${label} monthsInYear`); + + let sum = 0; + for (let month = 1; month <= 12; ++month) { + const monthStart = Temporal.PlainDate.from({ year, month, day: 1, calendar }); + const nextMonthStart = month < 12 ? Temporal.PlainDate.from({ year, month: month + 1, day: 1, calendar }) : next; + shouldBe(monthStart.until(nextMonthStart, { largestUnit: "days" }).days, monthStart.daysInMonth, `${label} M${month} daysInMonth vs next month start`); + sum += monthStart.daysInMonth; + } + shouldBe(sum, first.daysInYear, `${label} sum of daysInMonth`); + + const lastMonth = Temporal.PlainDate.from({ year, month: 12, day: 1, calendar }); + shouldBe(lastMonth.daysInMonth, 29 + leap, `${label} M12 daysInMonth`); + shouldBe(Temporal.PlainYearMonth.from({ year, month: 12, calendar }).daysInMonth, 29 + leap, `${label} PlainYearMonth M12 daysInMonth`); + shouldBe(Temporal.PlainDateTime.from({ year, month: 12, day: 1, calendar }).daysInYear, commonYear + leap, `${label} PlainDateTime daysInYear`); + shouldBe(Temporal.ZonedDateTime.from({ year, month: 12, day: 1, calendar, timeZone: "UTC" }).inLeapYear, leap, `${label} ZonedDateTime inLeapYear`); + + // The year's last day is day 354/355 (365/366), and the day after it is the next year's day 1. + const lastDay = lastMonth.with({ day: 30 }); + shouldBe(lastDay.day, 29 + leap, `${label} with({day: 30}) constrains`); + shouldBe(lastDay.dayOfYear, commonYear + leap, `${label} last dayOfYear`); + shouldBe(fields(lastDay.add({ days: 1 })), `${year + 1}-M01-1`, `${label} day after the last day`); + + const constrained = Temporal.PlainDate.from({ year, month: 12, day: 30, calendar }); + shouldBe(constrained.day, 29 + leap, `${label} from day 30 constrains`); + shouldBe(constrained.equals(next), false, `${label} 12-30 is not the next year's 1-1`); + if (leap) + shouldBe(Temporal.PlainDate.from({ year, monthCode: "M12", day: 30, calendar }, { overflow: "reject" }).day, 30, `${label} reject accepts day 30`); + else + shouldThrow(() => Temporal.PlainDate.from({ year, monthCode: "M12", day: 30, calendar }, { overflow: "reject" }), RangeError, `${label} reject day 30`); + } +} + +// Year/month arithmetic regulates the day against the real month length (pre-fix results in comments). +for (const calendar of hijriCalendars) { + // -4 is leap (30-day Dhu al-Hijjah); -3, -7 and -2 are common. + const leapLastDay = Temporal.PlainDate.from({ year: -4, month: 12, day: 30, calendar }); + shouldBe(fields(leapLastDay.add({ years: 1 })), "-3-M12-29", `${calendar} -4-12-30 + P1Y`); // was -2-M01-30 + shouldBe(fields(leapLastDay.subtract({ years: 3 })), "-7-M12-29", `${calendar} -4-12-30 - P3Y`); // was -6-M01-30 + shouldBe(fields(leapLastDay.add({ years: 3 })), "-1-M12-30", `${calendar} -4-12-30 + P3Y (leap to leap)`); + shouldThrow(() => leapLastDay.add({ years: 1 }, { overflow: "reject" }), RangeError, `${calendar} -4-12-30 + P1Y reject`); + shouldThrow(() => leapLastDay.subtract({ years: 3 }, { overflow: "reject" }), RangeError, `${calendar} -4-12-30 - P3Y reject`); + shouldBe(fields(leapLastDay.add({ years: 3 }, { overflow: "reject" })), "-1-M12-30", `${calendar} -4-12-30 + P3Y reject (fits)`); + + const muharram30 = Temporal.PlainDate.from({ year: -7, month: 1, day: 30, calendar }); + shouldBe(fields(muharram30.add({ months: 11 })), "-7-M12-29", `${calendar} -7-01-30 + P11M`); + shouldBe(fields(muharram30.add({ months: 23 })), "-6-M12-30", `${calendar} -7-01-30 + P23M (-6 is leap)`); + shouldBe(fields(muharram30.add({ months: 35 })), "-5-M12-29", `${calendar} -7-01-30 + P35M`); + shouldThrow(() => muharram30.add({ months: 11 }, { overflow: "reject" }), RangeError, `${calendar} -7-01-30 + P11M reject`); + shouldBe(fields(muharram30.add({ months: 23 }, { overflow: "reject" })), "-6-M12-30", `${calendar} -7-01-30 + P23M reject (fits)`); + shouldBe(fields(muharram30.add({ months: 11, days: 1 })), "-6-M01-1", `${calendar} -7-01-30 + P11M1D`); + + // until is the inverse of add. + const nextNewYear = Temporal.PlainDate.from({ year: -5, month: 1, day: 1, calendar }); + shouldBe(muharram30.until(nextNewYear, { largestUnit: "years" }).toString(), "P1Y11M1D", `${calendar} until years`); + shouldBe(muharram30.until(nextNewYear, { largestUnit: "months" }).toString(), "P23M1D", `${calendar} until months`); + shouldBe(nextNewYear.until(muharram30, { largestUnit: "months" }).toString(), "-P23M1D", `${calendar} until months reversed`); + shouldBe(muharram30.add("P1Y11M1D").equals(nextNewYear), true, `${calendar} add(until) round-trips`); + + // PlainYearMonth arithmetic takes the same path. + shouldBe(Temporal.PlainYearMonth.from({ year: -4, month: 12, calendar }).add({ years: 1 }).daysInMonth, 29, `${calendar} PlainYearMonth -4-12 + P1Y daysInMonth`); + shouldBe(Temporal.PlainYearMonth.from({ year: -7, month: 1, calendar }).until(Temporal.PlainYearMonth.from({ year: -5, month: 1, calendar })).toString(), "P2Y", `${calendar} PlainYearMonth until`); +} + +{ + // persian: -3 is leap (30-day Esfand); -2, -1 and 0 are common. + const calendar = "persian"; + const bahman30 = Temporal.PlainDate.from({ year: -1, month: 11, day: 30, calendar }); + shouldBe(fields(bahman30.add({ months: 1 })), "-1-M12-29", "persian -1-11-30 + P1M"); // threw RangeError + shouldThrow(() => bahman30.add({ months: 1 }, { overflow: "reject" }), RangeError, "persian -1-11-30 + P1M reject"); + const leapLastDay = Temporal.PlainDate.from({ year: -3, month: 12, day: 30, calendar }); + shouldBe(fields(leapLastDay.add({ years: 2 })), "-1-M12-29", "persian -3-12-30 + P2Y"); + shouldBe(fields(leapLastDay.add({ years: 4 })), "1-M12-30", "persian -3-12-30 + P4Y (leap to leap)"); + shouldBe(fields(leapLastDay.subtract({ years: 4 })), "-7-M12-30", "persian -3-12-30 - P4Y (leap to leap)"); + shouldBe(fields(leapLastDay.subtract({ years: 1 })), "-4-M12-29", "persian -3-12-30 - P1Y"); + shouldThrow(() => leapLastDay.add({ years: 2 }, { overflow: "reject" }), RangeError, "persian -3-12-30 + P2Y reject"); + const farvardin31 = Temporal.PlainDate.from({ year: -2, month: 1, day: 31, calendar }); + shouldBe(fields(farvardin31.add({ months: 11 })), "-2-M12-29", "persian -2-01-31 + P11M"); + shouldBe(fields(farvardin31.add({ months: 23 })), "-1-M12-29", "persian -2-01-31 + P23M"); + const target = Temporal.PlainDate.from({ year: 0, month: 1, day: 1, calendar }); + shouldBe(farvardin31.until(target, { largestUnit: "years" }).toString(), "P1Y11M1D", "persian until years"); + shouldBe(farvardin31.until(target, { largestUnit: "months" }).toString(), "P23M1D", "persian until months"); + shouldBe(farvardin31.add("P1Y11M1D").equals(target), true, "persian add(until) round-trips"); +} + +// The same dates agree with icu4x on the ISO side (year 1 of each calendar is unaffected). +shouldBe(Temporal.PlainDate.from({ year: -7, month: 1, day: 1, calendar: "islamic-civil" }).toString(), "0614-10-14[u-ca=islamic-civil]", "islamic-civil -7-01-01"); +shouldBe(Temporal.PlainDate.from({ year: -7, month: 12, day: 29, calendar: "islamic-civil" }).toString(), "0615-10-02[u-ca=islamic-civil]", "islamic-civil -7-12-29"); +shouldBe(Temporal.PlainDate.from({ year: -6, month: 1, day: 1, calendar: "islamic-civil" }).toString(), "0615-10-03[u-ca=islamic-civil]", "islamic-civil -6-01-01"); +shouldBe(Temporal.PlainDate.from({ year: -7, month: 1, day: 1, calendar: "islamic-tbla" }).toString(), "0614-10-13[u-ca=islamic-tbla]", "islamic-tbla -7-01-01"); +shouldBe(Temporal.PlainDate.from({ year: -7, month: 1, day: 1, calendar: "islamic-umalqura" }).toString(), "0614-10-14[u-ca=islamic-umalqura]", "islamic-umalqura -7-01-01"); +shouldBe(Temporal.PlainDate.from({ year: -1, month: 1, day: 1, calendar: "persian" }).toString(), "0620-03-21[u-ca=persian]", "persian -1-01-01"); +shouldBe(Temporal.PlainDate.from({ year: -1, month: 12, day: 29, calendar: "persian" }).toString(), "0621-03-20[u-ca=persian]", "persian -1-12-29"); +shouldBe(Temporal.PlainDate.from({ year: 0, month: 1, day: 1, calendar: "persian" }).toString(), "0621-03-21[u-ca=persian]", "persian 0-01-01"); + +// Years from 1 on were already right and must not move: 2, 5, 7, 10 and 13 AH are leap, 1403 AP is leap. +for (const calendar of hijriCalendars) { + for (const [year, leap] of [[1, false], [2, true], [3, false], [5, true], [7, true], [8, false], [10, true], [13, true], [30, false]]) { + const first = Temporal.PlainDate.from({ year, month: 1, day: 1, calendar }); + shouldBe(first.inLeapYear, leap, `${calendar} ${year} inLeapYear`); + shouldBe(first.daysInYear, 354 + leap, `${calendar} ${year} daysInYear`); + } +} +shouldBe(Temporal.PlainDate.from({ year: 1403, month: 12, day: 1, calendar: "persian" }).daysInMonth, 30, "persian 1403 Esfand"); +shouldBe(Temporal.PlainDate.from({ year: 1404, month: 12, day: 1, calendar: "persian" }).daysInMonth, 29, "persian 1404 Esfand"); +// islamic-umalqura keeps reading its 1300-1600 AH table from ICU, where it departs from the civil rule: +// 1442 is civil-leap but has a 29-day Dhu al-Hijjah, 1444 is civil-common but has a 30-day one and a 30-day Safar. +shouldBe(Temporal.PlainDate.from({ year: 1442, month: 12, day: 1, calendar: "islamic-civil" }).daysInMonth, 30, "islamic-civil 1442 Dhu al-Hijjah"); +shouldBe(Temporal.PlainDate.from({ year: 1442, month: 12, day: 1, calendar: "islamic-umalqura" }).daysInMonth, 29, "islamic-umalqura 1442 Dhu al-Hijjah"); +shouldThrow(() => Temporal.PlainDate.from({ year: 1444, month: 12, day: 30, calendar: "islamic-civil" }, { overflow: "reject" }), RangeError, "islamic-civil 1444-12-30 reject"); +shouldBe(Temporal.PlainDate.from({ year: 1444, month: 12, day: 30, calendar: "islamic-umalqura" }, { overflow: "reject" }).toString(), "2023-07-18[u-ca=islamic-umalqura]", "islamic-umalqura 1444-12-30"); +const safar30 = Temporal.PlainDate.from({ year: 1444, month: 2, day: 30, calendar: "islamic-umalqura" }, { overflow: "reject" }); +shouldBe(fields(safar30.add({ months: 1 })), "1444-M03-29", "islamic-umalqura 1444-02-30 + P1M"); +shouldBe(fields(safar30.add({ months: 10 })), "1444-M12-30", "islamic-umalqura 1444-02-30 + P10M"); +shouldBe(fields(safar30.add({ years: 1 })), "1445-M02-30", "islamic-umalqura 1444-02-30 + P1Y"); +shouldBe(safar30.until(safar30.add({ months: 10 }), { largestUnit: "months" }).toString(), "P10M", "islamic-umalqura until inside the table"); diff --git a/Source/JavaScriptCore/runtime/temporal/core/CalendarICUBridge.cpp b/Source/JavaScriptCore/runtime/temporal/core/CalendarICUBridge.cpp index da21b72573379..18c1fb6b368a4 100644 --- a/Source/JavaScriptCore/runtime/temporal/core/CalendarICUBridge.cpp +++ b/Source/JavaScriptCore/runtime/temporal/core/CalendarICUBridge.cpp @@ -1018,6 +1018,80 @@ static std::optional indianSakaToISO(int32_t sakaYear, uint8 return ISO8601::PlainDate(isoYear, isoMonth, isoDay); } +// ICU4C-WORKAROUND: IslamicCivilCalendar's civilLeapYear() is `(14 + 11 * year) % 30 < 11` (always +// was) and PersianCalendar::isLeapYear() is `(25 * year + 11) % 33 < 8` (since ICU 75: ICU-22633, +// unicode-org/icu@d43d216feb replaced a ClockMath::floorDivide there), both with C++'s truncating `%`, +// still so in ICU 78. Once the dividend is negative (Hijri year <= -2, Persian year <= -1) the +// remainder is <= 0 and every such year reads as leap. yearStart()/monthStart() floor-divide, so ICU +// still places every day where icu4x does; only handleGetYearLength()/handleGetMonthLength() +// over-report for those years (355/366 days, and a 30-day final month whose day 30 is the next +// year's day 1). islamic-umalqura applies the civil rule outside its 1300-1600 AH table, so it is +// affected too. +// For years below 1 the bridge answers lengths from the tabular rules with a floored remainder, as +// icu4x does (TabularAlgorithm::year in components/calendar/src/cal/hijri.rs, is_leap_year in +// utils/calendrical_calculations/src/persian.rs), and no Hijri or Persian year/month arithmetic +// goes through ucal_add(), whose DAY_OF_MONTH pin uses the same ICU lengths. +static bool calendarUsesTabularLeapRule(CalendarID calendarId) +{ + return calendarIsIslamic(calendarId) || calendarId == persianCalendarID(); +} + +static bool tabularLeapYear(CalendarID calendarId, int32_t extendedYear) +{ + ASSERT(calendarUsesTabularLeapRule(calendarId)); + bool isPersian = calendarId == persianCalendarID(); + int64_t dividend = isPersian ? 25 * static_cast(extendedYear) + 11 : 11 * static_cast(extendedYear) + 14; + int64_t divisor = isPersian ? 33 : 30; + int64_t remainder = dividend % divisor; + if (remainder < 0) + remainder += divisor; + return remainder < (isPersian ? 8 : 11); +} + +static int32_t tabularDaysInYear(CalendarID calendarId, int32_t extendedYear) +{ + return (calendarId == persianCalendarID() ? 365 : 354) + tabularLeapYear(calendarId, extendedYear); +} + +// month is ICU's 0-based UCAL_MONTH. Persian: 6 x 31, 5 x 30, Esfand 29/30. Hijri: 30/29 alternating, Dhu al-Hijjah 29/30. +static int32_t tabularDaysInMonth(CalendarID calendarId, int32_t extendedYear, int32_t month) +{ + ASSERT(month >= 0 && month < 12); + if (month == 11) + return 29 + tabularLeapYear(calendarId, extendedYear); + if (calendarId == persianCalendarID()) + return month < 6 ? 31 : 30; + return month % 2 ? 29 : 30; +} + +// The cursor's UCAL_EXTENDED_YEAR when it is a Hijri/Persian year below 1 (the years ICU mis-measures above), nullopt otherwise. +static TemporalResult> tabularYearBelowOneAtCursor(UCalendar* cal, CalendarID calendarId) +{ + if (!calendarUsesTabularLeapRule(calendarId)) + return std::optional { }; + auto extendedYear = readICUField(cal, UCAL_EXTENDED_YEAR); + if (!extendedYear) [[unlikely]] + return makeUnexpected(extendedYear.error()); + if (*extendedYear >= 1) + return std::optional { }; + return std::optional { *extendedYear }; +} + +// ucal_getLimit(UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM) for the cursor's month, corrected for the years above. +static TemporalResult daysInMonthAtCursor(UCalendar* cal, CalendarID calendarId) +{ + auto tabularYear = tabularYearBelowOneAtCursor(cal, calendarId); + if (!tabularYear) [[unlikely]] + return makeUnexpected(tabularYear.error()); + if (*tabularYear) { + auto month = readICUField(cal, UCAL_MONTH); + if (!month) [[unlikely]] + return makeUnexpected(month.error()); + return tabularDaysInMonth(calendarId, **tabularYear, *month); + } + return readICUFieldLimit(cal, UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM); +} + // Design choice, not an ICU4C workaround: ±10000 is icu4x's WELL_BEHAVED_ASTRONOMICAL_RANGE, and // must track nonISOCalendarDateToISO's fallback. ICU is only accurate inside gregorian 1900-2100. static bool calendarUsesISOFallbackForExtremeYear(CalendarID calendarId, int32_t isoYear) @@ -1379,7 +1453,7 @@ TemporalResult calendarDaysInMonth(CalendarID calendarId, const ISO8601 return makeUnexpected(rangeError(icuReadCalendarFailed)); return *result; } - return readICUFieldLimit(cal, UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM); + return daysInMonthAtCursor(cal, calendarId); }); } @@ -1402,6 +1476,12 @@ TemporalResult calendarDaysInYear(CalendarID calendarId, const ISO8601: if (!U_FAILURE(s) && !y) return 384; } + // ICU4C-WORKAROUND: tabular Hijri/Persian years below 1 (see tabularLeapYear). + auto tabularYear = tabularYearBelowOneAtCursor(cal, calendarId); + if (!tabularYear) [[unlikely]] + return makeUnexpected(tabularYear.error()); + if (*tabularYear) + return tabularDaysInYear(calendarId, **tabularYear); return readICUFieldLimit(cal, UCAL_DAY_OF_YEAR, UCAL_ACTUAL_MAXIMUM); }); } @@ -1489,7 +1569,13 @@ TemporalResult calendarInLeapYear(CalendarID calendarId, const ISO8601::Pl return makeUnexpected(months.error()); return *months > 12; } - return withCalendarSetToDate(gregorianArithmeticCalendarFor(calendarId), isoDate, [](UCalendar* cal) -> TemporalResult { + return withCalendarSetToDate(gregorianArithmeticCalendarFor(calendarId), isoDate, [&](UCalendar* cal) -> TemporalResult { + // ICU4C-WORKAROUND: tabular Hijri/Persian years below 1 (see tabularLeapYear). + auto tabularYear = tabularYearBelowOneAtCursor(cal, calendarId); + if (!tabularYear) [[unlikely]] + return makeUnexpected(tabularYear.error()); + if (*tabularYear) + return tabularLeapYear(calendarId, **tabularYear); auto actualMax = readICUFieldLimit(cal, UCAL_DAY_OF_YEAR, UCAL_ACTUAL_MAXIMUM); if (!actualMax) [[unlikely]] return makeUnexpected(actualMax.error()); @@ -1737,24 +1823,27 @@ static std::optional nonISODateSurpasses( return compareSurpassesOrdinally(sign, y0, *m0, sourceDay, targetYear, targetOrdinalMonth, targetDay); } -static bool calendarIsNonISOSolar(CalendarID calendarId) +// Calendars with the same months every year (no leap months): the five non-ISO solar calendars and +// the three tabular Hijri calendars. Their year/month arithmetic balances native fields directly +// instead of going through ucal_add (see tabularLeapYear for why Hijri must not). +static bool calendarHasFixedMonths(CalendarID calendarId) { return calendarId == copticCalendarID() || calendarId == ethiopicCalendarID() || calendarId == ethioaaCalendarID() - || calendarId == indianCalendarID() || calendarId == persianCalendarID(); + || calendarId == indianCalendarID() || calendarId == persianCalendarID() || calendarIsIslamic(calendarId); } -static int32_t fixedSolarMonthsInYear(CalendarID calendarId) +static int32_t fixedMonthsInYear(CalendarID calendarId) { - ASSERT(calendarIsNonISOSolar(calendarId)); + ASSERT(calendarHasFixedMonths(calendarId)); return calendarId == copticCalendarID() || calendarId == ethiopicCalendarID() || calendarId == ethioaaCalendarID() ? 13 : 12; } -struct FixedSolarYearMonth { +struct FixedMonthYearMonth { int32_t year; int32_t month; }; -static std::optional balanceFixedSolarYearMonth(int32_t sourceYear, int32_t sourceMonth, int32_t monthsInYear, int64_t years, int64_t months) +static std::optional balanceFixedMonthYearMonth(int32_t sourceYear, int32_t sourceMonth, int32_t monthsInYear, int64_t years, int64_t months) { CheckedInt64 checkedBalancedMonth = CheckedInt64(sourceMonth) + months; if (checkedBalancedMonth.hasOverflowed()) [[unlikely]] @@ -1773,10 +1862,10 @@ static std::optional balanceFixedSolarYearMonth(int32_t sou CheckedInt32 expectedYear = checkedExpectedYear; if (expectedYear.hasOverflowed()) [[unlikely]] return std::nullopt; - return FixedSolarYearMonth { expectedYear, expectedMonth }; + return FixedMonthYearMonth { expectedYear, expectedMonth }; } -static std::optional verifyAndCorrectFixedSolarDay(UCalendar* cal, UCalendarDateFields yearField, int32_t expectedYear, int32_t expectedMonth, int32_t expectedDay) +static std::optional verifyAndCorrectFixedMonthDay(UCalendar* cal, UCalendarDateFields yearField, int32_t expectedYear, int32_t expectedMonth, int32_t expectedDay) { UErrorCode status = U_ZERO_ERROR; int32_t actualYear = ucal_get(cal, yearField, &status); @@ -1808,7 +1897,7 @@ static std::optional verifyAndCorrectFixedSolarDay(UCalendar* cal, UCalend // Clear and construct an exact native year/month at day 1. Noon preserves Temporal's partial-day // endpoints. At ICU's extreme millisecond boundary, directly set fields can resolve one day off; // correct only that rounding after the expected year/month resolve, then verify every field. -static std::optional setFixedSolarCalendarToYearMonth(UCalendar* cal, CalendarID calendarId, const FixedSolarYearMonth& expected) +static std::optional setFixedMonthCalendarToYearMonth(UCalendar* cal, CalendarID calendarId, const FixedMonthYearMonth& expected) { ucal_clear(cal); auto yearField = calendarArithmeticYearField(calendarId); @@ -1823,10 +1912,10 @@ static std::optional setFixedSolarCalendarToYearMonth(UCalendar* cal, Cale ucal_getMillis(cal, &status); if (U_FAILURE(status)) [[unlikely]] return std::nullopt; - return verifyAndCorrectFixedSolarDay(cal, yearField, expected.year, expected.month, 1); + return verifyAndCorrectFixedMonthDay(cal, yearField, expected.year, expected.month, 1); } -static TemporalResult fixedSolarDateAdd(CalendarID calendarId, const ISO8601::PlainDate& isoDate, const ISO8601::Duration& duration, TemporalOverflow overflow) +static TemporalResult fixedMonthDateAdd(CalendarID calendarId, const ISO8601::PlainDate& isoDate, const ISO8601::Duration& duration, TemporalOverflow overflow) { auto baselineOrError = withCalendar(calendarId, [&](UCalendar* cal) -> TemporalResult { if (!cal) [[unlikely]] @@ -1846,21 +1935,21 @@ static TemporalResult fixedSolarDateAdd(CalendarID calendarI if (U_FAILURE(status)) [[unlikely]] return makeUnexpected(rangeError(icuReadCalendarFailed)); - auto expected = balanceFixedSolarYearMonth(sourceYear, sourceMonth, fixedSolarMonthsInYear(calendarId), duration.years(), duration.months()); + auto expected = balanceFixedMonthYearMonth(sourceYear, sourceMonth, fixedMonthsInYear(calendarId), duration.years(), duration.months()); if (!expected) [[unlikely]] return makeUnexpected(rangeError("Result of calendar date addition is outside representable range"_s)); - auto constructedExactly = setFixedSolarCalendarToYearMonth(cal, calendarId, *expected); + auto constructedExactly = setFixedMonthCalendarToYearMonth(cal, calendarId, *expected); if (!constructedExactly) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); if (!*constructedExactly) [[unlikely]] return makeUnexpected(rangeError("Result of calendar date addition is outside representable range"_s)); - int32_t maxDay = ucal_getLimit(cal, UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM, &status); - if (U_FAILURE(status)) [[unlikely]] - return makeUnexpected(rangeError(icuReadCalendarFailed)); - if (overflow == TemporalOverflow::Reject && sourceDay > maxDay) [[unlikely]] + auto maxDay = daysInMonthAtCursor(cal, calendarId); + if (!maxDay) [[unlikely]] + return makeUnexpected(maxDay.error()); + if (overflow == TemporalOverflow::Reject && sourceDay > *maxDay) [[unlikely]] return makeUnexpected(rangeError("day is out of range for the resulting month (overflow: reject)"_s)); - int32_t regulatedDay = std::min(sourceDay, maxDay); + int32_t regulatedDay = std::min(sourceDay, *maxDay); ucal_set(cal, UCAL_DAY_OF_MONTH, regulatedDay); ucal_getMillis(cal, &status); if (U_FAILURE(status)) [[unlikely]] @@ -1868,7 +1957,7 @@ static TemporalResult fixedSolarDateAdd(CalendarID calendarI // At ICU's extreme millisecond boundary, resolving a directly set day can round to // the adjacent day even though that native day is representable. Correct only the day // after the expected year/month have resolved exactly, then verify all fields again. - auto constructedRegulatedDay = verifyAndCorrectFixedSolarDay(cal, yearField, expected->year, expected->month, regulatedDay); + auto constructedRegulatedDay = verifyAndCorrectFixedMonthDay(cal, yearField, expected->year, expected->month, regulatedDay); if (!constructedRegulatedDay) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); if (!*constructedRegulatedDay) [[unlikely]] @@ -1890,7 +1979,8 @@ static TemporalResult fixedSolarDateAdd(CalendarID calendarI // calendarDateAdd — temporal_rs: Calendar::date_add (src/builtins/core/calendar.rs) // temporal_rs delegates to icu4x: AnyCalendar::add -> ArithmeticDate::added (components/calendar/src/calendar_arithmetic.rs) -// ICU4C has no equivalent: we use ucal_add(UCAL_EXTENDED_YEAR/UCAL_MONTH) with month-code re-resolution for lunisolar. +// ICU4C has no equivalent: fixed-month calendars balance native fields directly; lunisolar calendars use +// ucal_add(UCAL_EXTENDED_YEAR/UCAL_MONTH) with month-code re-resolution. // https://tc39.es/proposal-temporal/#sec-temporal-calendardateadd TemporalResult calendarDateAdd(CalendarID calendarId, const ISO8601::PlainDate& isoDate, const ISO8601::Duration& duration, TemporalOverflow overflow) { @@ -1902,9 +1992,10 @@ TemporalResult calendarDateAdd(CalendarID calendarId, const return isoDateAdd(isoDate, duration, overflow); if (calendarUsesISOFallbackForExtremeYear(calendarId, isoDate.year())) return isoDateAdd(isoDate, duration, overflow); - // Fixed solar calendars construct the exact expected native fields directly. - if (calendarIsNonISOSolar(calendarId)) - return fixedSolarDateAdd(calendarId, isoDate, duration, overflow); + // Fixed-month calendars construct the exact expected native fields directly. + if (calendarHasFixedMonths(calendarId)) + return fixedMonthDateAdd(calendarId, isoDate, duration, overflow); + ASSERT(calendarIsLunisolar(calendarId)); // ucal_add takes int32_t; larger components exceed Temporal's representable range. auto fitsInt32 = [](int64_t v) -> bool { @@ -2019,7 +2110,7 @@ static std::optional surpassesMonths( int32_t targetDay) { UErrorCode status = U_ZERO_ERROR; - if (calendarIsNonISOSolar(calendarId)) { + if (calendarHasFixedMonths(calendarId)) { auto yearField = calendarArithmeticYearField(calendarId); int32_t sourceYear = ucal_get(trialCal, yearField, &status); if (U_FAILURE(status)) [[unlikely]] @@ -2027,15 +2118,16 @@ static std::optional surpassesMonths( int32_t sourceMonth = ucal_get(trialCal, UCAL_MONTH, &status); if (U_FAILURE(status)) [[unlikely]] return std::nullopt; - auto expected = balanceFixedSolarYearMonth(sourceYear, sourceMonth, fixedSolarMonthsInYear(calendarId), 0, sign); + auto expected = balanceFixedMonthYearMonth(sourceYear, sourceMonth, fixedMonthsInYear(calendarId), 0, sign); if (!expected) return true; - auto advancedExactly = setFixedSolarCalendarToYearMonth(trialCal, calendarId, *expected); + auto advancedExactly = setFixedMonthCalendarToYearMonth(trialCal, calendarId, *expected); if (!advancedExactly) [[unlikely]] return std::nullopt; if (!*advancedExactly) return true; } else { + ASSERT(calendarIsLunisolar(calendarId)); ucal_add(trialCal, UCAL_MONTH, sign, &status); if (U_FAILURE(status)) [[unlikely]] return std::nullopt; @@ -2071,13 +2163,13 @@ static std::optional surpassesMonths( } // setMonths — icu4x: SurpassesChecker::set_months (components/calendar/src/calendar_arithmetic.rs) -static std::optional setMonths(UCalendar* cal, int32_t sourceDay) +static std::optional setMonths(UCalendar* cal, CalendarID calendarId, int32_t sourceDay) { UErrorCode status = U_ZERO_ERROR; - int32_t maxDay = ucal_getLimit(cal, UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM, &status); - if (U_FAILURE(status)) [[unlikely]] + auto maxDay = daysInMonthAtCursor(cal, calendarId); + if (!maxDay) [[unlikely]] return std::nullopt; - int32_t regulatedDay = std::min(sourceDay, maxDay); + int32_t regulatedDay = std::min(sourceDay, *maxDay); int32_t currentDay = ucal_get(cal, UCAL_DAY_OF_MONTH, &status); if (U_FAILURE(status)) [[unlikely]] return std::nullopt; @@ -2091,7 +2183,7 @@ static std::optional setMonths(UCalendar* cal, int32_t sourceDay) // NonISODateUntil — temporal_rs: Calendar::date_until (src/builtins/core/calendar.rs) // temporal_rs delegates to icu4x: AnyCalendar::until -> ArithmeticDate::until + SurpassesChecker (components/calendar/src/calendar_arithmetic.rs) -// ICU4C has no equivalent: fixed-solar calendars balance native fields directly; lunisolar calendars walk months with ucal_add. +// ICU4C has no equivalent: fixed-month calendars balance native fields directly; lunisolar calendars walk months with ucal_add. // https://tc39.es/proposal-intl-era-monthcode/#sup-temporal-nonisodateuntil static TemporalResult nonISODateUntil(CalendarID calendarId, const ISO8601::PlainDate& one, const ISO8601::PlainDate& two, TemporalUnit largestUnit) { @@ -2172,11 +2264,11 @@ static TemporalResult nonISODateUntil(CalendarID calendarId, ASSERT(source.epochMs != target.epochMs); int32_t sign = source.epochMs < target.epochMs ? 1 : -1; - // Fixed-solar calendars have a constant month count, so jump directly to the native + // Fixed-month calendars have a constant month count, so jump directly to the native // total-month difference. At most one candidate can surpass because it is already in // the target year/month; preserve the existing unregulated source-day comparison. - if (calendarIsNonISOSolar(calendarId) && largestUnit == TemporalUnit::Month) { - CheckedInt64 checkedMonths = (CheckedInt64(target.year) - source.year) * fixedSolarMonthsInYear(calendarId); + if (calendarHasFixedMonths(calendarId) && largestUnit == TemporalUnit::Month) { + CheckedInt64 checkedMonths = (CheckedInt64(target.year) - source.year) * fixedMonthsInYear(calendarId); checkedMonths += target.ordinalMonth - source.ordinalMonth; if (checkedMonths.hasOverflowed()) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); @@ -2236,7 +2328,7 @@ static TemporalResult nonISODateUntil(CalendarID calendarId, return makeUnexpected(rangeError(icuSetCalendarFailed)); UErrorCode status = U_ZERO_ERROR; - // Lunisolar month counts vary. Fixed-solar calendars reach this loop only for + // Lunisolar month counts vary. Fixed-month calendars reach this loop only for // largestUnit year, so direct construction is bounded to at most one native year. int32_t candidateMonths = sign; // d. Set cal to (one + years) with day=1 for clamping-free month advancement. @@ -2265,17 +2357,17 @@ static TemporalResult nonISODateUntil(CalendarID calendarId, if (U_FAILURE(status)) [[unlikely]] return makeUnexpected(rangeError(icuSetCalendarFailed)); if (months) { - if (calendarIsNonISOSolar(calendarId)) { + if (calendarHasFixedMonths(calendarId)) { int32_t sourceYear = ucal_get(cal, calendarArithmeticYearField(calendarId), &status); if (U_FAILURE(status)) [[unlikely]] return makeUnexpected(rangeError(icuReadCalendarFailed)); int32_t sourceMonth = ucal_get(cal, UCAL_MONTH, &status); if (U_FAILURE(status)) [[unlikely]] return makeUnexpected(rangeError(icuReadCalendarFailed)); - auto expected = balanceFixedSolarYearMonth(sourceYear, sourceMonth, fixedSolarMonthsInYear(calendarId), 0, months); + auto expected = balanceFixedMonthYearMonth(sourceYear, sourceMonth, fixedMonthsInYear(calendarId), 0, months); if (!expected) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); - auto advancedExactly = setFixedSolarCalendarToYearMonth(cal, calendarId, *expected); + auto advancedExactly = setFixedMonthCalendarToYearMonth(cal, calendarId, *expected); if (!advancedExactly || !*advancedExactly) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); } else { @@ -2287,7 +2379,7 @@ static TemporalResult nonISODateUntil(CalendarID calendarId, } } // Regulated day = min(sourceDay, end_of_month). - if (!setMonths(cal, source.day)) [[unlikely]] + if (!setMonths(cal, calendarId, source.day)) [[unlikely]] return makeUnexpected(rangeError(icuCalendarArithmeticFailed)); // Days: derived from epoch-ms delta between cal (source + years + months) and target. @@ -2845,9 +2937,10 @@ TemporalResult nonISOCalendarDateToISO(CalendarID calendarId } else { // CalendarDaysInMonth: cursor is already at the target month, so read [[DaysInMonth]] // straight off ICU instead of round-tripping through an ISO date. - maxDay = ucal_getLimit(cal, UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM, &status); - if (U_FAILURE(status)) [[unlikely]] - return makeUnexpected(rangeError(icuReadCalendarFailed)); + auto maxDayOrError = daysInMonthAtCursor(cal, calendarId); + if (!maxDayOrError) [[unlikely]] + return makeUnexpected(maxDayOrError.error()); + maxDay = *maxDayOrError; } {