Calendar.cpp 49 KB

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