Calendar.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023-2024, Shannon Booth <shannon@serenityos.org>
  5. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/NonnullRawPtr.h>
  10. #include <AK/QuickSort.h>
  11. #include <LibJS/Runtime/Temporal/Calendar.h>
  12. #include <LibJS/Runtime/Temporal/DateEquations.h>
  13. #include <LibJS/Runtime/Temporal/ISO8601.h>
  14. #include <LibJS/Runtime/Temporal/PlainDate.h>
  15. #include <LibJS/Runtime/Temporal/PlainMonthDay.h>
  16. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  17. #include <LibJS/Runtime/Temporal/TimeZone.h>
  18. #include <LibJS/Runtime/VM.h>
  19. #include <LibUnicode/Locale.h>
  20. #include <LibUnicode/UnicodeKeywords.h>
  21. namespace JS::Temporal {
  22. enum class CalendarFieldConversion {
  23. ToIntegerWithTruncation,
  24. ToMonthCode,
  25. ToOffsetString,
  26. ToPositiveIntegerWithTruncation,
  27. ToString,
  28. ToTemporalTimeZoneIdentifier,
  29. };
  30. // https://tc39.es/proposal-temporal/#table-temporal-calendar-fields-record-fields
  31. #define JS_ENUMERATE_CALENDAR_FIELDS \
  32. __JS_ENUMERATE(CalendarField::Era, era, vm.names.era, CalendarFieldConversion::ToString) \
  33. __JS_ENUMERATE(CalendarField::EraYear, era_year, vm.names.eraYear, CalendarFieldConversion::ToIntegerWithTruncation) \
  34. __JS_ENUMERATE(CalendarField::Year, year, vm.names.year, CalendarFieldConversion::ToIntegerWithTruncation) \
  35. __JS_ENUMERATE(CalendarField::Month, month, vm.names.month, CalendarFieldConversion::ToPositiveIntegerWithTruncation) \
  36. __JS_ENUMERATE(CalendarField::MonthCode, month_code, vm.names.monthCode, CalendarFieldConversion::ToMonthCode) \
  37. __JS_ENUMERATE(CalendarField::Day, day, vm.names.day, CalendarFieldConversion::ToPositiveIntegerWithTruncation) \
  38. __JS_ENUMERATE(CalendarField::Hour, hour, vm.names.hour, CalendarFieldConversion::ToIntegerWithTruncation) \
  39. __JS_ENUMERATE(CalendarField::Minute, minute, vm.names.minute, CalendarFieldConversion::ToIntegerWithTruncation) \
  40. __JS_ENUMERATE(CalendarField::Second, second, vm.names.second, CalendarFieldConversion::ToIntegerWithTruncation) \
  41. __JS_ENUMERATE(CalendarField::Millisecond, millisecond, vm.names.millisecond, CalendarFieldConversion::ToIntegerWithTruncation) \
  42. __JS_ENUMERATE(CalendarField::Microsecond, microsecond, vm.names.microsecond, CalendarFieldConversion::ToIntegerWithTruncation) \
  43. __JS_ENUMERATE(CalendarField::Nanosecond, nanosecond, vm.names.nanosecond, CalendarFieldConversion::ToIntegerWithTruncation) \
  44. __JS_ENUMERATE(CalendarField::Offset, offset, vm.names.offset, CalendarFieldConversion::ToOffsetString) \
  45. __JS_ENUMERATE(CalendarField::TimeZone, time_zone, vm.names.timeZone, CalendarFieldConversion::ToTemporalTimeZoneIdentifier)
  46. struct CalendarFieldData {
  47. CalendarField key;
  48. NonnullRawPtr<PropertyKey> property;
  49. CalendarFieldConversion conversion;
  50. };
  51. static Vector<CalendarFieldData> sorted_calendar_fields(VM& vm, CalendarFieldList fields)
  52. {
  53. auto data_for_field = [&](auto field) -> CalendarFieldData {
  54. switch (field) {
  55. #define __JS_ENUMERATE(enumeration, field_name, property_key, conversion) \
  56. case enumeration: \
  57. return { enumeration, property_key, conversion };
  58. JS_ENUMERATE_CALENDAR_FIELDS
  59. #undef __JS_ENUMERATE
  60. }
  61. VERIFY_NOT_REACHED();
  62. };
  63. Vector<CalendarFieldData> result;
  64. result.ensure_capacity(fields.size());
  65. for (auto field : fields)
  66. result.unchecked_append(data_for_field(field));
  67. quick_sort(result, [](auto const& lhs, auto const& rhs) {
  68. return StringView { lhs.property->as_string() } < StringView { rhs.property->as_string() };
  69. });
  70. return result;
  71. }
  72. template<typename T>
  73. static void set_field_value(CalendarField field, CalendarFields& fields, T&& value)
  74. {
  75. switch (field) {
  76. #define __JS_ENUMERATE(enumeration, field_name, property_key, conversion) \
  77. case enumeration: \
  78. if constexpr (IsAssignable<decltype(fields.field_name), RemoveCVReference<T>>) \
  79. fields.field_name = value; \
  80. return;
  81. JS_ENUMERATE_CALENDAR_FIELDS
  82. #undef __JS_ENUMERATE
  83. }
  84. VERIFY_NOT_REACHED();
  85. }
  86. static void set_default_field_value(CalendarField field, CalendarFields& fields)
  87. {
  88. CalendarFields default_ {};
  89. switch (field) {
  90. #define __JS_ENUMERATE(enumeration, field_name, property_key, conversion) \
  91. case enumeration: \
  92. fields.field_name = default_.field_name; \
  93. return;
  94. JS_ENUMERATE_CALENDAR_FIELDS
  95. #undef __JS_ENUMERATE
  96. }
  97. VERIFY_NOT_REACHED();
  98. }
  99. // 12.1.1 CanonicalizeCalendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal-canonicalizecalendar
  100. ThrowCompletionOr<String> canonicalize_calendar(VM& vm, StringView id)
  101. {
  102. // 1. Let calendars be AvailableCalendars().
  103. auto const& calendars = available_calendars();
  104. // 2. If calendars does not contain the ASCII-lowercase of id, throw a RangeError exception.
  105. for (auto const& calendar : calendars) {
  106. if (calendar.equals_ignoring_ascii_case(id)) {
  107. // 3. Return CanonicalizeUValue("ca", id).
  108. return Unicode::canonicalize_unicode_extension_values("ca"sv, id);
  109. }
  110. }
  111. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, id);
  112. }
  113. // 12.1.2 AvailableCalendars ( ), https://tc39.es/proposal-temporal/#sec-availablecalendars
  114. Vector<String> const& available_calendars()
  115. {
  116. // The implementation-defined abstract operation AvailableCalendars takes no arguments and returns a List of calendar
  117. // types. The returned List is sorted according to lexicographic code unit order, and contains unique calendar types
  118. // in canonical form (12.1) identifying the calendars for which the implementation provides the functionality of
  119. // Intl.DateTimeFormat objects, including their aliases (e.g., either both or neither of "islamicc" and
  120. // "islamic-civil"). The List must include "iso8601".
  121. return Unicode::available_calendars();
  122. }
  123. // 12.2.3 PrepareCalendarFields ( calendar, fields, calendarFieldNames, nonCalendarFieldNames, requiredFieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-preparecalendarfields
  124. ThrowCompletionOr<CalendarFields> prepare_calendar_fields(VM& vm, StringView calendar, Object const& fields, CalendarFieldList calendar_field_names, CalendarFieldList non_calendar_field_names, CalendarFieldListOrPartial required_field_names)
  125. {
  126. // 1. Assert: If requiredFieldNames is a List, requiredFieldNames contains zero or one of each of the elements of
  127. // calendarFieldNames and nonCalendarFieldNames.
  128. // 2. Let fieldNames be the list-concatenation of calendarFieldNames and nonCalendarFieldNames.
  129. Vector<CalendarField> field_names;
  130. field_names.append(calendar_field_names.data(), calendar_field_names.size());
  131. field_names.append(non_calendar_field_names.data(), non_calendar_field_names.size());
  132. // 3. Let extraFieldNames be CalendarExtraFields(calendar, calendarFieldNames).
  133. auto extra_field_names = calendar_extra_fields(calendar, calendar_field_names);
  134. // 4. Set fieldNames to the list-concatenation of fieldNames and extraFieldNames.
  135. field_names.extend(move(extra_field_names));
  136. // 5. Assert: fieldNames contains no duplicate elements.
  137. // 6. Let result be a Calendar Fields Record with all fields equal to UNSET.
  138. auto result = CalendarFields::unset();
  139. // 7. Let any be false.
  140. auto any = false;
  141. // 8. Let sortedPropertyNames be a List whose elements are the values in the Property Key column of Table 19
  142. // corresponding to the elements of fieldNames, sorted according to lexicographic code unit order.
  143. auto sorted_property_names = sorted_calendar_fields(vm, field_names);
  144. // 9. For each property name property of sortedPropertyNames, do
  145. for (auto const& [key, property, conversion] : sorted_property_names) {
  146. // a. Let key be the value in the Enumeration Key column of Table 19 corresponding to the row whose Property Key value is property.
  147. // b. Let value be ? Get(fields, property).
  148. auto value = TRY(fields.get(property));
  149. // c. If value is not undefined, then
  150. if (!value.is_undefined()) {
  151. // i. Set any to true.
  152. any = true;
  153. // ii. Let Conversion be the Conversion value of the same row.
  154. switch (conversion) {
  155. // iii. If Conversion is TO-INTEGER-WITH-TRUNCATION, then
  156. case CalendarFieldConversion::ToIntegerWithTruncation:
  157. // 1. Set value to ? ToIntegerWithTruncation(value).
  158. // 2. Set value to 𝔽(value).
  159. set_field_value(key, result, TRY(to_integer_with_truncation(vm, value, ErrorType::TemporalInvalidCalendarFieldName, *property)));
  160. break;
  161. // iv. Else if Conversion is TO-POSITIVE-INTEGER-WITH-TRUNCATION, then
  162. case CalendarFieldConversion::ToPositiveIntegerWithTruncation:
  163. // 1. Set value to ? ToPositiveIntegerWithTruncation(value).
  164. // 2. Set value to 𝔽(value).
  165. set_field_value(key, result, TRY(to_positive_integer_with_truncation(vm, value, ErrorType::TemporalInvalidCalendarFieldName, *property)));
  166. break;
  167. // v. Else if Conversion is TO-STRING, then
  168. case CalendarFieldConversion::ToString:
  169. // 1. Set value to ? ToString(value).
  170. set_field_value(key, result, TRY(value.to_string(vm)));
  171. break;
  172. // vi. Else if Conversion is TO-TEMPORAL-TIME-ZONE-IDENTIFIER, then
  173. case CalendarFieldConversion::ToTemporalTimeZoneIdentifier:
  174. // 1. Set value to ? ToTemporalTimeZoneIdentifier(value).
  175. set_field_value(key, result, TRY(to_temporal_time_zone_identifier(vm, value)));
  176. break;
  177. // vii. Else if Conversion is TO-MONTH-CODE, then
  178. case CalendarFieldConversion::ToMonthCode:
  179. // 1. Set value to ? ToMonthCode(value).
  180. set_field_value(key, result, TRY(to_month_code(vm, value)));
  181. break;
  182. // viii. Else,
  183. case CalendarFieldConversion::ToOffsetString:
  184. // 1. Assert: Conversion is TO-OFFSET-STRING.
  185. // 2. Set value to ? ToOffsetString(value).
  186. set_field_value(key, result, TRY(to_offset_string(vm, value)));
  187. break;
  188. }
  189. // ix. Set result's field whose name is given in the Field Name column of the same row to value.
  190. }
  191. // d. Else if requiredFieldNames is a List, then
  192. else if (auto const* required = required_field_names.get_pointer<CalendarFieldList>()) {
  193. // i. If requiredFieldNames contains key, then
  194. if (required->contains_slow(key)) {
  195. // 1. Throw a TypeError exception.
  196. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, *property);
  197. }
  198. // ii. Set result's field whose name is given in the Field Name column of the same row to the corresponding
  199. // Default value of the same row.
  200. set_default_field_value(key, result);
  201. }
  202. }
  203. // 10. If requiredFieldNames is PARTIAL and any is false, then
  204. if (required_field_names.has<Partial>() && !any) {
  205. // a. Throw a TypeError exception.
  206. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustBePartialTemporalObject);
  207. }
  208. // 11. Return result.
  209. return result;
  210. }
  211. // 12.2.4 CalendarFieldKeysPresent ( fields ), https://tc39.es/proposal-temporal/#sec-temporal-calendarfieldkeyspresent
  212. Vector<CalendarField> calendar_field_keys_present(CalendarFields const& fields)
  213. {
  214. // 1. Let list be « ».
  215. Vector<CalendarField> list;
  216. auto handle_field = [&](auto enumeration_key, auto const& value) {
  217. // a. Let value be fields' field whose name is given in the Field Name column of the row.
  218. // b. Let enumerationKey be the value in the Enumeration Key column of the row.
  219. // c. If value is not unset, append enumerationKey to list.
  220. if (value.has_value())
  221. list.append(enumeration_key);
  222. };
  223. // 2. For each row of Table 19, except the header row, do
  224. #define __JS_ENUMERATE(enumeration, field_name, property_key, conversion) \
  225. handle_field(enumeration, fields.field_name);
  226. JS_ENUMERATE_CALENDAR_FIELDS
  227. #undef __JS_ENUMERATE
  228. // 3. Return list.
  229. return list;
  230. }
  231. // 12.2.5 CalendarMergeFields ( calendar, fields, additionalFields ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmergefields
  232. CalendarFields calendar_merge_fields(StringView calendar, CalendarFields const& fields, CalendarFields const& additional_fields)
  233. {
  234. // 1. Let additionalKeys be CalendarFieldKeysPresent(additionalFields).
  235. auto additional_keys = calendar_field_keys_present(additional_fields);
  236. // 2. Let overriddenKeys be CalendarFieldKeysToIgnore(calendar, additionalKeys).
  237. auto overridden_keys = calendar_field_keys_to_ignore(calendar, additional_keys);
  238. // 3. Let merged be a Calendar Fields Record with all fields set to unset.
  239. auto merged = CalendarFields::unset();
  240. // 4. Let fieldsKeys be CalendarFieldKeysPresent(fields).
  241. auto fields_keys = calendar_field_keys_present(fields);
  242. auto merge_field = [&](auto key, auto& merged_field, auto const& fields_field, auto const& additional_fields_field) {
  243. // a. Let key be the value in the Enumeration Key column of the row.
  244. // b. If fieldsKeys contains key and overriddenKeys does not contain key, then
  245. if (fields_keys.contains_slow(key) && !overridden_keys.contains_slow(key)) {
  246. // i. Let propValue be fields' field whose name is given in the Field Name column of the row.
  247. // ii. Set merged's field whose name is given in the Field Name column of the row to propValue.
  248. merged_field = fields_field;
  249. }
  250. // c. If additionalKeys contains key, then
  251. if (additional_keys.contains_slow(key)) {
  252. // i. Let propValue be additionalFields' field whose name is given in the Field Name column of the row.
  253. // ii. Set merged's field whose name is given in the Field Name column of the row to propValue.
  254. merged_field = additional_fields_field;
  255. }
  256. };
  257. // 5. For each row of Table 19, except the header row, do
  258. #define __JS_ENUMERATE(enumeration, field_name, property_key, conversion) \
  259. merge_field(enumeration, merged.field_name, fields.field_name, additional_fields.field_name);
  260. JS_ENUMERATE_CALENDAR_FIELDS
  261. #undef __JS_ENUMERATE
  262. // 6. Return merged.
  263. return merged;
  264. }
  265. // 12.2.8 ToTemporalCalendarIdentifier ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendaridentifier
  266. ThrowCompletionOr<String> to_temporal_calendar_identifier(VM& vm, Value temporal_calendar_like)
  267. {
  268. // 1. If temporalCalendarLike is an Object, then
  269. if (temporal_calendar_like.is_object()) {
  270. auto const& temporal_calendar_object = temporal_calendar_like.as_object();
  271. // a. If temporalCalendarLike has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]],
  272. // [[InitializedTemporalMonthDay]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]]
  273. // internal slot, then
  274. // i. Return temporalCalendarLike.[[Calendar]].
  275. // FIXME: Add the other calendar-holding types as we define them.
  276. if (is<PlainMonthDay>(temporal_calendar_object))
  277. return static_cast<PlainMonthDay const&>(temporal_calendar_object).calendar();
  278. if (is<PlainYearMonth>(temporal_calendar_object))
  279. return static_cast<PlainYearMonth const&>(temporal_calendar_object).calendar();
  280. }
  281. // 2. If temporalCalendarLike is not a String, throw a TypeError exception.
  282. if (!temporal_calendar_like.is_string())
  283. return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidCalendar);
  284. // 3. Let identifier be ? ParseTemporalCalendarString(temporalCalendarLike).
  285. auto identifier = TRY(parse_temporal_calendar_string(vm, temporal_calendar_like.as_string().utf8_string()));
  286. // 4. Return ? CanonicalizeCalendar(identifier).
  287. return TRY(canonicalize_calendar(vm, identifier));
  288. }
  289. // 12.2.9 GetTemporalCalendarIdentifierWithISODefault ( item ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalcalendarslotvaluewithisodefault
  290. ThrowCompletionOr<String> get_temporal_calendar_identifier_with_iso_default(VM& vm, Object const& item)
  291. {
  292. // 1. If item has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]],
  293. // [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  294. // a. Return item.[[Calendar]].
  295. // FIXME: Add the other calendar-holding types as we define them.
  296. if (is<PlainMonthDay>(item))
  297. return static_cast<PlainMonthDay const&>(item).calendar();
  298. if (is<PlainYearMonth>(item))
  299. return static_cast<PlainYearMonth const&>(item).calendar();
  300. // 2. Let calendarLike be ? Get(item, "calendar").
  301. auto calendar_like = TRY(item.get(vm.names.calendar));
  302. // 3. If calendarLike is undefined, then
  303. if (calendar_like.is_undefined()) {
  304. // a. Return "iso8601".
  305. return "iso8601"_string;
  306. }
  307. // 4. Return ? ToTemporalCalendarIdentifier(calendarLike).
  308. return TRY(to_temporal_calendar_identifier(vm, calendar_like));
  309. }
  310. // 12.2.11 CalendarYearMonthFromFields ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryearmonthfromfields
  311. ThrowCompletionOr<ISODate> calendar_year_month_from_fields(VM& vm, StringView calendar, CalendarFields fields, Overflow overflow)
  312. {
  313. // 1. Perform ? CalendarResolveFields(calendar, fields, YEAR-MONTH).
  314. TRY(calendar_resolve_fields(vm, calendar, fields, DateType::YearMonth));
  315. // FIXME: 2. Let firstDayIndex be the 1-based index of the first day of the month described by fields (i.e., 1 unless the
  316. // month's first day is skipped by this calendar.)
  317. static auto constexpr first_day_index = 1;
  318. // 3. Set fields.[[Day]] to firstDayIndex.
  319. fields.day = first_day_index;
  320. // 4. Let result be ? CalendarDateToISO(calendar, fields, overflow).
  321. auto result = TRY(calendar_date_to_iso(vm, calendar, fields, overflow));
  322. // 5. If ISOYearMonthWithinLimits(result) is false, throw a RangeError exception.
  323. if (!iso_year_month_within_limits(result))
  324. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODate);
  325. // 6. Return result.
  326. return result;
  327. }
  328. // 12.2.12 CalendarMonthDayFromFields ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdayfromfields
  329. ThrowCompletionOr<ISODate> calendar_month_day_from_fields(VM& vm, StringView calendar, CalendarFields fields, Overflow overflow)
  330. {
  331. // 1. Perform ? CalendarResolveFields(calendar, fields, MONTH-DAY).
  332. TRY(calendar_resolve_fields(vm, calendar, fields, DateType::MonthDay));
  333. // 2. Let result be ? CalendarMonthDayToISOReferenceDate(calendar, fields, overflow).
  334. auto result = TRY(calendar_month_day_to_iso_reference_date(vm, calendar, fields, overflow));
  335. // 3. If ISODateWithinLimits(result) is false, throw a RangeError exception.
  336. if (!iso_date_within_limits(result))
  337. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODate);
  338. // 4. Return result.
  339. return result;
  340. }
  341. // 12.2.13 FormatCalendarAnnotation ( id, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-formatcalendarannotation
  342. String format_calendar_annotation(StringView id, ShowCalendar show_calendar)
  343. {
  344. // 1. If showCalendar is NEVER, return the empty String.
  345. if (show_calendar == ShowCalendar::Never)
  346. return String {};
  347. // 2. If showCalendar is AUTO and id is "iso8601", return the empty String.
  348. if (show_calendar == ShowCalendar::Auto && id == "iso8601"sv)
  349. return String {};
  350. // 3. If showCalendar is CRITICAL, let flag be "!"; else, let flag be the empty String.
  351. auto flag = show_calendar == ShowCalendar::Critical ? "!"sv : ""sv;
  352. // 4. Return the string-concatenation of "[", flag, "u-ca=", id, and "]".
  353. return MUST(String::formatted("[{}u-ca={}]", flag, id));
  354. }
  355. // 12.2.14 CalendarEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-calendarequals
  356. bool calendar_equals(StringView one, StringView two)
  357. {
  358. // 1. If CanonicalizeUValue("ca", one) is CanonicalizeUValue("ca", two), return true.
  359. // 2. Return false.
  360. return Unicode::canonicalize_unicode_extension_values("ca"sv, one)
  361. == Unicode::canonicalize_unicode_extension_values("ca"sv, two);
  362. }
  363. // 12.2.15 ISODaysInMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isodaysinmonth
  364. u8 iso_days_in_month(double year, double month)
  365. {
  366. // 1. If month is 1, 3, 5, 7, 8, 10, or 12, return 31.
  367. if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
  368. return 31;
  369. // 2. If month is 4, 6, 9, or 11, return 30.
  370. if (month == 4 || month == 6 || month == 9 || month == 11)
  371. return 30;
  372. // 3. Assert: month is 2.
  373. VERIFY(month == 2);
  374. // 4. Return 28 + MathematicalInLeapYear(EpochTimeForYear(year)).
  375. return 28 + mathematical_in_leap_year(epoch_time_for_year(year));
  376. }
  377. // 12.2.16 ISOWeekOfYear ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isoweekofyear
  378. YearWeek iso_week_of_year(ISODate const& iso_date)
  379. {
  380. // 1. Let year be isoDate.[[Year]].
  381. auto year = iso_date.year;
  382. // 2. Let wednesday be 3.
  383. static constexpr auto wednesday = 3;
  384. // 3. Let thursday be 4.
  385. static constexpr auto thursday = 4;
  386. // 4. Let friday be 5.
  387. static constexpr auto friday = 5;
  388. // 5. Let saturday be 6.
  389. static constexpr auto saturday = 6;
  390. // 6. Let daysInWeek be 7.
  391. static constexpr auto days_in_week = 7;
  392. // 7. Let maxWeekNumber be 53.
  393. static constexpr auto max_week_number = 53;
  394. // 8. Let dayOfYear be ISODayOfYear(isoDate).
  395. auto day_of_year = iso_day_of_year(iso_date);
  396. // 9. Let dayOfWeek be ISODayOfWeek(isoDate).
  397. auto day_of_week = iso_day_of_week(iso_date);
  398. // 10. Let week be floor((dayOfYear + daysInWeek - dayOfWeek + wednesday) / daysInWeek).
  399. auto week = floor(static_cast<double>(day_of_year + days_in_week - day_of_week + wednesday) / static_cast<double>(days_in_week));
  400. // 11. If week < 1, then
  401. if (week < 1) {
  402. // a. NOTE: This is the last week of the previous year.
  403. // b. Let jan1st be CreateISODateRecord(year, 1, 1).
  404. auto jan1st = create_iso_date_record(year, 1, 1);
  405. // c. Let dayOfJan1st be ISODayOfWeek(jan1st).
  406. auto day_of_jan1st = iso_day_of_week(jan1st);
  407. // d. If dayOfJan1st = friday, then
  408. if (day_of_jan1st == friday) {
  409. // i. Return Year-Week Record { [[Week]]: maxWeekNumber, [[Year]]: year - 1 }.
  410. return { .week = max_week_number, .year = year - 1 };
  411. }
  412. // e. If dayOfJan1st = saturday, and MathematicalInLeapYear(EpochTimeForYear(year - 1)) = 1, then
  413. if (day_of_jan1st == saturday && mathematical_in_leap_year(epoch_time_for_year(year - 1)) == 1) {
  414. // i. Return Year-Week Record { [[Week]]: maxWeekNumber. [[Year]]: year - 1 }.
  415. return { .week = max_week_number, .year = year - 1 };
  416. }
  417. // f. Return Year-Week Record { [[Week]]: maxWeekNumber - 1, [[Year]]: year - 1 }.
  418. return { .week = max_week_number - 1, .year = year - 1 };
  419. }
  420. // 12. If week = maxWeekNumber, then
  421. if (week == max_week_number) {
  422. // a. Let daysInYear be MathematicalDaysInYear(year).
  423. auto days_in_year = mathematical_days_in_year(year);
  424. // b. Let daysLaterInYear be daysInYear - dayOfYear.
  425. auto days_later_in_year = days_in_year - day_of_year;
  426. // c. Let daysAfterThursday be thursday - dayOfWeek.
  427. auto days_after_thursday = thursday - day_of_week;
  428. // d. If daysLaterInYear < daysAfterThursday, then
  429. if (days_later_in_year < days_after_thursday) {
  430. // i. Return Year-Week Record { [[Week]]: 1, [[Year]]: year + 1 }.
  431. return { .week = 1, .year = year + 1 };
  432. }
  433. }
  434. // 13. Return Year-Week Record { [[Week]]: week, [[Year]]: year }.
  435. return { .week = week, .year = year };
  436. }
  437. // 12.2.17 ISODayOfYear ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isodayofyear
  438. u16 iso_day_of_year(ISODate const& iso_date)
  439. {
  440. // 1. Let epochDays be ISODateToEpochDays(isoDate.[[Year]], isoDate.[[Month]] - 1, isoDate.[[Day]]).
  441. auto epoch_days = iso_date_to_epoch_days(iso_date.year, iso_date.month - 1, iso_date.day);
  442. // 2. Return EpochTimeToDayInYear(EpochDaysToEpochMs(epochDays, 0)) + 1.
  443. return epoch_time_to_day_in_year(epoch_days_to_epoch_ms(epoch_days, 0)) + 1;
  444. }
  445. // 12.2.18 ISODayOfWeek ( isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-isodayofweek
  446. u8 iso_day_of_week(ISODate const& iso_date)
  447. {
  448. // 1. Let epochDays be ISODateToEpochDays(isoDate.[[Year]], isoDate.[[Month]] - 1, isoDate.[[Day]]).
  449. auto epoch_days = iso_date_to_epoch_days(iso_date.year, iso_date.month - 1, iso_date.day);
  450. // 2. Let dayOfWeek be EpochTimeToWeekDay(EpochDaysToEpochMs(epochDays, 0)).
  451. auto day_of_week = epoch_time_to_week_day(epoch_days_to_epoch_ms(epoch_days, 0));
  452. // 3. If dayOfWeek = 0, return 7.
  453. if (day_of_week == 0)
  454. return 7;
  455. // 4. Return dayOfWeek.
  456. return day_of_week;
  457. }
  458. // 12.2.19 CalendarDateToISO ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendardatetoiso
  459. ThrowCompletionOr<ISODate> calendar_date_to_iso(VM& vm, StringView calendar, CalendarFields const& fields, Overflow overflow)
  460. {
  461. // 1. If calendar is "iso8601", then
  462. if (calendar == "iso8601"sv) {
  463. // a. Assert: fields.[[Year]], fields.[[Month]], and fields.[[Day]] are not UNSET.
  464. VERIFY(fields.year.has_value());
  465. VERIFY(fields.month.has_value());
  466. VERIFY(fields.day.has_value());
  467. // b. Return ? RegulateISODate(fields.[[Year]], fields.[[Month]], fields.[[Day]], overflow).
  468. return TRY(regulate_iso_date(vm, *fields.year, *fields.month, *fields.day, overflow));
  469. }
  470. // 2. Return an implementation-defined ISO Date Record, or throw a RangeError exception, as described below.
  471. // FIXME: Create an ISODateRecord based on an ISO8601 calendar for now. See also: CalendarResolveFields.
  472. return calendar_month_day_to_iso_reference_date(vm, "iso8601"sv, fields, overflow);
  473. }
  474. // 12.2.20 CalendarMonthDayToISOReferenceDate ( calendar, fields, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdaytoisoreferencedate
  475. ThrowCompletionOr<ISODate> calendar_month_day_to_iso_reference_date(VM& vm, StringView calendar, CalendarFields const& fields, Overflow overflow)
  476. {
  477. // 1. If calendar is "iso8601", then
  478. if (calendar == "iso8601"sv) {
  479. // a. Assert: fields.[[Month]] and fields.[[Day]] are not UNSET.
  480. VERIFY(fields.month.has_value());
  481. VERIFY(fields.day.has_value());
  482. // b. Let referenceISOYear be 1972 (the first ISO 8601 leap year after the epoch).
  483. static constexpr i32 reference_iso_year = 1972;
  484. // c. If fields.[[Year]] is UNSET, let year be referenceISOYear; else let year be fields.[[Year]].
  485. auto year = !fields.year.has_value() ? reference_iso_year : *fields.year;
  486. // d. Let result be ? RegulateISODate(year, fields.[[Month]], fields.[[Day]], overflow).
  487. auto result = TRY(regulate_iso_date(vm, year, *fields.month, *fields.day, overflow));
  488. // e. Return CreateISODateRecord(referenceISOYear, result.[[Month]], result.[[Day]]).
  489. return create_iso_date_record(reference_iso_year, result.month, result.day);
  490. }
  491. // 2. Return an implementation-defined ISO Date Record, or throw a RangeError exception, as described below.
  492. // FIXME: Create an ISODateRecord based on an ISO8601 calendar for now. See also: CalendarResolveFields.
  493. return calendar_month_day_to_iso_reference_date(vm, "iso8601"sv, fields, overflow);
  494. }
  495. // 12.2.21 CalendarISOToDate ( calendar, isoDate ), https://tc39.es/proposal-temporal/#sec-temporal-calendarisotodate
  496. CalendarDate calendar_iso_to_date(StringView calendar, ISODate const& iso_date)
  497. {
  498. // 1. If calendar is "iso8601", then
  499. if (calendar == "iso8601"sv) {
  500. // a. Let monthNumberPart be ToZeroPaddedDecimalString(isoDate.[[Month]], 2).
  501. // b. Let monthCode be the string-concatenation of "M" and monthNumberPart.
  502. auto month_code = MUST(String::formatted("M{:02}", iso_date.month));
  503. // c. If MathematicalInLeapYear(EpochTimeForYear(isoDate.[[Year]])) = 1, let inLeapYear be true; else let inLeapYear be false.
  504. auto in_leap_year = mathematical_in_leap_year(epoch_time_for_year(iso_date.year)) == 1;
  505. // d. Return Calendar Date Record { [[Era]]: undefined, [[EraYear]]: undefined, [[Year]]: isoDate.[[Year]],
  506. // [[Month]]: isoDate.[[Month]], [[MonthCode]]: monthCode, [[Day]]: isoDate.[[Day]], [[DayOfWeek]]: ISODayOfWeek(isoDate),
  507. // [[DayOfYear]]: ISODayOfYear(isoDate), [[WeekOfYear]]: ISOWeekOfYear(isoDate), [[DaysInWeek]]: 7,
  508. // [[DaysInMonth]]: ISODaysInMonth(isoDate.[[Year]], isoDate.[[Month]]), [[DaysInYear]]: MathematicalDaysInYear(isoDate.[[Year]]),
  509. // [[MonthsInYear]]: 12, [[InLeapYear]]: inLeapYear }.
  510. return CalendarDate {
  511. .era = {},
  512. .era_year = {},
  513. .year = iso_date.year,
  514. .month = iso_date.month,
  515. .month_code = move(month_code),
  516. .day = iso_date.day,
  517. .day_of_week = iso_day_of_week(iso_date),
  518. .day_of_year = iso_day_of_year(iso_date),
  519. .week_of_year = iso_week_of_year(iso_date),
  520. .days_in_week = 7,
  521. .days_in_month = iso_days_in_month(iso_date.year, iso_date.month),
  522. .days_in_year = mathematical_days_in_year(iso_date.year),
  523. .months_in_year = 12,
  524. .in_leap_year = in_leap_year,
  525. };
  526. }
  527. // 2. Return an implementation-defined Calendar Date Record with fields as described in Table 18.
  528. // FIXME: Return an ISO8601 calendar date for now.
  529. return calendar_iso_to_date("iso8601"sv, iso_date);
  530. }
  531. // 12.2.22 CalendarExtraFields ( calendar, fields ), https://tc39.es/proposal-temporal/#sec-temporal-calendarextrafields
  532. Vector<CalendarField> calendar_extra_fields(StringView calendar, CalendarFieldList)
  533. {
  534. // 1. If calendar is "iso8601", return an empty List.
  535. if (calendar == "iso8601"sv)
  536. return {};
  537. // FIXME: 2. Return an implementation-defined List as described above.
  538. return {};
  539. }
  540. // 12.2.23 CalendarFieldKeysToIgnore ( calendar, keys ), https://tc39.es/proposal-temporal/#sec-temporal-calendarfieldkeystoignore
  541. Vector<CalendarField> calendar_field_keys_to_ignore(StringView calendar, ReadonlySpan<CalendarField> keys)
  542. {
  543. // 1. If calendar is "iso8601", then
  544. if (calendar == "iso8601"sv) {
  545. // a. Let ignoredKeys be an empty List.
  546. Vector<CalendarField> ignored_keys;
  547. // b. For each element key of keys, do
  548. for (auto key : keys) {
  549. // i. Append key to ignoredKeys.
  550. ignored_keys.append(key);
  551. // ii. If key is MONTH, append MONTH-CODE to ignoredKeys.
  552. if (key == CalendarField::Month)
  553. ignored_keys.append(CalendarField::MonthCode);
  554. // iii. Else if key is MONTH-CODE, append MONTH to ignoredKeys.
  555. else if (key == CalendarField::MonthCode)
  556. ignored_keys.append(CalendarField::Month);
  557. }
  558. // c. NOTE: While ignoredKeys can have duplicate elements, this is not intended to be meaningful. This specification
  559. // only checks whether particular keys are or are not members of the list.
  560. // d. Return ignoredKeys.
  561. return ignored_keys;
  562. }
  563. // 2. Return an implementation-defined List as described below.
  564. // FIXME: Return keys for an ISO8601 calendar for now.
  565. return calendar_field_keys_to_ignore("iso8601"sv, keys);
  566. }
  567. // 12.2.24 CalendarResolveFields ( calendar, fields, type ), https://tc39.es/proposal-temporal/#sec-temporal-calendarresolvefields
  568. ThrowCompletionOr<void> calendar_resolve_fields(VM& vm, StringView calendar, CalendarFields& fields, DateType type)
  569. {
  570. // 1. If calendar is "iso8601", then
  571. if (calendar == "iso8601"sv) {
  572. // a. If type is DATE or YEAR-MONTH and fields.[[Year]] is UNSET, throw a TypeError exception.
  573. if ((type == DateType::Date || type == DateType::YearMonth) && !fields.year.has_value())
  574. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, "year"sv);
  575. // b. If type is DATE or MONTH-DAY and fields.[[Day]] is UNSET, throw a TypeError exception.
  576. if ((type == DateType::Date || type == DateType::MonthDay) && !fields.day.has_value())
  577. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, "day"sv);
  578. // c. Let month be fields.[[Month]].
  579. auto const& month = fields.month;
  580. // d. Let monthCode be fields.[[MonthCode]].
  581. auto const& month_code = fields.month_code;
  582. // e. If monthCode is UNSET, then
  583. if (!month_code.has_value()) {
  584. // i. If month is UNSET, throw a TypeError exception.
  585. if (!month.has_value())
  586. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, "month"sv);
  587. // ii. Return UNUSED.
  588. return {};
  589. }
  590. // f. Assert: monthCode is a String.
  591. VERIFY(month_code.has_value());
  592. // g. NOTE: The ISO 8601 calendar does not include leap months.
  593. // h. If the length of monthCode is not 3, throw a RangeError exception.
  594. if (month_code->byte_count() != 3)
  595. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFieldName, "monthCode"sv);
  596. // i. If the first code unit of monthCode is not 0x004D (LATIN CAPITAL LETTER M), throw a RangeError exception.
  597. if (month_code->bytes_as_string_view()[0] != 'M')
  598. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFieldName, "monthCode"sv);
  599. // j. Let monthCodeDigits be the substring of monthCode from 1.
  600. auto month_code_digits = month_code->bytes_as_string_view().substring_view(1);
  601. // k. If ParseText(StringToCodePoints(monthCodeDigits), DateMonth) is a List of errors, throw a RangeError exception.
  602. if (!parse_iso8601(Production::DateMonth, month_code_digits).has_value())
  603. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFieldName, "monthCode"sv);
  604. // l. Let monthCodeInteger be ℝ(StringToNumber(monthCodeDigits)).
  605. auto month_code_integer = month_code_digits.to_number<u8>().value();
  606. // m. If month is not UNSET and month ≠ monthCodeInteger, throw a RangeError exception.
  607. if (month.has_value() && month != month_code_integer)
  608. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFieldName, "month"sv);
  609. // n. Set fields.[[Month]] to monthCodeInteger.
  610. fields.month = month_code_integer;
  611. }
  612. // 2. Else,
  613. else {
  614. // a. Perform implementation-defined processing to mutate fields, or throw a TypeError or RangeError exception, as described below.
  615. // FIXME: Resolve fields as an ISO8601 calendar for now. See also: CalendarMonthDayToISOReferenceDate.
  616. TRY(calendar_resolve_fields(vm, "iso8601"sv, fields, type));
  617. }
  618. // 3. Return UNUSED.
  619. return {};
  620. }
  621. }