AbstractOperations.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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/PropertyKey.h>
  12. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  13. #include <LibJS/Runtime/Temporal/Duration.h>
  14. #include <LibJS/Runtime/Temporal/ISO8601.h>
  15. #include <LibJS/Runtime/Temporal/Instant.h>
  16. namespace JS::Temporal {
  17. // https://tc39.es/proposal-temporal/#table-temporal-units
  18. struct TemporalUnit {
  19. Unit value;
  20. StringView singular_property_name;
  21. StringView plural_property_name;
  22. UnitCategory category;
  23. RoundingIncrement maximum_duration_rounding_increment;
  24. };
  25. static auto temporal_units = to_array<TemporalUnit>({
  26. { Unit::Year, "year"sv, "years"sv, UnitCategory::Date, Unset {} },
  27. { Unit::Month, "month"sv, "months"sv, UnitCategory::Date, Unset {} },
  28. { Unit::Week, "week"sv, "weeks"sv, UnitCategory::Date, Unset {} },
  29. { Unit::Day, "day"sv, "days"sv, UnitCategory::Date, Unset {} },
  30. { Unit::Hour, "hour"sv, "hours"sv, UnitCategory::Time, 24 },
  31. { Unit::Minute, "minute"sv, "minutes"sv, UnitCategory::Time, 60 },
  32. { Unit::Second, "second"sv, "seconds"sv, UnitCategory::Time, 60 },
  33. { Unit::Millisecond, "millisecond"sv, "milliseconds"sv, UnitCategory::Time, 1000 },
  34. { Unit::Microsecond, "microsecond"sv, "microseconds"sv, UnitCategory::Time, 1000 },
  35. { Unit::Nanosecond, "nanosecond"sv, "nanoseconds"sv, UnitCategory::Time, 1000 },
  36. });
  37. StringView temporal_unit_to_string(Unit unit)
  38. {
  39. return temporal_units[to_underlying(unit)].singular_property_name;
  40. }
  41. // 13.14 ValidateTemporalRoundingIncrement ( increment, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-validatetemporalroundingincrement
  42. ThrowCompletionOr<void> validate_temporal_rounding_increment(VM& vm, u64 increment, u64 dividend, bool inclusive)
  43. {
  44. u64 maximum = 0;
  45. // 1. If inclusive is true, then
  46. if (inclusive) {
  47. // a. Let maximum be dividend.
  48. maximum = dividend;
  49. }
  50. // 2. Else,
  51. else {
  52. // a. Assert: dividend > 1.
  53. VERIFY(dividend > 1);
  54. // b. Let maximum be dividend - 1.
  55. maximum = dividend - 1;
  56. }
  57. // 3. If increment > maximum, throw a RangeError exception.
  58. if (increment > maximum)
  59. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  60. // 5. If dividend modulo increment ≠ 0, then
  61. if (modulo(dividend, increment) != 0) {
  62. // a. Throw a RangeError exception.
  63. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  64. }
  65. // 6. Return UNUSED.
  66. return {};
  67. }
  68. // 13.15 GetTemporalFractionalSecondDigitsOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalfractionalseconddigitsoption
  69. ThrowCompletionOr<Precision> get_temporal_fractional_second_digits_option(VM& vm, Object const& options)
  70. {
  71. // 1. Let digitsValue be ? Get(options, "fractionalSecondDigits").
  72. auto digits_value = TRY(options.get(vm.names.fractionalSecondDigits));
  73. // 2. If digitsValue is undefined, return AUTO.
  74. if (digits_value.is_undefined())
  75. return Precision { Auto {} };
  76. // 3. If digitsValue is not a Number, then
  77. if (!digits_value.is_number()) {
  78. // a. If ? ToString(digitsValue) is not "auto", throw a RangeError exception.
  79. auto digits_value_string = TRY(digits_value.to_string(vm));
  80. if (digits_value_string != "auto"sv)
  81. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  82. // b. Return AUTO.
  83. return Precision { Auto {} };
  84. }
  85. // 4. If digitsValue is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  86. if (digits_value.is_nan() || digits_value.is_infinity())
  87. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  88. // 5. Let digitCount be floor(ℝ(digitsValue)).
  89. auto digit_count = floor(digits_value.as_double());
  90. // 6. If digitCount < 0 or digitCount > 9, throw a RangeError exception.
  91. if (digit_count < 0 || digit_count > 9)
  92. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, digits_value, vm.names.fractionalSecondDigits);
  93. // 7. Return digitCount.
  94. return Precision { static_cast<u8>(digit_count) };
  95. }
  96. // 13.16 ToSecondsStringPrecisionRecord ( smallestUnit, fractionalDigitCount ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecisionrecord
  97. SecondsStringPrecision to_seconds_string_precision_record(UnitValue smallest_unit, Precision fractional_digit_count)
  98. {
  99. if (auto const* unit = smallest_unit.get_pointer<Unit>()) {
  100. // 1. If smallestUnit is MINUTE, then
  101. if (*unit == Unit::Minute) {
  102. // a. Return the Record { [[Precision]]: MINUTE, [[Unit]]: MINUTE, [[Increment]]: 1 }.
  103. return { .precision = SecondsStringPrecision::Minute {}, .unit = Unit::Minute, .increment = 1 };
  104. }
  105. // 2. If smallestUnit is SECOND, then
  106. if (*unit == Unit::Second) {
  107. // a. Return the Record { [[Precision]]: 0, [[Unit]]: SECOND, [[Increment]]: 1 }.
  108. return { .precision = 0, .unit = Unit::Second, .increment = 1 };
  109. }
  110. // 3. If smallestUnit is MILLISECOND, then
  111. if (*unit == Unit::Millisecond) {
  112. // a. Return the Record { [[Precision]]: 3, [[Unit]]: MILLISECOND, [[Increment]]: 1 }.
  113. return { .precision = 3, .unit = Unit::Millisecond, .increment = 1 };
  114. }
  115. // 4. If smallestUnit is MICROSECOND, then
  116. if (*unit == Unit::Microsecond) {
  117. // a. Return the Record { [[Precision]]: 6, [[Unit]]: MICROSECOND, [[Increment]]: 1 }.
  118. return { .precision = 6, .unit = Unit::Microsecond, .increment = 1 };
  119. }
  120. // 5. If smallestUnit is NANOSECOND, then
  121. if (*unit == Unit::Nanosecond) {
  122. // a. Return the Record { [[Precision]]: 9, [[Unit]]: NANOSECOND, [[Increment]]: 1 }.
  123. return { .precision = 9, .unit = Unit::Nanosecond, .increment = 1 };
  124. }
  125. }
  126. // 6. Assert: smallestUnit is UNSET.
  127. VERIFY(smallest_unit.has<Unset>());
  128. // 7. If fractionalDigitCount is auto, then
  129. if (fractional_digit_count.has<Auto>()) {
  130. // a. Return the Record { [[Precision]]: AUTO, [[Unit]]: NANOSECOND, [[Increment]]: 1 }.
  131. return { .precision = Auto {}, .unit = Unit::Nanosecond, .increment = 1 };
  132. }
  133. auto fractional_digits = fractional_digit_count.get<u8>();
  134. // 8. If fractionalDigitCount = 0, then
  135. if (fractional_digits == 0) {
  136. // a. Return the Record { [[Precision]]: 0, [[Unit]]: SECOND, [[Increment]]: 1 }.
  137. return { .precision = 0, .unit = Unit::Second, .increment = 1 };
  138. }
  139. // 9. If fractionalDigitCount is in the inclusive interval from 1 to 3, then
  140. if (fractional_digits >= 1 && fractional_digits <= 3) {
  141. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: MILLISECOND, [[Increment]]: 10**(3 - fractionalDigitCount) }.
  142. return { .precision = fractional_digits, .unit = Unit::Millisecond, .increment = static_cast<u8>(pow(10, 3 - fractional_digits)) };
  143. }
  144. // 10. If fractionalDigitCount is in the inclusive interval from 4 to 6, then
  145. if (fractional_digits >= 4 && fractional_digits <= 6) {
  146. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: MICROSECOND, [[Increment]]: 10**(6 - fractionalDigitCount) }.
  147. return { .precision = fractional_digits, .unit = Unit::Microsecond, .increment = static_cast<u8>(pow(10, 6 - fractional_digits)) };
  148. }
  149. // 11. Assert: fractionalDigitCount is in the inclusive interval from 7 to 9.
  150. VERIFY(fractional_digits >= 7 && fractional_digits <= 9);
  151. // 12. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: NANOSECOND, [[Increment]]: 10**(9 - fractionalDigitCount) }.
  152. return { .precision = fractional_digits, .unit = Unit::Nanosecond, .increment = static_cast<u8>(pow(10, 9 - fractional_digits)) };
  153. }
  154. // 13.17 GetTemporalUnitValuedOption ( options, key, unitGroup, default [ , extraValues ] ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalunitvaluedoption
  155. 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)
  156. {
  157. // 1. Let allowedValues be a new empty List.
  158. Vector<UnitValue> allowed_values;
  159. // 2. For each row of Table 21, except the header row, in table order, do
  160. for (auto const& row : temporal_units) {
  161. // a. Let unit be the value in the "Value" column of the row.
  162. auto unit = row.value;
  163. // b. If the "Category" column of the row is DATE and unitGroup is DATE or DATETIME, append unit to allowedValues.
  164. if (row.category == UnitCategory::Date && (unit_group == UnitGroup::Date || unit_group == UnitGroup::DateTime))
  165. allowed_values.append(unit);
  166. // c. Else if the "Category" column of the row is TIME and unitGroup is TIME or DATETIME, append unit to allowedValues.
  167. if (row.category == UnitCategory::Time && (unit_group == UnitGroup::Time || unit_group == UnitGroup::DateTime))
  168. allowed_values.append(unit);
  169. }
  170. // 3. If extraValues is present, then
  171. if (!extra_values.is_empty()) {
  172. // a. Set allowedValues to the list-concatenation of allowedValues and extraValues.
  173. for (auto value : extra_values)
  174. allowed_values.append(value);
  175. }
  176. OptionDefault default_value;
  177. // 4. If default is UNSET, then
  178. if (default_.has<Unset>()) {
  179. // a. Let defaultValue be undefined.
  180. default_value = {};
  181. }
  182. // 5. Else if default is REQUIRED, then
  183. else if (default_.has<Required>()) {
  184. // a. Let defaultValue be REQUIRED.
  185. default_value = Required {};
  186. }
  187. // 6. Else if default is AUTO, then
  188. else if (default_.has<Auto>()) {
  189. // a. Append default to allowedValues.
  190. allowed_values.append(Auto {});
  191. // b. Let defaultValue be "auto".
  192. default_value = "auto"sv;
  193. }
  194. // 7. Else,
  195. else {
  196. auto unit = default_.get<Unit>();
  197. // a. Assert: allowedValues contains default.
  198. // b. Let defaultValue be the value in the "Singular property name" column of Table 21 corresponding to the row
  199. // with default in the "Value" column.
  200. default_value = temporal_units[to_underlying(unit)].singular_property_name;
  201. }
  202. // 8. Let allowedStrings be a new empty List.
  203. Vector<StringView> allowed_strings;
  204. // 9. For each element value of allowedValues, do
  205. for (auto value : allowed_values) {
  206. // a. If value is auto, then
  207. if (value.has<Auto>()) {
  208. // i. Append "auto" to allowedStrings.
  209. allowed_strings.append("auto"sv);
  210. }
  211. // b. Else,
  212. else {
  213. auto unit = value.get<Unit>();
  214. // i. Let singularName be the value in the "Singular property name" column of Table 21 corresponding to the
  215. // row with value in the "Value" column.
  216. auto singular_name = temporal_units[to_underlying(unit)].singular_property_name;
  217. // ii. Append singularName to allowedStrings.
  218. allowed_strings.append(singular_name);
  219. // iii. Let pluralName be the value in the "Plural property name" column of the corresponding row.
  220. auto plural_name = temporal_units[to_underlying(unit)].plural_property_name;
  221. // iv. Append pluralName to allowedStrings.
  222. allowed_strings.append(plural_name);
  223. }
  224. }
  225. // 10. NOTE: For each singular Temporal unit name that is contained within allowedStrings, the corresponding plural
  226. // name is also contained within it.
  227. // 11. Let value be ? GetOption(options, key, STRING, allowedStrings, defaultValue).
  228. auto value = TRY(get_option(vm, options, key, OptionType::String, allowed_strings, default_value));
  229. // 12. If value is undefined, return UNSET.
  230. if (value.is_undefined())
  231. return UnitValue { Unset {} };
  232. auto value_string = value.as_string().utf8_string_view();
  233. // 13. If value is "auto", return AUTO.
  234. if (value_string == "auto"sv)
  235. return UnitValue { Auto {} };
  236. // 14. Return the value in the "Value" column of Table 21 corresponding to the row with value in its "Singular
  237. // property name" or "Plural property name" column.
  238. for (auto const& row : temporal_units) {
  239. if (value_string.is_one_of(row.singular_property_name, row.plural_property_name))
  240. return UnitValue { row.value };
  241. }
  242. VERIFY_NOT_REACHED();
  243. }
  244. // 13.18 GetTemporalRelativeToOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalrelativetooption
  245. ThrowCompletionOr<RelativeTo> get_temporal_relative_to_option(VM& vm, Object const& options)
  246. {
  247. // 1. Let value be ? Get(options, "relativeTo").
  248. auto value = TRY(options.get(vm.names.relativeTo));
  249. // 2. If value is undefined, return the Record { [[PlainRelativeTo]]: undefined, [[ZonedRelativeTo]]: undefined }.
  250. if (value.is_undefined())
  251. return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} };
  252. // FIXME: Implement the remaining steps of this AO when we have implemented PlainRelativeTo and ZonedRelativeTo.
  253. return RelativeTo { .plain_relative_to = {}, .zoned_relative_to = {} };
  254. }
  255. // 13.19 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  256. Unit larger_of_two_temporal_units(Unit unit1, Unit unit2)
  257. {
  258. // 1. For each row of Table 21, except the header row, in table order, do
  259. for (auto const& row : temporal_units) {
  260. // a. Let unit be the value in the "Value" column of the row.
  261. auto unit = row.value;
  262. // b. If u1 is unit, return unit.
  263. if (unit1 == unit)
  264. return unit;
  265. // c. If u2 is unit, return unit.
  266. if (unit2 == unit)
  267. return unit;
  268. }
  269. VERIFY_NOT_REACHED();
  270. }
  271. // 13.20 IsCalendarUnit ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-iscalendarunit
  272. bool is_calendar_unit(Unit unit)
  273. {
  274. // 1. If unit is year, return true.
  275. if (unit == Unit::Year)
  276. return true;
  277. // 2. If unit is month, return true.
  278. if (unit == Unit::Month)
  279. return true;
  280. // 3. If unit is week, return true.
  281. if (unit == Unit::Week)
  282. return true;
  283. // 4. Return false.
  284. return false;
  285. }
  286. // 13.21 TemporalUnitCategory ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-temporalunitcategory
  287. UnitCategory temporal_unit_category(Unit unit)
  288. {
  289. // 1. Return the value from the "Category" column of the row of Table 21 in which unit is in the "Value" column.
  290. return temporal_units[to_underlying(unit)].category;
  291. }
  292. // 13.22 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  293. RoundingIncrement maximum_temporal_duration_rounding_increment(Unit unit)
  294. {
  295. // 1. Return the value from the "Maximum duration rounding increment" column of the row of Table 21 in which unit is
  296. // in the "Value" column.
  297. return temporal_units[to_underlying(unit)].maximum_duration_rounding_increment;
  298. }
  299. // AD-HOC
  300. Crypto::UnsignedBigInteger const& temporal_unit_length_in_nanoseconds(Unit unit)
  301. {
  302. switch (unit) {
  303. case Unit::Day:
  304. return NANOSECONDS_PER_DAY;
  305. case Unit::Hour:
  306. return NANOSECONDS_PER_HOUR;
  307. case Unit::Minute:
  308. return NANOSECONDS_PER_MINUTE;
  309. case Unit::Second:
  310. return NANOSECONDS_PER_SECOND;
  311. case Unit::Millisecond:
  312. return NANOSECONDS_PER_MILLISECOND;
  313. case Unit::Microsecond:
  314. return NANOSECONDS_PER_MICROSECOND;
  315. case Unit::Nanosecond:
  316. return NANOSECONDS_PER_NANOSECOND;
  317. default:
  318. VERIFY_NOT_REACHED();
  319. }
  320. }
  321. // 13.24 FormatFractionalSeconds ( subSecondNanoseconds, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatfractionalseconds
  322. String format_fractional_seconds(u64 sub_second_nanoseconds, Precision precision)
  323. {
  324. String fraction_string;
  325. // 1. If precision is auto, then
  326. if (precision.has<Auto>()) {
  327. // a. If subSecondNanoseconds = 0, return the empty String.
  328. if (sub_second_nanoseconds == 0)
  329. return String {};
  330. // b. Let fractionString be ToZeroPaddedDecimalString(subSecondNanoseconds, 9).
  331. fraction_string = MUST(String::formatted("{:09}", sub_second_nanoseconds));
  332. // c. Set fractionString to the longest prefix of fractionString ending with a code unit other than 0x0030 (DIGIT ZERO).
  333. fraction_string = MUST(fraction_string.trim("0"sv, TrimMode::Right));
  334. }
  335. // 2. Else,
  336. else {
  337. // a. If precision = 0, return the empty String.
  338. if (precision.get<u8>() == 0)
  339. return String {};
  340. // b. Let fractionString be ToZeroPaddedDecimalString(subSecondNanoseconds, 9).
  341. fraction_string = MUST(String::formatted("{:09}", sub_second_nanoseconds));
  342. // c. Set fractionString to the substring of fractionString from 0 to precision.
  343. fraction_string = MUST(fraction_string.substring_from_byte_offset(0, precision.get<u8>()));
  344. }
  345. // 3. Return the string-concatenation of the code unit 0x002E (FULL STOP) and fractionString.
  346. return MUST(String::formatted(".{}", fraction_string));
  347. }
  348. // 13.26 GetUnsignedRoundingMode ( roundingMode, sign ), https://tc39.es/proposal-temporal/#sec-getunsignedroundingmode
  349. UnsignedRoundingMode get_unsigned_rounding_mode(RoundingMode rounding_mode, Sign sign)
  350. {
  351. // 1. Return the specification type in the "Unsigned Rounding Mode" column of Table 22 for the row where the value
  352. // in the "Rounding Mode" column is roundingMode and the value in the "Sign" column is sign.
  353. switch (rounding_mode) {
  354. case RoundingMode::Ceil:
  355. return sign == Sign::Positive ? UnsignedRoundingMode::Infinity : UnsignedRoundingMode::Zero;
  356. case RoundingMode::Floor:
  357. return sign == Sign::Positive ? UnsignedRoundingMode::Zero : UnsignedRoundingMode::Infinity;
  358. case RoundingMode::Expand:
  359. return UnsignedRoundingMode::Infinity;
  360. case RoundingMode::Trunc:
  361. return UnsignedRoundingMode::Zero;
  362. case RoundingMode::HalfCeil:
  363. return sign == Sign::Positive ? UnsignedRoundingMode::HalfInfinity : UnsignedRoundingMode::HalfZero;
  364. case RoundingMode::HalfFloor:
  365. return sign == Sign::Positive ? UnsignedRoundingMode::HalfZero : UnsignedRoundingMode::HalfInfinity;
  366. case RoundingMode::HalfExpand:
  367. return UnsignedRoundingMode::HalfInfinity;
  368. case RoundingMode::HalfTrunc:
  369. return UnsignedRoundingMode::HalfZero;
  370. case RoundingMode::HalfEven:
  371. return UnsignedRoundingMode::HalfEven;
  372. }
  373. VERIFY_NOT_REACHED();
  374. }
  375. // 13.27 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-applyunsignedroundingmode
  376. double apply_unsigned_rounding_mode(double x, double r1, double r2, UnsignedRoundingMode unsigned_rounding_mode)
  377. {
  378. // 1. If x = r1, return r1.
  379. if (x == r1)
  380. return r1;
  381. // 2. Assert: r1 < x < r2.
  382. VERIFY(r1 < x && x < r2);
  383. // 3. Assert: unsignedRoundingMode is not undefined.
  384. // 4. If unsignedRoundingMode is ZERO, return r1.
  385. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  386. return r1;
  387. // 5. If unsignedRoundingMode is INFINITY, return r2.
  388. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  389. return r2;
  390. // 6. Let d1 be x – r1.
  391. auto d1 = x - r1;
  392. // 7. Let d2 be r2 – x.
  393. auto d2 = r2 - x;
  394. // 8. If d1 < d2, return r1.
  395. if (d1 < d2)
  396. return r1;
  397. // 9. If d2 < d1, return r2.
  398. if (d2 < d1)
  399. return r2;
  400. // 10. Assert: d1 is equal to d2.
  401. VERIFY(d1 == d2);
  402. // 11. If unsignedRoundingMode is HALF-ZERO, return r1.
  403. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  404. return r1;
  405. // 12. If unsignedRoundingMode is HALF-INFINITY, return r2.
  406. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  407. return r2;
  408. // 13. Assert: unsignedRoundingMode is HALF-EVEN.
  409. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  410. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  411. auto cardinality = modulo((r1 / (r2 - r1)), 2);
  412. // 15. If cardinality = 0, return r1.
  413. if (cardinality == 0)
  414. return r1;
  415. // 16. Return r2.
  416. return r2;
  417. }
  418. // 13.27 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-applyunsignedroundingmode
  419. 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)
  420. {
  421. // 1. If x = r1, return r1.
  422. if (x.quotient == r1 && x.remainder.unsigned_value().is_zero())
  423. return r1;
  424. // 2. Assert: r1 < x < r2.
  425. // NOTE: Skipped for the sake of performance.
  426. // 3. Assert: unsignedRoundingMode is not undefined.
  427. // 4. If unsignedRoundingMode is ZERO, return r1.
  428. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  429. return r1;
  430. // 5. If unsignedRoundingMode is INFINITY, return r2.
  431. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  432. return r2;
  433. // 6. Let d1 be x – r1.
  434. auto d1 = x.remainder.unsigned_value();
  435. // 7. Let d2 be r2 – x.
  436. auto d2 = increment.minus(x.remainder.unsigned_value());
  437. // 8. If d1 < d2, return r1.
  438. if (d1 < d2)
  439. return r1;
  440. // 9. If d2 < d1, return r2.
  441. if (d2 < d1)
  442. return r2;
  443. // 10. Assert: d1 is equal to d2.
  444. // NOTE: Skipped for the sake of performance.
  445. // 11. If unsignedRoundingMode is HALF-ZERO, return r1.
  446. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  447. return r1;
  448. // 12. If unsignedRoundingMode is HALF-INFINITY, return r2.
  449. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  450. return r2;
  451. // 13. Assert: unsignedRoundingMode is HALF-EVEN.
  452. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  453. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  454. auto cardinality = modulo(r1.divided_by(r2.minus(r1)).quotient, "2"_bigint);
  455. // 15. If cardinality = 0, return r1.
  456. if (cardinality.unsigned_value().is_zero())
  457. return r1;
  458. // 16. Return r2.
  459. return r2;
  460. }
  461. // 13.28 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  462. double round_number_to_increment(double x, u64 increment, RoundingMode rounding_mode)
  463. {
  464. // 1. Let quotient be x / increment.
  465. auto quotient = x / static_cast<double>(increment);
  466. Sign is_negative;
  467. // 2. If quotient < 0, then
  468. if (quotient < 0) {
  469. // a. Let isNegative be NEGATIVE.
  470. is_negative = Sign::Negative;
  471. // b. Set quotient to -quotient.
  472. quotient = -quotient;
  473. }
  474. // 3. Else,
  475. else {
  476. // a. Let isNegative be POSITIVE.
  477. is_negative = Sign::Positive;
  478. }
  479. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  480. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  481. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  482. auto r1 = floor(quotient);
  483. // 6. Let r2 be the smallest integer such that r2 > quotient.
  484. auto r2 = ceil(quotient);
  485. if (quotient == r2)
  486. r2++;
  487. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  488. auto rounded = apply_unsigned_rounding_mode(quotient, r1, r2, unsigned_rounding_mode);
  489. // 8. If isNegative is NEGATIVE, set rounded to -rounded.
  490. if (is_negative == Sign::Negative)
  491. rounded = -rounded;
  492. // 9. Return rounded × increment.
  493. return rounded * static_cast<double>(increment);
  494. }
  495. // 13.28 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  496. Crypto::SignedBigInteger round_number_to_increment(Crypto::SignedBigInteger const& x, Crypto::UnsignedBigInteger const& increment, RoundingMode rounding_mode)
  497. {
  498. // OPTIMIZATION: If the increment is 1 the number is always rounded.
  499. if (increment == 1)
  500. return x;
  501. // 1. Let quotient be x / increment.
  502. auto division_result = x.divided_by(increment);
  503. // OPTIMIZATION: If there's no remainder the number is already rounded.
  504. if (division_result.remainder.unsigned_value().is_zero())
  505. return x;
  506. Sign is_negative;
  507. // 2. If quotient < 0, then
  508. if (division_result.quotient.is_negative()) {
  509. // a. Let isNegative be NEGATIVE.
  510. is_negative = Sign::Negative;
  511. // b. Set quotient to -quotient.
  512. division_result.quotient.negate();
  513. division_result.remainder.negate();
  514. }
  515. // 3. Else,
  516. else {
  517. // a. Let isNegative be POSITIVE.
  518. is_negative = Sign::Positive;
  519. }
  520. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  521. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  522. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  523. auto r1 = division_result.quotient;
  524. // 6. Let r2 be the smallest integer such that r2 > quotient.
  525. auto r2 = division_result.quotient.plus(1_bigint);
  526. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  527. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment);
  528. // 8. If isNegative is NEGATIVE, set rounded to -rounded.
  529. if (is_negative == Sign::Negative)
  530. rounded.negate();
  531. // 9. Return rounded × increment.
  532. return rounded.multiplied_by(increment);
  533. }
  534. // 13.35 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  535. ThrowCompletionOr<GC::Ref<Duration>> parse_temporal_duration_string(VM& vm, StringView iso_string)
  536. {
  537. // 1. Let duration be ParseText(StringToCodePoints(isoString), TemporalDurationString).
  538. auto parse_result = parse_iso8601(Production::TemporalDurationString, iso_string);
  539. // 2. If duration is a List of errors, throw a RangeError exception.
  540. if (!parse_result.has_value())
  541. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationString, iso_string);
  542. // 3. Let sign be the source text matched by the ASCIISign Parse Node contained within duration, or an empty sequence
  543. // of code points if not present.
  544. auto sign = parse_result->sign;
  545. // 4. If duration contains a DurationYearsPart Parse Node, then
  546. // a. Let yearsNode be that DurationYearsPart Parse Node contained within duration.
  547. // b. Let years be the source text matched by the DecimalDigits Parse Node contained within yearsNode.
  548. // 5. Else,
  549. // a. Let years be an empty sequence of code points.
  550. auto years = parse_result->duration_years.value_or({});
  551. // 6. If duration contains a DurationMonthsPart Parse Node, then
  552. // a. Let monthsNode be the DurationMonthsPart Parse Node contained within duration.
  553. // b. Let months be the source text matched by the DecimalDigits Parse Node contained within monthsNode.
  554. // 7. Else,
  555. // a. Let months be an empty sequence of code points.
  556. auto months = parse_result->duration_months.value_or({});
  557. // 8. If duration contains a DurationWeeksPart Parse Node, then
  558. // a. Let weeksNode be the DurationWeeksPart Parse Node contained within duration.
  559. // b. Let weeks be the source text matched by the DecimalDigits Parse Node contained within weeksNode.
  560. // 9. Else,
  561. // a. Let weeks be an empty sequence of code points.
  562. auto weeks = parse_result->duration_weeks.value_or({});
  563. // 10. If duration contains a DurationDaysPart Parse Node, then
  564. // a. Let daysNode be the DurationDaysPart Parse Node contained within duration.
  565. // b. Let days be the source text matched by the DecimalDigits Parse Node contained within daysNode.
  566. // 11. Else,
  567. // a. Let days be an empty sequence of code points.
  568. auto days = parse_result->duration_days.value_or({});
  569. // 12. If duration contains a DurationHoursPart Parse Node, then
  570. // a. Let hoursNode be the DurationHoursPart Parse Node contained within duration.
  571. // b. Let hours be the source text matched by the DecimalDigits Parse Node contained within hoursNode.
  572. // c. Let fHours be the source text matched by the TemporalDecimalFraction Parse Node contained within
  573. // hoursNode, or an empty sequence of code points if not present.
  574. // 13. Else,
  575. // a. Let hours be an empty sequence of code points.
  576. // b. Let fHours be an empty sequence of code points.
  577. auto hours = parse_result->duration_hours.value_or({});
  578. auto fractional_hours = parse_result->duration_hours_fraction.value_or({});
  579. // 14. If duration contains a DurationMinutesPart Parse Node, then
  580. // a. Let minutesNode be the DurationMinutesPart Parse Node contained within duration.
  581. // b. Let minutes be the source text matched by the DecimalDigits Parse Node contained within minutesNode.
  582. // c. Let fMinutes be the source text matched by the TemporalDecimalFraction Parse Node contained within
  583. // minutesNode, or an empty sequence of code points if not present.
  584. // 15. Else,
  585. // a. Let minutes be an empty sequence of code points.
  586. // b. Let fMinutes be an empty sequence of code points.
  587. auto minutes = parse_result->duration_minutes.value_or({});
  588. auto fractional_minutes = parse_result->duration_minutes_fraction.value_or({});
  589. // 16. If duration contains a DurationSecondsPart Parse Node, then
  590. // a. Let secondsNode be the DurationSecondsPart Parse Node contained within duration.
  591. // b. Let seconds be the source text matched by the DecimalDigits Parse Node contained within secondsNode.
  592. // c. Let fSeconds be the source text matched by the TemporalDecimalFraction Parse Node contained within
  593. // secondsNode, or an empty sequence of code points if not present.
  594. // 17. Else,
  595. // a. Let seconds be an empty sequence of code points.
  596. // b. Let fSeconds be an empty sequence of code points.
  597. auto seconds = parse_result->duration_seconds.value_or({});
  598. auto fractional_seconds = parse_result->duration_seconds_fraction.value_or({});
  599. // 18. Let yearsMV be ? ToIntegerWithTruncation(CodePointsToString(years)).
  600. auto years_value = TRY(to_integer_with_truncation(vm, years, ErrorType::TemporalInvalidDurationString, iso_string));
  601. // 19. Let monthsMV be ? ToIntegerWithTruncation(CodePointsToString(months)).
  602. auto months_value = TRY(to_integer_with_truncation(vm, months, ErrorType::TemporalInvalidDurationString, iso_string));
  603. // 20. Let weeksMV be ? ToIntegerWithTruncation(CodePointsToString(weeks)).
  604. auto weeks_value = TRY(to_integer_with_truncation(vm, weeks, ErrorType::TemporalInvalidDurationString, iso_string));
  605. // 21. Let daysMV be ? ToIntegerWithTruncation(CodePointsToString(days)).
  606. auto days_value = TRY(to_integer_with_truncation(vm, days, ErrorType::TemporalInvalidDurationString, iso_string));
  607. // 22. Let hoursMV be ? ToIntegerWithTruncation(CodePointsToString(hours)).
  608. auto hours_value = TRY(to_integer_with_truncation(vm, hours, ErrorType::TemporalInvalidDurationString, iso_string));
  609. Crypto::BigFraction minutes_value;
  610. Crypto::BigFraction seconds_value;
  611. Crypto::BigFraction milliseconds_value;
  612. auto remainder_one = [](Crypto::BigFraction const& value) {
  613. // FIXME: We should add a generic remainder() method to BigFraction, or a method equivalent to modf(). But for
  614. // now, since we know we are only dividing by powers of 10, we can implement a very situationally specific
  615. // method to extract the fractional part of the BigFraction.
  616. auto res = value.numerator().divided_by(value.denominator());
  617. return Crypto::BigFraction { move(res.remainder), value.denominator() };
  618. };
  619. // 23. If fHours is not empty, then
  620. if (!fractional_hours.is_empty()) {
  621. // a. Assert: minutes, fMinutes, seconds, and fSeconds are empty.
  622. VERIFY(minutes.is_empty());
  623. VERIFY(fractional_minutes.is_empty());
  624. VERIFY(seconds.is_empty());
  625. VERIFY(fractional_seconds.is_empty());
  626. // b. Let fHoursDigits be the substring of CodePointsToString(fHours) from 1.
  627. auto fractional_hours_digits = fractional_hours.substring_view(1);
  628. // c. Let fHoursScale be the length of fHoursDigits.
  629. auto fractional_hours_scale = fractional_hours_digits.length();
  630. // d. Let minutesMV be ? ToIntegerWithTruncation(fHoursDigits) / 10**fHoursScale × 60.
  631. auto minutes_integer = TRY(to_integer_with_truncation(vm, fractional_hours_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  632. minutes_value = Crypto::BigFraction { minutes_integer } / Crypto::BigFraction { pow(10.0, fractional_hours_scale) } * Crypto::BigFraction { 60.0 };
  633. }
  634. // 24. Else,
  635. else {
  636. // a. Let minutesMV be ? ToIntegerWithTruncation(CodePointsToString(minutes)).
  637. auto minutes_integer = TRY(to_integer_with_truncation(vm, minutes, ErrorType::TemporalInvalidDurationString, iso_string));
  638. minutes_value = Crypto::BigFraction { minutes_integer };
  639. }
  640. // 25. If fMinutes is not empty, then
  641. if (!fractional_minutes.is_empty()) {
  642. // a. Assert: seconds and fSeconds are empty.
  643. VERIFY(seconds.is_empty());
  644. VERIFY(fractional_seconds.is_empty());
  645. // b. Let fMinutesDigits be the substring of CodePointsToString(fMinutes) from 1.
  646. auto fractional_minutes_digits = fractional_minutes.substring_view(1);
  647. // c. Let fMinutesScale be the length of fMinutesDigits.
  648. auto fractional_minutes_scale = fractional_minutes_digits.length();
  649. // d. Let secondsMV be ? ToIntegerWithTruncation(fMinutesDigits) / 10**fMinutesScale × 60.
  650. auto seconds_integer = TRY(to_integer_with_truncation(vm, fractional_minutes_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  651. seconds_value = Crypto::BigFraction { seconds_integer } / Crypto::BigFraction { pow(10.0, fractional_minutes_scale) } * Crypto::BigFraction { 60.0 };
  652. }
  653. // 26. Else if seconds is not empty, then
  654. else if (!seconds.is_empty()) {
  655. // a. Let secondsMV be ? ToIntegerWithTruncation(CodePointsToString(seconds)).
  656. auto seconds_integer = TRY(to_integer_with_truncation(vm, seconds, ErrorType::TemporalInvalidDurationString, iso_string));
  657. seconds_value = Crypto::BigFraction { seconds_integer };
  658. }
  659. // 27. Else,
  660. else {
  661. // a. Let secondsMV be remainder(minutesMV, 1) × 60.
  662. seconds_value = remainder_one(minutes_value) * Crypto::BigFraction { 60.0 };
  663. }
  664. // 28. If fSeconds is not empty, then
  665. if (!fractional_seconds.is_empty()) {
  666. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  667. auto fractional_seconds_digits = fractional_seconds.substring_view(1);
  668. // b. Let fSecondsScale be the length of fSecondsDigits.
  669. auto fractional_seconds_scale = fractional_seconds_digits.length();
  670. // c. Let millisecondsMV be ? ToIntegerWithTruncation(fSecondsDigits) / 10**fSecondsScale × 1000.
  671. auto milliseconds_integer = TRY(to_integer_with_truncation(vm, fractional_seconds_digits, ErrorType::TemporalInvalidDurationString, iso_string));
  672. milliseconds_value = Crypto::BigFraction { milliseconds_integer } / Crypto::BigFraction { pow(10.0, fractional_seconds_scale) } * Crypto::BigFraction { 1000.0 };
  673. }
  674. // 29. Else,
  675. else {
  676. // a. Let millisecondsMV be remainder(secondsMV, 1) × 1000.
  677. milliseconds_value = remainder_one(seconds_value) * Crypto::BigFraction { 1000.0 };
  678. }
  679. // 30. Let microsecondsMV be remainder(millisecondsMV, 1) × 1000.
  680. auto microseconds_value = remainder_one(milliseconds_value) * Crypto::BigFraction { 1000.0 };
  681. // 31. Let nanosecondsMV be remainder(microsecondsMV, 1) × 1000.
  682. auto nanoseconds_value = remainder_one(microseconds_value) * Crypto::BigFraction { 1000.0 };
  683. // 32. If sign contains the code point U+002D (HYPHEN-MINUS), then
  684. // a. Let factor be -1.
  685. // 33. Else,
  686. // a. Let factor be 1.
  687. i8 factor = sign == '-' ? -1 : 1;
  688. // 34. Set yearsMV to yearsMV × factor.
  689. years_value *= factor;
  690. // 35. Set monthsMV to monthsMV × factor.
  691. months_value *= factor;
  692. // 36. Set weeksMV to weeksMV × factor.
  693. weeks_value *= factor;
  694. // 37. Set daysMV to daysMV × factor.
  695. days_value *= factor;
  696. // 38. Set hoursMV to hoursMV × factor.
  697. hours_value *= factor;
  698. // 39. Set minutesMV to floor(minutesMV) × factor.
  699. auto factored_minutes_value = floor(minutes_value.to_double()) * factor;
  700. // 40. Set secondsMV to floor(secondsMV) × factor.
  701. auto factored_seconds_value = floor(seconds_value.to_double()) * factor;
  702. // 41. Set millisecondsMV to floor(millisecondsMV) × factor.
  703. auto factored_milliseconds_value = floor(milliseconds_value.to_double()) * factor;
  704. // 42. Set microsecondsMV to floor(microsecondsMV) × factor.
  705. auto factored_microseconds_value = floor(microseconds_value.to_double()) * factor;
  706. // 43. Set nanosecondsMV to floor(nanosecondsMV) × factor.
  707. auto factored_nanoseconds_value = floor(nanoseconds_value.to_double()) * factor;
  708. // 44. Return ? CreateTemporalDuration(yearsMV, monthsMV, weeksMV, daysMV, hoursMV, minutesMV, secondsMV, millisecondsMV, microsecondsMV, nanosecondsMV).
  709. 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));
  710. }
  711. // 14.4.1.1 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  712. ThrowCompletionOr<GC::Ref<Object>> get_options_object(VM& vm, Value options)
  713. {
  714. auto& realm = *vm.current_realm();
  715. // 1. If options is undefined, then
  716. if (options.is_undefined()) {
  717. // a. Return OrdinaryObjectCreate(null).
  718. return Object::create(realm, nullptr);
  719. }
  720. // 2. If options is an Object, then
  721. if (options.is_object()) {
  722. // a. Return options.
  723. return options.as_object();
  724. }
  725. // 3. Throw a TypeError exception.
  726. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, "Options");
  727. }
  728. // 14.4.1.2 GetOption ( options, property, type, values, default ), https://tc39.es/proposal-temporal/#sec-getoption
  729. ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey const& property, OptionType type, ReadonlySpan<StringView> values, OptionDefault const& default_)
  730. {
  731. VERIFY(property.is_string());
  732. // 1. Let value be ? Get(options, property).
  733. auto value = TRY(options.get(property));
  734. // 2. If value is undefined, then
  735. if (value.is_undefined()) {
  736. // a. If default is REQUIRED, throw a RangeError exception.
  737. if (default_.has<Required>())
  738. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, "undefined"sv, property.as_string());
  739. // b. Return default.
  740. return default_.visit(
  741. [](Required) -> Value { VERIFY_NOT_REACHED(); },
  742. [](Empty) -> Value { return js_undefined(); },
  743. [](bool default_) -> Value { return Value { default_ }; },
  744. [](double default_) -> Value { return Value { default_ }; },
  745. [&](StringView default_) -> Value { return PrimitiveString::create(vm, default_); });
  746. }
  747. // 3. If type is BOOLEAN, then
  748. if (type == OptionType::Boolean) {
  749. // a. Set value to ToBoolean(value).
  750. value = Value { value.to_boolean() };
  751. }
  752. // 4. Else,
  753. else {
  754. // a. Assert: type is STRING.
  755. VERIFY(type == OptionType::String);
  756. // b. Set value to ? ToString(value).
  757. value = TRY(value.to_primitive_string(vm));
  758. }
  759. // 5. If values is not EMPTY and values does not contain value, throw a RangeError exception.
  760. if (!values.is_empty()) {
  761. // NOTE: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  762. VERIFY(value.is_string());
  763. if (auto value_string = value.as_string().utf8_string(); !values.contains_slow(value_string))
  764. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value_string, property.as_string());
  765. }
  766. // 6. Return value.
  767. return value;
  768. }
  769. // 14.4.1.3 GetRoundingModeOption ( options, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-getroundingmodeoption
  770. ThrowCompletionOr<RoundingMode> get_rounding_mode_option(VM& vm, Object const& options, RoundingMode fallback)
  771. {
  772. // 1. Let allowedStrings be the List of Strings from the "String Identifier" column of Table 26.
  773. 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 });
  774. // 2. Let stringFallback be the value from the "String Identifier" column of the row with fallback in its "Rounding Mode" column.
  775. auto string_fallback = allowed_strings[to_underlying(fallback)];
  776. // 3. Let stringValue be ? GetOption(options, "roundingMode", STRING, allowedStrings, stringFallback).
  777. auto string_value = TRY(get_option(vm, options, vm.names.roundingMode, OptionType::String, allowed_strings, string_fallback));
  778. // 4. Return the value from the "Rounding Mode" column of the row with stringValue in its "String Identifier" column.
  779. return static_cast<RoundingMode>(allowed_strings.first_index_of(string_value.as_string().utf8_string_view()).value());
  780. }
  781. // 14.4.1.4 GetRoundingIncrementOption ( options ), https://tc39.es/proposal-temporal/#sec-temporal-getroundingincrementoption
  782. ThrowCompletionOr<u64> get_rounding_increment_option(VM& vm, Object const& options)
  783. {
  784. // 1. Let value be ? Get(options, "roundingIncrement").
  785. auto value = TRY(options.get(vm.names.roundingIncrement));
  786. // 2. If value is undefined, return 1𝔽.
  787. if (value.is_undefined())
  788. return 1;
  789. // 3. Let integerIncrement be ? ToIntegerWithTruncation(value).
  790. auto integer_increment = TRY(to_integer_with_truncation(vm, value, ErrorType::OptionIsNotValidValue, value, "roundingIncrement"sv));
  791. // 4. If integerIncrement < 1 or integerIncrement > 10**9, throw a RangeError exception.
  792. if (integer_increment < 1 || integer_increment > 1'000'000'000u)
  793. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value, "roundingIncrement");
  794. // 5. Return integerIncrement.
  795. return static_cast<u64>(integer_increment);
  796. }
  797. }