Calendar.cpp 49 KB

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