AbstractOperations.cpp 73 KB

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