Calendar.cpp 46 KB

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