AbstractOperations.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/DateTimeLexer.h>
  9. #include <AK/TypeCasts.h>
  10. #include <AK/Variant.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibJS/Runtime/IteratorOperations.h>
  13. #include <LibJS/Runtime/PropertyKey.h>
  14. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  15. #include <LibJS/Runtime/Temporal/Calendar.h>
  16. #include <LibJS/Runtime/Temporal/Duration.h>
  17. #include <LibJS/Runtime/Temporal/PlainDate.h>
  18. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  19. #include <LibJS/Runtime/Temporal/PlainTime.h>
  20. #include <LibJS/Runtime/Temporal/TimeZone.h>
  21. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  22. namespace JS::Temporal {
  23. static Optional<OptionType> to_option_type(Value value)
  24. {
  25. if (value.is_boolean())
  26. return OptionType::Boolean;
  27. if (value.is_string())
  28. return OptionType::String;
  29. if (value.is_number())
  30. return OptionType::Number;
  31. return {};
  32. }
  33. // 13.1 IterableToListOfType ( items, elementTypes ), https://tc39.es/proposal-temporal/#sec-iterabletolistoftype
  34. ThrowCompletionOr<MarkedValueList> iterable_to_list_of_type(GlobalObject& global_object, Value items, Vector<OptionType> const& element_types)
  35. {
  36. auto& vm = global_object.vm();
  37. auto& heap = global_object.heap();
  38. // 1. Let iteratorRecord be ? GetIterator(items, sync).
  39. auto iterator_record = TRY(get_iterator(global_object, items, IteratorHint::Sync));
  40. // 2. Let values be a new empty List.
  41. MarkedValueList values(heap);
  42. // 3. Let next be true.
  43. auto next = true;
  44. // 4. Repeat, while next is not false,
  45. while (next) {
  46. // a. Set next to ? IteratorStep(iteratorRecord).
  47. auto* iterator_result = TRY(iterator_step(global_object, *iterator_record));
  48. next = iterator_result;
  49. // b. If next is not false, then
  50. if (next) {
  51. // i. Let nextValue be ? IteratorValue(next).
  52. auto next_value = TRY(iterator_value(global_object, *iterator_result));
  53. // ii. If Type(nextValue) is not an element of elementTypes, then
  54. if (auto type = to_option_type(next_value); !type.has_value() || !element_types.contains_slow(*type)) {
  55. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  56. auto completion = vm.throw_completion<TypeError>(global_object, ErrorType::IterableToListOfTypeInvalidValue, next_value.to_string_without_side_effects());
  57. // 2. Return ? IteratorClose(iteratorRecord, completion).
  58. return iterator_close(*iterator_record, move(completion));
  59. }
  60. // iii. Append nextValue to the end of the List values.
  61. values.append(next_value);
  62. }
  63. }
  64. // 5. Return values.
  65. return { move(values) };
  66. }
  67. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  68. ThrowCompletionOr<Object*> get_options_object(GlobalObject& global_object, Value options)
  69. {
  70. auto& vm = global_object.vm();
  71. // 1. If options is undefined, then
  72. if (options.is_undefined()) {
  73. // a. Return ! OrdinaryObjectCreate(null).
  74. return Object::create(global_object, nullptr);
  75. }
  76. // 2. If Type(options) is Object, then
  77. if (options.is_object()) {
  78. // a. Return options.
  79. return &options.as_object();
  80. }
  81. // 3. Throw a TypeError exception.
  82. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, "Options");
  83. }
  84. // 13.3 GetOption ( options, property, types, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  85. ThrowCompletionOr<Value> get_option(GlobalObject& global_object, Object const& options, PropertyKey const& property, Vector<OptionType> const& types, Vector<StringView> const& values, Value fallback)
  86. {
  87. VERIFY(property.is_string());
  88. auto& vm = global_object.vm();
  89. // 1. Assert: Type(options) is Object.
  90. // 2. Assert: Each element of types is Boolean, String, or Number.
  91. // 3. Let value be ? Get(options, property).
  92. auto value = TRY(options.get(property));
  93. // 4. If value is undefined, return fallback.
  94. if (value.is_undefined())
  95. return fallback;
  96. OptionType type;
  97. // 5. If types contains Type(value), then
  98. if (auto value_type = to_option_type(value); value_type.has_value() && types.contains_slow(*value_type)) {
  99. // a. Let type be Type(value).
  100. type = *value_type;
  101. }
  102. // 6. Else,
  103. else {
  104. // a. Let type be the last element of types.
  105. type = types.last();
  106. }
  107. // 7. If type is Boolean, then
  108. if (type == OptionType::Boolean) {
  109. // a. Set value to ! ToBoolean(value).
  110. value = Value(value.to_boolean());
  111. }
  112. // 8. Else if type is Number, then
  113. else if (type == OptionType::Number) {
  114. // a. Set value to ? ToNumber(value).
  115. value = TRY(value.to_number(global_object));
  116. // b. If value is NaN, throw a RangeError exception.
  117. if (value.is_nan())
  118. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property.as_string());
  119. }
  120. // 9. Else,
  121. else {
  122. // a. Set value to ? ToString(value).
  123. value = TRY(value.to_primitive_string(global_object));
  124. }
  125. // 10. If values is not empty, then
  126. if (!values.is_empty()) {
  127. VERIFY(value.is_string());
  128. // a. If values does not contain value, throw a RangeError exception.
  129. if (!values.contains_slow(value.as_string().string()))
  130. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  131. }
  132. // 11. Return value.
  133. return value;
  134. }
  135. // 13.4 GetStringOrNumberOption ( options, property, stringValues, minimum, maximum, fallback ), https://tc39.es/proposal-temporal/#sec-getstringornumberoption
  136. template<typename NumberType>
  137. 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)
  138. {
  139. auto& vm = global_object.vm();
  140. // 1. Assert: Type(options) is Object.
  141. // 2. Let value be ? GetOption(options, property, « Number, String », empty, fallback).
  142. auto value = TRY(get_option(global_object, options, property, { OptionType::Number, OptionType::String }, {}, fallback));
  143. // 3. If Type(value) is Number, then
  144. if (value.is_number()) {
  145. // a. If value < minimum or value > maximum, throw a RangeError exception.
  146. if (value.as_double() < minimum || value.as_double() > maximum)
  147. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_double(), property.as_string());
  148. // b. Return floor(ℝ(value)).
  149. return static_cast<NumberType>(floor(value.as_double()));
  150. }
  151. // 4. Assert: Type(value) is String.
  152. VERIFY(value.is_string());
  153. // 5. If stringValues does not contain value, throw a RangeError exception.
  154. if (!string_values.contains_slow(value.as_string().string()))
  155. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  156. // 6. Return value.
  157. return value.as_string().string();
  158. }
  159. // 13.6 ToTemporalOverflow ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  160. ThrowCompletionOr<String> to_temporal_overflow(GlobalObject& global_object, Object const& normalized_options)
  161. {
  162. auto& vm = global_object.vm();
  163. // 1. Return ? GetOption(normalizedOptions, "overflow", « String », « "constrain", "reject" », "constrain").
  164. auto option = TRY(get_option(global_object, normalized_options, vm.names.overflow, { OptionType::String }, { "constrain"sv, "reject"sv }, js_string(vm, "constrain")));
  165. VERIFY(option.is_string());
  166. return option.as_string().string();
  167. }
  168. // 13.7 ToTemporalDisambiguation ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldisambiguation
  169. ThrowCompletionOr<String> to_temporal_disambiguation(GlobalObject& global_object, Object const& normalized_options)
  170. {
  171. auto& vm = global_object.vm();
  172. // 1. Return ? GetOption(normalizedOptions, "disambiguation", « String », « "compatible", "earlier", "later", "reject" », "compatible").
  173. 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")));
  174. VERIFY(option.is_string());
  175. return option.as_string().string();
  176. }
  177. // 13.8 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  178. ThrowCompletionOr<String> to_temporal_rounding_mode(GlobalObject& global_object, Object const& normalized_options, String const& fallback)
  179. {
  180. auto& vm = global_object.vm();
  181. // 1. Return ? GetOption(normalizedOptions, "roundingMode", « String », « "ceil", "floor", "trunc", "halfExpand" », fallback).
  182. 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)));
  183. VERIFY(option.is_string());
  184. return option.as_string().string();
  185. }
  186. // 13.10 ToTemporalOffset ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloffset
  187. ThrowCompletionOr<String> to_temporal_offset(GlobalObject& global_object, Object const& normalized_options, String const& fallback)
  188. {
  189. auto& vm = global_object.vm();
  190. // 1. Return ? GetOption(normalizedOptions, "offset", « String », « "prefer", "use", "ignore", "reject" », fallback).
  191. 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)));
  192. VERIFY(option.is_string());
  193. return option.as_string().string();
  194. }
  195. // 13.11 ToShowCalendarOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowcalendaroption
  196. ThrowCompletionOr<String> to_show_calendar_option(GlobalObject& global_object, Object const& normalized_options)
  197. {
  198. auto& vm = global_object.vm();
  199. // 1. Return ? GetOption(normalizedOptions, "calendarName", « String », « "auto", "always", "never" », "auto").
  200. 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)));
  201. VERIFY(option.is_string());
  202. return option.as_string().string();
  203. }
  204. // 13.12 ToShowTimeZoneNameOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowtimezonenameoption
  205. ThrowCompletionOr<String> to_show_time_zone_name_option(GlobalObject& global_object, Object const& normalized_options)
  206. {
  207. auto& vm = global_object.vm();
  208. // 1. Return ? GetOption(normalizedOptions, "timeZoneName", « String », « "auto", "never" », "auto").
  209. auto option = TRY(get_option(global_object, normalized_options, vm.names.timeZoneName, { OptionType::String }, { "auto"sv, "never"sv }, js_string(vm, "auto"sv)));
  210. VERIFY(option.is_string());
  211. return option.as_string().string();
  212. }
  213. // 13.13 ToShowOffsetOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowoffsetoption
  214. ThrowCompletionOr<String> to_show_offset_option(GlobalObject& global_object, Object const& normalized_options)
  215. {
  216. auto& vm = global_object.vm();
  217. // 1. Return ? GetOption(normalizedOptions, "offset", « String », « "auto", "never" », "auto").
  218. auto option = TRY(get_option(global_object, normalized_options, vm.names.offset, { OptionType::String }, { "auto"sv, "never"sv }, js_string(vm, "auto"sv)));
  219. VERIFY(option.is_string());
  220. return option.as_string().string();
  221. }
  222. // 13.14 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  223. ThrowCompletionOr<u64> to_temporal_rounding_increment(GlobalObject& global_object, Object const& normalized_options, Optional<double> dividend, bool inclusive)
  224. {
  225. auto& vm = global_object.vm();
  226. double maximum;
  227. // 1. If dividend is undefined, then
  228. if (!dividend.has_value()) {
  229. // a. Let maximum be +∞.
  230. maximum = INFINITY;
  231. }
  232. // 2. Else if inclusive is true, then
  233. else if (inclusive) {
  234. // a. Let maximum be dividend.
  235. maximum = *dividend;
  236. }
  237. // 3. Else if dividend is more than 1, then
  238. else if (*dividend > 1) {
  239. // a. Let maximum be dividend − 1.
  240. maximum = *dividend - 1;
  241. }
  242. // 4. Else,
  243. else {
  244. // a. Let maximum be 1.
  245. maximum = 1;
  246. }
  247. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", « Number », empty, 1).
  248. auto increment_value = TRY(get_option(global_object, normalized_options, vm.names.roundingIncrement, { OptionType::Number }, {}, Value(1)));
  249. VERIFY(increment_value.is_number());
  250. auto increment = increment_value.as_double();
  251. // 6. If increment < 1 or increment > maximum, throw a RangeError exception.
  252. if (increment < 1 || increment > maximum)
  253. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  254. // 7. Set increment to floor(ℝ(increment)).
  255. auto floored_increment = static_cast<u64>(increment);
  256. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  257. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0)
  258. // a. Throw a RangeError exception.
  259. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  260. // 9. Return increment.
  261. return floored_increment;
  262. }
  263. // 13.15 ToTemporalDateTimeRoundingIncrement ( normalizedOptions, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetimeroundingincrement
  264. ThrowCompletionOr<u64> to_temporal_date_time_rounding_increment(GlobalObject& global_object, Object const& normalized_options, StringView smallest_unit)
  265. {
  266. double maximum;
  267. // 1. If smallestUnit is "day", then
  268. if (smallest_unit == "day"sv) {
  269. // a. Let maximum be 1.
  270. maximum = 1;
  271. }
  272. // 2. Else if smallestUnit is "hour", then
  273. else if (smallest_unit == "hour"sv) {
  274. // a. Let maximum be 24.
  275. maximum = 24;
  276. }
  277. // 3. Else if smallestUnit is "minute" or "second", then
  278. else if (smallest_unit.is_one_of("minute"sv, "second"sv)) {
  279. // a. Let maximum be 60.
  280. maximum = 60;
  281. }
  282. // 4. Else,
  283. else {
  284. // a. Assert: smallestUnit is "millisecond", "microsecond", or "nanosecond".
  285. VERIFY(smallest_unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  286. // b. Let maximum be 1000.
  287. maximum = 1000;
  288. }
  289. // 5. Return ? ToTemporalRoundingIncrement(normalizedOptions, maximum, false).
  290. return to_temporal_rounding_increment(global_object, normalized_options, maximum, false);
  291. }
  292. // 13.16 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
  293. ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(GlobalObject& global_object, Object const& normalized_options)
  294. {
  295. auto& vm = global_object.vm();
  296. // Let smallestUnit be ? ToSmallestTemporalUnit(normalizedOptions, « "year", "month", "week", "day", "hour" », undefined).
  297. auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, normalized_options, { "year"sv, "month"sv, "week"sv, "day"sv, "hour"sv }, {}));
  298. // 2. If smallestUnit is "minute", then
  299. if (smallest_unit == "minute"sv) {
  300. // a. Return the Record { [[Precision]]: "minute", [[Unit]]: "minute", [[Increment]]: 1 }.
  301. return SecondsStringPrecision { .precision = "minute"sv, .unit = "minute"sv, .increment = 1 };
  302. }
  303. // 3. If smallestUnit is "second", then
  304. if (smallest_unit == "second"sv) {
  305. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  306. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  307. }
  308. // 4. If smallestUnit is "millisecond", then
  309. if (smallest_unit == "millisecond"sv) {
  310. // a. Return the Record { [[Precision]]: 3, [[Unit]]: "millisecond", [[Increment]]: 1 }.
  311. return SecondsStringPrecision { .precision = 3, .unit = "millisecond"sv, .increment = 1 };
  312. }
  313. // 5. If smallestUnit is "microsecond", then
  314. if (smallest_unit == "microsecond"sv) {
  315. // a. Return the Record { [[Precision]]: 6, [[Unit]]: "microsecond", [[Increment]]: 1 }.
  316. return SecondsStringPrecision { .precision = 6, .unit = "microsecond"sv, .increment = 1 };
  317. }
  318. // 6. If smallestUnit is "nanosecond", then
  319. if (smallest_unit == "nanosecond"sv) {
  320. // a. Return the Record { [[Precision]]: 9, [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  321. return SecondsStringPrecision { .precision = 9, .unit = "nanosecond"sv, .increment = 1 };
  322. }
  323. // 7. Assert: smallestUnit is undefined.
  324. VERIFY(!smallest_unit.has_value());
  325. // 8. Let digits be ? GetStringOrNumberOption(normalizedOptions, "fractionalSecondDigits", « "auto" », 0, 9, "auto").
  326. 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)));
  327. // 9. If digits is "auto", then
  328. if (digits_variant.has<String>()) {
  329. VERIFY(digits_variant.get<String>() == "auto"sv);
  330. // a. Return the Record { [[Precision]]: "auto", [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  331. return SecondsStringPrecision { .precision = "auto"sv, .unit = "nanosecond"sv, .increment = 1 };
  332. }
  333. auto digits = digits_variant.get<u8>();
  334. // 10. If digits is 0, then
  335. if (digits == 0) {
  336. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  337. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  338. }
  339. // 11. If digits is 1, 2, or 3, then
  340. if (digits == 1 || digits == 2 || digits == 3) {
  341. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "millisecond", [[Increment]]: 10^(3 − digits) }.
  342. return SecondsStringPrecision { .precision = digits, .unit = "millisecond"sv, .increment = (u32)pow(10, 3 - digits) };
  343. }
  344. // 12. If digits is 4, 5, or 6, then
  345. if (digits == 4 || digits == 5 || digits == 6) {
  346. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "microsecond", [[Increment]]: 10^(6 − digits) }.
  347. return SecondsStringPrecision { .precision = digits, .unit = "microsecond"sv, .increment = (u32)pow(10, 6 - digits) };
  348. }
  349. // 13. Assert: digits is 7, 8, or 9.
  350. VERIFY(digits == 7 || digits == 8 || digits == 9);
  351. // 14. Return the Record { [[Precision]]: digits, [[Unit]]: "nanosecond", [[Increment]]: 10^(9 − digits) }.
  352. return SecondsStringPrecision { .precision = digits, .unit = "nanosecond"sv, .increment = (u32)pow(10, 9 - digits) };
  353. }
  354. // https://tc39.es/proposal-temporal/#table-temporal-singular-and-plural-units
  355. static HashMap<StringView, StringView> plural_to_singular_units = {
  356. { "years"sv, "year"sv },
  357. { "months"sv, "month"sv },
  358. { "weeks"sv, "week"sv },
  359. { "days"sv, "day"sv },
  360. { "hours"sv, "hour"sv },
  361. { "minutes"sv, "minute"sv },
  362. { "seconds"sv, "second"sv },
  363. { "milliseconds"sv, "millisecond"sv },
  364. { "microseconds"sv, "microsecond"sv },
  365. { "nanoseconds"sv, "nanosecond"sv }
  366. };
  367. // 13.17 ToLargestTemporalUnit ( normalizedOptions, disallowedUnits, fallback [ , autoValue ] ), https://tc39.es/proposal-temporal/#sec-temporal-tolargesttemporalunit
  368. ThrowCompletionOr<String> to_largest_temporal_unit(GlobalObject& global_object, Object const& normalized_options, Vector<StringView> const& disallowed_units, String const& fallback, Optional<String> auto_value)
  369. {
  370. auto& vm = global_object.vm();
  371. // 1. Assert: disallowedUnits does not contain fallback.
  372. // 2. Assert: disallowedUnits does not contain "auto".
  373. // 3. Assert: autoValue is not present or fallback is "auto".
  374. VERIFY(!auto_value.has_value() || fallback == "auto"sv);
  375. // 4. Assert: autoValue is not present or disallowedUnits does not contain autoValue.
  376. // 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).
  377. 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 }, js_string(vm, fallback)));
  378. auto largest_unit = largest_unit_value.as_string().string();
  379. // 6. If largestUnit is "auto" and autoValue is present, then
  380. if (largest_unit == "auto"sv && auto_value.has_value()) {
  381. // a. Return autoValue.
  382. return *auto_value;
  383. }
  384. // 7. If largestUnit is in the Plural column of Table 12, then
  385. if (auto singular_unit = plural_to_singular_units.get(largest_unit); singular_unit.has_value()) {
  386. // a. Set largestUnit to the corresponding Singular value of the same row.
  387. largest_unit = singular_unit.value();
  388. }
  389. // 8. If disallowedUnits contains largestUnit, then
  390. if (disallowed_units.contains_slow(largest_unit)) {
  391. // a. Throw a RangeError exception.
  392. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, largest_unit, vm.names.largestUnit.as_string());
  393. }
  394. // 9. Return largestUnit.
  395. return largest_unit;
  396. }
  397. // 13.18 ToSmallestTemporalUnit ( normalizedOptions, disallowedUnits, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-tosmallesttemporalunit
  398. ThrowCompletionOr<Optional<String>> to_smallest_temporal_unit(GlobalObject& global_object, Object const& normalized_options, Vector<StringView> const& disallowed_units, Optional<String> fallback)
  399. {
  400. auto& vm = global_object.vm();
  401. // 1. Assert: disallowedUnits does not contain fallback.
  402. // 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).
  403. 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()));
  404. // OPTIMIZATION: We skip the following string-only checks for the fallback to tidy up the code a bit
  405. if (smallest_unit_value.is_undefined())
  406. return Optional<String> {};
  407. VERIFY(smallest_unit_value.is_string());
  408. auto smallest_unit = smallest_unit_value.as_string().string();
  409. // 3. If smallestUnit is in the Plural column of Table 12, then
  410. if (auto singular_unit = plural_to_singular_units.get(smallest_unit); singular_unit.has_value()) {
  411. // a. Set smallestUnit to the corresponding Singular value of the same row.
  412. smallest_unit = singular_unit.value();
  413. }
  414. // 4. If disallowedUnits contains smallestUnit, then
  415. if (disallowed_units.contains_slow(smallest_unit)) {
  416. // a. Throw a RangeError exception.
  417. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, smallest_unit, vm.names.smallestUnit.as_string());
  418. }
  419. // 5. Return smallestUnit.
  420. return smallest_unit;
  421. }
  422. // 13.22 ValidateTemporalUnitRange ( largestUnit, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-validatetemporalunitrange
  423. ThrowCompletionOr<void> validate_temporal_unit_range(GlobalObject& global_object, StringView largest_unit, StringView smallest_unit)
  424. {
  425. auto& vm = global_object.vm();
  426. // 1. If smallestUnit is "year" and largestUnit is not "year", then
  427. if (smallest_unit == "year"sv && largest_unit != "year"sv) {
  428. // a. Throw a RangeError exception.
  429. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  430. }
  431. // 2. If smallestUnit is "month" and largestUnit is not "year" or "month", then
  432. if (smallest_unit == "month"sv && !largest_unit.is_one_of("year"sv, "month"sv)) {
  433. // a. Throw a RangeError exception.
  434. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  435. }
  436. // 3. If smallestUnit is "week" and largestUnit is not one of "year", "month", or "week", then
  437. if (smallest_unit == "week"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv)) {
  438. // a. Throw a RangeError exception.
  439. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  440. }
  441. // 4. If smallestUnit is "day" and largestUnit is not one of "year", "month", "week", or "day", then
  442. if (smallest_unit == "day"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  443. // a. Throw a RangeError exception.
  444. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  445. }
  446. // 5. If smallestUnit is "hour" and largestUnit is not one of "year", "month", "week", "day", or "hour", then
  447. if (smallest_unit == "hour"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv, "hour"sv)) {
  448. // a. Throw a RangeError exception.
  449. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  450. }
  451. // 6. If smallestUnit is "minute" and largestUnit is "second", "millisecond", "microsecond", or "nanosecond", then
  452. if (smallest_unit == "minute"sv && largest_unit.is_one_of("second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  453. // a. Throw a RangeError exception.
  454. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  455. }
  456. // 7. If smallestUnit is "second" and largestUnit is "millisecond", "microsecond", or "nanosecond", then
  457. if (smallest_unit == "second"sv && largest_unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  458. // a. Throw a RangeError exception.
  459. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  460. }
  461. // 8. If smallestUnit is "millisecond" and largestUnit is "microsecond" or "nanosecond", then
  462. if (smallest_unit == "millisecond"sv && largest_unit.is_one_of("microsecond"sv, "nanosecond"sv)) {
  463. // a. Throw a RangeError exception.
  464. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  465. }
  466. // 9. If smallestUnit is "microsecond" and largestUnit is "nanosecond", then
  467. if (smallest_unit == "microsecond"sv && largest_unit == "nanosecond"sv) {
  468. // a. Throw a RangeError exception.
  469. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  470. }
  471. return {};
  472. }
  473. // 13.23 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  474. String larger_of_two_temporal_units(StringView unit1, StringView unit2)
  475. {
  476. // 1. If either u1 or u2 is "year", return "year".
  477. if (unit1 == "year"sv || unit2 == "year"sv)
  478. return "year"sv;
  479. // 2. If either u1 or u2 is "month", return "month".
  480. if (unit1 == "month"sv || unit2 == "month"sv)
  481. return "month"sv;
  482. // 3. If either u1 or u2 is "week", return "week".
  483. if (unit1 == "week"sv || unit2 == "week"sv)
  484. return "week"sv;
  485. // 4. If either u1 or u2 is "day", return "day".
  486. if (unit1 == "day"sv || unit2 == "day"sv)
  487. return "day"sv;
  488. // 5. If either u1 or u2 is "hour", return "hour".
  489. if (unit1 == "hour"sv || unit2 == "hour"sv)
  490. return "hour"sv;
  491. // 6. If either u1 or u2 is "minute", return "minute".
  492. if (unit1 == "minute"sv || unit2 == "minute"sv)
  493. return "minute"sv;
  494. // 7. If either u1 or u2 is "second", return "second".
  495. if (unit1 == "second"sv || unit2 == "second"sv)
  496. return "second"sv;
  497. // 8. If either u1 or u2 is "millisecond", return "millisecond".
  498. if (unit1 == "millisecond"sv || unit2 == "millisecond"sv)
  499. return "millisecond"sv;
  500. // 9. If either u1 or u2 is "microsecond", return "microsecond".
  501. if (unit1 == "microsecond"sv || unit2 == "microsecond"sv)
  502. return "microsecond"sv;
  503. // 10. Return "nanosecond".
  504. return "nanosecond"sv;
  505. }
  506. // 13.24 MergeLargestUnitOption ( options, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-mergelargestunitoption
  507. ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject& global_object, Object& options, String largest_unit)
  508. {
  509. auto& vm = global_object.vm();
  510. // 1. Let merged be ! OrdinaryObjectCreate(%Object.prototype%).
  511. auto* merged = Object::create(global_object, global_object.object_prototype());
  512. // 2. Let keys be ? EnumerableOwnPropertyNames(options, key).
  513. auto keys = TRY(options.enumerable_own_property_names(Object::PropertyKind::Key));
  514. // 3. For each element nextKey of keys, do
  515. for (auto& key : keys) {
  516. auto next_key = PropertyKey::from_value(global_object, key);
  517. // a. Let propValue be ? Get(options, nextKey).
  518. auto prop_value = TRY(options.get(next_key));
  519. // b. Perform ! CreateDataPropertyOrThrow(merged, nextKey, propValue).
  520. MUST(merged->create_data_property_or_throw(next_key, prop_value));
  521. }
  522. // 4. Perform ! CreateDataPropertyOrThrow(merged, "largestUnit", largestUnit).
  523. MUST(merged->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, move(largest_unit))));
  524. // 5. Return merged.
  525. return merged;
  526. }
  527. // 13.25 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  528. Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit)
  529. {
  530. // 1. If unit is "year", "month", "week", or "day", then
  531. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  532. // a. Return undefined.
  533. return {};
  534. }
  535. // 2. If unit is "hour", then
  536. if (unit == "hour"sv) {
  537. // a. Return 24.
  538. return 24;
  539. }
  540. // 3. If unit is "minute" or "second", then
  541. if (unit.is_one_of("minute"sv, "second"sv)) {
  542. // a. Return 60.
  543. return 60;
  544. }
  545. // 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
  546. VERIFY(unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  547. // 5. Return 1000.
  548. return 1000;
  549. }
  550. // 13.26 RejectObjectWithCalendarOrTimeZone ( object ), https://tc39.es/proposal-temporal/#sec-temporal-rejectobjectwithcalendarortimezone
  551. ThrowCompletionOr<void> reject_object_with_calendar_or_time_zone(GlobalObject& global_object, Object& object)
  552. {
  553. auto& vm = global_object.vm();
  554. // 1. Assert: Type(object) is Object.
  555. // 2. If object has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  556. if (is<PlainDate>(object) || is<PlainDateTime>(object) || is<PlainMonthDay>(object) || is<PlainTime>(object) || is<PlainYearMonth>(object) || is<ZonedDateTime>(object)) {
  557. // a. Throw a TypeError exception.
  558. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "calendar or timeZone");
  559. }
  560. // 3. Let calendarProperty be ? Get(object, "calendar").
  561. auto calendar_property = TRY(object.get(vm.names.calendar));
  562. // 4. If calendarProperty is not undefined, then
  563. if (!calendar_property.is_undefined()) {
  564. // a. Throw a TypeError exception.
  565. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "calendar");
  566. }
  567. // 5. Let timeZoneProperty be ? Get(object, "timeZone").
  568. auto time_zone_property = TRY(object.get(vm.names.timeZone));
  569. // 6. If timeZoneProperty is not undefined, then
  570. if (!time_zone_property.is_undefined()) {
  571. // a. Throw a TypeError exception.
  572. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "timeZone");
  573. }
  574. return {};
  575. }
  576. // 13.27 FormatSecondsStringPart ( second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatsecondsstringpart
  577. String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  578. {
  579. // 1. Assert: second, millisecond, microsecond and nanosecond are integers.
  580. // Non-standard sanity check
  581. if (precision.has<StringView>())
  582. VERIFY(precision.get<StringView>().is_one_of("minute"sv, "auto"sv));
  583. // 2. If precision is "minute", return "".
  584. if (precision.has<StringView>() && precision.get<StringView>() == "minute"sv)
  585. return String::empty();
  586. // 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.
  587. auto seconds_string = String::formatted(":{:02}", second);
  588. // 4. Let fraction be millisecond × 10^6 + microsecond × 10^3 + nanosecond.
  589. u32 fraction = millisecond * 1'000'000 + microsecond * 1'000 + nanosecond;
  590. String fraction_string;
  591. // 5. If precision is "auto", then
  592. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  593. // a. If fraction is 0, return secondsString.
  594. if (fraction == 0)
  595. return seconds_string;
  596. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  597. fraction_string = String::formatted("{:09}", fraction);
  598. // c. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  599. fraction_string = fraction_string.trim("0"sv, TrimMode::Right);
  600. }
  601. // 6. Else,
  602. else {
  603. // a. If precision is 0, return secondsString.
  604. if (precision.get<u8>() == 0)
  605. return seconds_string;
  606. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  607. fraction_string = String::formatted("{:09}", fraction);
  608. // c. Set fraction to the substring of fraction from 0 to precision.
  609. fraction_string = fraction_string.substring(0, precision.get<u8>());
  610. }
  611. // 7. Return the string-concatenation of secondsString, the code unit 0x002E (FULL STOP), and fraction.
  612. return String::formatted("{}.{}", seconds_string, fraction_string);
  613. }
  614. // 13.28 Sign ( n ), https://tc39.es/proposal-temporal/#sec-temporal-sign
  615. double sign(double n)
  616. {
  617. // 1. If n is NaN, n is +0𝔽, or n is −0𝔽, return n.
  618. if (isnan(n) || n == 0)
  619. return n;
  620. // 2. If n < +0𝔽, return −1𝔽.
  621. if (n < 0)
  622. return -1;
  623. // 3. Return 1𝔽.
  624. return 1;
  625. }
  626. // 13.29 ConstrainToRange ( x, minimum, maximum ), https://tc39.es/proposal-temporal/#sec-temporal-constraintorange
  627. double constrain_to_range(double x, double minimum, double maximum)
  628. {
  629. // 1. Assert: x, minimum and maximum are mathematical values.
  630. // 2. Return min(max(x, minimum), maximum).
  631. return min(max(x, minimum), maximum);
  632. }
  633. // NOTE: We have two variants of this function, one using doubles and one using BigInts - most of the time
  634. // doubles will be fine, but take care to choose the right one. The spec is not very clear about this, as
  635. // it uses mathematical values which can be arbitrarily (but not infinitely) large.
  636. // Incidentally V8's Temporal implementation does the same :^)
  637. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  638. i64 round_number_to_increment(double x, u64 increment, StringView rounding_mode)
  639. {
  640. // 1. Assert: x and increment are mathematical values.
  641. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  642. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  643. // 3. Let quotient be x / increment.
  644. auto quotient = x / (double)increment;
  645. double rounded;
  646. // 4. If roundingMode is "ceil", then
  647. if (rounding_mode == "ceil"sv) {
  648. // a. Let rounded be −floor(−quotient).
  649. rounded = -floor(-quotient);
  650. }
  651. // 5. Else if roundingMode is "floor", then
  652. else if (rounding_mode == "floor"sv) {
  653. // a. Let rounded be floor(quotient).
  654. rounded = floor(quotient);
  655. }
  656. // 6. Else if roundingMode is "trunc", then
  657. else if (rounding_mode == "trunc"sv) {
  658. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  659. rounded = trunc(quotient);
  660. }
  661. // 7. Else,
  662. else {
  663. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  664. rounded = round(quotient);
  665. }
  666. // 8. Return rounded × increment.
  667. return (i64)rounded * (i64)increment;
  668. }
  669. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  670. BigInt* round_number_to_increment(GlobalObject& global_object, BigInt const& x, u64 increment, StringView rounding_mode)
  671. {
  672. auto& heap = global_object.heap();
  673. // 1. Assert: x and increment are mathematical values.
  674. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  675. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  676. // OPTIMIZATION: If the increment is 1 the number is always rounded
  677. if (increment == 1)
  678. return js_bigint(heap, x.big_integer());
  679. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  680. // 3. Let quotient be x / increment.
  681. auto division_result = x.big_integer().divided_by(increment_big_int);
  682. // OPTIMIZATION: If there's no remainder the number is already rounded
  683. if (division_result.remainder == Crypto::UnsignedBigInteger { 0 })
  684. return js_bigint(heap, x.big_integer());
  685. Crypto::SignedBigInteger rounded = move(division_result.quotient);
  686. // 4. If roundingMode is "ceil", then
  687. if (rounding_mode == "ceil"sv) {
  688. // a. Let rounded be −floor(−quotient).
  689. if (!division_result.remainder.is_negative())
  690. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  691. }
  692. // 5. Else if roundingMode is "floor", then
  693. else if (rounding_mode == "floor"sv) {
  694. // a. Let rounded be floor(quotient).
  695. if (division_result.remainder.is_negative())
  696. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  697. }
  698. // 6. Else if roundingMode is "trunc", then
  699. else if (rounding_mode == "trunc"sv) {
  700. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  701. // NOTE: This is a no-op
  702. }
  703. // 7. Else,
  704. else {
  705. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  706. if (division_result.remainder.multiplied_by(Crypto::UnsignedBigInteger { 2 }).unsigned_value() >= increment_big_int) {
  707. if (division_result.remainder.is_negative())
  708. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  709. else
  710. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  711. }
  712. }
  713. // 8. Return rounded × increment.
  714. return js_bigint(heap, rounded.multiplied_by(increment_big_int));
  715. }
  716. // 13.34 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  717. ThrowCompletionOr<ISODateTime> parse_iso_date_time(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  718. {
  719. auto& vm = global_object.vm();
  720. // 1. Assert: Type(isoString) is String.
  721. // 2. Let year, month, day, hour, minute, second, fraction, and calendar be the parts of isoString produced respectively by the DateYear, DateMonth, DateDay, TimeHour, TimeMinute, TimeSecond, TimeFractionalPart, and CalendarName productions, or undefined if not present.
  722. Optional<StringView> year_part;
  723. Optional<StringView> month_part;
  724. Optional<StringView> day_part;
  725. Optional<StringView> hour_part;
  726. Optional<StringView> minute_part;
  727. Optional<StringView> second_part;
  728. Optional<StringView> fraction_part;
  729. Optional<StringView> calendar_part;
  730. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseISODateTime");
  731. // 3. Let year be the part of isoString produced by the DateYear production.
  732. // 4. If the first code unit of year is 0x2212 (MINUS SIGN), replace it with the code unit 0x002D (HYPHEN-MINUS).
  733. String normalized_year;
  734. if (year_part.has_value() && year_part->starts_with("\xE2\x88\x92"sv))
  735. normalized_year = String::formatted("-{}", year_part->substring_view(3));
  736. else
  737. normalized_year = year_part.value_or("");
  738. // 5. Set year to ! ToIntegerOrInfinity(year).
  739. i32 year = MUST(Value(js_string(vm, normalized_year)).to_integer_or_infinity(global_object));
  740. u8 month;
  741. // 6. If month is undefined, then
  742. if (!month_part.has_value()) {
  743. // a. Set month to 1.
  744. month = 1;
  745. }
  746. // 7. Else,
  747. else {
  748. // a. Set month to ! ToIntegerOrInfinity(month).
  749. month = *month_part->to_uint<u8>();
  750. }
  751. u8 day;
  752. // 8. If day is undefined, then
  753. if (!day_part.has_value()) {
  754. // a. Set day to 1.
  755. day = 1;
  756. }
  757. // 9. Else,
  758. else {
  759. // a. Set day to ! ToIntegerOrInfinity(day).
  760. day = *day_part->to_uint<u8>();
  761. }
  762. // 10. Set hour to ! ToIntegerOrInfinity(hour).
  763. u8 hour = hour_part->to_uint<u8>().value_or(0);
  764. // 11. Set minute to ! ToIntegerOrInfinity(minute).
  765. u8 minute = minute_part->to_uint<u8>().value_or(0);
  766. // 12. Set second to ! ToIntegerOrInfinity(second).
  767. u8 second = second_part->to_uint<u8>().value_or(0);
  768. // 13. If second is 60, then
  769. if (second == 60) {
  770. // a. Set second to 59.
  771. second = 59;
  772. }
  773. u16 millisecond;
  774. u16 microsecond;
  775. u16 nanosecond;
  776. // 14. If fraction is not undefined, then
  777. if (fraction_part.has_value()) {
  778. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  779. auto fraction = String::formatted("{}000000000", *fraction_part);
  780. // b. Let millisecond be the String value equal to the substring of fraction from 0 to 3.
  781. // c. Set millisecond to ! ToIntegerOrInfinity(millisecond).
  782. millisecond = *fraction.substring(0, 3).to_uint<u16>();
  783. // d. Let microsecond be the String value equal to the substring of fraction from 3 to 6.
  784. // e. Set microsecond to ! ToIntegerOrInfinity(microsecond).
  785. microsecond = *fraction.substring(3, 3).to_uint<u16>();
  786. // f. Let nanosecond be the String value equal to the substring of fraction from 6 to 9.
  787. // g. Set nanosecond to ! ToIntegerOrInfinity(nanosecond).
  788. nanosecond = *fraction.substring(6, 3).to_uint<u16>();
  789. }
  790. // 15. Else,
  791. else {
  792. // a. Let millisecond be 0.
  793. millisecond = 0;
  794. // b. Let microsecond be 0.
  795. microsecond = 0;
  796. // c. Let nanosecond be 0.
  797. nanosecond = 0;
  798. }
  799. // 16. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  800. if (!is_valid_iso_date(year, month, day))
  801. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidISODate);
  802. // 17. If ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  803. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  804. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTime);
  805. // 18. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond, [[Calendar]]: calendar }.
  806. return ISODateTime { .year = year, .month = month, .day = day, .hour = hour, .minute = minute, .second = second, .millisecond = millisecond, .microsecond = microsecond, .nanosecond = nanosecond, .calendar = calendar_part.has_value() ? *calendar_part : Optional<String>() };
  807. }
  808. // 13.35 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  809. ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject& global_object, String const& iso_string)
  810. {
  811. // 1. Assert: Type(isoString) is String.
  812. // 2. If isoString does not satisfy the syntax of a TemporalInstantString (see 13.33), then
  813. // a. Throw a RangeError exception.
  814. // TODO
  815. // 3. Let result be ! ParseISODateTime(isoString).
  816. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  817. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  818. auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string));
  819. // 5. Let offsetString be timeZoneResult.[[OffsetString]].
  820. auto offset_string = time_zone_result.offset;
  821. // 6. If timeZoneResult.[[Z]] is true, then
  822. if (time_zone_result.z) {
  823. // a. Set offsetString to "+00:00".
  824. offset_string = "+00:00"sv;
  825. }
  826. // 7. Assert: offsetString is not undefined.
  827. VERIFY(offset_string.has_value());
  828. // 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 }.
  829. 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) };
  830. }
  831. // 13.36 ParseTemporalZonedDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalzoneddatetimestring
  832. ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_zoned_date_time_string(GlobalObject& global_object, String const& iso_string)
  833. {
  834. // 1. Assert: Type(isoString) is String.
  835. // 2. If isoString does not satisfy the syntax of a TemporalZonedDateTimeString (see 13.33), then
  836. // a. Throw a RangeError exception.
  837. // TODO
  838. // 3. Let result be ! ParseISODateTime(isoString).
  839. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  840. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  841. auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string));
  842. // 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]] }.
  843. // 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.
  844. // InterpretTemporalDateTimeFields returns an ISODateTime, so the moved in `result` here is subsequently moved into ParseTemporalZonedDateTimeString's `result` variable.
  845. return TemporalZonedDateTime { .date_time = move(result), .time_zone = move(time_zone_result) };
  846. }
  847. // 13.37 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  848. ThrowCompletionOr<String> parse_temporal_calendar_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  849. {
  850. auto& vm = global_object.vm();
  851. // 1. Assert: Type(isoString) is String.
  852. // 2. If isoString does not satisfy the syntax of a TemporalCalendarString (see 13.33), then
  853. // a. Throw a RangeError exception.
  854. // 3. Let id be the part of isoString produced by the CalendarName production, or undefined if not present.
  855. Optional<StringView> id_part;
  856. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalCalendarString");
  857. // 4. If id is undefined, then
  858. if (!id_part.has_value()) {
  859. // a. Return "iso8601".
  860. return "iso8601"sv;
  861. }
  862. // 5. If ! IsBuiltinCalendar(id) is false, then
  863. if (!is_builtin_calendar(*id_part)) {
  864. // a. Throw a RangeError exception.
  865. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, *id_part);
  866. }
  867. // 6. Return id.
  868. return id_part.value();
  869. }
  870. // 13.38 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  871. ThrowCompletionOr<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string)
  872. {
  873. // 1. Assert: Type(isoString) is String.
  874. // 2. If isoString does not satisfy the syntax of a TemporalDateString (see 13.33), then
  875. // a. Throw a RangeError exception.
  876. // TODO
  877. // 3. Let result be ? ParseISODateTime(isoString).
  878. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  879. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  880. return TemporalDate { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  881. }
  882. // 13.39 ParseTemporalDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatetimestring
  883. ThrowCompletionOr<ISODateTime> parse_temporal_date_time_string(GlobalObject& global_object, String const& iso_string)
  884. {
  885. // 1. Assert: Type(isoString) is String.
  886. // 2. If isoString does not satisfy the syntax of a TemporalDateTimeString (see 13.33), then
  887. // a. Throw a RangeError exception.
  888. // TODO
  889. // 3. Let result be ? ParseISODateTime(isoString).
  890. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  891. // 4. Return result.
  892. return result;
  893. }
  894. // 13.40 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  895. ThrowCompletionOr<TemporalDuration> parse_temporal_duration_string(GlobalObject& global_object, String const& iso_string)
  896. {
  897. (void)iso_string;
  898. auto& vm = global_object.vm();
  899. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalDurationString");
  900. }
  901. // 13.41 ParseTemporalMonthDayString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalmonthdaystring
  902. ThrowCompletionOr<TemporalMonthDay> parse_temporal_month_day_string(GlobalObject& global_object, String const& iso_string)
  903. {
  904. // 1. Assert: Type(isoString) is String.
  905. // 2. If isoString does not satisfy the syntax of a TemporalMonthDayString (see 13.33), then
  906. // a. Throw a RangeError exception.
  907. // TODO
  908. // 3. Let result be ? ParseISODateTime(isoString).
  909. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  910. // 4. Let year be result.[[Year]].
  911. Optional<i32> year = result.year;
  912. // 5. If no part of isoString is produced by the DateYear production, then
  913. // a. Set year to undefined.
  914. // TODO (this is the case when TemporalMonthDayString is a DateSpecMonthDay)
  915. // 6. Return the Record { [[Year]]: year, [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  916. return TemporalMonthDay { .year = year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  917. }
  918. // 13.43 ParseTemporalTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimestring
  919. ThrowCompletionOr<TemporalTime> parse_temporal_time_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  920. {
  921. // 1. Assert: Type(isoString) is String.
  922. // 2. If isoString does not satisfy the syntax of a TemporalTimeString (see 13.33), then
  923. // a. Throw a RangeError exception.
  924. // TODO
  925. // 3. Let result be ? ParseISODateTime(isoString).
  926. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  927. // 4. Return the Record { [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[Calendar]]: result.[[Calendar]] }.
  928. return TemporalTime { .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .calendar = move(result.calendar) };
  929. }
  930. // 13.44 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  931. ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  932. {
  933. auto& vm = global_object.vm();
  934. // 1. Assert: Type(isoString) is String.
  935. // 2. If isoString does not satisfy the syntax of a TemporalTimeZoneString (see 13.33), then
  936. // a. Throw a RangeError exception.
  937. // 3. Let z, sign, hours, minutes, seconds, fraction and name be the parts of isoString produced respectively by the UTCDesignator, TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, TimeZoneUTCOffsetFractionalPart, and TimeZoneIANAName productions, or undefined if not present.
  938. Optional<StringView> z_part;
  939. Optional<StringView> sign_part;
  940. Optional<StringView> hours_part;
  941. Optional<StringView> minutes_part;
  942. Optional<StringView> seconds_part;
  943. Optional<StringView> fraction_part;
  944. Optional<StringView> name_part;
  945. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalTimeZoneString");
  946. // 4. If z is not undefined, then
  947. if (z_part.has_value()) {
  948. // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
  949. return TemporalTimeZone { .z = true, .offset = {}, .name = name_part.has_value() ? String { *name_part } : Optional<String> {} };
  950. }
  951. Optional<String> offset;
  952. // 5. If hours is undefined, then
  953. if (!hours_part.has_value()) {
  954. // a. Let offsetString be undefined.
  955. // NOTE: No-op.
  956. }
  957. // 6. Else,
  958. else {
  959. // a. Assert: sign is not undefined.
  960. VERIFY(sign_part.has_value());
  961. // b. Set hours to ! ToIntegerOrInfinity(hours).
  962. u8 hours = MUST(Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object));
  963. u8 sign;
  964. // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then
  965. if (sign_part->is_one_of("-", "\u2212")) {
  966. // i. Set sign to −1.
  967. sign = -1;
  968. }
  969. // d. Else,
  970. else {
  971. // i. Set sign to 1.
  972. sign = 1;
  973. }
  974. // e. Set minutes to ! ToIntegerOrInfinity(minutes).
  975. u8 minutes = MUST(Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object));
  976. // f. Set seconds to ! ToIntegerOrInfinity(seconds).
  977. u8 seconds = MUST(Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object));
  978. i32 nanoseconds;
  979. // g. If fraction is not undefined, then
  980. if (fraction_part.has_value()) {
  981. // i. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  982. auto fraction = String::formatted("{}000000000", *fraction_part);
  983. // ii. Let nanoseconds be the String value equal to the substring of fraction from 1 to 10.
  984. // iii. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  985. nanoseconds = MUST(Value(js_string(vm, fraction.substring(1, 10))).to_integer_or_infinity(global_object));
  986. }
  987. // h. Else,
  988. else {
  989. // i. Let nanoseconds be 0.
  990. nanoseconds = 0;
  991. }
  992. // i. Let offsetNanoseconds be sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  993. auto offset_nanoseconds = sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  994. // j. Let offsetString be ! FormatTimeZoneOffsetString(offsetNanoseconds).
  995. offset = format_time_zone_offset_string(offset_nanoseconds);
  996. }
  997. Optional<String> name;
  998. // 7. If name is not undefined, then
  999. if (name_part.has_value()) {
  1000. // a. If ! IsValidTimeZoneName(name) is false, throw a RangeError exception.
  1001. if (!is_valid_time_zone_name(*name_part))
  1002. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName);
  1003. // b. Set name to ! CanonicalizeTimeZoneName(name).
  1004. name = canonicalize_time_zone_name(*name_part);
  1005. }
  1006. // 8. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
  1007. return TemporalTimeZone { .z = false, .offset = offset, .name = name };
  1008. }
  1009. // 13.45 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
  1010. ThrowCompletionOr<TemporalYearMonth> parse_temporal_year_month_string(GlobalObject& global_object, String const& iso_string)
  1011. {
  1012. // 1. Assert: Type(isoString) is String.
  1013. // 2. If isoString does not satisfy the syntax of a TemporalYearMonthString (see 13.33), then
  1014. // a. Throw a RangeError exception.
  1015. // TODO
  1016. // 3. Let result be ? ParseISODateTime(isoString).
  1017. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1018. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1019. return TemporalYearMonth { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1020. }
  1021. // 13.46 ToPositiveInteger ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveinteger
  1022. ThrowCompletionOr<double> to_positive_integer(GlobalObject& global_object, Value argument)
  1023. {
  1024. auto& vm = global_object.vm();
  1025. // 1. Let integer be ? ToIntegerThrowOnInfinity(argument).
  1026. auto integer = TRY(to_integer_throw_on_infinity(global_object, argument, ErrorType::TemporalPropertyMustBePositiveInteger));
  1027. // 2. If integer ≤ 0, then
  1028. if (integer <= 0) {
  1029. // a. Throw a RangeError exception.
  1030. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalPropertyMustBePositiveInteger);
  1031. }
  1032. // 3. Return integer.
  1033. return integer;
  1034. }
  1035. // 13.48 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  1036. ThrowCompletionOr<Object*> prepare_temporal_fields(GlobalObject& global_object, Object const& fields, Vector<String> const& field_names, Vector<StringView> const& required_fields)
  1037. {
  1038. auto& vm = global_object.vm();
  1039. // 1. Assert: Type(fields) is Object.
  1040. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  1041. auto* result = Object::create(global_object, global_object.object_prototype());
  1042. VERIFY(result);
  1043. // 3. For each value property of fieldNames, do
  1044. for (auto& property : field_names) {
  1045. // a. Let value be ? Get(fields, property).
  1046. auto value = TRY(fields.get(property));
  1047. // b. If value is undefined, then
  1048. if (value.is_undefined()) {
  1049. // i. If requiredFields contains property, then
  1050. if (required_fields.contains_slow(property)) {
  1051. // 1. Throw a TypeError exception.
  1052. return vm.throw_completion<TypeError>(global_object, ErrorType::MissingRequiredProperty, property);
  1053. }
  1054. // ii. If property is in the Property column of Table 13, then
  1055. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  1056. if (property.is_one_of("hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  1057. // 1. Set value to the corresponding Default value of the same row.
  1058. value = Value(0);
  1059. }
  1060. }
  1061. // c. Else,
  1062. else {
  1063. // i. If property is in the Property column of Table 13 and there is a Conversion value in the same row, then
  1064. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  1065. // 2. Set value to ? Conversion(value).
  1066. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv))
  1067. value = Value(TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite)));
  1068. else if (property.is_one_of("month"sv, "day"sv))
  1069. value = Value(TRY(to_positive_integer(global_object, value)));
  1070. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv))
  1071. value = TRY(value.to_primitive_string(global_object));
  1072. }
  1073. // d. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1074. MUST(result->create_data_property_or_throw(property, value));
  1075. }
  1076. // 4. Return result.
  1077. return result;
  1078. }
  1079. // 13.49 PreparePartialTemporalFields ( fields, fieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-preparepartialtemporalfields
  1080. ThrowCompletionOr<Object*> prepare_partial_temporal_fields(GlobalObject& global_object, Object const& fields, Vector<String> const& field_names)
  1081. {
  1082. auto& vm = global_object.vm();
  1083. // 1. Assert: Type(fields) is Object.
  1084. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  1085. auto* result = Object::create(global_object, global_object.object_prototype());
  1086. // 3. Let any be false.
  1087. auto any = false;
  1088. // 4. For each value property of fieldNames, do
  1089. for (auto& property : field_names) {
  1090. // a. Let value be ? Get(fields, property).
  1091. auto value = TRY(fields.get(property));
  1092. // b. If value is not undefined, then
  1093. if (!value.is_undefined()) {
  1094. // i. Set any to true.
  1095. any = true;
  1096. // ii. If property is in the Property column of Table 13, then
  1097. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  1098. // 2. Set value to ? Conversion(value).
  1099. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv))
  1100. value = Value(TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite)));
  1101. else if (property.is_one_of("month"sv, "day"sv))
  1102. value = Value(TRY(to_positive_integer(global_object, value)));
  1103. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv))
  1104. value = TRY(value.to_primitive_string(global_object));
  1105. // NOTE: According to the spec this is step 4c, but I believe that's incorrect. See https://github.com/tc39/proposal-temporal/issues/1910.
  1106. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1107. MUST(result->create_data_property_or_throw(property, value));
  1108. }
  1109. }
  1110. // 5. If any is false, then
  1111. if (!any) {
  1112. // a. Throw a TypeError exception.
  1113. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustHaveOneOf, String::join(", "sv, field_names));
  1114. }
  1115. // 6. Return result.
  1116. return result;
  1117. }
  1118. }