Calendar.cpp 49 KB

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