AbstractOperations.cpp 67 KB

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