AbstractOperations.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /*
  2. * Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/DateTimeLexer.h>
  10. #include <AK/TypeCasts.h>
  11. #include <AK/Variant.h>
  12. #include <LibJS/Runtime/AbstractOperations.h>
  13. #include <LibJS/Runtime/Completion.h>
  14. #include <LibJS/Runtime/IteratorOperations.h>
  15. #include <LibJS/Runtime/PropertyKey.h>
  16. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  17. #include <LibJS/Runtime/Temporal/Calendar.h>
  18. #include <LibJS/Runtime/Temporal/Duration.h>
  19. #include <LibJS/Runtime/Temporal/ISO8601.h>
  20. #include <LibJS/Runtime/Temporal/PlainDate.h>
  21. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  22. #include <LibJS/Runtime/Temporal/PlainTime.h>
  23. #include <LibJS/Runtime/Temporal/TimeZone.h>
  24. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  25. #include <stdlib.h>
  26. namespace JS::Temporal {
  27. static Optional<OptionType> to_option_type(Value value)
  28. {
  29. if (value.is_boolean())
  30. return OptionType::Boolean;
  31. if (value.is_string())
  32. return OptionType::String;
  33. if (value.is_number())
  34. return OptionType::Number;
  35. return {};
  36. }
  37. // 13.1 IterableToListOfType ( items, elementTypes ), https://tc39.es/proposal-temporal/#sec-iterabletolistoftype
  38. ThrowCompletionOr<MarkedVector<Value>> iterable_to_list_of_type(VM& vm, Value items, Vector<OptionType> const& element_types)
  39. {
  40. // 1. Let iteratorRecord be ? GetIterator(items, sync).
  41. auto iterator_record = TRY(get_iterator(vm, items, IteratorHint::Sync));
  42. // 2. Let values be a new empty List.
  43. MarkedVector<Value> values(vm.heap());
  44. // 3. Let next be true.
  45. auto next = true;
  46. // 4. Repeat, while next is not false,
  47. while (next) {
  48. // a. Set next to ? IteratorStep(iteratorRecord).
  49. auto* iterator_result = TRY(iterator_step(vm, iterator_record));
  50. next = iterator_result;
  51. // b. If next is not false, then
  52. if (next) {
  53. // i. Let nextValue be ? IteratorValue(next).
  54. auto next_value = TRY(iterator_value(vm, *iterator_result));
  55. // ii. If Type(nextValue) is not an element of elementTypes, then
  56. if (auto type = to_option_type(next_value); !type.has_value() || !element_types.contains_slow(*type)) {
  57. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  58. auto completion = vm.throw_completion<TypeError>(ErrorType::IterableToListOfTypeInvalidValue, next_value.to_string_without_side_effects());
  59. // 2. Return ? IteratorClose(iteratorRecord, completion).
  60. return iterator_close(vm, iterator_record, move(completion));
  61. }
  62. // iii. Append nextValue to the end of the List values.
  63. values.append(next_value);
  64. }
  65. }
  66. // 5. Return values.
  67. return { move(values) };
  68. }
  69. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  70. ThrowCompletionOr<Object*> get_options_object(VM& vm, Value options)
  71. {
  72. auto& realm = *vm.current_realm();
  73. // 1. If options is undefined, then
  74. if (options.is_undefined()) {
  75. // a. Return OrdinaryObjectCreate(null).
  76. return Object::create(realm, nullptr);
  77. }
  78. // 2. If Type(options) is Object, then
  79. if (options.is_object()) {
  80. // a. Return options.
  81. return &options.as_object();
  82. }
  83. // 3. Throw a TypeError exception.
  84. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, "Options");
  85. }
  86. // 13.3 GetOption ( options, property, type, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  87. ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey const& property, OptionType type, Span<StringView const> values, OptionDefault const& default_)
  88. {
  89. VERIFY(property.is_string());
  90. // 1. Let value be ? Get(options, property).
  91. auto value = TRY(options.get(property));
  92. // 2. If value is undefined, then
  93. if (value.is_undefined()) {
  94. // a. If default is required, throw a RangeError exception.
  95. if (default_.has<GetOptionRequired>())
  96. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, "undefined"sv, property.as_string());
  97. // b. Return default.
  98. return default_.visit(
  99. [](GetOptionRequired) -> Value { VERIFY_NOT_REACHED(); },
  100. [](Empty) { return js_undefined(); },
  101. [](bool b) { return Value(b); },
  102. [](double d) { return Value(d); },
  103. [&vm](StringView s) { return Value(js_string(vm, s)); });
  104. }
  105. // 5. If type is "boolean", then
  106. if (type == OptionType::Boolean) {
  107. // a. Set value to ToBoolean(value).
  108. value = Value(value.to_boolean());
  109. }
  110. // 6. Else if type is "number", then
  111. else if (type == OptionType::Number) {
  112. // a. Set value to ? ToNumber(value).
  113. value = TRY(value.to_number(vm));
  114. // b. If value is NaN, throw a RangeError exception.
  115. if (value.is_nan())
  116. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property.as_string());
  117. }
  118. // 7. Else,
  119. else {
  120. // a. Assert: type is "string".
  121. VERIFY(type == OptionType::String);
  122. // b. Set value to ? ToString(value).
  123. value = TRY(value.to_primitive_string(vm));
  124. }
  125. // 8. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
  126. if (!values.is_empty()) {
  127. // NOTE: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  128. VERIFY(value.is_string());
  129. if (!values.contains_slow(value.as_string().string()))
  130. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  131. }
  132. // 9. Return value.
  133. return value;
  134. }
  135. // 13.4 ToTemporalOverflow ( options ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  136. ThrowCompletionOr<String> to_temporal_overflow(VM& vm, Object const* options)
  137. {
  138. // 1. If options is undefined, return "constrain".
  139. if (options == nullptr)
  140. return "constrain"sv;
  141. // 2. Return ? GetOption(options, "overflow", "string", « "constrain", "reject" », "constrain").
  142. auto option = TRY(get_option(vm, *options, vm.names.overflow, OptionType::String, { "constrain"sv, "reject"sv }, "constrain"sv));
  143. VERIFY(option.is_string());
  144. return option.as_string().string();
  145. }
  146. // 13.5 ToTemporalDisambiguation ( options ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldisambiguation
  147. ThrowCompletionOr<String> to_temporal_disambiguation(VM& vm, Object const* options)
  148. {
  149. // 1. If options is undefined, return "compatible".
  150. if (options == nullptr)
  151. return "compatible"sv;
  152. // 2. Return ? GetOption(options, "disambiguation", "string", « "compatible", "earlier", "later", "reject" », "compatible").
  153. auto option = TRY(get_option(vm, *options, vm.names.disambiguation, OptionType::String, { "compatible"sv, "earlier"sv, "later"sv, "reject"sv }, "compatible"sv));
  154. VERIFY(option.is_string());
  155. return option.as_string().string();
  156. }
  157. // 13.6 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  158. ThrowCompletionOr<String> to_temporal_rounding_mode(VM& vm, Object const& normalized_options, String const& fallback)
  159. {
  160. // 1. Return ? GetOption(normalizedOptions, "roundingMode", "string", « "ceil", "floor", "trunc", "halfExpand" », fallback).
  161. auto option = TRY(get_option(vm, normalized_options, vm.names.roundingMode, OptionType::String, { "ceil"sv, "floor"sv, "trunc"sv, "halfExpand"sv }, fallback.view()));
  162. VERIFY(option.is_string());
  163. return option.as_string().string();
  164. }
  165. // 13.7 NegateTemporalRoundingMode ( roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-negatetemporalroundingmode
  166. StringView negate_temporal_rounding_mode(String const& rounding_mode)
  167. {
  168. // 1. If roundingMode is "ceil", return "floor".
  169. if (rounding_mode == "ceil"sv)
  170. return "floor"sv;
  171. // 2. If roundingMode is "floor", return "ceil".
  172. if (rounding_mode == "floor"sv)
  173. return "ceil"sv;
  174. // 3. Return roundingMode.
  175. return rounding_mode;
  176. }
  177. // 13.8 ToTemporalOffset ( options, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloffset
  178. ThrowCompletionOr<String> to_temporal_offset(VM& vm, Object const* options, String const& fallback)
  179. {
  180. // 1. If options is undefined, return fallback.
  181. if (options == nullptr)
  182. return fallback;
  183. // 2. Return ? GetOption(options, "offset", "string", « "prefer", "use", "ignore", "reject" », fallback).
  184. auto option = TRY(get_option(vm, *options, vm.names.offset, OptionType::String, { "prefer"sv, "use"sv, "ignore"sv, "reject"sv }, fallback.view()));
  185. VERIFY(option.is_string());
  186. return option.as_string().string();
  187. }
  188. // 13.9 ToShowCalendarOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowcalendaroption
  189. ThrowCompletionOr<String> to_show_calendar_option(VM& vm, Object const& normalized_options)
  190. {
  191. // 1. Return ? GetOption(normalizedOptions, "calendarName", "string", « "auto", "always", "never" », "auto").
  192. auto option = TRY(get_option(vm, normalized_options, vm.names.calendarName, OptionType::String, { "auto"sv, "always"sv, "never"sv }, "auto"sv));
  193. VERIFY(option.is_string());
  194. return option.as_string().string();
  195. }
  196. // 13.10 ToShowTimeZoneNameOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowtimezonenameoption
  197. ThrowCompletionOr<String> to_show_time_zone_name_option(VM& vm, Object const& normalized_options)
  198. {
  199. // 1. Return ? GetOption(normalizedOptions, "timeZoneName", "string, « "auto", "never" », "auto").
  200. auto option = TRY(get_option(vm, normalized_options, vm.names.timeZoneName, OptionType::String, { "auto"sv, "never"sv }, "auto"sv));
  201. VERIFY(option.is_string());
  202. return option.as_string().string();
  203. }
  204. // 13.11 ToShowOffsetOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowoffsetoption
  205. ThrowCompletionOr<String> to_show_offset_option(VM& vm, Object const& normalized_options)
  206. {
  207. // 1. Return ? GetOption(normalizedOptions, "offset", "string", « "auto", "never" », "auto").
  208. auto option = TRY(get_option(vm, normalized_options, vm.names.offset, OptionType::String, { "auto"sv, "never"sv }, "auto"sv));
  209. VERIFY(option.is_string());
  210. return option.as_string().string();
  211. }
  212. // 13.12 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  213. ThrowCompletionOr<u64> to_temporal_rounding_increment(VM& vm, Object const& normalized_options, Optional<double> dividend, bool inclusive)
  214. {
  215. double maximum;
  216. // 1. If dividend is undefined, then
  217. if (!dividend.has_value()) {
  218. // a. Let maximum be +∞𝔽.
  219. maximum = INFINITY;
  220. }
  221. // 2. Else if inclusive is true, then
  222. else if (inclusive) {
  223. // a. Let maximum be 𝔽(dividend).
  224. maximum = *dividend;
  225. }
  226. // 3. Else if dividend is more than 1, then
  227. else if (*dividend > 1) {
  228. // a. Let maximum be 𝔽(dividend - 1).
  229. maximum = *dividend - 1;
  230. }
  231. // 4. Else,
  232. else {
  233. // a. Let maximum be 1𝔽.
  234. maximum = 1;
  235. }
  236. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", "number", undefined, 1𝔽).
  237. auto increment_value = TRY(get_option(vm, normalized_options, vm.names.roundingIncrement, OptionType::Number, {}, 1.0));
  238. VERIFY(increment_value.is_number());
  239. auto increment = increment_value.as_double();
  240. // 6. If increment < 1𝔽 or increment > maximum, throw a RangeError exception.
  241. if (increment < 1 || increment > maximum)
  242. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  243. // 7. Set increment to floor(ℝ(increment)).
  244. auto floored_increment = static_cast<u64>(increment);
  245. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  246. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0)
  247. // a. Throw a RangeError exception.
  248. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  249. // 9. Return increment.
  250. return floored_increment;
  251. }
  252. // 13.13 ToTemporalDateTimeRoundingIncrement ( normalizedOptions, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetimeroundingincrement
  253. ThrowCompletionOr<u64> to_temporal_date_time_rounding_increment(VM& vm, Object const& normalized_options, StringView smallest_unit)
  254. {
  255. u16 maximum;
  256. // 1. If smallestUnit is "day", then
  257. if (smallest_unit == "day"sv) {
  258. // a. Let maximum be 1.
  259. maximum = 1;
  260. }
  261. // 2. Else,
  262. else {
  263. // a. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  264. // b. Assert: maximum is not undefined.
  265. maximum = *maximum_temporal_duration_rounding_increment(smallest_unit);
  266. }
  267. // 3. Return ? ToTemporalRoundingIncrement(normalizedOptions, maximum, false).
  268. return to_temporal_rounding_increment(vm, normalized_options, maximum, false);
  269. }
  270. // 13.14 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
  271. ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(VM& vm, Object const& normalized_options)
  272. {
  273. // 1. Let smallestUnit be ? GetTemporalUnit(normalizedOptions, "smallestUnit", time, undefined).
  274. auto smallest_unit = TRY(get_temporal_unit(vm, normalized_options, vm.names.smallestUnit, UnitGroup::Time, Optional<StringView> {}));
  275. // 2. If smallestUnit is "hour", throw a RangeError exception.
  276. if (smallest_unit == "hour"sv)
  277. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *smallest_unit, "smallestUnit"sv);
  278. // 3. If smallestUnit is "minute", then
  279. if (smallest_unit == "minute"sv) {
  280. // a. Return the Record { [[Precision]]: "minute", [[Unit]]: "minute", [[Increment]]: 1 }.
  281. return SecondsStringPrecision { .precision = "minute"sv, .unit = "minute"sv, .increment = 1 };
  282. }
  283. // 4. If smallestUnit is "second", then
  284. if (smallest_unit == "second"sv) {
  285. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  286. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  287. }
  288. // 5. If smallestUnit is "millisecond", then
  289. if (smallest_unit == "millisecond"sv) {
  290. // a. Return the Record { [[Precision]]: 3, [[Unit]]: "millisecond", [[Increment]]: 1 }.
  291. return SecondsStringPrecision { .precision = 3, .unit = "millisecond"sv, .increment = 1 };
  292. }
  293. // 6. If smallestUnit is "microsecond", then
  294. if (smallest_unit == "microsecond"sv) {
  295. // a. Return the Record { [[Precision]]: 6, [[Unit]]: "microsecond", [[Increment]]: 1 }.
  296. return SecondsStringPrecision { .precision = 6, .unit = "microsecond"sv, .increment = 1 };
  297. }
  298. // 7. If smallestUnit is "nanosecond", then
  299. if (smallest_unit == "nanosecond"sv) {
  300. // a. Return the Record { [[Precision]]: 9, [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  301. return SecondsStringPrecision { .precision = 9, .unit = "nanosecond"sv, .increment = 1 };
  302. }
  303. // 8. Assert: smallestUnit is undefined.
  304. VERIFY(!smallest_unit.has_value());
  305. // 9. Let fractionalDigitsVal be ? Get(normalizedOptions, "fractionalSecondDigits").
  306. auto fractional_digits_value = TRY(normalized_options.get(vm.names.fractionalSecondDigits));
  307. // 10. If Type(fractionalDigitsVal) is not Number, then
  308. if (!fractional_digits_value.is_number()) {
  309. // a. If fractionalDigitsVal is not undefined, then
  310. if (!fractional_digits_value.is_undefined()) {
  311. // i. If ? ToString(fractionalDigitsVal) is not "auto", throw a RangeError exception.
  312. if (TRY(fractional_digits_value.to_string(vm)) != "auto"sv)
  313. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  314. }
  315. // b. Return the Record { [[Precision]]: "auto", [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  316. return SecondsStringPrecision { .precision = "auto"sv, .unit = "nanosecond"sv, .increment = 1 };
  317. }
  318. // 11. If fractionalDigitsVal is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  319. if (fractional_digits_value.is_nan() || fractional_digits_value.is_infinity())
  320. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  321. // 12. Let fractionalDigitCount be RoundTowardsZero(ℝ(fractionalDigitsVal)).
  322. auto fractional_digit_count_unchecked = trunc(fractional_digits_value.as_double());
  323. // 13. If fractionalDigitCount < 0 or fractionalDigitCount > 9, throw a RangeError exception.
  324. if (fractional_digit_count_unchecked < 0 || fractional_digit_count_unchecked > 9)
  325. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  326. auto fractional_digit_count = static_cast<u8>(fractional_digit_count_unchecked);
  327. // 14. If fractionalDigitCount is 0, then
  328. if (fractional_digit_count == 0) {
  329. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  330. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  331. }
  332. // 15. If fractionalDigitCount is 1, 2, or 3, then
  333. if (fractional_digit_count == 1 || fractional_digit_count == 2 || fractional_digit_count == 3) {
  334. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "millisecond", [[Increment]]: 10^(3 - fractionalDigitCount) }.
  335. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "millisecond"sv, .increment = (u32)pow(10, 3 - fractional_digit_count) };
  336. }
  337. // 16. If fractionalDigitCount is 4, 5, or 6, then
  338. if (fractional_digit_count == 4 || fractional_digit_count == 5 || fractional_digit_count == 6) {
  339. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "microsecond", [[Increment]]: 10^(6 - fractionalDigitCount) }.
  340. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "microsecond"sv, .increment = (u32)pow(10, 6 - fractional_digit_count) };
  341. }
  342. // 17. Assert: fractionalDigitCount is 7, 8, or 9.
  343. VERIFY(fractional_digit_count == 7 || fractional_digit_count == 8 || fractional_digit_count == 9);
  344. // 18. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "nanosecond", [[Increment]]: 10^(9 - fractionalDigitCount) }.
  345. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "nanosecond"sv, .increment = (u32)pow(10, 9 - fractional_digit_count) };
  346. }
  347. struct TemporalUnit {
  348. StringView singular;
  349. StringView plural;
  350. UnitGroup category;
  351. };
  352. // https://tc39.es/proposal-temporal/#table-temporal-units
  353. static Vector<TemporalUnit> temporal_units = {
  354. { "year"sv, "years"sv, UnitGroup::Date },
  355. { "month"sv, "months"sv, UnitGroup::Date },
  356. { "week"sv, "weeks"sv, UnitGroup::Date },
  357. { "day"sv, "days"sv, UnitGroup::Date },
  358. { "hour"sv, "hours"sv, UnitGroup::Time },
  359. { "minute"sv, "minutes"sv, UnitGroup::Time },
  360. { "second"sv, "seconds"sv, UnitGroup::Time },
  361. { "millisecond"sv, "milliseconds"sv, UnitGroup::Time },
  362. { "microsecond"sv, "microseconds"sv, UnitGroup::Time },
  363. { "nanosecond"sv, "nanoseconds"sv, UnitGroup::Time }
  364. };
  365. // 13.15 GetTemporalUnit ( normalizedOptions, key, unitGroup, default [ , extraValues ] ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalunit
  366. ThrowCompletionOr<Optional<String>> get_temporal_unit(VM& vm, Object const& normalized_options, PropertyKey const& key, UnitGroup unit_group, TemporalUnitDefault const& default_, Vector<StringView> const& extra_values)
  367. {
  368. // 1. Let singularNames be a new empty List.
  369. Vector<StringView> singular_names;
  370. // 2. For each row of Table 13, except the header row, in table order, do
  371. for (auto const& row : temporal_units) {
  372. // a. Let unit be the value in the Singular column of the row.
  373. auto unit = row.singular;
  374. // b. If the Category column of the row is date and unitGroup is date or datetime, append unit to singularNames.
  375. if (row.category == UnitGroup::Date && (unit_group == UnitGroup::Date || unit_group == UnitGroup::DateTime))
  376. singular_names.append(unit);
  377. // c. Else if the Category column of the row is time and unitGroup is time or datetime, append unit to singularNames.
  378. else if (row.category == UnitGroup::Time && (unit_group == UnitGroup::Time || unit_group == UnitGroup::DateTime))
  379. singular_names.append(unit);
  380. }
  381. // 3. If extraValues is present, then
  382. if (!extra_values.is_empty()) {
  383. // a. Set singularNames to the list-concatenation of singularNames and extraValues.
  384. singular_names.extend(extra_values);
  385. }
  386. OptionDefault default_value;
  387. // 4. If default is required, then
  388. if (default_.has<TemporalUnitRequired>()) {
  389. // a. Let defaultValue be undefined.
  390. default_value = {};
  391. }
  392. // 5. Else,
  393. else {
  394. auto default_string = default_.get<Optional<StringView>>();
  395. // a. Let defaultValue be default.
  396. default_value = default_string.has_value() ? OptionDefault { *default_string } : OptionDefault {};
  397. // b. If defaultValue is not undefined and singularNames does not contain defaultValue, then
  398. if (default_string.has_value() && !singular_names.contains_slow(*default_string)) {
  399. // i. Append defaultValue to singularNames.
  400. singular_names.append(*default_string);
  401. }
  402. }
  403. // 6. Let allowedValues be a copy of singularNames.
  404. auto allowed_values = singular_names;
  405. // 7. For each element singularName of singularNames, do
  406. for (auto const& singular_name : singular_names) {
  407. for (auto const& row : temporal_units) {
  408. // a. If singularName is listed in the Singular column of Table 13, then
  409. if (singular_name == row.singular) {
  410. // i. Let pluralName be the value in the Plural column of the corresponding row.
  411. auto plural_name = row.plural;
  412. // ii. Append pluralName to allowedValues.
  413. allowed_values.append(plural_name);
  414. }
  415. }
  416. }
  417. // 8. NOTE: For each singular Temporal unit name that is contained within allowedValues, the corresponding plural name is also contained within it.
  418. // 9. Let value be ? GetOption(normalizedOptions, key, "string", allowedValues, defaultValue).
  419. auto option_value = TRY(get_option(vm, normalized_options, key, OptionType::String, allowed_values.span(), default_value));
  420. // 10. If value is undefined and default is required, throw a RangeError exception.
  421. if (option_value.is_undefined() && default_.has<TemporalUnitRequired>())
  422. return vm.throw_completion<RangeError>(ErrorType::IsUndefined, String::formatted("{} option value", key.as_string()));
  423. Optional<String> value = option_value.is_undefined()
  424. ? Optional<String> {}
  425. : option_value.as_string().string();
  426. // 11. If value is listed in the Plural column of Table 13, then
  427. for (auto const& row : temporal_units) {
  428. if (row.plural == value) {
  429. // a. Set value to the value in the Singular column of the corresponding row.
  430. value = row.singular;
  431. }
  432. }
  433. // 12. Return value.
  434. return value;
  435. }
  436. // 13.16 ToRelativeTemporalObject ( options ), https://tc39.es/proposal-temporal/#sec-temporal-torelativetemporalobject
  437. ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& options)
  438. {
  439. auto& realm = *vm.current_realm();
  440. // 1. Assert: Type(options) is Object.
  441. // 2. Let value be ? Get(options, "relativeTo").
  442. auto value = TRY(options.get(vm.names.relativeTo));
  443. // 3. If value is undefined, then
  444. if (value.is_undefined()) {
  445. // a. Return value.
  446. return value;
  447. }
  448. // 4. Let offsetBehaviour be option.
  449. auto offset_behavior = OffsetBehavior::Option;
  450. // 5. Let matchBehaviour be match exactly.
  451. auto match_behavior = MatchBehavior::MatchExactly;
  452. ISODateTime result;
  453. Value offset_string;
  454. Value time_zone;
  455. Object* calendar = nullptr;
  456. // 6. If Type(value) is Object, then
  457. if (value.is_object()) {
  458. auto& value_object = value.as_object();
  459. // a. If value has either an [[InitializedTemporalDate]] or [[InitializedTemporalZonedDateTime]] internal slot, then
  460. if (is<PlainDate>(value_object) || is<ZonedDateTime>(value_object)) {
  461. // i. Return value.
  462. return value;
  463. }
  464. // b. If value has an [[InitializedTemporalDateTime]] internal slot, then
  465. if (is<PlainDateTime>(value_object)) {
  466. auto& plain_date_time = static_cast<PlainDateTime&>(value_object);
  467. // i. Return ? CreateTemporalDate(value.[[ISOYear]], value.[[ISOMonth]], value.[[ISODay]], 0, 0, 0, 0, 0, 0, value.[[Calendar]]).
  468. return TRY(create_temporal_date(vm, plain_date_time.iso_year(), plain_date_time.iso_month(), plain_date_time.iso_day(), plain_date_time.calendar()));
  469. }
  470. // c. Let calendar be ? GetTemporalCalendarWithISODefault(value).
  471. calendar = TRY(get_temporal_calendar_with_iso_default(vm, value_object));
  472. // d. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  473. auto field_names = TRY(calendar_fields(vm, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv }));
  474. // e. Let fields be ? PrepareTemporalFields(value, fieldNames, «»).
  475. auto* fields = TRY(prepare_temporal_fields(vm, value_object, field_names, Vector<StringView> {}));
  476. // f. Let dateOptions be OrdinaryObjectCreate(null).
  477. auto* date_options = Object::create(realm, nullptr);
  478. // g. Perform ! CreateDataPropertyOrThrow(dateOptions, "overflow", "constrain").
  479. MUST(date_options->create_data_property_or_throw(vm.names.overflow, js_string(vm, "constrain"sv)));
  480. // h. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, dateOptions).
  481. result = TRY(interpret_temporal_date_time_fields(vm, *calendar, *fields, *date_options));
  482. // i. Let offsetString be ? Get(value, "offset").
  483. offset_string = TRY(value_object.get(vm.names.offset));
  484. // j. Let timeZone be ? Get(value, "timeZone").
  485. time_zone = TRY(value_object.get(vm.names.timeZone));
  486. // k. If timeZone is not undefined, then
  487. if (!time_zone.is_undefined()) {
  488. // i. Set timeZone to ? ToTemporalTimeZone(timeZone).
  489. time_zone = TRY(to_temporal_time_zone(vm, time_zone));
  490. }
  491. // l. If offsetString is undefined, then
  492. if (offset_string.is_undefined()) {
  493. // i. Set offsetBehaviour to wall.
  494. offset_behavior = OffsetBehavior::Wall;
  495. }
  496. }
  497. // 7. Else,
  498. else {
  499. // a. Let string be ? ToString(value).
  500. auto string = TRY(value.to_string(vm));
  501. // b. Let result be ? ParseTemporalRelativeToString(string).
  502. auto parsed_result = TRY(parse_temporal_relative_to_string(vm, string));
  503. // NOTE: The ISODateTime struct inside `parsed_result` will be moved into `result` at the end of this path to avoid mismatching names.
  504. // Thus, all remaining references to `result` in this path actually refer to `parsed_result`.
  505. // c. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  506. calendar = TRY(to_temporal_calendar_with_iso_default(vm, parsed_result.date_time.calendar.has_value() ? js_string(vm, *parsed_result.date_time.calendar) : js_undefined()));
  507. // d. Let offsetString be result.[[TimeZoneOffsetString]].
  508. offset_string = parsed_result.time_zone.offset_string.has_value() ? js_string(vm, *parsed_result.time_zone.offset_string) : js_undefined();
  509. // e. Let timeZoneName be result.[[TimeZoneIANAName]].
  510. auto time_zone_name = parsed_result.time_zone.name;
  511. // f. If timeZoneName is not undefined, then
  512. if (time_zone_name.has_value()) {
  513. // i. If ParseText(StringToCodePoints(timeZoneName), TimeZoneNumericUTCOffset) is a List of errors, then
  514. if (!is_valid_time_zone_numeric_utc_offset_syntax(*time_zone_name)) {
  515. // 1. If IsValidTimeZoneName(timeZoneName) is false, throw a RangeError exception.
  516. if (!is_valid_time_zone_name(*time_zone_name))
  517. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, *time_zone_name);
  518. // 2. Set timeZoneName to ! CanonicalizeTimeZoneName(timeZoneName).
  519. time_zone_name = canonicalize_time_zone_name(*time_zone_name);
  520. }
  521. // ii. Let timeZone be ! CreateTemporalTimeZone(timeZoneName).
  522. time_zone = MUST(create_temporal_time_zone(vm, *time_zone_name));
  523. }
  524. // g. Else,
  525. else {
  526. // i. Let timeZone be undefined.
  527. time_zone = js_undefined();
  528. }
  529. // h. If result.[[TimeZoneZ]] is true, then
  530. if (parsed_result.time_zone.z) {
  531. // i. Set offsetBehaviour to exact.
  532. offset_behavior = OffsetBehavior::Exact;
  533. }
  534. // i. Else if offsetString is undefined, then
  535. else if (offset_string.is_undefined()) {
  536. // i. Set offsetBehaviour to wall.
  537. offset_behavior = OffsetBehavior::Wall;
  538. }
  539. // j. Set matchBehaviour to match minutes.
  540. match_behavior = MatchBehavior::MatchMinutes;
  541. // See NOTE above about why this is done.
  542. result = move(parsed_result.date_time);
  543. }
  544. // 8. If timeZone is not undefined, then
  545. if (!time_zone.is_undefined()) {
  546. double offset_ns;
  547. // a. If offsetBehaviour is option, then
  548. if (offset_behavior == OffsetBehavior::Option) {
  549. // i. Set offsetString to ? ToString(offsetString).
  550. // NOTE: offsetString is not used after this path, so we don't need to put this into the original offset_string which is of type JS::Value.
  551. auto actual_offset_string = TRY(offset_string.to_string(vm));
  552. // ii. Let offsetNs be ? ParseTimeZoneOffsetString(offsetString).
  553. offset_ns = TRY(parse_time_zone_offset_string(vm, actual_offset_string));
  554. }
  555. // b. Else,
  556. else {
  557. // i. Let offsetNs be 0.
  558. offset_ns = 0;
  559. }
  560. // c. Let epochNanoseconds be ? InterpretISODateTimeOffset(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], offsetBehaviour, offsetNs, timeZone, "compatible", "reject", matchBehaviour).
  561. auto* epoch_nanoseconds = TRY(interpret_iso_date_time_offset(vm, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, offset_behavior, offset_ns, time_zone, "compatible"sv, "reject"sv, match_behavior));
  562. // d. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  563. return MUST(create_temporal_zoned_date_time(vm, *epoch_nanoseconds, time_zone.as_object(), *calendar));
  564. }
  565. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  566. return TRY(create_temporal_date(vm, result.year, result.month, result.day, *calendar));
  567. }
  568. // 13.17 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  569. StringView larger_of_two_temporal_units(StringView unit1, StringView unit2)
  570. {
  571. // 1. Assert: Both u1 and u2 are listed in the Singular column of Table 13.
  572. // 2. For each row of Table 13, except the header row, in table order, do
  573. for (auto const& row : temporal_units) {
  574. // a. Let unit be the value in the Singular column of the row.
  575. auto unit = row.singular;
  576. // b. If SameValue(u1, unit) is true, return unit.
  577. if (unit1 == unit)
  578. return unit;
  579. // c. If SameValue(u2, unit) is true, return unit.
  580. if (unit2 == unit)
  581. return unit;
  582. }
  583. VERIFY_NOT_REACHED();
  584. }
  585. // 13.18 MergeLargestUnitOption ( options, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-mergelargestunitoption
  586. ThrowCompletionOr<Object*> merge_largest_unit_option(VM& vm, Object const& options, String largest_unit)
  587. {
  588. auto& realm = *vm.current_realm();
  589. // 1. Let merged be OrdinaryObjectCreate(null).
  590. auto* merged = Object::create(realm, nullptr);
  591. // 2. Let keys be ? EnumerableOwnPropertyNames(options, key).
  592. auto keys = TRY(options.enumerable_own_property_names(Object::PropertyKind::Key));
  593. // 3. For each element nextKey of keys, do
  594. for (auto& key : keys) {
  595. auto next_key = MUST(PropertyKey::from_value(vm, key));
  596. // a. Let propValue be ? Get(options, nextKey).
  597. auto prop_value = TRY(options.get(next_key));
  598. // b. Perform ! CreateDataPropertyOrThrow(merged, nextKey, propValue).
  599. MUST(merged->create_data_property_or_throw(next_key, prop_value));
  600. }
  601. // 4. Perform ! CreateDataPropertyOrThrow(merged, "largestUnit", largestUnit).
  602. MUST(merged->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, move(largest_unit))));
  603. // 5. Return merged.
  604. return merged;
  605. }
  606. // 13.19 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  607. Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit)
  608. {
  609. // 1. If unit is "year", "month", "week", or "day", then
  610. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  611. // a. Return undefined.
  612. return {};
  613. }
  614. // 2. If unit is "hour", then
  615. if (unit == "hour"sv) {
  616. // a. Return 24.
  617. return 24;
  618. }
  619. // 3. If unit is "minute" or "second", then
  620. if (unit.is_one_of("minute"sv, "second"sv)) {
  621. // a. Return 60.
  622. return 60;
  623. }
  624. // 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
  625. VERIFY(unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  626. // 5. Return 1000.
  627. return 1000;
  628. }
  629. // 13.20 RejectObjectWithCalendarOrTimeZone ( object ), https://tc39.es/proposal-temporal/#sec-temporal-rejectobjectwithcalendarortimezone
  630. ThrowCompletionOr<void> reject_object_with_calendar_or_time_zone(VM& vm, Object& object)
  631. {
  632. // 1. Assert: Type(object) is Object.
  633. // 2. If object has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  634. if (is<PlainDate>(object) || is<PlainDateTime>(object) || is<PlainMonthDay>(object) || is<PlainTime>(object) || is<PlainYearMonth>(object) || is<ZonedDateTime>(object)) {
  635. // a. Throw a TypeError exception.
  636. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "calendar or timeZone");
  637. }
  638. // 3. Let calendarProperty be ? Get(object, "calendar").
  639. auto calendar_property = TRY(object.get(vm.names.calendar));
  640. // 4. If calendarProperty is not undefined, then
  641. if (!calendar_property.is_undefined()) {
  642. // a. Throw a TypeError exception.
  643. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "calendar");
  644. }
  645. // 5. Let timeZoneProperty be ? Get(object, "timeZone").
  646. auto time_zone_property = TRY(object.get(vm.names.timeZone));
  647. // 6. If timeZoneProperty is not undefined, then
  648. if (!time_zone_property.is_undefined()) {
  649. // a. Throw a TypeError exception.
  650. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "timeZone");
  651. }
  652. return {};
  653. }
  654. // 13.21 FormatSecondsStringPart ( second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatsecondsstringpart
  655. String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  656. {
  657. // 1. Assert: second, millisecond, microsecond, and nanosecond are integers.
  658. // Non-standard sanity check
  659. if (precision.has<StringView>())
  660. VERIFY(precision.get<StringView>().is_one_of("minute"sv, "auto"sv));
  661. // 2. If precision is "minute", return "".
  662. if (precision.has<StringView>() && precision.get<StringView>() == "minute"sv)
  663. return String::empty();
  664. // 3. Let secondsString be the string-concatenation of the code unit 0x003A (COLON) and ToZeroPaddedDecimalString(second, 2).
  665. auto seconds_string = String::formatted(":{:02}", second);
  666. // 4. Let fraction be millisecond × 10^6 + microsecond × 10^3 + nanosecond.
  667. u32 fraction = millisecond * 1'000'000 + microsecond * 1'000 + nanosecond;
  668. String fraction_string;
  669. // 5. If precision is "auto", then
  670. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  671. // a. If fraction is 0, return secondsString.
  672. if (fraction == 0)
  673. return seconds_string;
  674. // b. Set fraction to ToZeroPaddedDecimalString(fraction, 9).
  675. fraction_string = String::formatted("{:09}", fraction);
  676. // c. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  677. fraction_string = fraction_string.trim("0"sv, TrimMode::Right);
  678. }
  679. // 6. Else,
  680. else {
  681. // a. If precision is 0, return secondsString.
  682. if (precision.get<u8>() == 0)
  683. return seconds_string;
  684. // b. Set fraction to ToZeroPaddedDecimalString(fraction, 9)
  685. fraction_string = String::formatted("{:09}", fraction);
  686. // c. Set fraction to the substring of fraction from 0 to precision.
  687. fraction_string = fraction_string.substring(0, precision.get<u8>());
  688. }
  689. // 7. Return the string-concatenation of secondsString, the code unit 0x002E (FULL STOP), and fraction.
  690. return String::formatted("{}.{}", seconds_string, fraction_string);
  691. }
  692. // 13.23 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/proposal-temporal/#sec-temporal-getunsignedroundingmode
  693. UnsignedRoundingMode get_unsigned_rounding_mode(StringView rounding_mode, bool is_negative)
  694. {
  695. // 1. If isNegative is true, return the specification type in the third column of Table 14 where the first column is roundingMode and the second column is "negative".
  696. if (is_negative) {
  697. if (rounding_mode == "ceil"sv)
  698. return UnsignedRoundingMode::Zero;
  699. if (rounding_mode == "floor"sv)
  700. return UnsignedRoundingMode::Infinity;
  701. if (rounding_mode == "expand"sv)
  702. return UnsignedRoundingMode::Infinity;
  703. if (rounding_mode == "trunc"sv)
  704. return UnsignedRoundingMode::Zero;
  705. if (rounding_mode == "halfCeil"sv)
  706. return UnsignedRoundingMode::HalfZero;
  707. if (rounding_mode == "halfFloor"sv)
  708. return UnsignedRoundingMode::HalfInfinity;
  709. if (rounding_mode == "halfExpand"sv)
  710. return UnsignedRoundingMode::HalfInfinity;
  711. if (rounding_mode == "halfTrunc"sv)
  712. return UnsignedRoundingMode::HalfZero;
  713. if (rounding_mode == "halfEven"sv)
  714. return UnsignedRoundingMode::HalfEven;
  715. VERIFY_NOT_REACHED();
  716. }
  717. // 2. Else, return the specification type in the third column of Table 14 where the first column is roundingMode and the second column is "positive".
  718. else {
  719. if (rounding_mode == "ceil"sv)
  720. return UnsignedRoundingMode::Infinity;
  721. if (rounding_mode == "floor"sv)
  722. return UnsignedRoundingMode::Zero;
  723. if (rounding_mode == "expand"sv)
  724. return UnsignedRoundingMode::Infinity;
  725. if (rounding_mode == "trunc"sv)
  726. return UnsignedRoundingMode::Zero;
  727. if (rounding_mode == "halfCeil"sv)
  728. return UnsignedRoundingMode::HalfInfinity;
  729. if (rounding_mode == "halfFloor"sv)
  730. return UnsignedRoundingMode::HalfZero;
  731. if (rounding_mode == "halfExpand"sv)
  732. return UnsignedRoundingMode::HalfInfinity;
  733. if (rounding_mode == "halfTrunc"sv)
  734. return UnsignedRoundingMode::HalfZero;
  735. if (rounding_mode == "halfEven"sv)
  736. return UnsignedRoundingMode::HalfEven;
  737. VERIFY_NOT_REACHED();
  738. }
  739. }
  740. // NOTE: We have two variants of these functions, one using doubles and one using BigInts - most of the time
  741. // doubles will be fine, but take care to choose the right one. The spec is not very clear about this, as
  742. // it uses mathematical values which can be arbitrarily (but not infinitely) large.
  743. // Incidentally V8's Temporal implementation does the same :^)
  744. // 13.24 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-applyunsignedroundingmode
  745. double apply_unsigned_rounding_mode(double x, double r1, double r2, Optional<UnsignedRoundingMode> const& unsigned_rounding_mode)
  746. {
  747. // 1. If x is equal to r1, return r1.
  748. if (x == r1)
  749. return r1;
  750. // 2. Assert: r1 < x < r2.
  751. VERIFY(r1 < x && x < r2);
  752. // 3. Assert: unsignedRoundingMode is not undefined.
  753. VERIFY(unsigned_rounding_mode.has_value());
  754. // 4. If unsignedRoundingMode is zero, return r1.
  755. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  756. return r1;
  757. // 5. If unsignedRoundingMode is infinity, return r2.
  758. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  759. return r2;
  760. // 6. Let d1 be x – r1.
  761. auto d1 = x - r1;
  762. // 7. Let d2 be r2 – x.
  763. auto d2 = r2 - x;
  764. // 8. If d1 < d2, return r1.
  765. if (d1 < d2)
  766. return r1;
  767. // 9. If d2 < d1, return r2.
  768. if (d2 < d1)
  769. return r2;
  770. // 10. Assert: d1 is equal to d2.
  771. VERIFY(d1 == d2);
  772. // 11. If unsignedRoundingMode is half-zero, return r1.
  773. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  774. return r1;
  775. // 12. If unsignedRoundingMode is half-infinity, return r2.
  776. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  777. return r2;
  778. // 13. Assert: unsignedRoundingMode is half-even.
  779. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  780. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  781. auto cardinality = modulo((r1 / (r2 - r1)), 2);
  782. // 15. If cardinality is 0, return r1.
  783. if (cardinality == 0)
  784. return r1;
  785. // 16. Return r2.
  786. return r2;
  787. }
  788. // 13.24 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-applyunsignedroundingmode
  789. Crypto::SignedBigInteger apply_unsigned_rounding_mode(Crypto::SignedDivisionResult const& x, Crypto::SignedBigInteger const& r1, Crypto::SignedBigInteger const& r2, Optional<UnsignedRoundingMode> const& unsigned_rounding_mode, Crypto::UnsignedBigInteger const& increment)
  790. {
  791. // 1. If x is equal to r1, return r1.
  792. if (x.quotient == r1 && x.remainder.unsigned_value().is_zero())
  793. return r1;
  794. // 2. Assert: r1 < x < r2.
  795. // NOTE: Skipped for the sake of performance
  796. // 3. Assert: unsignedRoundingMode is not undefined.
  797. VERIFY(unsigned_rounding_mode.has_value());
  798. // 4. If unsignedRoundingMode is zero, return r1.
  799. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  800. return r1;
  801. // 5. If unsignedRoundingMode is infinity, return r2.
  802. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  803. return r2;
  804. // 6. Let d1 be x – r1.
  805. auto d1 = x.remainder.unsigned_value();
  806. // 7. Let d2 be r2 – x.
  807. auto d2 = increment.minus(x.remainder.unsigned_value());
  808. // 8. If d1 < d2, return r1.
  809. if (d1 < d2)
  810. return r1;
  811. // 9. If d2 < d1, return r2.
  812. if (d2 < d1)
  813. return r2;
  814. // 10. Assert: d1 is equal to d2.
  815. // NOTE: Skipped for the sake of performance
  816. // 11. If unsignedRoundingMode is half-zero, return r1.
  817. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  818. return r1;
  819. // 12. If unsignedRoundingMode is half-infinity, return r2.
  820. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  821. return r2;
  822. // 13. Assert: unsignedRoundingMode is half-even.
  823. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  824. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  825. auto cardinality = modulo(r1.divided_by(r2.minus(r1)).quotient, "2"_bigint);
  826. // 15. If cardinality is 0, return r1.
  827. if (cardinality.unsigned_value().is_zero())
  828. return r1;
  829. // 16. Return r2.
  830. return r2;
  831. }
  832. // 13.25 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  833. double round_number_to_increment(double x, u64 increment, StringView rounding_mode)
  834. {
  835. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  836. // 1. Let quotient be x / increment.
  837. auto quotient = x / static_cast<double>(increment);
  838. bool is_negative;
  839. // 2. If quotient < 0, then
  840. if (quotient < 0) {
  841. // a. Let isNegative be true.
  842. is_negative = true;
  843. // b. Set quotient to -quotient.
  844. quotient = -quotient;
  845. }
  846. // 3. Else,
  847. else {
  848. // a. Let isNegative be false.
  849. is_negative = false;
  850. }
  851. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  852. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  853. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  854. auto r1 = floor(quotient);
  855. // 6. Let r2 be the smallest integer such that r2 > quotient.
  856. auto r2 = ceil(quotient);
  857. if (quotient == r2)
  858. r2++;
  859. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  860. auto rounded = apply_unsigned_rounding_mode(quotient, r1, r2, unsigned_rounding_mode);
  861. // 8. If isNegative is true, set rounded to -rounded.
  862. if (is_negative)
  863. rounded = -rounded;
  864. // 9. Return rounded × increment.
  865. return rounded * static_cast<double>(increment);
  866. }
  867. // 13.25 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  868. Crypto::SignedBigInteger round_number_to_increment(Crypto::SignedBigInteger const& x, u64 increment, StringView rounding_mode)
  869. {
  870. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  871. // OPTIMIZATION: If the increment is 1 the number is always rounded
  872. if (increment == 1)
  873. return x;
  874. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  875. // 1. Let quotient be x / increment.
  876. auto division_result = x.divided_by(increment_big_int);
  877. // OPTIMIZATION: If there's no remainder the number is already rounded
  878. if (division_result.remainder.unsigned_value().is_zero())
  879. return x;
  880. bool is_negative;
  881. // 2. If quotient < 0, then
  882. if (division_result.quotient.is_negative()) {
  883. // a. Let isNegative be true.
  884. is_negative = true;
  885. // b. Set quotient to -quotient.
  886. division_result.quotient.negate();
  887. division_result.remainder.negate();
  888. }
  889. // 3. Else,
  890. else {
  891. // a. Let isNegative be false.
  892. is_negative = false;
  893. }
  894. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  895. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  896. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  897. auto r1 = division_result.quotient;
  898. // 6. Let r2 be the smallest integer such that r2 > quotient.
  899. auto r2 = division_result.quotient.plus("1"_bigint);
  900. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  901. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment_big_int);
  902. // 8. If isNegative is true, set rounded to -rounded.
  903. if (is_negative)
  904. rounded.negate();
  905. // 9. Return rounded × increment.
  906. return rounded.multiplied_by(increment_big_int);
  907. }
  908. // 13.26 RoundNumberToIncrementAsIfPositive ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrementasifpositive
  909. Crypto::SignedBigInteger round_number_to_increment_as_if_positive(Crypto::SignedBigInteger const& x, u64 increment, StringView rounding_mode)
  910. {
  911. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  912. // OPTIMIZATION: If the increment is 1 the number is always rounded
  913. if (increment == 1)
  914. return x;
  915. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  916. // 1. Let quotient be x / increment.
  917. auto division_result = x.divided_by(increment_big_int);
  918. // OPTIMIZATION: If there's no remainder the number is already rounded
  919. if (division_result.remainder.unsigned_value().is_zero())
  920. return x;
  921. // 2. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, false).
  922. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, false);
  923. // 3. Let r1 be the largest integer such that r1 ≤ quotient.
  924. auto r1 = division_result.quotient;
  925. // 4. Let r2 be the smallest integer such that r2 > quotient.
  926. auto r2 = division_result.quotient.plus("1"_bigint);
  927. // 5. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  928. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment_big_int);
  929. // 6. Return rounded × increment.
  930. return rounded.multiplied_by(increment_big_int);
  931. }
  932. // 13.28 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  933. ThrowCompletionOr<ISODateTime> parse_iso_date_time(VM& vm, ParseResult const& parse_result)
  934. {
  935. // 1. Let parseResult be empty.
  936. // 2. For each nonterminal goal of « TemporalDateTimeString, TemporalInstantString, TemporalMonthDayString, TemporalTimeString, TemporalYearMonthString, TemporalZonedDateTimeString », do
  937. // a. If parseResult is not a Parse Node, set parseResult to ParseText(StringToCodePoints(isoString), goal).
  938. // 3. Assert: parseResult is a Parse Node.
  939. // NOTE: All of this is done by receiving an already parsed ISO string (ParseResult).
  940. // 4. Let each of year, month, day, fSeconds, and calendar be the source text matched by the respective DateYear, DateMonth, DateDay, TimeFraction, and CalendarName Parse Node contained within parseResult, or an empty sequence of code points if not present.
  941. auto year = parse_result.date_year;
  942. auto month = parse_result.date_month;
  943. auto day = parse_result.date_day;
  944. auto f_seconds = parse_result.time_fraction;
  945. auto calendar = parse_result.calendar_name;
  946. // 5. Let hour be the source text matched by the TimeHour, TimeHourNotValidMonth, TimeHourNotThirtyOneDayMonth, or TimeHourTwoOnly Parse Node contained within parseResult, or an empty sequence of code points if none of those are present.
  947. auto hour = parse_result.time_hour;
  948. if (!hour.has_value())
  949. hour = parse_result.time_hour_not_valid_month;
  950. if (!hour.has_value())
  951. hour = parse_result.time_hour_not_thirty_one_day_month;
  952. if (!hour.has_value())
  953. hour = parse_result.time_hour_two_only;
  954. // 6. Let minute be the source text matched by the TimeMinute, TimeMinuteNotValidDay, TimeMinuteThirtyOnly, or TimeMinuteThirtyOneOnly Parse Node contained within parseResult, or an empty sequence of code points if none of those are present.
  955. auto minute = parse_result.time_minute;
  956. if (!minute.has_value())
  957. minute = parse_result.time_minute_not_valid_day;
  958. if (!minute.has_value())
  959. minute = parse_result.time_minute_thirty_only;
  960. if (!minute.has_value())
  961. minute = parse_result.time_minute_thirty_one_only;
  962. // 7. Let second be the source text matched by the TimeSecond or TimeSecondNotValidMonth Parse Node contained within parseResult, or an empty sequence of code points if neither of those are present.
  963. auto second = parse_result.time_second;
  964. if (!second.has_value())
  965. second = parse_result.time_second_not_valid_month;
  966. // 8. If the first code point of year is U+2212 (MINUS SIGN), replace the first code point with U+002D (HYPHEN-MINUS).
  967. Optional<String> normalized_year;
  968. if (year.has_value()) {
  969. normalized_year = year->starts_with("\xE2\x88\x92"sv)
  970. ? String::formatted("-{}", year->substring_view(3))
  971. : String { *year };
  972. }
  973. // 9. Let yearMV be ! ToIntegerOrInfinity(CodePointsToString(year)).
  974. auto year_mv = *normalized_year.value_or("0"sv).to_int<i32>();
  975. // 10. If month is empty, then
  976. // a. Let monthMV be 1.
  977. // 11. Else,
  978. // a. Let monthMV be ! ToIntegerOrInfinity(CodePointsToString(month)).
  979. auto month_mv = *month.value_or("1"sv).to_uint<u8>();
  980. // 12. If day is empty, then
  981. // a. Let dayMV be 1.
  982. // 13. Else,
  983. // a. Let dayMV be ! ToIntegerOrInfinity(CodePointsToString(day)).
  984. auto day_mv = *day.value_or("1"sv).to_uint<u8>();
  985. // 14. Let hourMV be ! ToIntegerOrInfinity(CodePointsToString(hour)).
  986. auto hour_mv = *hour.value_or("0"sv).to_uint<u8>();
  987. // 15. Let minuteMV be ! ToIntegerOrInfinity(CodePointsToString(minute)).
  988. auto minute_mv = *minute.value_or("0"sv).to_uint<u8>();
  989. // 16. Let secondMV be ! ToIntegerOrInfinity(CodePointsToString(second)).
  990. auto second_mv = *second.value_or("0"sv).to_uint<u8>();
  991. // 17. If secondMV is 60, then
  992. if (second_mv == 60) {
  993. // a. Set secondMV to 59.
  994. second_mv = 59;
  995. }
  996. u16 millisecond_mv;
  997. u16 microsecond_mv;
  998. u16 nanosecond_mv;
  999. // 18. If fSeconds is not empty, then
  1000. if (f_seconds.has_value()) {
  1001. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  1002. auto f_seconds_digits = f_seconds->substring_view(1);
  1003. // b. Let fSecondsDigitsExtended be the string-concatenation of fSecondsDigits and "000000000".
  1004. auto f_seconds_digits_extended = String::formatted("{}000000000", f_seconds_digits);
  1005. // c. Let millisecond be the substring of fSecondsDigitsExtended from 0 to 3.
  1006. auto millisecond = f_seconds_digits_extended.substring(0, 3);
  1007. // d. Let microsecond be the substring of fSecondsDigitsExtended from 3 to 6.
  1008. auto microsecond = f_seconds_digits_extended.substring(3, 3);
  1009. // e. Let nanosecond be the substring of fSecondsDigitsExtended from 6 to 9.
  1010. auto nanosecond = f_seconds_digits_extended.substring(6, 3);
  1011. // f. Let millisecondMV be ! ToIntegerOrInfinity(millisecond).
  1012. millisecond_mv = *millisecond.to_uint<u16>();
  1013. // g. Let microsecondMV be ! ToIntegerOrInfinity(microsecond).
  1014. microsecond_mv = *microsecond.to_uint<u16>();
  1015. // h. Let nanosecondMV be ! ToIntegerOrInfinity(nanosecond).
  1016. nanosecond_mv = *nanosecond.to_uint<u16>();
  1017. }
  1018. // 19. Else,
  1019. else {
  1020. // a. Let millisecondMV be 0.
  1021. millisecond_mv = 0;
  1022. // b. Let microsecondMV be 0.
  1023. microsecond_mv = 0;
  1024. // c. Let nanosecondMV be 0.
  1025. nanosecond_mv = 0;
  1026. }
  1027. // 20. If IsValidISODate(yearMV, monthMV, dayMV) is false, throw a RangeError exception.
  1028. if (!is_valid_iso_date(year_mv, month_mv, day_mv))
  1029. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODate);
  1030. // 21. If IsValidTime(hourMV, minuteMV, secondMV, millisecondMV, microsecondMV, nanosecondMV) is false, throw a RangeError exception.
  1031. if (!is_valid_time(hour_mv, minute_mv, second_mv, millisecond_mv, microsecond_mv, nanosecond_mv))
  1032. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTime);
  1033. Optional<String> calendar_val;
  1034. // 22. If calendar is empty, then
  1035. if (!calendar.has_value()) {
  1036. // a. Let calendarVal be undefined.
  1037. calendar_val = {};
  1038. }
  1039. // 23. Else,
  1040. else {
  1041. // a. Let calendarVal be CodePointsToString(calendar).
  1042. // NOTE: This turns the StringView into a String.
  1043. calendar_val = *calendar;
  1044. }
  1045. // 24. Return the Record { [[Year]]: yearMV, [[Month]]: monthMV, [[Day]]: dayMV, [[Hour]]: hourMV, [[Minute]]: minuteMV, [[Second]]: secondMV, [[Millisecond]]: millisecondMV, [[Microsecond]]: microsecondMV, [[Nanosecond]]: nanosecondMV, [[Calendar]]: calendarVal, }.
  1046. return ISODateTime { .year = year_mv, .month = month_mv, .day = day_mv, .hour = hour_mv, .minute = minute_mv, .second = second_mv, .millisecond = millisecond_mv, .microsecond = microsecond_mv, .nanosecond = nanosecond_mv, .calendar = move(calendar_val) };
  1047. }
  1048. // 13.29 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  1049. ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(VM& vm, String const& iso_string)
  1050. {
  1051. // 1. If ParseText(StringToCodePoints(isoString), TemporalInstantString) is a List of errors, throw a RangeError exception.
  1052. auto parse_result = parse_iso8601(Production::TemporalInstantString, iso_string);
  1053. if (!parse_result.has_value())
  1054. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidInstantString, iso_string);
  1055. // 2. Let result be ? ParseISODateTime(isoString).
  1056. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1057. // 3. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  1058. auto time_zone_result = TRY(parse_temporal_time_zone_string(vm, iso_string));
  1059. // 4. Let offsetString be timeZoneResult.[[OffsetString]].
  1060. auto offset_string = time_zone_result.offset_string;
  1061. // 5. If timeZoneResult.[[Z]] is true, then
  1062. if (time_zone_result.z) {
  1063. // a. Set offsetString to "+00:00".
  1064. offset_string = "+00:00"sv;
  1065. }
  1066. // 6. Assert: offsetString is not undefined.
  1067. VERIFY(offset_string.has_value());
  1068. // 7. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[TimeZoneOffsetString]]: offsetString }.
  1069. return TemporalInstant { .year = result.year, .month = result.month, .day = result.day, .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .time_zone_offset = move(offset_string) };
  1070. }
  1071. // 13.30 ParseTemporalZonedDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalzoneddatetimestring
  1072. ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_zoned_date_time_string(VM& vm, String const& iso_string)
  1073. {
  1074. // 1. If ParseText(StringToCodePoints(isoString), TemporalZonedDateTimeString) is a List of errors, throw a RangeError exception.
  1075. auto parse_result = parse_iso8601(Production::TemporalZonedDateTimeString, iso_string);
  1076. if (!parse_result.has_value())
  1077. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidZonedDateTimeString, iso_string);
  1078. // 2. Let result be ? ParseISODateTime(isoString).
  1079. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1080. // 3. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  1081. auto time_zone_result = TRY(parse_temporal_time_zone_string(vm, iso_string));
  1082. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[Calendar]]: result.[[Calendar]], [[TimeZoneZ]]: timeZoneResult.[[Z]], [[TimeZoneOffsetString]]: timeZoneResult.[[OffsetString]], [[TimeZoneName]]: timeZoneResult.[[Name]] }.
  1083. // NOTE: This returns the two structs together instead of separated to avoid a copy in ToTemporalZonedDateTime, as the spec tries to put the result of InterpretTemporalDateTimeFields and ParseTemporalZonedDateTimeString into the same `result` variable.
  1084. // InterpretTemporalDateTimeFields returns an ISODateTime, so the moved in `result` here is subsequently moved into ParseTemporalZonedDateTimeString's `result` variable.
  1085. return TemporalZonedDateTime { .date_time = move(result), .time_zone = move(time_zone_result) };
  1086. }
  1087. // 13.31 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  1088. ThrowCompletionOr<String> parse_temporal_calendar_string(VM& vm, String const& iso_string)
  1089. {
  1090. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalCalendarString).
  1091. auto parse_result = parse_iso8601(Production::TemporalCalendarString, iso_string);
  1092. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1093. if (!parse_result.has_value())
  1094. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarString, iso_string);
  1095. // 3. Let id be the source text matched by the CalendarName Parse Node contained within parseResult, or an empty sequence of code points if not present.
  1096. auto id = parse_result->calendar_name;
  1097. // 4. If id is empty, then
  1098. if (!id.has_value()) {
  1099. // a. Return "iso8601".
  1100. return "iso8601"sv;
  1101. }
  1102. // 5. Return CodePointsToString(id).
  1103. return id.value();
  1104. }
  1105. // 13.32 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  1106. ThrowCompletionOr<TemporalDate> parse_temporal_date_string(VM& vm, String const& iso_string)
  1107. {
  1108. // 1. Let parts be ? ParseTemporalDateTimeString(isoString).
  1109. auto parts = TRY(parse_temporal_date_time_string(vm, iso_string));
  1110. // 2. Return the Record { [[Year]]: parts.[[Year]], [[Month]]: parts.[[Month]], [[Day]]: parts.[[Day]], [[Calendar]]: parts.[[Calendar]] }.
  1111. return TemporalDate { .year = parts.year, .month = parts.month, .day = parts.day, .calendar = move(parts.calendar) };
  1112. }
  1113. // 13.33 ParseTemporalDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatetimestring
  1114. ThrowCompletionOr<ISODateTime> parse_temporal_date_time_string(VM& vm, String const& iso_string)
  1115. {
  1116. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalDateTimeString).
  1117. auto parse_result = parse_iso8601(Production::TemporalDateTimeString, iso_string);
  1118. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1119. if (!parse_result.has_value())
  1120. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeString, iso_string);
  1121. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1122. if (parse_result->utc_designator.has_value())
  1123. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeStringUTCDesignator, iso_string);
  1124. // 4. Return ? ParseISODateTime(isoString).
  1125. return parse_iso_date_time(vm, *parse_result);
  1126. }
  1127. // 13.34 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  1128. ThrowCompletionOr<DurationRecord> parse_temporal_duration_string(VM& vm, String const& iso_string)
  1129. {
  1130. // 1. Let duration be ParseText(StringToCodePoints(isoString), TemporalDurationString).
  1131. auto parse_result = parse_iso8601(Production::TemporalDurationString, iso_string);
  1132. // 2. If duration is a List of errors, throw a RangeError exception.
  1133. if (!parse_result.has_value())
  1134. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationString, iso_string);
  1135. // 3. Let each of sign, years, months, weeks, days, hours, fHours, minutes, fMinutes, seconds, and fSeconds be the source text matched by the respective Sign, DurationYears, DurationMonths, DurationWeeks, DurationDays, DurationWholeHours, DurationHoursFraction, DurationWholeMinutes, DurationMinutesFraction, DurationWholeSeconds, and DurationSecondsFraction Parse Node contained within duration, or an empty sequence of code points if not present.
  1136. auto sign_part = parse_result->sign;
  1137. auto years_part = parse_result->duration_years;
  1138. auto months_part = parse_result->duration_months;
  1139. auto weeks_part = parse_result->duration_weeks;
  1140. auto days_part = parse_result->duration_days;
  1141. auto hours_part = parse_result->duration_whole_hours;
  1142. auto f_hours_part = parse_result->duration_hours_fraction;
  1143. auto minutes_part = parse_result->duration_whole_minutes;
  1144. auto f_minutes_part = parse_result->duration_minutes_fraction;
  1145. auto seconds_part = parse_result->duration_whole_seconds;
  1146. auto f_seconds_part = parse_result->duration_seconds_fraction;
  1147. // FIXME: I can has StringView::to<double>()?
  1148. // 4. Let yearsMV be ! ToIntegerOrInfinity(CodePointsToString(years)).
  1149. auto years = strtod(String { years_part.value_or("0"sv) }.characters(), nullptr);
  1150. // 5. Let monthsMV be ! ToIntegerOrInfinity(CodePointsToString(months)).
  1151. auto months = strtod(String { months_part.value_or("0"sv) }.characters(), nullptr);
  1152. // 6. Let weeksMV be ! ToIntegerOrInfinity(CodePointsToString(weeks)).
  1153. auto weeks = strtod(String { weeks_part.value_or("0"sv) }.characters(), nullptr);
  1154. // 7. Let daysMV be ! ToIntegerOrInfinity(CodePointsToString(days)).
  1155. auto days = strtod(String { days_part.value_or("0"sv) }.characters(), nullptr);
  1156. // 8. Let hoursMV be ! ToIntegerOrInfinity(CodePointsToString(hours)).
  1157. auto hours = strtod(String { hours_part.value_or("0"sv) }.characters(), nullptr);
  1158. double minutes;
  1159. // 9. If fHours is not empty, then
  1160. if (f_hours_part.has_value()) {
  1161. // a. If any of minutes, fMinutes, seconds, fSeconds is not empty, throw a RangeError exception.
  1162. if (minutes_part.has_value() || f_minutes_part.has_value() || seconds_part.has_value() || f_seconds_part.has_value())
  1163. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationStringFractionNotLast, iso_string, "hours"sv, "minutes or seconds"sv);
  1164. // b. Let fHoursDigits be the substring of CodePointsToString(fHours) from 1.
  1165. auto f_hours_digits = f_hours_part->substring_view(1);
  1166. // c. Let fHoursScale be the length of fHoursDigits.
  1167. auto f_hours_scale = (double)f_hours_digits.length();
  1168. // d. Let minutesMV be ! ToIntegerOrInfinity(fHoursDigits) / 10^fHoursScale × 60.
  1169. minutes = strtod(String { f_hours_digits }.characters(), nullptr) / pow(10, f_hours_scale) * 60;
  1170. }
  1171. // 10. Else,
  1172. else {
  1173. // a. Let minutesMV be ! ToIntegerOrInfinity(CodePointsToString(minutes)).
  1174. minutes = strtod(String { minutes_part.value_or("0"sv) }.characters(), nullptr);
  1175. }
  1176. double seconds;
  1177. // 11. If fMinutes is not empty, then
  1178. if (f_minutes_part.has_value()) {
  1179. // a. If any of seconds, fSeconds is not empty, throw a RangeError exception.
  1180. if (seconds_part.has_value() || f_seconds_part.has_value())
  1181. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationStringFractionNotLast, iso_string, "minutes"sv, "seconds"sv);
  1182. // b. Let fMinutesDigits be the substring of CodePointsToString(fMinutes) from 1.
  1183. auto f_minutes_digits = f_minutes_part->substring_view(1);
  1184. // c. Let fMinutesScale be the length of fMinutesDigits.
  1185. auto f_minutes_scale = (double)f_minutes_digits.length();
  1186. // d. Let secondsMV be ! ToIntegerOrInfinity(fMinutesDigits) / 10^fMinutesScale × 60.
  1187. seconds = strtod(String { f_minutes_digits }.characters(), nullptr) / pow(10, f_minutes_scale) * 60;
  1188. }
  1189. // 12. Else if seconds is not empty, then
  1190. else if (seconds_part.has_value()) {
  1191. // a. Let secondsMV be ! ToIntegerOrInfinity(CodePointsToString(seconds)).
  1192. seconds = strtod(String { *seconds_part }.characters(), nullptr);
  1193. }
  1194. // 13. Else,
  1195. else {
  1196. // a. Let secondsMV be remainder(minutesMV, 1) × 60.
  1197. seconds = fmod(minutes, 1) * 60;
  1198. }
  1199. double milliseconds;
  1200. // 14. If fSeconds is not empty, then
  1201. if (f_seconds_part.has_value()) {
  1202. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  1203. auto f_seconds_digits = f_seconds_part->substring_view(1);
  1204. // b. Let fSecondsScale be the length of fSecondsDigits.
  1205. auto f_seconds_scale = (double)f_seconds_digits.length();
  1206. // c. Let millisecondsMV be ! ToIntegerOrInfinity(fSecondsDigits) / 10^fSecondsScale × 1000.
  1207. milliseconds = strtod(String { f_seconds_digits }.characters(), nullptr) / pow(10, f_seconds_scale) * 1000;
  1208. }
  1209. // 15. Else,
  1210. else {
  1211. // a. Let millisecondsMV be remainder(secondsMV, 1) × 1000.
  1212. milliseconds = fmod(seconds, 1) * 1000;
  1213. }
  1214. // FIXME: This suffers from floating point (im)precision issues - e.g. "PT0.0000001S" ends up
  1215. // getting parsed as 99.999999 nanoseconds, which is floor()'d to 99 instead of the
  1216. // expected 100. Oof. This is the reason all of these are suffixed with "MV" in the spec:
  1217. // mathematical values are not supposed to have this issue.
  1218. // 16. Let microsecondsMV be remainder(millisecondsMV, 1) × 1000.
  1219. auto microseconds = fmod(milliseconds, 1) * 1000;
  1220. // 17. Let nanosecondsMV be remainder(microsecondsMV, 1) × 1000.
  1221. auto nanoseconds = fmod(microseconds, 1) * 1000;
  1222. i8 factor;
  1223. // 18. If sign contains the code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
  1224. if (sign_part.has_value() && sign_part->is_one_of("-", "\u2212")) {
  1225. // a. Let factor be -1.
  1226. factor = -1;
  1227. }
  1228. // 19. Else,
  1229. else {
  1230. // a. Let factor be 1.
  1231. factor = 1;
  1232. }
  1233. // 20. Return ? CreateDurationRecord(yearsMV × factor, monthsMV × factor, weeksMV × factor, daysMV × factor, hoursMV × factor, floor(minutesMV) × factor, floor(secondsMV) × factor, floor(millisecondsMV) × factor, floor(microsecondsMV) × factor, floor(nanosecondsMV) × factor).
  1234. return create_duration_record(vm, years * factor, months * factor, weeks * factor, days * factor, hours * factor, floor(minutes) * factor, floor(seconds) * factor, floor(milliseconds) * factor, floor(microseconds) * factor, floor(nanoseconds) * factor);
  1235. }
  1236. // 13.35 ParseTemporalMonthDayString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalmonthdaystring
  1237. ThrowCompletionOr<TemporalMonthDay> parse_temporal_month_day_string(VM& vm, String const& iso_string)
  1238. {
  1239. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalMonthDayString).
  1240. auto parse_result = parse_iso8601(Production::TemporalMonthDayString, iso_string);
  1241. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1242. if (!parse_result.has_value())
  1243. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthDayString, iso_string);
  1244. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1245. if (parse_result->utc_designator.has_value())
  1246. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthDayStringUTCDesignator, iso_string);
  1247. // 4. Let result be ? ParseISODateTime(isoString).
  1248. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1249. // 5. Let year be result.[[Year]].
  1250. Optional<i32> year = result.year;
  1251. // 6. If parseResult does not contain a DateYear Parse Node, then
  1252. if (!parse_result->date_year.has_value()) {
  1253. // a. Set year to undefined.
  1254. year = {};
  1255. }
  1256. // 7. Return the Record { [[Year]]: year, [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1257. return TemporalMonthDay { .year = year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1258. }
  1259. // 13.36 ParseTemporalRelativeToString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalrelativetostring
  1260. ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_relative_to_string(VM& vm, String const& iso_string)
  1261. {
  1262. // 1. If ParseText(StringToCodePoints(isoString), TemporalDateTimeString) is a List of errors, throw a RangeError exception.
  1263. auto parse_result = parse_iso8601(Production::TemporalDateTimeString, iso_string);
  1264. if (!parse_result.has_value())
  1265. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeString, iso_string);
  1266. // 2. Let result be ? ParseISODateTime(isoString).
  1267. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1268. bool z;
  1269. Optional<String> offset_string;
  1270. Optional<String> time_zone;
  1271. // 3. If ParseText(StringToCodePoints(isoString), TemporalZonedDateTimeString) is a Parse Node, then
  1272. parse_result = parse_iso8601(Production::TemporalZonedDateTimeString, iso_string);
  1273. if (parse_result.has_value()) {
  1274. // a. Let timeZoneResult be ! ParseTemporalTimeZoneString(isoString).
  1275. auto time_zone_result = MUST(parse_temporal_time_zone_string(vm, iso_string));
  1276. // b. Let z be timeZoneResult.[[Z]].
  1277. z = time_zone_result.z;
  1278. // c. Let offsetString be timeZoneResult.[[OffsetString]].
  1279. offset_string = time_zone_result.offset_string;
  1280. // d. Let timeZone be timeZoneResult.[[Name]].
  1281. time_zone = time_zone_result.name;
  1282. }
  1283. // 4. Else,
  1284. else {
  1285. // a. Let z be false.
  1286. z = false;
  1287. // b. Let offsetString be undefined.
  1288. // c. Let timeZone be undefined.
  1289. }
  1290. // 5. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[Calendar]]: result.[[Calendar]], [[TimeZoneZ]]: z, [[TimeZoneOffsetString]]: offsetString, [[TimeZoneIANAName]]: timeZone }.
  1291. return TemporalZonedDateTime { .date_time = move(result), .time_zone = { .z = z, .offset_string = move(offset_string), .name = move(time_zone) } };
  1292. }
  1293. // 13.37 ParseTemporalTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimestring
  1294. ThrowCompletionOr<TemporalTime> parse_temporal_time_string(VM& vm, String const& iso_string)
  1295. {
  1296. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalTimeString).
  1297. auto parse_result = parse_iso8601(Production::TemporalTimeString, iso_string);
  1298. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1299. if (!parse_result.has_value())
  1300. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeString, iso_string);
  1301. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1302. if (parse_result->utc_designator.has_value())
  1303. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeStringUTCDesignator, iso_string);
  1304. // 4. Let result be ? ParseISODateTime(isoString).
  1305. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1306. // 5. Return the Record { [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[Calendar]]: result.[[Calendar]] }.
  1307. return TemporalTime { .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .calendar = move(result.calendar) };
  1308. }
  1309. // 13.38 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  1310. ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(VM& vm, String const& iso_string)
  1311. {
  1312. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalTimeZoneString).
  1313. auto parse_result = parse_iso8601(Production::TemporalTimeZoneString, iso_string);
  1314. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1315. if (!parse_result.has_value())
  1316. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneString, iso_string);
  1317. // 3. Let each of z, offsetString, and name be the source text matched by the respective UTCDesignator, TimeZoneNumericUTCOffset, and TimeZoneIdentifier Parse Nodes contained within parseResult, or an empty sequence of code points if not present.
  1318. auto z = parse_result->utc_designator;
  1319. auto offset_string = parse_result->time_zone_numeric_utc_offset;
  1320. auto name = parse_result->time_zone_identifier;
  1321. // 4. If name is empty, then
  1322. // a. Set name to undefined.
  1323. // 5. Else,
  1324. // a. Set name to CodePointsToString(name).
  1325. // NOTE: No-op.
  1326. // 6. If z is not empty, then
  1327. if (z.has_value()) {
  1328. // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
  1329. return TemporalTimeZone { .z = true, .offset_string = {}, .name = Optional<String>(move(name)) };
  1330. }
  1331. // 7. If offsetString is empty, then
  1332. // a. Set offsetString to undefined.
  1333. // 8. Else,
  1334. // a. Set offsetString to CodePointsToString(offsetString).
  1335. // NOTE: No-op.
  1336. // 9. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
  1337. return TemporalTimeZone { .z = false, .offset_string = Optional<String>(move(offset_string)), .name = Optional<String>(move(name)) };
  1338. }
  1339. // 13.39 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
  1340. ThrowCompletionOr<TemporalYearMonth> parse_temporal_year_month_string(VM& vm, String const& iso_string)
  1341. {
  1342. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalYearMonthString).
  1343. auto parse_result = parse_iso8601(Production::TemporalYearMonthString, iso_string);
  1344. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1345. if (!parse_result.has_value())
  1346. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidYearMonthString, iso_string);
  1347. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1348. if (parse_result->utc_designator.has_value())
  1349. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidYearMonthStringUTCDesignator, iso_string);
  1350. // 4. Let result be ? ParseISODateTime(isoString).
  1351. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1352. // 5. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1353. return TemporalYearMonth { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1354. }
  1355. // 13.40 ToPositiveInteger ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveinteger
  1356. ThrowCompletionOr<double> to_positive_integer(VM& vm, Value argument)
  1357. {
  1358. // 1. Let integer be ? ToIntegerThrowOnInfinity(argument).
  1359. auto integer = TRY(to_integer_throw_on_infinity(vm, argument, ErrorType::TemporalPropertyMustBePositiveInteger));
  1360. // 2. If integer ≤ 0, then
  1361. if (integer <= 0) {
  1362. // a. Throw a RangeError exception.
  1363. return vm.throw_completion<RangeError>(ErrorType::TemporalPropertyMustBePositiveInteger);
  1364. }
  1365. // 3. Return integer.
  1366. return integer;
  1367. }
  1368. // 13.43 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  1369. ThrowCompletionOr<Object*> prepare_temporal_fields(VM& vm, Object const& fields, Vector<String> const& field_names, Variant<PrepareTemporalFieldsPartial, Vector<StringView>> const& required_fields)
  1370. {
  1371. auto& realm = *vm.current_realm();
  1372. // 1. Let result be OrdinaryObjectCreate(null).
  1373. auto* result = Object::create(realm, nullptr);
  1374. VERIFY(result);
  1375. // 2. Let any be false.
  1376. auto any = false;
  1377. // 3. For each value property of fieldNames, do
  1378. for (auto& property : field_names) {
  1379. // a. Let value be ? Get(fields, property).
  1380. auto value = TRY(fields.get(property));
  1381. // b. If value is not undefined, then
  1382. if (!value.is_undefined()) {
  1383. // i. Set any to true.
  1384. any = true;
  1385. // ii. If property is in the Property column of Table 15 and there is a Conversion value in the same row, then
  1386. // 1. Let Conversion be the Conversion value of the same row.
  1387. // 2. If Conversion is ToIntegerThrowOnInfinity, then
  1388. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv)) {
  1389. // a. Set value to ? ToIntegerThrowOnInfinity(value).
  1390. // b. Set value to 𝔽(value).
  1391. value = Value(TRY(to_integer_throw_on_infinity(vm, value, ErrorType::TemporalPropertyMustBeFinite)));
  1392. }
  1393. // 3. Else if Conversion is ToPositiveInteger, then
  1394. else if (property.is_one_of("month"sv, "day"sv)) {
  1395. // a. Set value to ? ToPositiveInteger(value).
  1396. // b. Set value to 𝔽(value).
  1397. value = Value(TRY(to_positive_integer(vm, value)));
  1398. }
  1399. // 4. Else,
  1400. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv)) {
  1401. // a. Assert: Conversion is ToString.
  1402. // b. Set value to ? ToString(value).
  1403. value = TRY(value.to_primitive_string(vm));
  1404. }
  1405. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1406. MUST(result->create_data_property_or_throw(property, value));
  1407. }
  1408. // c. Else if requiredFields is a List, then
  1409. else if (required_fields.has<Vector<StringView>>()) {
  1410. // i. If requiredFields contains property, then
  1411. if (required_fields.get<Vector<StringView>>().contains_slow(property)) {
  1412. // 1. Throw a TypeError exception.
  1413. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, property);
  1414. }
  1415. // ii. If property is in the Property column of Table 13, then
  1416. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  1417. if (property.is_one_of("hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  1418. // 1. Set value to the corresponding Default value of the same row.
  1419. value = Value(0);
  1420. }
  1421. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1422. MUST(result->create_data_property_or_throw(property, value));
  1423. }
  1424. }
  1425. // 4. If requiredFields is partial and any is false, then
  1426. if (required_fields.has<PrepareTemporalFieldsPartial>() && !any) {
  1427. // a. Throw a TypeError exception.
  1428. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustHaveOneOf, String::join(", "sv, field_names));
  1429. }
  1430. // 5. Return result.
  1431. return result;
  1432. }
  1433. // 13.44 GetDifferenceSettings ( operation, options, unitGroup, disallowedUnits, fallbackSmallestUnit, smallestLargestDefaultUnit ), https://tc39.es/proposal-temporal/#sec-temporal-getdifferencesettings
  1434. ThrowCompletionOr<DifferenceSettings> get_difference_settings(VM& vm, DifferenceOperation operation, Value options_value, UnitGroup unit_group, Vector<StringView> const& disallowed_units, TemporalUnitDefault const& fallback_smallest_unit, StringView smallest_largest_default_unit)
  1435. {
  1436. // 1. Set options to ? GetOptionsObject(options).
  1437. auto* options = TRY(get_options_object(vm, options_value));
  1438. // 2. Let smallestUnit be ? GetTemporalUnit(options, "smallestUnit", unitGroup, fallbackSmallestUnit).
  1439. auto smallest_unit = TRY(get_temporal_unit(vm, *options, vm.names.smallestUnit, unit_group, fallback_smallest_unit));
  1440. // 3. If disallowedUnits contains smallestUnit, throw a RangeError exception.
  1441. if (disallowed_units.contains_slow(*smallest_unit))
  1442. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *smallest_unit, "smallestUnit"sv);
  1443. // 4. Let defaultLargestUnit be ! LargerOfTwoTemporalUnits(smallestLargestDefaultUnit, smallestUnit).
  1444. auto default_largest_unit = larger_of_two_temporal_units(smallest_largest_default_unit, *smallest_unit);
  1445. // 5. Let largestUnit be ? GetTemporalUnit(options, "largestUnit", unitGroup, "auto").
  1446. auto largest_unit = TRY(get_temporal_unit(vm, *options, vm.names.largestUnit, unit_group, { "auto"sv }));
  1447. // 6. If disallowedUnits contains largestUnit, throw a RangeError exception.
  1448. if (disallowed_units.contains_slow(*largest_unit))
  1449. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *largest_unit, "largestUnit"sv);
  1450. // 7. If largestUnit is "auto", set largestUnit to defaultLargestUnit.
  1451. if (largest_unit == "auto"sv)
  1452. largest_unit = default_largest_unit;
  1453. // 8. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
  1454. if (larger_of_two_temporal_units(*largest_unit, *smallest_unit) != largest_unit)
  1455. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidUnitRange, *smallest_unit, *largest_unit);
  1456. // 9. Let roundingMode be ? ToTemporalRoundingMode(options, "trunc").
  1457. auto rounding_mode = TRY(to_temporal_rounding_mode(vm, *options, "trunc"sv));
  1458. // 10. If operation is since, then
  1459. if (operation == DifferenceOperation::Since) {
  1460. // a. Set roundingMode to ! NegateTemporalRoundingMode(roundingMode).
  1461. rounding_mode = negate_temporal_rounding_mode(rounding_mode);
  1462. }
  1463. // 11. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  1464. auto maximum = maximum_temporal_duration_rounding_increment(*smallest_unit);
  1465. // 12. Let roundingIncrement be ? ToTemporalRoundingIncrement(options, maximum, false).
  1466. auto rounding_increment = TRY(to_temporal_rounding_increment(vm, *options, Optional<double> { maximum }, false));
  1467. // 13. Return the Record { [[SmallestUnit]]: smallestUnit, [[LargestUnit]]: largestUnit, [[RoundingMode]]: roundingMode, [[RoundingIncrement]]: roundingIncrement, [[Options]]: options }.
  1468. return DifferenceSettings {
  1469. .smallest_unit = smallest_unit.release_value(),
  1470. .largest_unit = largest_unit.release_value(),
  1471. .rounding_mode = move(rounding_mode),
  1472. .rounding_increment = rounding_increment,
  1473. .options = *options,
  1474. };
  1475. }
  1476. }