AbstractOperations.cpp 80 KB

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