Calendar.cpp 48 KB

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