Calendar.cpp 48 KB

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