AbstractOperations.cpp 73 KB

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