Calendar.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/TypeCasts.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  13. #include <LibJS/Runtime/Temporal/Calendar.h>
  14. #include <LibJS/Runtime/Temporal/CalendarConstructor.h>
  15. #include <LibJS/Runtime/Temporal/Duration.h>
  16. #include <LibJS/Runtime/Temporal/ISO8601.h>
  17. #include <LibJS/Runtime/Temporal/PlainDate.h>
  18. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  19. #include <LibJS/Runtime/Temporal/PlainMonthDay.h>
  20. #include <LibJS/Runtime/Temporal/PlainTime.h>
  21. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  22. #include <LibJS/Runtime/Temporal/TimeZone.h>
  23. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  24. #include <LibJS/Runtime/Value.h>
  25. namespace JS::Temporal {
  26. // 12 Temporal.Calendar Objects, https://tc39.es/proposal-temporal/#sec-temporal-calendar-objects
  27. Calendar::Calendar(String identifier, Object& prototype)
  28. : Object(prototype)
  29. , m_identifier(move(identifier))
  30. {
  31. }
  32. // 12.1.1 IsBuiltinCalendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal-isbuiltincalendar
  33. bool is_builtin_calendar(String const& identifier)
  34. {
  35. // 1. Let calendars be AvailableCalendars().
  36. auto calendars = available_calendars();
  37. // 2. If calendars contains the ASCII-lowercase of id, return true.
  38. for (auto calendar : calendars) {
  39. if (calendar.equals_ignoring_case(identifier))
  40. return true;
  41. }
  42. // 3. Return false.
  43. return false;
  44. }
  45. // 12.1.2 AvailableCalendars ( ), https://tc39.es/proposal-temporal/#sec-temporal-availablecalendars
  46. Span<StringView const> available_calendars()
  47. {
  48. // 1. Let calendars be the List of String values representing calendar types supported by the implementation.
  49. // NOTE: This can be removed in favor of using `Unicode::get_available_calendars()` once everything is updated to handle non-iso8601 calendars.
  50. static constexpr AK::Array calendars { "iso8601"sv };
  51. // 2. Assert: calendars contains "iso8601".
  52. // 3. Assert: calendars does not contain any element that does not identify a calendar type in the Unicode Common Locale Data Repository (CLDR).
  53. // 4. Sort calendars in order as if an Array of the same values had been sorted using %Array.prototype.sort% with undefined as comparefn.
  54. // 5. Return calendars.
  55. return calendars.span();
  56. }
  57. // 12.2.1 CreateTemporalCalendar ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalcalendar
  58. ThrowCompletionOr<Calendar*> create_temporal_calendar(VM& vm, String const& identifier, FunctionObject const* new_target)
  59. {
  60. auto& realm = *vm.current_realm();
  61. // 1. Assert: IsBuiltinCalendar(identifier) is true.
  62. VERIFY(is_builtin_calendar(identifier));
  63. // 2. If newTarget is not provided, set newTarget to %Temporal.Calendar%.
  64. if (!new_target)
  65. new_target = realm.intrinsics().temporal_calendar_constructor();
  66. // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Calendar.prototype%", « [[InitializedTemporalCalendar]], [[Identifier]] »).
  67. // 4. Set object.[[Identifier]] to the ASCII-lowercase of identifier.
  68. auto* object = TRY(ordinary_create_from_constructor<Calendar>(vm, *new_target, &Intrinsics::temporal_calendar_prototype, identifier.to_lowercase()));
  69. // 5. Return object.
  70. return object;
  71. }
  72. // 12.2.2 GetBuiltinCalendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal-getbuiltincalendar
  73. ThrowCompletionOr<Calendar*> get_builtin_calendar(VM& vm, String const& identifier)
  74. {
  75. // 1. If IsBuiltinCalendar(id) is false, throw a RangeError exception.
  76. if (!is_builtin_calendar(identifier))
  77. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  78. // 2. Return ! CreateTemporalCalendar(id).
  79. return MUST(create_temporal_calendar(vm, identifier));
  80. }
  81. // 12.2.3 GetISO8601Calendar ( ), https://tc39.es/proposal-temporal/#sec-temporal-getiso8601calendar
  82. Calendar* get_iso8601_calendar(VM& vm)
  83. {
  84. // 1. Return ! GetBuiltinCalendar("iso8601").
  85. return MUST(get_builtin_calendar(vm, "iso8601"));
  86. }
  87. // 12.2.4 CalendarFields ( calendar, fieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-calendarfields
  88. ThrowCompletionOr<Vector<String>> calendar_fields(VM& vm, Object& calendar, Vector<StringView> const& field_names)
  89. {
  90. auto& realm = *vm.current_realm();
  91. // 1. Let fields be ? GetMethod(calendar, "fields").
  92. auto fields = TRY(Value(&calendar).get_method(vm, vm.names.fields));
  93. // 2. If fields is undefined, return fieldNames.
  94. if (!fields) {
  95. Vector<String> result;
  96. for (auto& value : field_names)
  97. result.append(value);
  98. return result;
  99. }
  100. // 3. Let fieldsArray be ? Call(fields, calendar, « CreateArrayFromList(fieldNames) »).
  101. auto fields_array = TRY(call(vm, *fields, &calendar, Array::create_from<StringView>(realm, field_names, [&](auto value) { return js_string(vm, value); })));
  102. // 4. Return ? IterableToListOfType(fieldsArray, « String »).
  103. auto list = TRY(iterable_to_list_of_type(vm, fields_array, { OptionType::String }));
  104. Vector<String> result;
  105. for (auto& value : list)
  106. result.append(value.as_string().string());
  107. return result;
  108. }
  109. // 12.2.5 CalendarMergeFields ( calendar, fields, additionalFields ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmergefields
  110. ThrowCompletionOr<Object*> calendar_merge_fields(VM& vm, Object& calendar, Object& fields, Object& additional_fields)
  111. {
  112. // 1. Let mergeFields be ? GetMethod(calendar, "mergeFields").
  113. auto* merge_fields = TRY(Value(&calendar).get_method(vm, vm.names.mergeFields));
  114. // 2. If mergeFields is undefined, then
  115. if (!merge_fields) {
  116. // a. Return ? DefaultMergeCalendarFields(fields, additionalFields).
  117. return TRY(default_merge_calendar_fields(vm, fields, additional_fields));
  118. }
  119. // 3. Let result be ? Call(mergeFields, calendar, « fields, additionalFields »).
  120. auto result = TRY(call(vm, merge_fields, &calendar, &fields, &additional_fields));
  121. // 4. If Type(result) is not Object, throw a TypeError exception.
  122. if (!result.is_object())
  123. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, result.to_string_without_side_effects());
  124. // 5. Return result.
  125. return &result.as_object();
  126. }
  127. // 12.2.6 CalendarDateAdd ( calendar, date, duration [ , options [ , dateAdd ] ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendardateadd
  128. ThrowCompletionOr<PlainDate*> calendar_date_add(VM& vm, Object& calendar, Value date, Duration& duration, Object* options, FunctionObject* date_add)
  129. {
  130. // NOTE: `date` is a `Value` because we sometimes need to pass a PlainDate, sometimes a PlainDateTime, and sometimes undefined.
  131. // 1. Assert: Type(calendar) is Object.
  132. // 2. If options is not present, set options to undefined.
  133. // 3. Assert: Type(options) is Object or Undefined.
  134. // 4. If dateAdd is not present, set dateAdd to ? GetMethod(calendar, "dateAdd").
  135. if (!date_add)
  136. date_add = TRY(Value(&calendar).get_method(vm, vm.names.dateAdd));
  137. // 5. Let addedDate be ? Call(dateAdd, calendar, « date, duration, options »).
  138. auto added_date = TRY(call(vm, date_add ?: js_undefined(), &calendar, date, &duration, options ?: js_undefined()));
  139. // 6. Perform ? RequireInternalSlot(addedDate, [[InitializedTemporalDate]]).
  140. auto* added_date_object = TRY(added_date.to_object(vm));
  141. if (!is<PlainDate>(added_date_object))
  142. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate");
  143. // 7. Return addedDate.
  144. return static_cast<PlainDate*>(added_date_object);
  145. }
  146. // 12.2.7 CalendarDateUntil ( calendar, one, two, options [ , dateUntil ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendardateuntil
  147. ThrowCompletionOr<Duration*> calendar_date_until(VM& vm, Object& calendar, Value one, Value two, Object& options, FunctionObject* date_until)
  148. {
  149. // 1. Assert: Type(calendar) is Object.
  150. // 2. If dateUntil is not present, set dateUntil to ? GetMethod(calendar, "dateUntil").
  151. if (!date_until)
  152. date_until = TRY(Value(&calendar).get_method(vm, vm.names.dateUntil));
  153. // 3. Let duration be ? Call(dateUntil, calendar, « one, two, options »).
  154. auto duration = TRY(call(vm, date_until ?: js_undefined(), &calendar, one, two, &options));
  155. // 4. Perform ? RequireInternalSlot(duration, [[InitializedTemporalDuration]]).
  156. auto* duration_object = TRY(duration.to_object(vm));
  157. if (!is<Duration>(duration_object))
  158. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.Duration");
  159. // 5. Return duration.
  160. return static_cast<Duration*>(duration_object);
  161. }
  162. // 12.2.8 CalendarYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryear
  163. ThrowCompletionOr<double> calendar_year(VM& vm, Object& calendar, Object& date_like)
  164. {
  165. // 1. Assert: Type(calendar) is Object.
  166. // 2. Let result be ? Invoke(calendar, "year", « dateLike »).
  167. auto result = TRY(Value(&calendar).invoke(vm, vm.names.year, &date_like));
  168. // 3. If result is undefined, throw a RangeError exception.
  169. if (result.is_undefined())
  170. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.year.as_string(), vm.names.undefined.as_string());
  171. // 4. Return ? ToIntegerThrowOnInfinity(result).
  172. return TRY(to_integer_throw_on_infinity(vm, result, ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.year.as_string(), vm.names.Infinity.as_string()));
  173. }
  174. // 12.2.9 CalendarMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonth
  175. ThrowCompletionOr<double> calendar_month(VM& vm, Object& calendar, Object& date_like)
  176. {
  177. // 1. Assert: Type(calendar) is Object.
  178. // 2. Let result be ? Invoke(calendar, "month", « dateLike »).
  179. auto result = TRY(Value(&calendar).invoke(vm, vm.names.month, &date_like));
  180. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  181. if (result.is_undefined())
  182. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.month.as_string(), vm.names.undefined.as_string());
  183. // 3. Return ? ToPositiveInteger(result).
  184. return TRY(to_positive_integer(vm, result));
  185. }
  186. // 12.2.10 CalendarMonthCode ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthcode
  187. ThrowCompletionOr<String> calendar_month_code(VM& vm, Object& calendar, Object& date_like)
  188. {
  189. // 1. Assert: Type(calendar) is Object.
  190. // 2. Let result be ? Invoke(calendar, "monthCode", « dateLike »).
  191. auto result = TRY(Value(&calendar).invoke(vm, vm.names.monthCode, &date_like));
  192. // 3. If result is undefined, throw a RangeError exception.
  193. if (result.is_undefined())
  194. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.monthCode.as_string(), vm.names.undefined.as_string());
  195. // 4. Return ? ToString(result).
  196. return result.to_string(vm);
  197. }
  198. // 12.2.11 CalendarDay ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarday
  199. ThrowCompletionOr<double> calendar_day(VM& vm, Object& calendar, Object& date_like)
  200. {
  201. // 1. Assert: Type(calendar) is Object.
  202. // 2. Let result be ? Invoke(calendar, "day", « dateLike »).
  203. auto result = TRY(Value(&calendar).invoke(vm, vm.names.day, &date_like));
  204. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  205. if (result.is_undefined())
  206. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.day.as_string(), vm.names.undefined.as_string());
  207. // 3. Return ? ToPositiveInteger(result).
  208. return TRY(to_positive_integer(vm, result));
  209. }
  210. // 12.2.12 CalendarDayOfWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofweek
  211. ThrowCompletionOr<Value> calendar_day_of_week(VM& vm, Object& calendar, Object& date_like)
  212. {
  213. // 1. Assert: Type(calendar) is Object.
  214. // 2. Let result be ? Invoke(calendar, "dayOfWeek", « dateLike »).
  215. auto result = TRY(Value(&calendar).invoke(vm, vm.names.dayOfWeek, &date_like));
  216. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  217. if (result.is_undefined())
  218. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.dayOfWeek.as_string(), vm.names.undefined.as_string());
  219. // 3. Return ? ToPositiveInteger(result).
  220. return TRY(to_positive_integer(vm, result));
  221. }
  222. // 12.2.13 CalendarDayOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardayofyear
  223. ThrowCompletionOr<Value> calendar_day_of_year(VM& vm, Object& calendar, Object& date_like)
  224. {
  225. // 1. Assert: Type(calendar) is Object.
  226. // 2. Let result be ? Invoke(calendar, "dayOfYear", « dateLike »).
  227. auto result = TRY(Value(&calendar).invoke(vm, vm.names.dayOfYear, &date_like));
  228. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  229. if (result.is_undefined())
  230. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.dayOfYear.as_string(), vm.names.undefined.as_string());
  231. // 3. Return ? ToPositiveInteger(result).
  232. return TRY(to_positive_integer(vm, result));
  233. }
  234. // 12.2.14 CalendarWeekOfYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarweekofyear
  235. ThrowCompletionOr<Value> calendar_week_of_year(VM& vm, Object& calendar, Object& date_like)
  236. {
  237. // 1. Assert: Type(calendar) is Object.
  238. // 2. Let result be ? Invoke(calendar, "weekOfYear", « dateLike »).
  239. auto result = TRY(Value(&calendar).invoke(vm, vm.names.weekOfYear, &date_like));
  240. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  241. if (result.is_undefined())
  242. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.weekOfYear.as_string(), vm.names.undefined.as_string());
  243. // 3. Return ? ToPositiveInteger(result).
  244. return TRY(to_positive_integer(vm, result));
  245. }
  246. // 12.2.14 CalendarDaysInWeek ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinweek
  247. ThrowCompletionOr<Value> calendar_days_in_week(VM& vm, Object& calendar, Object& date_like)
  248. {
  249. // 1. Assert: Type(calendar) is Object.
  250. // 2. Let result be ? Invoke(calendar, "daysInWeek", « dateLike »).
  251. auto result = TRY(Value(&calendar).invoke(vm, vm.names.daysInWeek, &date_like));
  252. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  253. if (result.is_undefined())
  254. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.daysInWeek.as_string(), vm.names.undefined.as_string());
  255. // 3. Return ? ToPositiveInteger(result).
  256. return TRY(to_positive_integer(vm, result));
  257. }
  258. // 12.2.16 CalendarDaysInMonth ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinmonth
  259. ThrowCompletionOr<Value> calendar_days_in_month(VM& vm, Object& calendar, Object& date_like)
  260. {
  261. // 1. Assert: Type(calendar) is Object.
  262. // 2. Let result be ? Invoke(calendar, "daysInMonth", « dateLike »).
  263. auto result = TRY(Value(&calendar).invoke(vm, vm.names.daysInMonth, &date_like));
  264. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  265. if (result.is_undefined())
  266. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.daysInMonth.as_string(), vm.names.undefined.as_string());
  267. // 3. Return ? ToPositiveInteger(result).
  268. return TRY(to_positive_integer(vm, result));
  269. }
  270. // 12.2.17 CalendarDaysInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendardaysinyear
  271. ThrowCompletionOr<Value> calendar_days_in_year(VM& vm, Object& calendar, Object& date_like)
  272. {
  273. // 1. Assert: Type(calendar) is Object.
  274. // 2. Let result be ? Invoke(calendar, "daysInYear", « dateLike »).
  275. auto result = TRY(Value(&calendar).invoke(vm, vm.names.daysInYear, &date_like));
  276. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  277. if (result.is_undefined())
  278. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.daysInYear.as_string(), vm.names.undefined.as_string());
  279. // 3. Return ? ToPositiveInteger(result).
  280. return TRY(to_positive_integer(vm, result));
  281. }
  282. // 12.2.18 CalendarMonthsInYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthsinyear
  283. ThrowCompletionOr<Value> calendar_months_in_year(VM& vm, Object& calendar, Object& date_like)
  284. {
  285. // 1. Assert: Type(calendar) is Object.
  286. // 2. Let result be ? Invoke(calendar, "monthsInYear", « dateLike »).
  287. auto result = TRY(Value(&calendar).invoke(vm, vm.names.monthsInYear, &date_like));
  288. // NOTE: Explicitly handled for a better error message similar to the other calendar property AOs
  289. if (result.is_undefined())
  290. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.monthsInYear.as_string(), vm.names.undefined.as_string());
  291. // 3. Return ? ToPositiveInteger(result).
  292. return TRY(to_positive_integer(vm, result));
  293. }
  294. // 12.2.29 CalendarInLeapYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarinleapyear
  295. ThrowCompletionOr<Value> calendar_in_leap_year(VM& vm, Object& calendar, Object& date_like)
  296. {
  297. // 1. Assert: Type(calendar) is Object.
  298. // 2. Let result be ? Invoke(calendar, "inLeapYear", « dateLike »).
  299. auto result = TRY(Value(&calendar).invoke(vm, vm.names.inLeapYear, &date_like));
  300. // 3. Return ToBoolean(result).
  301. return result.to_boolean();
  302. }
  303. // 15.6.1.1 CalendarEra ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarera
  304. ThrowCompletionOr<Value> calendar_era(VM& vm, Object& calendar, Object& date_like)
  305. {
  306. // 1. Assert: Type(calendar) is Object.
  307. // 2. Let result be ? Invoke(calendar, "era", « dateLike »).
  308. auto result = TRY(Value(&calendar).invoke(vm, vm.names.era, &date_like));
  309. // 3. If result is not undefined, set result to ? ToString(result).
  310. if (!result.is_undefined())
  311. result = js_string(vm, TRY(result.to_string(vm)));
  312. // 4. Return result.
  313. return result;
  314. }
  315. // 15.6.1.2 CalendarEraYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendarerayear
  316. ThrowCompletionOr<Value> calendar_era_year(VM& vm, Object& calendar, Object& date_like)
  317. {
  318. // 1. Assert: Type(calendar) is Object.
  319. // 2. Let result be ? Invoke(calendar, "eraYear", « dateLike »).
  320. auto result = TRY(Value(&calendar).invoke(vm, vm.names.eraYear, &date_like));
  321. // 3. If result is not undefined, set result to ? ToIntegerThrowOnInfinity(result).
  322. if (!result.is_undefined())
  323. result = Value(TRY(to_integer_throw_on_infinity(vm, result, ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.eraYear.as_string(), "Infinity"sv)));
  324. // 4. Return result.
  325. return result;
  326. }
  327. // 12.2.20 ToTemporalCalendar ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendar
  328. ThrowCompletionOr<Object*> to_temporal_calendar(VM& vm, Value temporal_calendar_like)
  329. {
  330. // 1. If Type(temporalCalendarLike) is Object, then
  331. if (temporal_calendar_like.is_object()) {
  332. auto& temporal_calendar_like_object = temporal_calendar_like.as_object();
  333. // a. If temporalCalendarLike has an [[InitializedTemporalCalendar]] internal slot, then
  334. if (is<Calendar>(temporal_calendar_like_object)) {
  335. // i. Return temporalCalendarLike.
  336. return &temporal_calendar_like_object;
  337. }
  338. // b. If temporalCalendarLike has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  339. // i. Return temporalCalendarLike.[[Calendar]].
  340. if (is<PlainDate>(temporal_calendar_like_object))
  341. return &static_cast<PlainDate&>(temporal_calendar_like_object).calendar();
  342. if (is<PlainDateTime>(temporal_calendar_like_object))
  343. return &static_cast<PlainDateTime&>(temporal_calendar_like_object).calendar();
  344. if (is<PlainMonthDay>(temporal_calendar_like_object))
  345. return &static_cast<PlainMonthDay&>(temporal_calendar_like_object).calendar();
  346. if (is<PlainTime>(temporal_calendar_like_object))
  347. return &static_cast<PlainTime&>(temporal_calendar_like_object).calendar();
  348. if (is<PlainYearMonth>(temporal_calendar_like_object))
  349. return &static_cast<PlainYearMonth&>(temporal_calendar_like_object).calendar();
  350. if (is<ZonedDateTime>(temporal_calendar_like_object))
  351. return &static_cast<ZonedDateTime&>(temporal_calendar_like_object).calendar();
  352. // c. If temporalCalendarLike has an [[InitializedTemporalTimeZone]] internal slot, throw a RangeError exception.
  353. if (is<TimeZone>(temporal_calendar_like_object))
  354. return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedTimeZoneObject);
  355. // d. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike.
  356. if (!TRY(temporal_calendar_like_object.has_property(vm.names.calendar)))
  357. return &temporal_calendar_like_object;
  358. // e. Set temporalCalendarLike to ? Get(temporalCalendarLike, "calendar").
  359. temporal_calendar_like = TRY(temporal_calendar_like_object.get(vm.names.calendar));
  360. // f. If Type(temporalCalendarLike) is Object, then
  361. if (temporal_calendar_like.is_object()) {
  362. // i. If temporalCalendarLike has an [[InitializedTemporalTimeZone]] internal slot, throw a RangeError exception.
  363. if (is<TimeZone>(temporal_calendar_like.as_object()))
  364. return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedTimeZoneObject);
  365. // ii. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike.
  366. if (!TRY(temporal_calendar_like.as_object().has_property(vm.names.calendar)))
  367. return &temporal_calendar_like.as_object();
  368. }
  369. }
  370. // 2. Let identifier be ? ToString(temporalCalendarLike).
  371. auto identifier = TRY(temporal_calendar_like.to_string(vm));
  372. // 3. Set identifier to ? ParseTemporalCalendarString(identifier).
  373. identifier = TRY(parse_temporal_calendar_string(vm, identifier));
  374. // 4. If IsBuiltinCalendar(identifier) is false, throw a RangeError exception.
  375. if (!is_builtin_calendar(identifier))
  376. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  377. // 5. Return ! CreateTemporalCalendar(identifier).
  378. return MUST(create_temporal_calendar(vm, identifier));
  379. }
  380. // 12.2.21 ToTemporalCalendarWithISODefault ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendarwithisodefault
  381. ThrowCompletionOr<Object*> to_temporal_calendar_with_iso_default(VM& vm, Value temporal_calendar_like)
  382. {
  383. // 1. If temporalCalendarLike is undefined, then
  384. if (temporal_calendar_like.is_undefined()) {
  385. // a. Return ! GetISO8601Calendar().
  386. return get_iso8601_calendar(vm);
  387. }
  388. // 2. Return ? ToTemporalCalendar(temporalCalendarLike).
  389. return to_temporal_calendar(vm, temporal_calendar_like);
  390. }
  391. // 12.2.22 GetTemporalCalendarWithISODefault ( item ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalcalendarwithisodefault
  392. ThrowCompletionOr<Object*> get_temporal_calendar_with_iso_default(VM& vm, Object& item)
  393. {
  394. // 1. If item has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  395. // a. Return item.[[Calendar]].
  396. if (is<PlainDate>(item))
  397. return &static_cast<PlainDate&>(item).calendar();
  398. if (is<PlainDateTime>(item))
  399. return &static_cast<PlainDateTime&>(item).calendar();
  400. if (is<PlainMonthDay>(item))
  401. return &static_cast<PlainMonthDay&>(item).calendar();
  402. if (is<PlainTime>(item))
  403. return &static_cast<PlainTime&>(item).calendar();
  404. if (is<PlainYearMonth>(item))
  405. return &static_cast<PlainYearMonth&>(item).calendar();
  406. if (is<ZonedDateTime>(item))
  407. return &static_cast<ZonedDateTime&>(item).calendar();
  408. // 2. Let calendarLike be ? Get(item, "calendar").
  409. auto calendar_like = TRY(item.get(vm.names.calendar));
  410. // 3. Return ? ToTemporalCalendarWithISODefault(calendarLike).
  411. return to_temporal_calendar_with_iso_default(vm, calendar_like);
  412. }
  413. // 12.2.23 CalendarDateFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendardatefromfields
  414. ThrowCompletionOr<PlainDate*> calendar_date_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
  415. {
  416. // 1. If options is not present, set options to undefined.
  417. // 2. Let date be ? Invoke(calendar, "dateFromFields", « fields, options »).
  418. auto date = TRY(Value(&calendar).invoke(vm, vm.names.dateFromFields, &fields, options ?: js_undefined()));
  419. // 3. Perform ? RequireInternalSlot(date, [[InitializedTemporalDate]]).
  420. auto* date_object = TRY(date.to_object(vm));
  421. if (!is<PlainDate>(date_object))
  422. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainDate");
  423. // 4. Return date.
  424. return static_cast<PlainDate*>(date_object);
  425. }
  426. // 12.2.24 CalendarYearMonthFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryearmonthfromfields
  427. ThrowCompletionOr<PlainYearMonth*> calendar_year_month_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
  428. {
  429. // 1. If options is not present, set options to undefined.
  430. // 2. Let yearMonth be ? Invoke(calendar, "yearMonthFromFields", « fields, options »).
  431. auto year_month = TRY(Value(&calendar).invoke(vm, vm.names.yearMonthFromFields, &fields, options ?: js_undefined()));
  432. // 3. Perform ? RequireInternalSlot(yearMonth, [[InitializedTemporalYearMonth]]).
  433. auto* year_month_object = TRY(year_month.to_object(vm));
  434. if (!is<PlainYearMonth>(year_month_object))
  435. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainYearMonth");
  436. // 4. Return yearMonth.
  437. return static_cast<PlainYearMonth*>(year_month_object);
  438. }
  439. // 12.2.25 CalendarMonthDayFromFields ( calendar, fields [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-calendarmonthdayfromfields
  440. ThrowCompletionOr<PlainMonthDay*> calendar_month_day_from_fields(VM& vm, Object& calendar, Object const& fields, Object const* options)
  441. {
  442. // 1. If options is not present, set options to undefined.
  443. // 2. Let monthDay be ? Invoke(calendar, "monthDayFromFields", « fields, options »).
  444. auto month_day = TRY(Value(&calendar).invoke(vm, vm.names.monthDayFromFields, &fields, options ?: js_undefined()));
  445. // 3. Perform ? RequireInternalSlot(monthDay, [[InitializedTemporalMonthDay]]).
  446. auto* month_day_object = TRY(month_day.to_object(vm));
  447. if (!is<PlainMonthDay>(month_day_object))
  448. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.PlainMonthDay");
  449. // 4. Return monthDay.
  450. return static_cast<PlainMonthDay*>(month_day_object);
  451. }
  452. // 12.2.26 MaybeFormatCalendarAnnotation ( calendarObject, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-maybeformatcalendarannotation
  453. ThrowCompletionOr<String> maybe_format_calendar_annotation(VM& vm, Object const* calendar_object, StringView show_calendar)
  454. {
  455. // 1. If showCalendar is "never", return the empty String.
  456. if (show_calendar == "never"sv)
  457. return String::empty();
  458. // 2. Assert: Type(calendarObject) is Object.
  459. VERIFY(calendar_object);
  460. // 3. Let calendarID be ? ToString(calendarObject).
  461. auto calendar_id = TRY(Value(calendar_object).to_string(vm));
  462. // 4. Return FormatCalendarAnnotation(calendarID, showCalendar).
  463. return format_calendar_annotation(calendar_id, show_calendar);
  464. }
  465. // 12.2.27 FormatCalendarAnnotation ( id, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-formatcalendarannotation
  466. String format_calendar_annotation(StringView id, StringView show_calendar)
  467. {
  468. VERIFY(show_calendar == "auto"sv || show_calendar == "always"sv || show_calendar == "never"sv || show_calendar == "critical"sv);
  469. // 1. If showCalendar is "never", return the empty String.
  470. if (show_calendar == "never"sv)
  471. return String::empty();
  472. // 2. If showCalendar is "auto" and id is "iso8601", return the empty String.
  473. if (show_calendar == "auto"sv && id == "iso8601"sv)
  474. return String::empty();
  475. // 3. If showCalendar is "critical", let flag be "!"; else, let flag be the empty String.
  476. auto flag = show_calendar == "critical"sv ? "!"sv : ""sv;
  477. // 4. Return the string-concatenation of "[", flag, "u-ca=", id, and "]".
  478. return String::formatted("[{}u-ca={}]", flag, id);
  479. }
  480. // 12.2.28 CalendarEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-calendarequals
  481. ThrowCompletionOr<bool> calendar_equals(VM& vm, Object& one, Object& two)
  482. {
  483. // 1. If one and two are the same Object value, return true.
  484. if (&one == &two)
  485. return true;
  486. // 2. Let calendarOne be ? ToString(one).
  487. auto calendar_one = TRY(Value(&one).to_string(vm));
  488. // 3. Let calendarTwo be ? ToString(two).
  489. auto calendar_two = TRY(Value(&two).to_string(vm));
  490. // 4. If calendarOne is calendarTwo, return true.
  491. if (calendar_one == calendar_two)
  492. return true;
  493. // 5. Return false.
  494. return false;
  495. }
  496. // 12.2.29 ConsolidateCalendars ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-consolidatecalendars
  497. ThrowCompletionOr<Object*> consolidate_calendars(VM& vm, Object& one, Object& two)
  498. {
  499. // 1. If one and two are the same Object value, return two.
  500. if (&one == &two)
  501. return &two;
  502. // 2. Let calendarOne be ? ToString(one).
  503. auto calendar_one = TRY(Value(&one).to_string(vm));
  504. // 3. Let calendarTwo be ? ToString(two).
  505. auto calendar_two = TRY(Value(&two).to_string(vm));
  506. // 4. If calendarOne is calendarTwo, return two.
  507. if (calendar_one == calendar_two)
  508. return &two;
  509. // 5. If calendarOne is "iso8601", return two.
  510. if (calendar_one == "iso8601"sv)
  511. return &two;
  512. // 6. If calendarTwo is "iso8601", return one.
  513. if (calendar_two == "iso8601"sv)
  514. return &one;
  515. // 7. Throw a RangeError exception.
  516. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendar);
  517. }
  518. // 12.2.30 ISODaysInMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isodaysinmonth
  519. u8 iso_days_in_month(i32 year, u8 month)
  520. {
  521. // 1. Assert: year is an integer.
  522. // 2. Assert: month is an integer, month ≥ 1, and month ≤ 12.
  523. VERIFY(month >= 1 && month <= 12);
  524. // 3. If month is 1, 3, 5, 7, 8, 10, or 12, return 31.
  525. if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
  526. return 31;
  527. // 4. If month is 4, 6, 9, or 11, return 30.
  528. if (month == 4 || month == 6 || month == 9 || month == 11)
  529. return 30;
  530. // 5. Return 28 + ℝ(InLeapYear(TimeFromYear(𝔽(year)))).
  531. return 28 + JS::in_leap_year(time_from_year(year));
  532. }
  533. // 12.2.31 ToISOWeekOfYear ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-toisoweekofyear
  534. u8 to_iso_week_of_year(i32 year, u8 month, u8 day)
  535. {
  536. // 1. Assert: IsValidISODate(year, month, day) is true.
  537. VERIFY(is_valid_iso_date(year, month, day));
  538. // 2. Let wednesday be 3.
  539. constexpr auto wednesday = 3;
  540. // 3. Let thursday be 4.
  541. constexpr auto thursday = 4;
  542. // 4. Let friday be 5.
  543. constexpr auto friday = 5;
  544. // 5. Let saturday be 6.
  545. constexpr auto saturday = 6;
  546. // 6. Let daysInWeek be 7.
  547. constexpr auto days_in_week = 7;
  548. // 7. Let maxWeekNumber be 53.
  549. constexpr auto max_week_number = 53;
  550. // 8. Let dayOfYear be ToISODayOfYear(year, month, day).
  551. auto day_of_year = to_iso_day_of_year(year, month, day);
  552. // 9. Let dayOfWeek be ToISODayOfWeek(year, month, day).
  553. auto day_of_week = to_iso_day_of_week(year, month, day);
  554. // 10. Let week be floor((dayOfYear + daysInWeek - dayOfWeek + wednesday ) / daysInWeek).
  555. auto week = static_cast<i32>(floor(static_cast<double>(day_of_year + days_in_week - day_of_week + wednesday) / days_in_week));
  556. // 11. If week < 1, then
  557. if (week < 1) {
  558. // a. NOTE: This is the last week of the previous year.
  559. // b. Let dayOfJan1st be ToISODayOfWeek(year, 1, 1).
  560. auto day_of_jan_1st = to_iso_day_of_week(year, 1, 1);
  561. // c. If dayOfJan1st is friday, then
  562. if (day_of_jan_1st == friday) {
  563. // i. Return maxWeekNumber.
  564. return max_week_number;
  565. }
  566. // d. If dayOfJan1st is saturday, and InLeapYear(TimeFromYear(𝔽(year - 1))) is 1𝔽, then
  567. if (day_of_jan_1st == saturday && in_leap_year(time_from_year(year - 1))) {
  568. // i. Return maxWeekNumber.
  569. return max_week_number;
  570. }
  571. // e. Return maxWeekNumber - 1.
  572. return max_week_number - 1;
  573. }
  574. // 12. If week is maxWeekNumber, then
  575. if (week == max_week_number) {
  576. // a. Let daysInYear be DaysInYear(𝔽(year)).
  577. auto days_in_year = JS::days_in_year(year);
  578. // b. Let daysLaterInYear be daysInYear - dayOfYear.
  579. auto days_later_in_year = days_in_year - day_of_year;
  580. // c. Let daysAfterThursday be thursday - dayOfWeek.
  581. auto days_after_thursday = thursday - day_of_week;
  582. // d. If daysLaterInYear < daysAfterThursday, then
  583. if (days_later_in_year < days_after_thursday) {
  584. // i. Return 1.
  585. return 1;
  586. }
  587. }
  588. // 13. Return week.
  589. return week;
  590. }
  591. // 12.2.32 ISOMonthCode ( month ), https://tc39.es/proposal-temporal/#sec-temporal-isomonthcode
  592. String iso_month_code(u8 month)
  593. {
  594. // 1. Let numberPart be ToZeroPaddedDecimalString(month, 2).
  595. // 2. Return the string-concatenation of "M" and numberPart.
  596. return String::formatted("M{:02}", month);
  597. }
  598. // 12.2.33 ResolveISOMonth ( fields ), https://tc39.es/proposal-temporal/#sec-temporal-resolveisomonth
  599. ThrowCompletionOr<double> resolve_iso_month(VM& vm, Object const& fields)
  600. {
  601. // 1. Assert: fields is an ordinary object with no more and no less than the own data properties listed in Table 13.
  602. // 2. Let month be ! Get(fields, "month").
  603. auto month = MUST(fields.get(vm.names.month));
  604. // 3. Assert: month is undefined or month is a Number.
  605. VERIFY(month.is_undefined() || month.is_number());
  606. // 4. Let monthCode be ! Get(fields, "monthCode").
  607. auto month_code = MUST(fields.get(vm.names.monthCode));
  608. // 5. If monthCode is undefined, then
  609. if (month_code.is_undefined()) {
  610. // a. If month is undefined, throw a TypeError exception.
  611. if (month.is_undefined())
  612. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, vm.names.month.as_string());
  613. // b. Return ℝ(month).
  614. return month.as_double();
  615. }
  616. // 6. Assert: Type(monthCode) is String.
  617. VERIFY(month_code.is_string());
  618. auto& month_code_string = month_code.as_string().string();
  619. // 7. If the length of monthCode is not 3, throw a RangeError exception.
  620. auto month_length = month_code_string.length();
  621. if (month_length != 3)
  622. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  623. // 8. If the first code unit of monthCode is not 0x004D (LATIN CAPITAL LETTER M), throw a RangeError exception.
  624. if (month_code_string[0] != 0x4D)
  625. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  626. // 9. Let monthCodeDigits be the substring of monthCode from 1.
  627. auto month_code_digits = month_code_string.substring(1);
  628. // 10. If ParseText(StringToCodePoints(monthCodeDigits), DateMonth) is a List of errors, throw a RangeError exception.
  629. auto parse_result = parse_iso8601(Production::DateMonth, month_code_digits);
  630. if (!parse_result.has_value())
  631. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  632. // 11. Let monthCodeNumber be ! ToIntegerOrInfinity(monthCodeDigits).
  633. auto month_code_number = MUST(Value(js_string(vm, move(month_code_digits))).to_integer_or_infinity(vm));
  634. // 12. Assert: SameValue(monthCode, ISOMonthCode(monthCodeNumber)) is true.
  635. VERIFY(month_code_string == iso_month_code(month_code_number));
  636. // 13. If month is not undefined and SameValue(month, monthCodeNumber) is false, throw a RangeError exception.
  637. if (!month.is_undefined() && month.as_double() != month_code_number)
  638. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  639. // 14. Return monthCodeNumber.
  640. return month_code_number;
  641. }
  642. // 12.2.34 ISODateFromFields ( fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-isodatefromfields
  643. ThrowCompletionOr<ISODateRecord> iso_date_from_fields(VM& vm, Object const& fields, Object const& options)
  644. {
  645. // 1. Assert: Type(fields) is Object.
  646. // 2. Set fields to ? PrepareTemporalFields(fields, « "day", "month", "monthCode", "year" », « "year", "day" »).
  647. auto* prepared_fields = TRY(prepare_temporal_fields(vm, fields, { "day", "month", "monthCode", "year" }, Vector<StringView> { "year"sv, "day"sv }));
  648. // 3. Let overflow be ? ToTemporalOverflow(options).
  649. auto overflow = TRY(to_temporal_overflow(vm, &options));
  650. // 4. Let year be ! Get(fields, "year").
  651. auto year = MUST(prepared_fields->get(vm.names.year));
  652. // 5. Assert: Type(year) is Number.
  653. VERIFY(year.is_number());
  654. // 6. Let month be ? ResolveISOMonth(fields).
  655. auto month = TRY(resolve_iso_month(vm, *prepared_fields));
  656. // 7. Let day be ! Get(fields, "day").
  657. auto day = MUST(prepared_fields->get(vm.names.day));
  658. // 8. Assert: Type(day) is Number.
  659. VERIFY(day.is_number());
  660. // 9. Return ? RegulateISODate(ℝ(year), month, ℝ(day), overflow).
  661. return regulate_iso_date(vm, year.as_double(), month, day.as_double(), overflow);
  662. }
  663. // 12.2.35 ISOYearMonthFromFields ( fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthfromfields
  664. ThrowCompletionOr<ISOYearMonth> iso_year_month_from_fields(VM& vm, Object const& fields, Object const& options)
  665. {
  666. // 1. Assert: Type(fields) is Object.
  667. // 2. Set fields to ? PrepareTemporalFields(fields, « "month", "monthCode", "year" », « "year" »).
  668. auto* prepared_fields = TRY(prepare_temporal_fields(vm, fields, { "month"sv, "monthCode"sv, "year"sv }, Vector<StringView> { "year"sv }));
  669. // 3. Let overflow be ? ToTemporalOverflow(options).
  670. auto overflow = TRY(to_temporal_overflow(vm, &options));
  671. // 4. Let year be ! Get(fields, "year").
  672. auto year = MUST(prepared_fields->get(vm.names.year));
  673. // 5. Assert: Type(year) is Number.
  674. VERIFY(year.is_number());
  675. // 6. Let month be ? ResolveISOMonth(fields).
  676. auto month = TRY(resolve_iso_month(vm, *prepared_fields));
  677. // 7. Let result be ? RegulateISOYearMonth(ℝ(year), month, overflow).
  678. auto result = TRY(regulate_iso_year_month(vm, year.as_double(), month, overflow));
  679. // 8. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[ReferenceISODay]]: 1 }.
  680. return ISOYearMonth { .year = result.year, .month = result.month, .reference_iso_day = 1 };
  681. }
  682. // 12.2.36 ISOMonthDayFromFields ( fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-isomonthdayfromfields
  683. ThrowCompletionOr<ISOMonthDay> iso_month_day_from_fields(VM& vm, Object const& fields, Object const& options)
  684. {
  685. // 1. Assert: Type(fields) is Object.
  686. // 2. Set fields to ? PrepareTemporalFields(fields, « "day", "month", "monthCode", "year" », « "day" »).
  687. auto* prepared_fields = TRY(prepare_temporal_fields(vm, fields, { "day"sv, "month"sv, "monthCode"sv, "year"sv }, Vector<StringView> { "day"sv }));
  688. // 3. Let overflow be ? ToTemporalOverflow(options).
  689. auto overflow = TRY(to_temporal_overflow(vm, &options));
  690. // 4. Let month be ! Get(fields, "month").
  691. auto month_value = MUST(prepared_fields->get(vm.names.month));
  692. // 5. Let monthCode be ! Get(fields, "monthCode").
  693. auto month_code = MUST(prepared_fields->get(vm.names.monthCode));
  694. // 6. Let year be ! Get(fields, "year").
  695. auto year = MUST(prepared_fields->get(vm.names.year));
  696. // 7. If month is not undefined, and monthCode and year are both undefined, then
  697. if (!month_value.is_undefined() && month_code.is_undefined() && year.is_undefined()) {
  698. // a. Throw a TypeError exception.
  699. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, "monthCode or year");
  700. }
  701. // 8. Set month to ? ResolveISOMonth(fields).
  702. auto month = TRY(resolve_iso_month(vm, *prepared_fields));
  703. // 9. Let day be ! Get(fields, "day").
  704. auto day = MUST(prepared_fields->get(vm.names.day));
  705. // 10. Assert: Type(day) is Number.
  706. VERIFY(day.is_number());
  707. // 11. Let referenceISOYear be 1972 (the first leap year after the Unix epoch).
  708. i32 reference_iso_year = 1972;
  709. Optional<ISODateRecord> result;
  710. // 12. If monthCode is undefined, then
  711. if (month_code.is_undefined()) {
  712. // a. Assert: Type(year) is Number.
  713. VERIFY(year.is_number());
  714. // b. Let result be ? RegulateISODate(ℝ(year), month, ℝ(day), overflow).
  715. result = TRY(regulate_iso_date(vm, year.as_double(), month, day.as_double(), overflow));
  716. }
  717. // 13. Else,
  718. else {
  719. // a. Let result be ? RegulateISODate(referenceISOYear, month, ℝ(day), overflow).
  720. result = TRY(regulate_iso_date(vm, reference_iso_year, month, day.as_double(), overflow));
  721. }
  722. // 14. Return the Record { [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[ReferenceISOYear]]: referenceISOYear }.
  723. return ISOMonthDay { .month = result->month, .day = result->day, .reference_iso_year = reference_iso_year };
  724. }
  725. // 12.2.37 DefaultMergeCalendarFields ( fields, additionalFields ), https://tc39.es/proposal-temporal/#sec-temporal-defaultmergecalendarfields
  726. ThrowCompletionOr<Object*> default_merge_calendar_fields(VM& vm, Object const& fields, Object const& additional_fields)
  727. {
  728. auto& realm = *vm.current_realm();
  729. // 1. Let merged be OrdinaryObjectCreate(%Object.prototype%).
  730. auto* merged = Object::create(realm, realm.intrinsics().object_prototype());
  731. // 2. Let fieldsKeys be ? EnumerableOwnPropertyNames(fields, key).
  732. auto fields_keys = TRY(fields.enumerable_own_property_names(Object::PropertyKind::Key));
  733. // 3. For each element key of fieldsKeys, do
  734. for (auto& key : fields_keys) {
  735. // a. If key is not "month" or "monthCode", then
  736. if (key.as_string().string() != vm.names.month.as_string() && key.as_string().string() != vm.names.monthCode.as_string()) {
  737. auto property_key = MUST(PropertyKey::from_value(vm, key));
  738. // i. Let propValue be ? Get(fields, key).
  739. auto prop_value = TRY(fields.get(property_key));
  740. // ii. If propValue is not undefined, then
  741. if (!prop_value.is_undefined()) {
  742. // 1. Perform ! CreateDataPropertyOrThrow(merged, key, propValue).
  743. MUST(merged->create_data_property_or_throw(property_key, prop_value));
  744. }
  745. }
  746. }
  747. // 4. Let additionalFieldsKeys be ? EnumerableOwnPropertyNames(additionalFields, key).
  748. auto additional_fields_keys = TRY(additional_fields.enumerable_own_property_names(Object::PropertyKind::Key));
  749. // IMPLEMENTATION DEFINED: This is an optimization, so we don't have to iterate new_keys three times (worst case), but only once.
  750. bool additional_fields_keys_contains_month_or_month_code_property = false;
  751. // 5. For each element key of additionalFieldsKeys, do
  752. for (auto& key : additional_fields_keys) {
  753. auto property_key = MUST(PropertyKey::from_value(vm, key));
  754. // a. Let propValue be ? Get(additionalFields, key).
  755. auto prop_value = TRY(additional_fields.get(property_key));
  756. // b. If propValue is not undefined, then
  757. if (!prop_value.is_undefined()) {
  758. // i. Perform ! CreateDataPropertyOrThrow(merged, key, propValue).
  759. MUST(merged->create_data_property_or_throw(property_key, prop_value));
  760. }
  761. // See comment above.
  762. additional_fields_keys_contains_month_or_month_code_property |= key.as_string().string() == vm.names.month.as_string() || key.as_string().string() == vm.names.monthCode.as_string();
  763. }
  764. // 6. If additionalFieldsKeys does not contain either "month" or "monthCode", then
  765. if (!additional_fields_keys_contains_month_or_month_code_property) {
  766. // a. Let month be ? Get(fields, "month").
  767. auto month = TRY(fields.get(vm.names.month));
  768. // b. If month is not undefined, then
  769. if (!month.is_undefined()) {
  770. // i. Perform ! CreateDataPropertyOrThrow(merged, "month", month).
  771. MUST(merged->create_data_property_or_throw(vm.names.month, month));
  772. }
  773. // c. Let monthCode be ? Get(fields, "monthCode").
  774. auto month_code = TRY(fields.get(vm.names.monthCode));
  775. // d. If monthCode is not undefined, then
  776. if (!month_code.is_undefined()) {
  777. // i. Perform ! CreateDataPropertyOrThrow(merged, "monthCode", monthCode).
  778. MUST(merged->create_data_property_or_throw(vm.names.monthCode, month_code));
  779. }
  780. }
  781. // 7. Return merged.
  782. return merged;
  783. }
  784. // 12.2.38 ToISODayOfYear ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-toisodayofyear
  785. u16 to_iso_day_of_year(i32 year, u8 month, u8 day)
  786. {
  787. // 1. Assert: IsValidISODate(year, month, day) is true.
  788. VERIFY(is_valid_iso_date(year, month, day));
  789. // 2. Let epochDays be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  790. auto epoch_days = make_day(year, month - 1, day);
  791. // 3. Assert: epochDays is finite.
  792. VERIFY(isfinite(epoch_days));
  793. // 4. Return ℝ(DayWithinYear(MakeDate(epochDays, +0𝔽))) + 1.
  794. return day_within_year(make_date(epoch_days, 0)) + 1;
  795. }
  796. // 12.2.39 ToISODayOfWeek ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-toisodayofweek
  797. u8 to_iso_day_of_week(i32 year, u8 month, u8 day)
  798. {
  799. // 1. Assert: IsValidISODate(year, month, day) is true.
  800. VERIFY(is_valid_iso_date(year, month, day));
  801. // 2. Let epochDays be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  802. auto epoch_days = make_day(year, month - 1, day);
  803. // 3. Assert: epochDays is finite.
  804. VERIFY(isfinite(epoch_days));
  805. // 4. Let dayOfWeek be WeekDay(MakeDate(epochDays, +0𝔽)).
  806. auto day_of_week = week_day(make_date(epoch_days, 0));
  807. // 5. If dayOfWeek = +0𝔽, return 7.
  808. if (day_of_week == 0)
  809. return 7;
  810. // 6. Return ℝ(dayOfWeek).
  811. return day_of_week;
  812. }
  813. }