Calendar.cpp 48 KB

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