AbstractOperations.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. /*
  2. * Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2024, Tim Flynn <trflynn89@ladybird.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibCrypto/BigFraction/BigFraction.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/PropertyKey.h>
  13. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  14. #include <LibJS/Runtime/Temporal/Calendar.h>
  15. #include <LibJS/Runtime/Temporal/Duration.h>
  16. #include <LibJS/Runtime/Temporal/Instant.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/TimeZone.h>
  21. namespace JS::Temporal {
  22. // https://tc39.es/proposal-temporal/#table-temporal-units
  23. struct TemporalUnit {
  24. Unit value;
  25. StringView singular_property_name;
  26. StringView plural_property_name;
  27. UnitCategory category;
  28. RoundingIncrement maximum_duration_rounding_increment;
  29. };
  30. static auto temporal_units = to_array<TemporalUnit>({
  31. { Unit::Year, "year"sv, "years"sv, UnitCategory::Date, Unset {} },
  32. { Unit::Month, "month"sv, "months"sv, UnitCategory::Date, Unset {} },
  33. { Unit::Week, "week"sv, "weeks"sv, UnitCategory::Date, Unset {} },
  34. { Unit::Day, "day"sv, "days"sv, UnitCategory::Date, Unset {} },
  35. { Unit::Hour, "hour"sv, "hours"sv, UnitCategory::Time, 24 },
  36. { Unit::Minute, "minute"sv, "minutes"sv, UnitCategory::Time, 60 },
  37. { Unit::Second, "second"sv, "seconds"sv, UnitCategory::Time, 60 },
  38. { Unit::Millisecond, "millisecond"sv, "milliseconds"sv, UnitCategory::Time, 1000 },
  39. { Unit::Microsecond, "microsecond"sv, "microseconds"sv, UnitCategory::Time, 1000 },
  40. { Unit::Nanosecond, "nanosecond"sv, "nanoseconds"sv, UnitCategory::Time, 1000 },
  41. });
  42. StringView temporal_unit_to_string(Unit unit)
  43. {
  44. return temporal_units[to_underlying(unit)].singular_property_name;
  45. }
  46. // 13.1 ISODateToEpochDays ( year, month, date ), https://tc39.es/proposal-temporal/#sec-isodatetoepochdays
  47. double iso_date_to_epoch_days(double year, double month, double date)
  48. {
  49. // 1. Let resolvedYear be year + floor(month / 12).
  50. // 2. Let resolvedMonth be month modulo 12.
  51. // 3. Find a time t such that EpochTimeToEpochYear(t) = resolvedYear, EpochTimeToMonthInYear(t) = resolvedMonth, and EpochTimeToDate(t) = 1.
  52. // 4. Return EpochTimeToDayNumber(t) + date - 1.
  53. // EDITOR'S NOTE: This operation corresponds to ECMA-262 operation MakeDay(year, month, date). It calculates the
  54. // result in mathematical values instead of Number values. These two operations would be unified when
  55. // https://github.com/tc39/ecma262/issues/1087 is fixed.
  56. // Since we don't have a real MV type to work with, let's defer to MakeDay.
  57. return JS::make_day(year, month, date);
  58. }
  59. // 13.2 EpochDaysToEpochMs ( day, time ), https://tc39.es/proposal-temporal/#sec-epochdaystoepochms
  60. double epoch_days_to_epoch_ms(double day, double time)
  61. {
  62. // 1. Return day × ℝ(msPerDay) + time.
  63. return day * JS::ms_per_day + time;
  64. }
  65. // 13.6 GetTemporalOverflowOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporaloverflowoption
  66. ThrowCompletionOr<Overflow> get_temporal_overflow_option(VM& vm, Object const& options)
  67. {
  68. // 1. Let stringValue be ? GetOption(options, "overflow", STRING, « "constrain", "reject" », "constrain").
  69. auto string_value = TRY(get_option(vm, options, vm.names.overflow, OptionType::String, { "constrain"sv, "reject"sv }, "constrain"sv));
  70. // 2. If stringValue is "constrain", return CONSTRAIN.
  71. if (string_value.as_string().utf8_string() == "constrain"sv)
  72. return Overflow::Constrain;
  73. // 3. Return REJECT.
  74. return Overflow::Reject;
  75. }
  76. // 13.10 GetTemporalShowCalendarNameOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalshowcalendarnameoption
  77. ThrowCompletionOr<ShowCalendar> get_temporal_show_calendar_name_option(VM& vm, Object const& options)
  78. {
  79. // 1. Let stringValue be ? GetOption(options, "calendarName", STRING, « "auto", "always", "never", "critical" », "auto").
  80. auto string_value = TRY(get_option(vm, options, vm.names.calendarName, OptionType::String, { "auto"sv, "always"sv, "never"sv, "critical"sv }, "auto"sv));
  81. // 2. If stringValue is "always", return ALWAYS.
  82. if (string_value.as_string().utf8_string_view() == "always"sv)
  83. return ShowCalendar::Always;
  84. // 3. If stringValue is "never", return NEVER.
  85. if (string_value.as_string().utf8_string_view() == "never"sv)
  86. return ShowCalendar::Never;
  87. // 4. If stringValue is "critical", return CRITICAL.
  88. if (string_value.as_string().utf8_string_view() == "critical"sv)
  89. return ShowCalendar::Critical;
  90. // 5. Return AUTO.
  91. return ShowCalendar::Auto;
  92. }
  93. // 13.14 ValidateTemporalRoundingIncrement ( increment, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-validatetemporalroundingincrement
  94. ThrowCompletionOr<void> validate_temporal_rounding_increment(VM& vm, u64 increment, u64 dividend, bool inclusive)
  95. {
  96. u64 maximum = 0;
  97. // 1. If inclusive is true, then
  98. if (inclusive) {
  99. // a. Let maximum be dividend.
  100. maximum = dividend;
  101. }
  102. // 2. Else,
  103. else {
  104. // a. Assert: dividend > 1.
  105. VERIFY(dividend > 1);
  106. // b. Let maximum be dividend - 1.
  107. maximum = dividend - 1;
  108. }
  109. // 3. If increment > maximum, throw a RangeError exception.
  110. if (increment > maximum)
  111. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  112. // 5. If dividend modulo increment ≠ 0, then
  113. if (modulo(dividend, increment) != 0) {
  114. // a. Throw a RangeError exception.
  115. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  116. }
  117. // 6. Return UNUSED.
  118. return {};
  119. }
  120. // 13.15 GetTemporalFractionalSecondDigitsOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalfractionalseconddigitsoption
  121. ThrowCompletionOr<Precision> get_temporal_fractional_second_digits_option(VM& vm, Object const& options)
  122. {
  123. // 1. Let digitsValue be ? Get(options, "fractionalSecondDigits").
  124. auto digits_value = TRY(options.get(vm.names.fractionalSecondDigits));
  125. // 2. If digitsValue is undefined, return AUTO.
  126. if (digits_value.is_undefined())
  127. return Precision { Auto {} };
  128. // 3. If digitsValue is not a Number, then
  129. if (!digits_value.is_number()) {
  130. // a. If ? ToString(digitsValue) is not "auto", throw a RangeError exception.
  131. auto digits_value_string = TRY(digits_value.to_string(vm));
  132. if (digits_value_string != "auto"sv)
  133. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  134. // b. Return AUTO.
  135. return Precision { Auto {} };
  136. }
  137. // 4. If digitsValue is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  138. if (digits_value.is_nan() || digits_value.is_infinity())
  139. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  140. // 5. Let digitCount be floor(ℝ(digitsValue)).
  141. auto digit_count = floor(digits_value.as_double());
  142. // 6. If digitCount < 0 or digitCount > 9, throw a RangeError exception.
  143. if (digit_count < 0 || digit_count > 9)
  144. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  145. // 7. Return digitCount.
  146. return Precision { static_cast<u8>(digit_count) };
  147. }
  148. // 13.16 ToSecondsStringPrecisionRecord ( smallestUnit, fractionalDigitCount ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecisionrecord
  149. SecondsStringPrecision to_seconds_string_precision_record(UnitValue smallest_unit, Precision fractional_digit_count)
  150. {
  151. if (auto const* unit = smallest_unit.get_pointer<Unit>()) {
  152. // 1. If smallestUnit is MINUTE, then
  153. if (*unit == Unit::Minute) {
  154. // a. Return the Record { [[Precision]]: MINUTE, [[Unit]]: MINUTE, [[Increment]]: 1 }.
  155. return { .precision = SecondsStringPrecision::Minute {}, .unit = Unit::Minute, .increment = 1 };
  156. }
  157. // 2. If smallestUnit is SECOND, then
  158. if (*unit == Unit::Second) {
  159. // a. Return the Record { [[Precision]]: 0, [[Unit]]: SECOND, [[Increment]]: 1 }.
  160. return { .precision = 0, .unit = Unit::Second, .increment = 1 };
  161. }
  162. // 3. If smallestUnit is MILLISECOND, then
  163. if (*unit == Unit::Millisecond) {
  164. // a. Return the Record { [[Precision]]: 3, [[Unit]]: MILLISECOND, [[Increment]]: 1 }.
  165. return { .precision = 3, .unit = Unit::Millisecond, .increment = 1 };
  166. }
  167. // 4. If smallestUnit is MICROSECOND, then
  168. if (*unit == Unit::Microsecond) {
  169. // a. Return the Record { [[Precision]]: 6, [[Unit]]: MICROSECOND, [[Increment]]: 1 }.
  170. return { .precision = 6, .unit = Unit::Microsecond, .increment = 1 };
  171. }
  172. // 5. If smallestUnit is NANOSECOND, then
  173. if (*unit == Unit::Nanosecond) {
  174. // a. Return the Record { [[Precision]]: 9, [[Unit]]: NANOSECOND, [[Increment]]: 1 }.
  175. return { .precision = 9, .unit = Unit::Nanosecond, .increment = 1 };
  176. }
  177. }
  178. // 6. Assert: smallestUnit is UNSET.
  179. VERIFY(smallest_unit.has<Unset>());
  180. // 7. If fractionalDigitCount is auto, then
  181. if (fractional_digit_count.has<Auto>()) {
  182. // a. Return the Record { [[Precision]]: AUTO, [[Unit]]: NANOSECOND, [[Increment]]: 1 }.
  183. return { .precision = Auto {}, .unit = Unit::Nanosecond, .increment = 1 };
  184. }
  185. auto fractional_digits = fractional_digit_count.get<u8>();
  186. // 8. If fractionalDigitCount = 0, then
  187. if (fractional_digits == 0) {
  188. // a. Return the Record { [[Precision]]: 0, [[Unit]]: SECOND, [[Increment]]: 1 }.
  189. return { .precision = 0, .unit = Unit::Second, .increment = 1 };
  190. }
  191. // 9. If fractionalDigitCount is in the inclusive interval from 1 to 3, then
  192. if (fractional_digits >= 1 && fractional_digits <= 3) {
  193. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: MILLISECOND, [[Increment]]: 10**(3 - fractionalDigitCount) }.
  194. return { .precision = fractional_digits, .unit = Unit::Millisecond, .increment = static_cast<u8>(pow(10, 3 - fractional_digits)) };
  195. }
  196. // 10. If fractionalDigitCount is in the inclusive interval from 4 to 6, then
  197. if (fractional_digits >= 4 && fractional_digits <= 6) {
  198. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: MICROSECOND, [[Increment]]: 10**(6 - fractionalDigitCount) }.
  199. return { .precision = fractional_digits, .unit = Unit::Microsecond, .increment = static_cast<u8>(pow(10, 6 - fractional_digits)) };
  200. }
  201. // 11. Assert: fractionalDigitCount is in the inclusive interval from 7 to 9.
  202. VERIFY(fractional_digits >= 7 && fractional_digits <= 9);
  203. // 12. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: NANOSECOND, [[Increment]]: 10**(9 - fractionalDigitCount) }.
  204. return { .precision = fractional_digits, .unit = Unit::Nanosecond, .increment = static_cast<u8>(pow(10, 9 - fractional_digits)) };
  205. }
  206. // 13.17 GetTemporalUnitValuedOption ( options, key, unitGroup, default [ , extraValues ] ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalunitvaluedoption
  207. ThrowCompletionOr<UnitValue> get_temporal_unit_valued_option(VM& vm, Object const& options, PropertyKey const& key, UnitGroup unit_group, UnitDefault const& default_, ReadonlySpan<UnitValue> extra_values)
  208. {
  209. // 1. Let allowedValues be a new empty List.
  210. Vector<UnitValue> allowed_values;
  211. // 2. For each row of Table 21, except the header row, in table order, do
  212. for (auto const& row : temporal_units) {
  213. // a. Let unit be the value in the "Value" column of the row.
  214. auto unit = row.value;
  215. // b. If the "Category" column of the row is DATE and unitGroup is DATE or DATETIME, append unit to allowedValues.
  216. if (row.category == UnitCategory::Date && (unit_group == UnitGroup::Date || unit_group == UnitGroup::DateTime))
  217. allowed_values.append(unit);
  218. // c. Else if the "Category" column of the row is TIME and unitGroup is TIME or DATETIME, append unit to allowedValues.
  219. if (row.category == UnitCategory::Time && (unit_group == UnitGroup::Time || unit_group == UnitGroup::DateTime))
  220. allowed_values.append(unit);
  221. }
  222. // 3. If extraValues is present, then
  223. if (!extra_values.is_empty()) {
  224. // a. Set allowedValues to the list-concatenation of allowedValues and extraValues.
  225. for (auto value : extra_values)
  226. allowed_values.append(value);
  227. }
  228. OptionDefault default_value;
  229. // 4. If default is UNSET, then
  230. if (default_.has<Unset>()) {
  231. // a. Let defaultValue be undefined.
  232. default_value = {};
  233. }
  234. // 5. Else if default is REQUIRED, then
  235. else if (default_.has<Required>()) {
  236. // a. Let defaultValue be REQUIRED.
  237. default_value = Required {};
  238. }
  239. // 6. Else if default is AUTO, then
  240. else if (default_.has<Auto>()) {
  241. // a. Append default to allowedValues.
  242. allowed_values.append(Auto {});
  243. // b. Let defaultValue be "auto".
  244. default_value = "auto"sv;
  245. }
  246. // 7. Else,
  247. else {
  248. auto unit = default_.get<Unit>();
  249. // a. Assert: allowedValues contains default.
  250. // b. Let defaultValue be the value in the "Singular property name" column of Table 21 corresponding to the row
  251. // with default in the "Value" column.
  252. default_value = temporal_units[to_underlying(unit)].singular_property_name;
  253. }
  254. // 8. Let allowedStrings be a new empty List.
  255. Vector<StringView> allowed_strings;
  256. // 9. For each element value of allowedValues, do
  257. for (auto value : allowed_values) {
  258. // a. If value is auto, then
  259. if (value.has<Auto>()) {
  260. // i. Append "auto" to allowedStrings.
  261. allowed_strings.append("auto"sv);
  262. }
  263. // b. Else,
  264. else {
  265. auto unit = value.get<Unit>();
  266. // i. Let singularName be the value in the "Singular property name" column of Table 21 corresponding to the
  267. // row with value in the "Value" column.
  268. auto singular_name = temporal_units[to_underlying(unit)].singular_property_name;
  269. // ii. Append singularName to allowedStrings.
  270. allowed_strings.append(singular_name);
  271. // iii. Let pluralName be the value in the "Plural property name" column of the corresponding row.
  272. auto plural_name = temporal_units[to_underlying(unit)].plural_property_name;
  273. // iv. Append pluralName to allowedStrings.
  274. allowed_strings.append(plural_name);
  275. }
  276. }
  277. // 10. NOTE: For each singular Temporal unit name that is contained within allowedStrings, the corresponding plural
  278. // name is also contained within it.
  279. // 11. Let value be ? GetOption(options, key, STRING, allowedStrings, defaultValue).
  280. auto value = TRY(get_option(vm, options, key, OptionType::String, allowed_strings, default_value));
  281. // 12. If value is undefined, return UNSET.
  282. if (value.is_undefined())
  283. return UnitValue { Unset {} };
  284. auto value_string = value.as_string().utf8_string_view();
  285. // 13. If value is "auto", return AUTO.
  286. if (value_string == "auto"sv)
  287. return UnitValue { Auto {} };
  288. // 14. Return the value in the "Value" column of Table 21 corresponding to the row with value in its "Singular
  289. // property name" or "Plural property name" column.
  290. for (auto const& row : temporal_units) {
  291. if (value_string.is_one_of(row.singular_property_name, row.plural_property_name))
  292. return UnitValue { row.value };
  293. }
  294. VERIFY_NOT_REACHED();
  295. }
  296. // 13.18 GetTemporalRelativeToOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalrelativetooption
  297. ThrowCompletionOr<RelativeTo> get_temporal_relative_to_option(VM& vm, Object const& options)
  298. {
  299. // 1. Let value be ? Get(options, "relativeTo").
  300. auto value = TRY(options.get(vm.names.relativeTo));
  301. // 2. If value is undefined, return the Record { [[PlainRelativeTo]]: undefined, [[ZonedRelativeTo]]: undefined }.
  302. if (value.is_undefined())
  303. return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} };
  304. // FIXME: Implement the remaining steps of this AO when we have implemented PlainRelativeTo and ZonedRelativeTo.
  305. return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} };
  306. }
  307. // 13.19 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  308. Unit larger_of_two_temporal_units(Unit unit1, Unit unit2)
  309. {
  310. // 1. For each row of Table 21, except the header row, in table order, do
  311. for (auto const& row : temporal_units) {
  312. // a. Let unit be the value in the "Value" column of the row.
  313. auto unit = row.value;
  314. // b. If u1 is unit, return unit.
  315. if (unit1 == unit)
  316. return unit;
  317. // c. If u2 is unit, return unit.
  318. if (unit2 == unit)
  319. return unit;
  320. }
  321. VERIFY_NOT_REACHED();
  322. }
  323. // 13.20 IsCalendarUnit ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-iscalendarunit
  324. bool is_calendar_unit(Unit unit)
  325. {
  326. // 1. If unit is year, return true.
  327. if (unit == Unit::Year)
  328. return true;
  329. // 2. If unit is month, return true.
  330. if (unit == Unit::Month)
  331. return true;
  332. // 3. If unit is week, return true.
  333. if (unit == Unit::Week)
  334. return true;
  335. // 4. Return false.
  336. return false;
  337. }
  338. // 13.21 TemporalUnitCategory ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-temporalunitcategory
  339. UnitCategory temporal_unit_category(Unit unit)
  340. {
  341. // 1. Return the value from the "Category" column of the row of Table 21 in which unit is in the "Value" column.
  342. return temporal_units[to_underlying(unit)].category;
  343. }
  344. // 13.22 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  345. RoundingIncrement maximum_temporal_duration_rounding_increment(Unit unit)
  346. {
  347. // 1. Return the value from the "Maximum duration rounding increment" column of the row of Table 21 in which unit is
  348. // in the "Value" column.
  349. return temporal_units[to_underlying(unit)].maximum_duration_rounding_increment;
  350. }
  351. // AD-HOC
  352. Crypto::UnsignedBigInteger const& temporal_unit_length_in_nanoseconds(Unit unit)
  353. {
  354. switch (unit) {
  355. case Unit::Day:
  356. return NANOSECONDS_PER_DAY;
  357. case Unit::Hour:
  358. return NANOSECONDS_PER_HOUR;
  359. case Unit::Minute:
  360. return NANOSECONDS_PER_MINUTE;
  361. case Unit::Second:
  362. return NANOSECONDS_PER_SECOND;
  363. case Unit::Millisecond:
  364. return NANOSECONDS_PER_MILLISECOND;
  365. case Unit::Microsecond:
  366. return NANOSECONDS_PER_MICROSECOND;
  367. case Unit::Nanosecond:
  368. return NANOSECONDS_PER_NANOSECOND;
  369. default:
  370. VERIFY_NOT_REACHED();
  371. }
  372. }
  373. // 13.23 IsPartialTemporalObject ( value ), https://tc39.es/proposal-temporal/#sec-temporal-ispartialtemporalobject
  374. ThrowCompletionOr<bool> is_partial_temporal_object(VM& vm, Value value)
  375. {
  376. // 1. If value is not an Object, return false.
  377. if (!value.is_object())
  378. return false;
  379. auto const& object = value.as_object();
  380. // 2. If value has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]],
  381. // [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal
  382. // slot, return false.
  383. // FIXME: Add the other types as we define them.
  384. if (is<PlainMonthDay>(object))
  385. return false;
  386. // 3. Let calendarProperty be ? Get(value, "calendar").
  387. auto calendar_property = TRY(object.get(vm.names.calendar));
  388. // 4. If calendarProperty is not undefined, return false.
  389. if (!calendar_property.is_undefined())
  390. return false;
  391. // 5. Let timeZoneProperty be ? Get(value, "timeZone").
  392. auto time_zone_property = TRY(object.get(vm.names.timeZone));
  393. // 6. If timeZoneProperty is not undefined, return false.
  394. if (!time_zone_property.is_undefined())
  395. return false;
  396. // 7. Return true.
  397. return true;
  398. }
  399. // 13.24 FormatFractionalSeconds ( subSecondNanoseconds, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatfractionalseconds
  400. String format_fractional_seconds(u64 sub_second_nanoseconds, Precision precision)
  401. {
  402. String fraction_string;
  403. // 1. If precision is auto, then
  404. if (precision.has<Auto>()) {
  405. // a. If subSecondNanoseconds = 0, return the empty String.
  406. if (sub_second_nanoseconds == 0)
  407. return String {};
  408. // b. Let fractionString be ToZeroPaddedDecimalString(subSecondNanoseconds, 9).
  409. fraction_string = MUST(String::formatted("{:09}", sub_second_nanoseconds));
  410. // c. Set fractionString to the longest prefix of fractionString ending with a code unit other than 0x0030 (DIGIT ZERO).
  411. fraction_string = MUST(fraction_string.trim("0"sv, TrimMode::Right));
  412. }
  413. // 2. Else,
  414. else {
  415. // a. If precision = 0, return the empty String.
  416. if (precision.get<u8>() == 0)
  417. return String {};
  418. // b. Let fractionString be ToZeroPaddedDecimalString(subSecondNanoseconds, 9).
  419. fraction_string = MUST(String::formatted("{:09}", sub_second_nanoseconds));
  420. // c. Set fractionString to the substring of fractionString from 0 to precision.
  421. fraction_string = MUST(fraction_string.substring_from_byte_offset(0, precision.get<u8>()));
  422. }
  423. // 3. Return the string-concatenation of the code unit 0x002E (FULL STOP) and fractionString.
  424. return MUST(String::formatted(".{}", fraction_string));
  425. }
  426. // 13.25 FormatTimeString ( hour, minute, second, subSecondNanoseconds, precision [ , style ] ), https://tc39.es/proposal-temporal/#sec-temporal-formattimestring
  427. String format_time_string(u8 hour, u8 minute, u8 second, u16 sub_second_nanoseconds, SecondsStringPrecision::Precision precision, Optional<TimeStyle> style)
  428. {
  429. // 1. If style is present and style is UNSEPARATED, let separator be the empty String; otherwise, let separator be ":".
  430. auto separator = style == TimeStyle::Unseparated ? ""sv : ":"sv;
  431. // 2. Let hh be ToZeroPaddedDecimalString(hour, 2).
  432. // 3. Let mm be ToZeroPaddedDecimalString(minute, 2).
  433. // 4. If precision is minute, return the string-concatenation of hh, separator, and mm.
  434. if (precision.has<SecondsStringPrecision::Minute>())
  435. return MUST(String::formatted("{:02}{}{:02}", hour, separator, minute));
  436. // 5. Let ss be ToZeroPaddedDecimalString(second, 2).
  437. // 6. Let subSecondsPart be FormatFractionalSeconds(subSecondNanoseconds, precision).
  438. auto sub_seconds_part = format_fractional_seconds(sub_second_nanoseconds, precision.downcast<Auto, u8>());
  439. // 7. Return the string-concatenation of hh, separator, mm, separator, ss, and subSecondsPart.
  440. return MUST(String::formatted("{:02}{}{:02}{}{:02}{}", hour, separator, minute, separator, second, sub_seconds_part));
  441. }
  442. // 13.26 GetUnsignedRoundingMode ( roundingMode, sign ), https://tc39.es/proposal-temporal/#sec-getunsignedroundingmode
  443. UnsignedRoundingMode get_unsigned_rounding_mode(RoundingMode rounding_mode, Sign sign)
  444. {
  445. // 1. Return the specification type in the "Unsigned Rounding Mode" column of Table 22 for the row where the value
  446. // in the "Rounding Mode" column is roundingMode and the value in the "Sign" column is sign.
  447. switch (rounding_mode) {
  448. case RoundingMode::Ceil:
  449. return sign == Sign::Positive ? UnsignedRoundingMode::Infinity : UnsignedRoundingMode::Zero;
  450. case RoundingMode::Floor:
  451. return sign == Sign::Positive ? UnsignedRoundingMode::Zero : UnsignedRoundingMode::Infinity;
  452. case RoundingMode::Expand:
  453. return UnsignedRoundingMode::Infinity;
  454. case RoundingMode::Trunc:
  455. return UnsignedRoundingMode::Zero;
  456. case RoundingMode::HalfCeil:
  457. return sign == Sign::Positive ? UnsignedRoundingMode::HalfInfinity : UnsignedRoundingMode::HalfZero;
  458. case RoundingMode::HalfFloor:
  459. return sign == Sign::Positive ? UnsignedRoundingMode::HalfZero : UnsignedRoundingMode::HalfInfinity;
  460. case RoundingMode::HalfExpand:
  461. return UnsignedRoundingMode::HalfInfinity;
  462. case RoundingMode::HalfTrunc:
  463. return UnsignedRoundingMode::HalfZero;
  464. case RoundingMode::HalfEven:
  465. return UnsignedRoundingMode::HalfEven;
  466. }
  467. VERIFY_NOT_REACHED();
  468. }
  469. // 13.27 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-applyunsignedroundingmode
  470. double apply_unsigned_rounding_mode(double x, double r1, double r2, UnsignedRoundingMode unsigned_rounding_mode)
  471. {
  472. // 1. If x = r1, return r1.
  473. if (x == r1)
  474. return r1;
  475. // 2. Assert: r1 < x < r2.
  476. VERIFY(r1 < x && x < r2);
  477. // 3. Assert: unsignedRoundingMode is not undefined.
  478. // 4. If unsignedRoundingMode is ZERO, return r1.
  479. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  480. return r1;
  481. // 5. If unsignedRoundingMode is INFINITY, return r2.
  482. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  483. return r2;
  484. // 6. Let d1 be x – r1.
  485. auto d1 = x - r1;
  486. // 7. Let d2 be r2 – x.
  487. auto d2 = r2 - x;
  488. // 8. If d1 < d2, return r1.
  489. if (d1 < d2)
  490. return r1;
  491. // 9. If d2 < d1, return r2.
  492. if (d2 < d1)
  493. return r2;
  494. // 10. Assert: d1 is equal to d2.
  495. VERIFY(d1 == d2);
  496. // 11. If unsignedRoundingMode is HALF-ZERO, return r1.
  497. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  498. return r1;
  499. // 12. If unsignedRoundingMode is HALF-INFINITY, return r2.
  500. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  501. return r2;
  502. // 13. Assert: unsignedRoundingMode is HALF-EVEN.
  503. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  504. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  505. auto cardinality = modulo((r1 / (r2 - r1)), 2);
  506. // 15. If cardinality = 0, return r1.
  507. if (cardinality == 0)
  508. return r1;
  509. // 16. Return r2.
  510. return r2;
  511. }
  512. // 13.27 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-applyunsignedroundingmode
  513. Crypto::SignedBigInteger apply_unsigned_rounding_mode(Crypto::SignedDivisionResult const& x, Crypto::SignedBigInteger const& r1, Crypto::SignedBigInteger const& r2, UnsignedRoundingMode unsigned_rounding_mode, Crypto::UnsignedBigInteger const& increment)
  514. {
  515. // 1. If x = r1, return r1.
  516. if (x.quotient == r1 && x.remainder.unsigned_value().is_zero())
  517. return r1;
  518. // 2. Assert: r1 < x < r2.
  519. // NOTE: Skipped for the sake of performance.
  520. // 3. Assert: unsignedRoundingMode is not undefined.
  521. // 4. If unsignedRoundingMode is ZERO, return r1.
  522. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  523. return r1;
  524. // 5. If unsignedRoundingMode is INFINITY, return r2.
  525. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  526. return r2;
  527. // 6. Let d1 be x – r1.
  528. auto d1 = x.remainder.unsigned_value();
  529. // 7. Let d2 be r2 – x.
  530. auto d2 = increment.minus(x.remainder.unsigned_value());
  531. // 8. If d1 < d2, return r1.
  532. if (d1 < d2)
  533. return r1;
  534. // 9. If d2 < d1, return r2.
  535. if (d2 < d1)
  536. return r2;
  537. // 10. Assert: d1 is equal to d2.
  538. // NOTE: Skipped for the sake of performance.
  539. // 11. If unsignedRoundingMode is HALF-ZERO, return r1.
  540. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  541. return r1;
  542. // 12. If unsignedRoundingMode is HALF-INFINITY, return r2.
  543. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  544. return r2;
  545. // 13. Assert: unsignedRoundingMode is HALF-EVEN.
  546. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  547. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  548. auto cardinality = modulo(r1.divided_by(r2.minus(r1)).quotient, "2"_bigint);
  549. // 15. If cardinality = 0, return r1.
  550. if (cardinality.unsigned_value().is_zero())
  551. return r1;
  552. // 16. Return r2.
  553. return r2;
  554. }
  555. // 13.28 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  556. double round_number_to_increment(double x, u64 increment, RoundingMode rounding_mode)
  557. {
  558. // 1. Let quotient be x / increment.
  559. auto quotient = x / static_cast<double>(increment);
  560. Sign is_negative;
  561. // 2. If quotient < 0, then
  562. if (quotient < 0) {
  563. // a. Let isNegative be NEGATIVE.
  564. is_negative = Sign::Negative;
  565. // b. Set quotient to -quotient.
  566. quotient = -quotient;
  567. }
  568. // 3. Else,
  569. else {
  570. // a. Let isNegative be POSITIVE.
  571. is_negative = Sign::Positive;
  572. }
  573. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  574. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  575. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  576. auto r1 = floor(quotient);
  577. // 6. Let r2 be the smallest integer such that r2 > quotient.
  578. auto r2 = ceil(quotient);
  579. if (quotient == r2)
  580. r2++;
  581. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  582. auto rounded = apply_unsigned_rounding_mode(quotient, r1, r2, unsigned_rounding_mode);
  583. // 8. If isNegative is NEGATIVE, set rounded to -rounded.
  584. if (is_negative == Sign::Negative)
  585. rounded = -rounded;
  586. // 9. Return rounded × increment.
  587. return rounded * static_cast<double>(increment);
  588. }
  589. // 13.28 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  590. Crypto::SignedBigInteger round_number_to_increment(Crypto::SignedBigInteger const& x, Crypto::UnsignedBigInteger const& increment, RoundingMode rounding_mode)
  591. {
  592. // OPTIMIZATION: If the increment is 1 the number is always rounded.
  593. if (increment == 1)
  594. return x;
  595. // 1. Let quotient be x / increment.
  596. auto division_result = x.divided_by(increment);
  597. // OPTIMIZATION: If there's no remainder the number is already rounded.
  598. if (division_result.remainder.unsigned_value().is_zero())
  599. return x;
  600. Sign is_negative;
  601. // 2. If quotient < 0, then
  602. if (division_result.quotient.is_negative()) {
  603. // a. Let isNegative be NEGATIVE.
  604. is_negative = Sign::Negative;
  605. // b. Set quotient to -quotient.
  606. division_result.quotient.negate();
  607. division_result.remainder.negate();
  608. }
  609. // 3. Else,
  610. else {
  611. // a. Let isNegative be POSITIVE.
  612. is_negative = Sign::Positive;
  613. }
  614. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  615. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  616. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  617. auto r1 = division_result.quotient;
  618. // 6. Let r2 be the smallest integer such that r2 > quotient.
  619. auto r2 = division_result.quotient.plus(1_bigint);
  620. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  621. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment);
  622. // 8. If isNegative is NEGATIVE, set rounded to -rounded.
  623. if (is_negative == Sign::Negative)
  624. rounded.negate();
  625. // 9. Return rounded × increment.
  626. return rounded.multiplied_by(increment);
  627. }
  628. // 13.33 ParseISODateTime ( isoString, allowedFormats ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  629. ThrowCompletionOr<ParsedISODateTime> parse_iso_date_time(VM& vm, StringView iso_string, ReadonlySpan<Production> allowed_formats)
  630. {
  631. // 1. Let parseResult be EMPTY.
  632. Optional<ParseResult> parse_result;
  633. // 2. Let calendar be EMPTY.
  634. Optional<String> calendar;
  635. // 3. Let yearAbsent be false.
  636. auto year_absent = false;
  637. // 4. For each nonterminal goal of allowedFormats, do
  638. for (auto goal : allowed_formats) {
  639. // a. If parseResult is not a Parse Node, then
  640. if (parse_result.has_value())
  641. break;
  642. // i. Set parseResult to ParseText(StringToCodePoints(isoString), goal).
  643. parse_result = parse_iso8601(goal, iso_string);
  644. // ii. If parseResult is a Parse Node, then
  645. if (parse_result.has_value()) {
  646. // 1. Let calendarWasCritical be false.
  647. auto calendar_was_critical = false;
  648. // 2. For each Annotation Parse Node annotation contained within parseResult, do
  649. for (auto const& annotation : parse_result->annotations) {
  650. // a. Let key be the source text matched by the AnnotationKey Parse Node contained within annotation.
  651. auto const& key = annotation.key;
  652. // b. Let value be the source text matched by the AnnotationValue Parse Node contained within annotation.
  653. auto const& value = annotation.value;
  654. // c. If CodePointsToString(key) is "u-ca", then
  655. if (key == "u-ca"sv) {
  656. // i. If calendar is EMPTY, then
  657. if (!calendar.has_value()) {
  658. // i. Set calendar to CodePointsToString(value).
  659. calendar = String::from_utf8_without_validation(value.bytes());
  660. // ii. If annotation contains an AnnotationCriticalFlag Parse Node, set calendarWasCritical to true.
  661. if (annotation.critical)
  662. calendar_was_critical = true;
  663. }
  664. // ii. Else,
  665. else {
  666. // i. If annotation contains an AnnotationCriticalFlag Parse Node, or calendarWasCritical is true,
  667. // throw a RangeError exception.
  668. if (annotation.critical || calendar_was_critical)
  669. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCriticalAnnotation, key, value);
  670. }
  671. }
  672. // d. Else,
  673. else {
  674. // i. If annotation contains an AnnotationCriticalFlag Parse Node, throw a RangeError exception.
  675. if (annotation.critical)
  676. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCriticalAnnotation, key, value);
  677. }
  678. }
  679. // 3. If goal is TemporalMonthDayString or TemporalYearMonthString, calendar is not EMPTY, and the
  680. // ASCII-lowercase of calendar is not "iso8601", throw a RangeError exception.
  681. if (goal == Production::TemporalMonthDayString || goal == Production::TemporalYearMonthString) {
  682. if (calendar.has_value() && !calendar->equals_ignoring_ascii_case("iso8601"sv))
  683. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarIdentifier, *calendar);
  684. }
  685. // 4. If goal is TemporalMonthDayString and parseResult does not contain a DateYear Parse Node, then
  686. if (goal == Production::TemporalMonthDayString && !parse_result->date_year.has_value()) {
  687. // a. Assert: goal is the last element of allowedFormats.
  688. VERIFY(goal == allowed_formats.last());
  689. // b. Set yearAbsent to true.
  690. year_absent = true;
  691. }
  692. }
  693. }
  694. // 5. If parseResult is not a Parse Node, throw a RangeError exception.
  695. if (!parse_result.has_value())
  696. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODateTime);
  697. // 6. NOTE: Applications of StringToNumber below do not lose precision, since each of the parsed values is guaranteed
  698. // to be a sufficiently short string of decimal digits.
  699. // 7. Let each of year, month, day, hour, minute, second, and fSeconds be the source text matched by the respective
  700. // DateYear, DateMonth, DateDay, the first Hour, the first MinuteSecond, TimeSecond, and the first
  701. // TemporalDecimalFraction Parse Node contained within parseResult, or an empty sequence of code points if not present.
  702. auto year = parse_result->date_year.value_or({});
  703. auto month = parse_result->date_month.value_or({});
  704. auto day = parse_result->date_day.value_or({});
  705. auto hour = parse_result->time_hour.value_or({});
  706. auto minute = parse_result->time_minute.value_or({});
  707. auto second = parse_result->time_second.value_or({});
  708. auto fractional_seconds = parse_result->time_fraction.value_or({});
  709. // 8. Let yearMV be ℝ(StringToNumber(CodePointsToString(year))).
  710. auto year_value = string_to_number(year);
  711. // 9. If month is empty, then
  712. // a. Let monthMV be 1.
  713. // 10. Else,
  714. // a. Let monthMV be ℝ(StringToNumber(CodePointsToString(month))).
  715. auto month_value = month.is_empty() ? 1 : string_to_number(month);
  716. // 11. If day is empty, then
  717. // a. Let dayMV be 1.
  718. // 12. Else,
  719. // a. Let dayMV be ℝ(StringToNumber(CodePointsToString(day))).
  720. auto day_value = day.is_empty() ? 1 : string_to_number(day);
  721. // 13. If hour is empty, then
  722. // a. Let hourMV be 0.
  723. // 14. Else,
  724. // a. Let hourMV be ℝ(StringToNumber(CodePointsToString(hour))).
  725. auto hour_value = hour.is_empty() ? 0 : string_to_number(hour);
  726. // 15. If minute is empty, then
  727. // a. Let minuteMV be 0.
  728. // 16. Else,
  729. // a. Let minuteMV be ℝ(StringToNumber(CodePointsToString(minute))).
  730. auto minute_value = minute.is_empty() ? 0 : string_to_number(minute);
  731. // 17. If second is empty, then
  732. // a. Let secondMV be 0.
  733. // 18. Else,
  734. // a. Let secondMV be ℝ(StringToNumber(CodePointsToString(second))).
  735. // b. If secondMV = 60, then
  736. // i. Set secondMV to 59.
  737. auto second_value = second.is_empty() ? 0 : min(string_to_number(second), 59.0);
  738. double millisecond_value = 0;
  739. double microsecond_value = 0;
  740. double nanosecond_value = 0;
  741. // 19. If fSeconds is not empty, then
  742. if (!fractional_seconds.is_empty()) {
  743. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  744. auto fractional_seconds_digits = fractional_seconds.substring_view(1);
  745. // b. Let fSecondsDigitsExtended be the string-concatenation of fSecondsDigits and "000000000".
  746. auto fractional_seconds_extended = MUST(String::formatted("{}000000000", fractional_seconds_digits));
  747. // c. Let millisecond be the substring of fSecondsDigitsExtended from 0 to 3.
  748. auto millisecond = fractional_seconds_extended.bytes_as_string_view().substring_view(0, 3);
  749. // d. Let microsecond be the substring of fSecondsDigitsExtended from 3 to 6.
  750. auto microsecond = fractional_seconds_extended.bytes_as_string_view().substring_view(3, 3);
  751. // e. Let nanosecond be the substring of fSecondsDigitsExtended from 6 to 9.
  752. auto nanosecond = fractional_seconds_extended.bytes_as_string_view().substring_view(6, 3);
  753. // f. Let millisecondMV be ℝ(StringToNumber(millisecond)).
  754. millisecond_value = string_to_number(millisecond);
  755. // g. Let microsecondMV be ℝ(StringToNumber(microsecond)).
  756. microsecond_value = string_to_number(microsecond);
  757. // h. Let nanosecondMV be ℝ(StringToNumber(nanosecond)).
  758. nanosecond_value = string_to_number(nanosecond);
  759. }
  760. // 20. Else,
  761. else {
  762. // a. Let millisecondMV be 0.
  763. // b. Let microsecondMV be 0.
  764. // c. Let nanosecondMV be 0.
  765. }
  766. // 21. Assert: IsValidISODate(yearMV, monthMV, dayMV) is true.
  767. VERIFY(is_valid_iso_date(year_value, month_value, day_value));
  768. Variant<ParsedISODateTime::StartOfDay, Time> time { ParsedISODateTime::StartOfDay {} };
  769. // 22. If hour is empty, then
  770. if (hour.is_empty()) {
  771. // a. Let time be START-OF-DAY.
  772. }
  773. // 23. Else,
  774. else {
  775. // a. Let time be CreateTimeRecord(hourMV, minuteMV, secondMV, millisecondMV, microsecondMV, nanosecondMV).
  776. time = create_time_record(hour_value, minute_value, second_value, millisecond_value, microsecond_value, nanosecond_value);
  777. }
  778. // 24. Let timeZoneResult be ISO String Time Zone Parse Record { [[Z]]: false, [[OffsetString]]: EMPTY, [[TimeZoneAnnotation]]: EMPTY }.
  779. ParsedISOTimeZone time_zone_result;
  780. // 25. If parseResult contains a TimeZoneIdentifier Parse Node, then
  781. if (parse_result->time_zone_identifier.has_value()) {
  782. // a. Let identifier be the source text matched by the TimeZoneIdentifier Parse Node contained within parseResult.
  783. // b. Set timeZoneResult.[[TimeZoneAnnotation]] to CodePointsToString(identifier).
  784. time_zone_result.time_zone_annotation = String::from_utf8_without_validation(parse_result->time_zone_identifier->bytes());
  785. }
  786. // 26. If parseResult contains a UTCDesignator Parse Node, then
  787. if (parse_result->utc_designator.has_value()) {
  788. // a. Set timeZoneResult.[[Z]] to true.
  789. time_zone_result.z_designator = true;
  790. }
  791. // 27. Else if parseResult contains a UTCOffset[+SubMinutePrecision] Parse Node, then
  792. else if (parse_result->date_time_offset.has_value()) {
  793. // a. Let offset be the source text matched by the UTCOffset[+SubMinutePrecision] Parse Node contained within parseResult.
  794. // b. Set timeZoneResult.[[OffsetString]] to CodePointsToString(offset).
  795. time_zone_result.offset_string = String::from_utf8_without_validation(parse_result->date_time_offset->source_text.bytes());
  796. }
  797. // 28. If yearAbsent is true, let yearReturn be EMPTY; else let yearReturn be yearMV.
  798. Optional<i32> year_return;
  799. if (!year_absent)
  800. year_return = static_cast<i32>(year_value);
  801. // 29. Return ISO Date-Time Parse Record { [[Year]]: yearReturn, [[Month]]: monthMV, [[Day]]: dayMV, [[Time]]: time, [[TimeZone]]: timeZoneResult, [[Calendar]]: calendar }.
  802. return ParsedISODateTime { .year = year_return, .month = static_cast<u8>(month_value), .day = static_cast<u8>(day_value), .time = move(time), .time_zone = move(time_zone_result), .calendar = move(calendar) };
  803. }
  804. // 13.34 ParseTemporalCalendarString ( string ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  805. ThrowCompletionOr<String> parse_temporal_calendar_string(VM& vm, String const& string)
  806. {
  807. // 1. Let parseResult be Completion(ParseISODateTime(string, « TemporalDateTimeString[+Zoned], TemporalDateTimeString[~Zoned],
  808. // TemporalInstantString, TemporalTimeString, TemporalMonthDayString, TemporalYearMonthString »)).
  809. static constexpr auto productions = to_array<Production>({
  810. Production::TemporalZonedDateTimeString,
  811. Production::TemporalDateTimeString,
  812. Production::TemporalInstantString,
  813. Production::TemporalTimeString,
  814. Production::TemporalMonthDayString,
  815. Production::TemporalYearMonthString,
  816. });
  817. auto parse_result = parse_iso_date_time(vm, string, productions);
  818. // 2. If parseResult is a normal completion, then
  819. if (!parse_result.is_error()) {
  820. // a. Let calendar be parseResult.[[Value]].[[Calendar]].
  821. auto calendar = parse_result.value().calendar;
  822. // b. If calendar is empty, return "iso8601".
  823. // c. Else, return calendar.
  824. return calendar.value_or("iso8601"_string);
  825. }
  826. // 3. Else,
  827. else {
  828. // a. Set parseResult to ParseText(StringToCodePoints(string), AnnotationValue).
  829. auto annotation_parse_result = parse_iso8601(Production::AnnotationValue, string);
  830. // b. If parseResult is a List of errors, throw a RangeError exception.
  831. if (!annotation_parse_result.has_value())
  832. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarString, string);
  833. // c. Else, return string.
  834. return string;
  835. }
  836. }
  837. // 13.35 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  838. ThrowCompletionOr<GC::Ref<Duration>> parse_temporal_duration_string(VM& vm, StringView iso_string)
  839. {
  840. // 1. Let duration be ParseText(StringToCodePoints(isoString), TemporalDurationString).
  841. auto parse_result = parse_iso8601(Production::TemporalDurationString, iso_string);
  842. // 2. If duration is a List of errors, throw a RangeError exception.
  843. if (!parse_result.has_value())
  844. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationString, iso_string);
  845. // 3. Let sign be the source text matched by the ASCIISign Parse Node contained within duration, or an empty sequence
  846. // of code points if not present.
  847. auto sign = parse_result->sign;
  848. // 4. If duration contains a DurationYearsPart Parse Node, then
  849. // a. Let yearsNode be that DurationYearsPart Parse Node contained within duration.
  850. // b. Let years be the source text matched by the DecimalDigits Parse Node contained within yearsNode.
  851. // 5. Else,
  852. // a. Let years be an empty sequence of code points.
  853. auto years = parse_result->duration_years.value_or({});
  854. // 6. If duration contains a DurationMonthsPart Parse Node, then
  855. // a. Let monthsNode be the DurationMonthsPart Parse Node contained within duration.
  856. // b. Let months be the source text matched by the DecimalDigits Parse Node contained within monthsNode.
  857. // 7. Else,
  858. // a. Let months be an empty sequence of code points.
  859. auto months = parse_result->duration_months.value_or({});
  860. // 8. If duration contains a DurationWeeksPart Parse Node, then
  861. // a. Let weeksNode be the DurationWeeksPart Parse Node contained within duration.
  862. // b. Let weeks be the source text matched by the DecimalDigits Parse Node contained within weeksNode.
  863. // 9. Else,
  864. // a. Let weeks be an empty sequence of code points.
  865. auto weeks = parse_result->duration_weeks.value_or({});
  866. // 10. If duration contains a DurationDaysPart Parse Node, then
  867. // a. Let daysNode be the DurationDaysPart Parse Node contained within duration.
  868. // b. Let days be the source text matched by the DecimalDigits Parse Node contained within daysNode.
  869. // 11. Else,
  870. // a. Let days be an empty sequence of code points.
  871. auto days = parse_result->duration_days.value_or({});
  872. // 12. If duration contains a DurationHoursPart Parse Node, then
  873. // a. Let hoursNode be the DurationHoursPart Parse Node contained within duration.
  874. // b. Let hours be the source text matched by the DecimalDigits Parse Node contained within hoursNode.
  875. // c. Let fHours be the source text matched by the TemporalDecimalFraction Parse Node contained within
  876. // hoursNode, or an empty sequence of code points if not present.
  877. // 13. Else,
  878. // a. Let hours be an empty sequence of code points.
  879. // b. Let fHours be an empty sequence of code points.
  880. auto hours = parse_result->duration_hours.value_or({});
  881. auto fractional_hours = parse_result->duration_hours_fraction.value_or({});
  882. // 14. If duration contains a DurationMinutesPart Parse Node, then
  883. // a. Let minutesNode be the DurationMinutesPart Parse Node contained within duration.
  884. // b. Let minutes be the source text matched by the DecimalDigits Parse Node contained within minutesNode.
  885. // c. Let fMinutes be the source text matched by the TemporalDecimalFraction Parse Node contained within
  886. // minutesNode, or an empty sequence of code points if not present.
  887. // 15. Else,
  888. // a. Let minutes be an empty sequence of code points.
  889. // b. Let fMinutes be an empty sequence of code points.
  890. auto minutes = parse_result->duration_minutes.value_or({});
  891. auto fractional_minutes = parse_result->duration_minutes_fraction.value_or({});
  892. // 16. If duration contains a DurationSecondsPart Parse Node, then
  893. // a. Let secondsNode be the DurationSecondsPart Parse Node contained within duration.
  894. // b. Let seconds be the source text matched by the DecimalDigits Parse Node contained within secondsNode.
  895. // c. Let fSeconds be the source text matched by the TemporalDecimalFraction Parse Node contained within
  896. // secondsNode, or an empty sequence of code points if not present.
  897. // 17. Else,
  898. // a. Let seconds be an empty sequence of code points.
  899. // b. Let fSeconds be an empty sequence of code points.
  900. auto seconds = parse_result->duration_seconds.value_or({});
  901. auto fractional_seconds = parse_result->duration_seconds_fraction.value_or({});
  902. // 18. Let yearsMV be ? ToIntegerWithTruncation(CodePointsToString(years)).
  903. auto years_value = TRY(to_integer_with_truncation(vm, years, ErrorType::TemporalInvalidDurationString, iso_string));
  904. // 19. Let monthsMV be ? ToIntegerWithTruncation(CodePointsToString(months)).
  905. auto months_value = TRY(to_integer_with_truncation(vm, months, ErrorType::TemporalInvalidDurationString, iso_string));
  906. // 20. Let weeksMV be ? ToIntegerWithTruncation(CodePointsToString(weeks)).
  907. auto weeks_value = TRY(to_integer_with_truncation(vm, weeks, ErrorType::TemporalInvalidDurationString, iso_string));
  908. // 21. Let daysMV be ? ToIntegerWithTruncation(CodePointsToString(days)).
  909. auto days_value = TRY(to_integer_with_truncation(vm, days, ErrorType::TemporalInvalidDurationString, iso_string));
  910. // 22. Let hoursMV be ? ToIntegerWithTruncation(CodePointsToString(hours)).
  911. auto hours_value = TRY(to_integer_with_truncation(vm, hours, ErrorType::TemporalInvalidDurationString, iso_string));
  912. Crypto::BigFraction minutes_value;
  913. Crypto::BigFraction seconds_value;
  914. Crypto::BigFraction milliseconds_value;
  915. auto remainder_one = [](Crypto::BigFraction const& value) {
  916. // FIXME: We should add a generic remainder() method to BigFraction, or a method equivalent to modf(). But for
  917. // now, since we know we are only dividing by powers of 10, we can implement a very situationally specific
  918. // method to extract the fractional part of the BigFraction.
  919. auto res = value.numerator().divided_by(value.denominator());
  920. return Crypto::BigFraction { move(res.remainder), value.denominator() };
  921. };
  922. // 23. If fHours is not empty, then
  923. if (!fractional_hours.is_empty()) {
  924. // a. Assert: minutes, fMinutes, seconds, and fSeconds are empty.
  925. VERIFY(minutes.is_empty());
  926. VERIFY(fractional_minutes.is_empty());
  927. VERIFY(seconds.is_empty());
  928. VERIFY(fractional_seconds.is_empty());
  929. // b. Let fHoursDigits be the substring of CodePointsToString(fHours) from 1.
  930. auto fractional_hours_digits = fractional_hours.substring_view(1);
  931. // c. Let fHoursScale be the length of fHoursDigits.
  932. auto fractional_hours_scale = fractional_hours_digits.length();
  933. // d. Let minutesMV be ? ToIntegerWithTruncation(fHoursDigits) / 10**fHoursScale × 60.
  934. auto minutes_integer = TRY(to_integer_with_truncation(vm, fractional_hours_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  935. minutes_value = Crypto::BigFraction { minutes_integer } / Crypto::BigFraction { pow(10.0, fractional_hours_scale) } * Crypto::BigFraction { 60.0 };
  936. }
  937. // 24. Else,
  938. else {
  939. // a. Let minutesMV be ? ToIntegerWithTruncation(CodePointsToString(minutes)).
  940. auto minutes_integer = TRY(to_integer_with_truncation(vm, minutes, ErrorType::TemporalInvalidDurationString, iso_string));
  941. minutes_value = Crypto::BigFraction { minutes_integer };
  942. }
  943. // 25. If fMinutes is not empty, then
  944. if (!fractional_minutes.is_empty()) {
  945. // a. Assert: seconds and fSeconds are empty.
  946. VERIFY(seconds.is_empty());
  947. VERIFY(fractional_seconds.is_empty());
  948. // b. Let fMinutesDigits be the substring of CodePointsToString(fMinutes) from 1.
  949. auto fractional_minutes_digits = fractional_minutes.substring_view(1);
  950. // c. Let fMinutesScale be the length of fMinutesDigits.
  951. auto fractional_minutes_scale = fractional_minutes_digits.length();
  952. // d. Let secondsMV be ? ToIntegerWithTruncation(fMinutesDigits) / 10**fMinutesScale × 60.
  953. auto seconds_integer = TRY(to_integer_with_truncation(vm, fractional_minutes_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  954. seconds_value = Crypto::BigFraction { seconds_integer } / Crypto::BigFraction { pow(10.0, fractional_minutes_scale) } * Crypto::BigFraction { 60.0 };
  955. }
  956. // 26. Else if seconds is not empty, then
  957. else if (!seconds.is_empty()) {
  958. // a. Let secondsMV be ? ToIntegerWithTruncation(CodePointsToString(seconds)).
  959. auto seconds_integer = TRY(to_integer_with_truncation(vm, seconds, ErrorType::TemporalInvalidDurationString, iso_string));
  960. seconds_value = Crypto::BigFraction { seconds_integer };
  961. }
  962. // 27. Else,
  963. else {
  964. // a. Let secondsMV be remainder(minutesMV, 1) × 60.
  965. seconds_value = remainder_one(minutes_value) * Crypto::BigFraction { 60.0 };
  966. }
  967. // 28. If fSeconds is not empty, then
  968. if (!fractional_seconds.is_empty()) {
  969. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  970. auto fractional_seconds_digits = fractional_seconds.substring_view(1);
  971. // b. Let fSecondsScale be the length of fSecondsDigits.
  972. auto fractional_seconds_scale = fractional_seconds_digits.length();
  973. // c. Let millisecondsMV be ? ToIntegerWithTruncation(fSecondsDigits) / 10**fSecondsScale × 1000.
  974. auto milliseconds_integer = TRY(to_integer_with_truncation(vm, fractional_seconds_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  975. milliseconds_value = Crypto::BigFraction { milliseconds_integer } / Crypto::BigFraction { pow(10.0, fractional_seconds_scale) } * Crypto::BigFraction { 1000.0 };
  976. }
  977. // 29. Else,
  978. else {
  979. // a. Let millisecondsMV be remainder(secondsMV, 1) × 1000.
  980. milliseconds_value = remainder_one(seconds_value) * Crypto::BigFraction { 1000.0 };
  981. }
  982. // 30. Let microsecondsMV be remainder(millisecondsMV, 1) × 1000.
  983. auto microseconds_value = remainder_one(milliseconds_value) * Crypto::BigFraction { 1000.0 };
  984. // 31. Let nanosecondsMV be remainder(microsecondsMV, 1) × 1000.
  985. auto nanoseconds_value = remainder_one(microseconds_value) * Crypto::BigFraction { 1000.0 };
  986. // 32. If sign contains the code point U+002D (HYPHEN-MINUS), then
  987. // a. Let factor be -1.
  988. // 33. Else,
  989. // a. Let factor be 1.
  990. i8 factor = sign == '-' ? -1 : 1;
  991. // 34. Set yearsMV to yearsMV × factor.
  992. years_value *= factor;
  993. // 35. Set monthsMV to monthsMV × factor.
  994. months_value *= factor;
  995. // 36. Set weeksMV to weeksMV × factor.
  996. weeks_value *= factor;
  997. // 37. Set daysMV to daysMV × factor.
  998. days_value *= factor;
  999. // 38. Set hoursMV to hoursMV × factor.
  1000. hours_value *= factor;
  1001. // 39. Set minutesMV to floor(minutesMV) × factor.
  1002. auto factored_minutes_value = floor(minutes_value.to_double()) * factor;
  1003. // 40. Set secondsMV to floor(secondsMV) × factor.
  1004. auto factored_seconds_value = floor(seconds_value.to_double()) * factor;
  1005. // 41. Set millisecondsMV to floor(millisecondsMV) × factor.
  1006. auto factored_milliseconds_value = floor(milliseconds_value.to_double()) * factor;
  1007. // 42. Set microsecondsMV to floor(microsecondsMV) × factor.
  1008. auto factored_microseconds_value = floor(microseconds_value.to_double()) * factor;
  1009. // 43. Set nanosecondsMV to floor(nanosecondsMV) × factor.
  1010. auto factored_nanoseconds_value = floor(nanoseconds_value.to_double()) * factor;
  1011. // 44. Return ? CreateTemporalDuration(yearsMV, monthsMV, weeksMV, daysMV, hoursMV, minutesMV, secondsMV, millisecondsMV, microsecondsMV, nanosecondsMV).
  1012. return TRY(create_temporal_duration(vm, years_value, months_value, weeks_value, days_value, hours_value, factored_minutes_value, factored_seconds_value, factored_milliseconds_value, factored_microseconds_value, factored_nanoseconds_value));
  1013. }
  1014. // 13.36 ParseTemporalTimeZoneString ( timeZoneString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  1015. ThrowCompletionOr<TimeZone> parse_temporal_time_zone_string(VM& vm, StringView time_zone_string)
  1016. {
  1017. // 1. Let parseResult be ParseText(StringToCodePoints(timeZoneString), TimeZoneIdentifier).
  1018. auto parse_result = parse_iso8601(Production::TimeZoneIdentifier, time_zone_string);
  1019. // 2. If parseResult is a Parse Node, then
  1020. if (parse_result.has_value()) {
  1021. // a. Return ! ParseTimeZoneIdentifier(timeZoneString).
  1022. return parse_time_zone_identifier(parse_result.release_value());
  1023. }
  1024. // 3. Let result be ? ParseISODateTime(timeZoneString, « TemporalDateTimeString[+Zoned], TemporalDateTimeString[~Zoned],
  1025. // TemporalInstantString, TemporalTimeString, TemporalMonthDayString, TemporalYearMonthString »).
  1026. static constexpr auto productions = to_array<Production>({
  1027. Production::TemporalZonedDateTimeString,
  1028. Production::TemporalDateTimeString,
  1029. Production::TemporalInstantString,
  1030. Production::TemporalTimeString,
  1031. Production::TemporalMonthDayString,
  1032. Production::TemporalYearMonthString,
  1033. });
  1034. auto result = TRY(parse_iso_date_time(vm, time_zone_string, productions));
  1035. // 4. Let timeZoneResult be result.[[TimeZone]].
  1036. auto time_zone_result = move(result.time_zone);
  1037. // 5. If timeZoneResult.[[TimeZoneAnnotation]] is not empty, then
  1038. if (time_zone_result.time_zone_annotation.has_value()) {
  1039. // a. Return ! ParseTimeZoneIdentifier(timeZoneResult.[[TimeZoneAnnotation]]).
  1040. return MUST(parse_time_zone_identifier(vm, *time_zone_result.time_zone_annotation));
  1041. }
  1042. // 6. If timeZoneResult.[[Z]] is true, then
  1043. if (time_zone_result.z_designator) {
  1044. // a. Return ! ParseTimeZoneIdentifier("UTC").
  1045. return MUST(parse_time_zone_identifier(vm, "UTC"sv));
  1046. }
  1047. // 7. If timeZoneResult.[[OffsetString]] is not empty, then
  1048. if (time_zone_result.offset_string.has_value()) {
  1049. // a. Return ? ParseTimeZoneIdentifier(timeZoneResult.[[OffsetString]]).
  1050. return TRY(parse_time_zone_identifier(vm, *time_zone_result.offset_string));
  1051. }
  1052. // 8. Throw a RangeError exception.
  1053. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneString, time_zone_string);
  1054. }
  1055. // 13.40 ToMonthCode ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-tomonthcode
  1056. ThrowCompletionOr<String> to_month_code(VM& vm, Value argument)
  1057. {
  1058. // 1. Let monthCode be ? ToPrimitive(argument, STRING).
  1059. auto month_code = TRY(argument.to_primitive(vm, Value::PreferredType::String));
  1060. // 2. If monthCode is not a String, throw a TypeError exception.
  1061. if (!month_code.is_string())
  1062. return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidMonthCode);
  1063. auto month_code_string = month_code.as_string().utf8_string_view();
  1064. // 3. If the length of monthCode is not 3 or 4, throw a RangeError exception.
  1065. if (month_code_string.length() != 3 && month_code_string.length() != 4)
  1066. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1067. // 4. If the first code unit of monthCode is not 0x004D (LATIN CAPITAL LETTER M), throw a RangeError exception.
  1068. if (month_code_string[0] != 'M')
  1069. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1070. // 5. If the second code unit of monthCode is not in the inclusive interval from 0x0030 (DIGIT ZERO) to 0x0039 (DIGIT NINE),
  1071. // throw a RangeError exception.
  1072. if (!is_ascii_digit(month_code_string[1]) || parse_ascii_digit(month_code_string[1]) > 9)
  1073. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1074. // 6. If the third code unit of monthCode is not in the inclusive interval from 0x0030 (DIGIT ZERO) to 0x0039 (DIGIT NINE),
  1075. // throw a RangeError exception.
  1076. if (!is_ascii_digit(month_code_string[2]) || parse_ascii_digit(month_code_string[2]) > 9)
  1077. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1078. // 7. If the length of monthCode is 4 and the fourth code unit of monthCode is not 0x004C (LATIN CAPITAL LETTER L),
  1079. // throw a RangeError exception.
  1080. if (month_code_string.length() == 4 && month_code_string[3] != 'L')
  1081. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1082. // 8. Let monthCodeDigits be the substring of monthCode from 1 to 3.
  1083. auto month_code_digits = month_code_string.substring_view(1, 2);
  1084. // 9. Let monthCodeInteger be ℝ(StringToNumber(monthCodeDigits)).
  1085. auto month_code_integer = month_code_digits.to_number<u8>().value();
  1086. // 10. If monthCodeInteger is 0 and the length of monthCode is not 4, throw a RangeError exception.
  1087. if (month_code_integer == 0 && month_code_string.length() != 4)
  1088. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthCode);
  1089. // 11. Return monthCode.
  1090. return month_code.as_string().utf8_string();
  1091. }
  1092. // 13.41 ToOffsetString ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-tooffsetstring
  1093. ThrowCompletionOr<String> to_offset_string(VM& vm, Value argument)
  1094. {
  1095. // 1. Let offset be ? ToPrimitive(argument, STRING).
  1096. auto offset = TRY(argument.to_primitive(vm, Value::PreferredType::String));
  1097. // 2. If offset is not a String, throw a TypeError exception.
  1098. if (!offset.is_string())
  1099. return vm.throw_completion<TypeError>(ErrorType::TemporalInvalidTimeZoneString, offset);
  1100. // 3. Perform ? ParseDateTimeUTCOffset(offset).
  1101. // FIXME: ParseTimeZoneOffsetString should be renamed to ParseDateTimeUTCOffset and updated for Temporal. For now, we
  1102. // can just check with the ISO8601 parser directly.
  1103. if (!parse_utc_offset(argument.as_string().utf8_string_view(), SubMinutePrecision::Yes).has_value())
  1104. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneString, offset);
  1105. // 4. Return offset.
  1106. return offset.as_string().utf8_string();
  1107. }
  1108. // 13.42 ISODateToFields ( calendar, isoDate, type ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetofields
  1109. CalendarFields iso_date_to_fields(StringView calendar, ISODate const& iso_date, DateType type)
  1110. {
  1111. // 1. Let fields be an empty Calendar Fields Record with all fields set to unset.
  1112. auto fields = CalendarFields::unset();
  1113. // 2. Let calendarDate be CalendarISOToDate(calendar, isoDate).
  1114. auto calendar_date = calendar_iso_to_date(calendar, iso_date);
  1115. // 3. Set fields.[[MonthCode]] to calendarDate.[[MonthCode]].
  1116. fields.month_code = calendar_date.month_code;
  1117. // 4. If type is MONTH-DAY or DATE, then
  1118. if (type == DateType::MonthDay || type == DateType::Date) {
  1119. // a. Set fields.[[Day]] to calendarDate.[[Day]].
  1120. fields.day = calendar_date.day;
  1121. }
  1122. // 5. If type is YEAR-MONTH or DATE, then
  1123. if (type == DateType::YearMonth || type == DateType::Date) {
  1124. // a. Set fields.[[Year]] to calendarDate.[[Year]].
  1125. fields.year = calendar_date.year;
  1126. }
  1127. // 6. Return fields.
  1128. return fields;
  1129. }
  1130. // 14.4.1.1 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  1131. ThrowCompletionOr<GC::Ref<Object>> get_options_object(VM& vm, Value options)
  1132. {
  1133. auto& realm = *vm.current_realm();
  1134. // 1. If options is undefined, then
  1135. if (options.is_undefined()) {
  1136. // a. Return OrdinaryObjectCreate(null).
  1137. return Object::create(realm, nullptr);
  1138. }
  1139. // 2. If options is an Object, then
  1140. if (options.is_object()) {
  1141. // a. Return options.
  1142. return options.as_object();
  1143. }
  1144. // 3. Throw a TypeError exception.
  1145. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, "Options");
  1146. }
  1147. // 14.4.1.2 GetOption ( options, property, type, values, default ), https://tc39.es/proposal-temporal/#sec-getoption
  1148. ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey const& property, OptionType type, ReadonlySpan<StringView> values, OptionDefault const& default_)
  1149. {
  1150. VERIFY(property.is_string());
  1151. // 1. Let value be ? Get(options, property).
  1152. auto value = TRY(options.get(property));
  1153. // 2. If value is undefined, then
  1154. if (value.is_undefined()) {
  1155. // a. If default is REQUIRED, throw a RangeError exception.
  1156. if (default_.has<Required>())
  1157. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, "undefined"sv, property.as_string());
  1158. // b. Return default.
  1159. return default_.visit(
  1160. [](Required) -> Value { VERIFY_NOT_REACHED(); },
  1161. [](Empty) -> Value { return js_undefined(); },
  1162. [](bool default_) -> Value { return Value { default_ }; },
  1163. [](double default_) -> Value { return Value { default_ }; },
  1164. [&](StringView default_) -> Value { return PrimitiveString::create(vm, default_); });
  1165. }
  1166. // 3. If type is BOOLEAN, then
  1167. if (type == OptionType::Boolean) {
  1168. // a. Set value to ToBoolean(value).
  1169. value = Value { value.to_boolean() };
  1170. }
  1171. // 4. Else,
  1172. else {
  1173. // a. Assert: type is STRING.
  1174. VERIFY(type == OptionType::String);
  1175. // b. Set value to ? ToString(value).
  1176. value = TRY(value.to_primitive_string(vm));
  1177. }
  1178. // 5. If values is not EMPTY and values does not contain value, throw a RangeError exception.
  1179. if (!values.is_empty()) {
  1180. // NOTE: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  1181. VERIFY(value.is_string());
  1182. if (auto value_string = value.as_string().utf8_string(); !values.contains_slow(value_string))
  1183. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value_string, property.as_string());
  1184. }
  1185. // 6. Return value.
  1186. return value;
  1187. }
  1188. // 14.4.1.3 GetRoundingModeOption ( options, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-getroundingmodeoption
  1189. ThrowCompletionOr<RoundingMode> get_rounding_mode_option(VM& vm, Object const& options, RoundingMode fallback)
  1190. {
  1191. // 1. Let allowedStrings be the List of Strings from the "String Identifier" column of Table 26.
  1192. static constexpr auto allowed_strings = to_array({ "ceil"sv, "floor"sv, "expand"sv, "trunc"sv, "halfCeil"sv, "halfFloor"sv, "halfExpand"sv, "halfTrunc"sv, "halfEven"sv });
  1193. // 2. Let stringFallback be the value from the "String Identifier" column of the row with fallback in its "Rounding Mode" column.
  1194. auto string_fallback = allowed_strings[to_underlying(fallback)];
  1195. // 3. Let stringValue be ? GetOption(options, "roundingMode", STRING, allowedStrings, stringFallback).
  1196. auto string_value = TRY(get_option(vm, options, vm.names.roundingMode, OptionType::String, allowed_strings, string_fallback));
  1197. // 4. Return the value from the "Rounding Mode" column of the row with stringValue in its "String Identifier" column.
  1198. return static_cast<RoundingMode>(allowed_strings.first_index_of(string_value.as_string().utf8_string_view()).value());
  1199. }
  1200. // 14.4.1.4 GetRoundingIncrementOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-getroundingincrementoption
  1201. ThrowCompletionOr<u64> get_rounding_increment_option(VM& vm, Object const& options)
  1202. {
  1203. // 1. Let value be ? Get(options, "roundingIncrement").
  1204. auto value = TRY(options.get(vm.names.roundingIncrement));
  1205. // 2. If value is undefined, return 1𝔽.
  1206. if (value.is_undefined())
  1207. return 1;
  1208. // 3. Let integerIncrement be ? ToIntegerWithTruncation(value).
  1209. auto integer_increment = TRY(to_integer_with_truncation(vm, value, ErrorType::OptionIsNotValidValue, value, "roundingIncrement"sv));
  1210. // 4. If integerIncrement < 1 or integerIncrement > 10**9, throw a RangeError exception.
  1211. if (integer_increment < 1 || integer_increment > 1'000'000'000u)
  1212. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value, "roundingIncrement");
  1213. // 5. Return integerIncrement.
  1214. return static_cast<u64>(integer_increment);
  1215. }
  1216. // 14.5.1 GetUTCEpochNanoseconds ( isoDateTime ), https://tc39.es/proposal-temporal/#sec-getutcepochnanoseconds
  1217. Crypto::SignedBigInteger get_utc_epoch_nanoseconds(ISODateTime const& iso_date_time)
  1218. {
  1219. return JS::get_utc_epoch_nanoseconds(
  1220. iso_date_time.iso_date.year,
  1221. iso_date_time.iso_date.month,
  1222. iso_date_time.iso_date.day,
  1223. iso_date_time.time.hour,
  1224. iso_date_time.time.minute,
  1225. iso_date_time.time.second,
  1226. iso_date_time.time.millisecond,
  1227. iso_date_time.time.microsecond,
  1228. iso_date_time.time.nanosecond);
  1229. }
  1230. }