AbstractOperations.cpp 87 KB

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