Calendar.cpp 49 KB

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