Calendar.cpp 49 KB

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