Calendar.cpp 33 KB

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