AbstractOperations.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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/PropertyName.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. iterator_close(*iterator_record);
  59. return completion;
  60. }
  61. // iii. Append nextValue to the end of the List values.
  62. values.append(next_value);
  63. }
  64. }
  65. // 5. Return values.
  66. return { move(values) };
  67. }
  68. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  69. ThrowCompletionOr<Object*> get_options_object(GlobalObject& global_object, Value options)
  70. {
  71. auto& vm = global_object.vm();
  72. // 1. If options is undefined, then
  73. if (options.is_undefined()) {
  74. // a. Return ! OrdinaryObjectCreate(null).
  75. return Object::create(global_object, nullptr);
  76. }
  77. // 2. If Type(options) is Object, then
  78. if (options.is_object()) {
  79. // a. Return options.
  80. return &options.as_object();
  81. }
  82. // 3. Throw a TypeError exception.
  83. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, "Options");
  84. }
  85. // 13.3 GetOption ( options, property, types, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  86. ThrowCompletionOr<Value> get_option(GlobalObject& global_object, Object const& options, PropertyName const& property, Vector<OptionType> const& types, Vector<StringView> const& values, Value fallback)
  87. {
  88. VERIFY(property.is_string());
  89. auto& vm = global_object.vm();
  90. // 1. Assert: Type(options) is Object.
  91. // 2. Assert: Each element of types is Boolean, String, or Number.
  92. // 3. Let value be ? Get(options, property).
  93. auto value = TRY(options.get(property));
  94. // 4. If value is undefined, return fallback.
  95. if (value.is_undefined())
  96. return fallback;
  97. OptionType type;
  98. // 5. If types contains Type(value), then
  99. if (auto value_type = to_option_type(value); value_type.has_value() && types.contains_slow(*value_type)) {
  100. // a. Let type be Type(value).
  101. type = *value_type;
  102. }
  103. // 6. Else,
  104. else {
  105. // a. Let type be the last element of types.
  106. type = types.last();
  107. }
  108. // 7. If type is Boolean, then
  109. if (type == OptionType::Boolean) {
  110. // a. Set value to ! ToBoolean(value).
  111. value = Value(value.to_boolean());
  112. }
  113. // 8. Else if type is Number, then
  114. else if (type == OptionType::Number) {
  115. // a. Set value to ? ToNumber(value).
  116. value = TRY(value.to_number(global_object));
  117. // b. If value is NaN, throw a RangeError exception.
  118. if (value.is_nan())
  119. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property.as_string());
  120. }
  121. // 9. Else,
  122. else {
  123. // a. Set value to ? ToString(value).
  124. value = TRY(value.to_primitive_string(global_object));
  125. }
  126. // 10. If values is not empty, then
  127. if (!values.is_empty()) {
  128. VERIFY(value.is_string());
  129. // a. If values does not contain value, throw a RangeError exception.
  130. if (!values.contains_slow(value.as_string().string()))
  131. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  132. }
  133. // 11. Return value.
  134. return value;
  135. }
  136. // 13.4 GetStringOrNumberOption ( options, property, stringValues, minimum, maximum, fallback ), https://tc39.es/proposal-temporal/#sec-getstringornumberoption
  137. template<typename NumberType>
  138. ThrowCompletionOr<Variant<String, NumberType>> get_string_or_number_option(GlobalObject& global_object, Object const& options, PropertyName const& property, Vector<StringView> const& string_values, NumberType minimum, NumberType maximum, Value fallback)
  139. {
  140. auto& vm = global_object.vm();
  141. // 1. Assert: Type(options) is Object.
  142. // 2. Let value be ? GetOption(options, property, « Number, String », empty, fallback).
  143. auto value = TRY(get_option(global_object, options, property, { OptionType::Number, OptionType::String }, {}, fallback));
  144. // 3. If Type(value) is Number, then
  145. if (value.is_number()) {
  146. // a. If value < minimum or value > maximum, throw a RangeError exception.
  147. if (value.as_double() < minimum || value.as_double() > maximum)
  148. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_double(), property.as_string());
  149. // b. Return floor(ℝ(value)).
  150. return { static_cast<NumberType>(floor(value.as_double())) };
  151. }
  152. // 4. Assert: Type(value) is String.
  153. VERIFY(value.is_string());
  154. // 5. If stringValues does not contain value, throw a RangeError exception.
  155. if (!string_values.contains_slow(value.as_string().string()))
  156. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  157. // 6. Return value.
  158. return { value.as_string().string() };
  159. }
  160. // 13.6 ToTemporalOverflow ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  161. ThrowCompletionOr<String> to_temporal_overflow(GlobalObject& global_object, Object const& normalized_options)
  162. {
  163. auto& vm = global_object.vm();
  164. // 1. Return ? GetOption(normalizedOptions, "overflow", « String », « "constrain", "reject" », "constrain").
  165. auto option = TRY(get_option(global_object, normalized_options, vm.names.overflow, { OptionType::String }, { "constrain"sv, "reject"sv }, js_string(vm, "constrain")));
  166. VERIFY(option.is_string());
  167. return option.as_string().string();
  168. }
  169. // 13.8 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  170. ThrowCompletionOr<String> to_temporal_rounding_mode(GlobalObject& global_object, Object const& normalized_options, String const& fallback)
  171. {
  172. auto& vm = global_object.vm();
  173. // 1. Return ? GetOption(normalizedOptions, "roundingMode", « String », « "ceil", "floor", "trunc", "halfExpand" », fallback).
  174. 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)));
  175. VERIFY(option.is_string());
  176. return option.as_string().string();
  177. }
  178. // 13.11 ToShowCalendarOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowcalendaroption
  179. ThrowCompletionOr<String> to_show_calendar_option(GlobalObject& global_object, Object const& normalized_options)
  180. {
  181. auto& vm = global_object.vm();
  182. // 1. Return ? GetOption(normalizedOptions, "calendarName", « String », « "auto", "always", "never" », "auto").
  183. 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)));
  184. VERIFY(option.is_string());
  185. return option.as_string().string();
  186. }
  187. // 13.14 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  188. ThrowCompletionOr<u64> to_temporal_rounding_increment(GlobalObject& global_object, Object const& normalized_options, Optional<double> dividend, bool inclusive)
  189. {
  190. auto& vm = global_object.vm();
  191. double maximum;
  192. // 1. If dividend is undefined, then
  193. if (!dividend.has_value()) {
  194. // a. Let maximum be +∞.
  195. maximum = INFINITY;
  196. }
  197. // 2. Else if inclusive is true, then
  198. else if (inclusive) {
  199. // a. Let maximum be dividend.
  200. maximum = *dividend;
  201. }
  202. // 3. Else if dividend is more than 1, then
  203. else if (*dividend > 1) {
  204. // a. Let maximum be dividend − 1.
  205. maximum = *dividend - 1;
  206. }
  207. // 4. Else,
  208. else {
  209. // a. Let maximum be 1.
  210. maximum = 1;
  211. }
  212. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", « Number », empty, 1).
  213. auto increment_value = TRY(get_option(global_object, normalized_options, vm.names.roundingIncrement, { OptionType::Number }, {}, Value(1)));
  214. VERIFY(increment_value.is_number());
  215. auto increment = increment_value.as_double();
  216. // 6. If increment < 1 or increment > maximum, throw a RangeError exception.
  217. if (increment < 1 || increment > maximum)
  218. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  219. // 7. Set increment to floor(ℝ(increment)).
  220. auto floored_increment = static_cast<u64>(increment);
  221. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  222. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0)
  223. // a. Throw a RangeError exception.
  224. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  225. // 9. Return increment.
  226. return floored_increment;
  227. }
  228. // 13.16 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
  229. ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(GlobalObject& global_object, Object const& normalized_options)
  230. {
  231. auto& vm = global_object.vm();
  232. // Let smallestUnit be ? ToSmallestTemporalUnit(normalizedOptions, « "year", "month", "week", "day", "hour" », undefined).
  233. auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, normalized_options, { "year"sv, "month"sv, "week"sv, "day"sv, "hour"sv }, {}));
  234. // 2. If smallestUnit is "minute", then
  235. if (smallest_unit == "minute"sv) {
  236. // a. Return the Record { [[Precision]]: "minute", [[Unit]]: "minute", [[Increment]]: 1 }.
  237. return SecondsStringPrecision { .precision = "minute"sv, .unit = "minute"sv, .increment = 1 };
  238. }
  239. // 3. If smallestUnit is "second", then
  240. if (smallest_unit == "second"sv) {
  241. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  242. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  243. }
  244. // 4. If smallestUnit is "millisecond", then
  245. if (smallest_unit == "millisecond"sv) {
  246. // a. Return the Record { [[Precision]]: 3, [[Unit]]: "millisecond", [[Increment]]: 1 }.
  247. return SecondsStringPrecision { .precision = 3, .unit = "millisecond"sv, .increment = 1 };
  248. }
  249. // 5. If smallestUnit is "microsecond", then
  250. if (smallest_unit == "microsecond"sv) {
  251. // a. Return the Record { [[Precision]]: 6, [[Unit]]: "microsecond", [[Increment]]: 1 }.
  252. return SecondsStringPrecision { .precision = 6, .unit = "microsecond"sv, .increment = 1 };
  253. }
  254. // 6. If smallestUnit is "nanosecond", then
  255. if (smallest_unit == "nanosecond"sv) {
  256. // a. Return the Record { [[Precision]]: 9, [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  257. return SecondsStringPrecision { .precision = 9, .unit = "nanosecond"sv, .increment = 1 };
  258. }
  259. // 7. Assert: smallestUnit is undefined.
  260. VERIFY(!smallest_unit.has_value());
  261. // 8. Let digits be ? GetStringOrNumberOption(normalizedOptions, "fractionalSecondDigits", « "auto" », 0, 9, "auto").
  262. 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)));
  263. // 9. If digits is "auto", then
  264. if (digits_variant.has<String>()) {
  265. VERIFY(digits_variant.get<String>() == "auto"sv);
  266. // a. Return the Record { [[Precision]]: "auto", [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  267. return SecondsStringPrecision { .precision = "auto"sv, .unit = "nanosecond"sv, .increment = 1 };
  268. }
  269. auto digits = digits_variant.get<u8>();
  270. // 10. If digits is 0, then
  271. if (digits == 0) {
  272. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  273. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  274. }
  275. // 11. If digits is 1, 2, or 3, then
  276. if (digits == 1 || digits == 2 || digits == 3) {
  277. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "millisecond", [[Increment]]: 10^(3 − digits) }.
  278. return SecondsStringPrecision { .precision = digits, .unit = "millisecond"sv, .increment = (u32)pow(10, 3 - digits) };
  279. }
  280. // 12. If digits is 4, 5, or 6, then
  281. if (digits == 4 || digits == 5 || digits == 6) {
  282. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "microsecond", [[Increment]]: 10^(6 − digits) }.
  283. return SecondsStringPrecision { .precision = digits, .unit = "microsecond"sv, .increment = (u32)pow(10, 6 - digits) };
  284. }
  285. // 13. Assert: digits is 7, 8, or 9.
  286. VERIFY(digits == 7 || digits == 8 || digits == 9);
  287. // 14. Return the Record { [[Precision]]: digits, [[Unit]]: "nanosecond", [[Increment]]: 10^(9 − digits) }.
  288. return SecondsStringPrecision { .precision = digits, .unit = "nanosecond"sv, .increment = (u32)pow(10, 9 - digits) };
  289. }
  290. // https://tc39.es/proposal-temporal/#table-temporal-singular-and-plural-units
  291. static HashMap<StringView, StringView> plural_to_singular_units = {
  292. { "years"sv, "year"sv },
  293. { "months"sv, "month"sv },
  294. { "weeks"sv, "week"sv },
  295. { "days"sv, "day"sv },
  296. { "hours"sv, "hour"sv },
  297. { "minutes"sv, "minute"sv },
  298. { "seconds"sv, "second"sv },
  299. { "milliseconds"sv, "millisecond"sv },
  300. { "microseconds"sv, "microsecond"sv },
  301. { "nanoseconds"sv, "nanosecond"sv }
  302. };
  303. // 13.17 ToLargestTemporalUnit ( normalizedOptions, disallowedUnits, fallback [ , autoValue ] ), https://tc39.es/proposal-temporal/#sec-temporal-tolargesttemporalunit
  304. 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)
  305. {
  306. auto& vm = global_object.vm();
  307. // 1. Assert: disallowedUnits does not contain fallback.
  308. // 2. Assert: disallowedUnits does not contain "auto".
  309. // 3. Assert: autoValue is not present or fallback is "auto".
  310. VERIFY(!auto_value.has_value() || fallback == "auto"sv);
  311. // 4. Assert: autoValue is not present or disallowedUnits does not contain autoValue.
  312. // 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).
  313. 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)));
  314. auto largest_unit = largest_unit_value.as_string().string();
  315. // 6. If largestUnit is "auto" and autoValue is present, then
  316. if (largest_unit == "auto"sv && auto_value.has_value()) {
  317. // a. Return autoValue.
  318. return *auto_value;
  319. }
  320. // 7. If largestUnit is in the Plural column of Table 12, then
  321. if (auto singular_unit = plural_to_singular_units.get(largest_unit); singular_unit.has_value()) {
  322. // a. Set largestUnit to the corresponding Singular value of the same row.
  323. largest_unit = singular_unit.value();
  324. }
  325. // 8. If disallowedUnits contains largestUnit, then
  326. if (disallowed_units.contains_slow(largest_unit)) {
  327. // a. Throw a RangeError exception.
  328. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, largest_unit, vm.names.largestUnit.as_string());
  329. }
  330. // 9. Return largestUnit.
  331. return largest_unit;
  332. }
  333. // 13.18 ToSmallestTemporalUnit ( normalizedOptions, disallowedUnits, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-tosmallesttemporalunit
  334. ThrowCompletionOr<Optional<String>> to_smallest_temporal_unit(GlobalObject& global_object, Object const& normalized_options, Vector<StringView> const& disallowed_units, Optional<String> fallback)
  335. {
  336. auto& vm = global_object.vm();
  337. // 1. Assert: disallowedUnits does not contain fallback.
  338. // 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).
  339. 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()));
  340. // OPTIMIZATION: We skip the following string-only checks for the fallback to tidy up the code a bit
  341. if (smallest_unit_value.is_undefined())
  342. return Optional<String> {};
  343. VERIFY(smallest_unit_value.is_string());
  344. auto smallest_unit = smallest_unit_value.as_string().string();
  345. // 3. If smallestUnit is in the Plural column of Table 12, then
  346. if (auto singular_unit = plural_to_singular_units.get(smallest_unit); singular_unit.has_value()) {
  347. // a. Set smallestUnit to the corresponding Singular value of the same row.
  348. smallest_unit = singular_unit.value();
  349. }
  350. // 4. If disallowedUnits contains smallestUnit, then
  351. if (disallowed_units.contains_slow(smallest_unit)) {
  352. // a. Throw a RangeError exception.
  353. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, smallest_unit, vm.names.smallestUnit.as_string());
  354. }
  355. // 5. Return smallestUnit.
  356. return { smallest_unit };
  357. }
  358. // 13.22 ValidateTemporalUnitRange ( largestUnit, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-validatetemporalunitrange
  359. ThrowCompletionOr<void> validate_temporal_unit_range(GlobalObject& global_object, StringView largest_unit, StringView smallest_unit)
  360. {
  361. auto& vm = global_object.vm();
  362. // 1. If smallestUnit is "year" and largestUnit is not "year", then
  363. if (smallest_unit == "year"sv && largest_unit != "year"sv) {
  364. // a. Throw a RangeError exception.
  365. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  366. }
  367. // 2. If smallestUnit is "month" and largestUnit is not "year" or "month", then
  368. if (smallest_unit == "month"sv && !largest_unit.is_one_of("year"sv, "month"sv)) {
  369. // a. Throw a RangeError exception.
  370. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  371. }
  372. // 3. If smallestUnit is "week" and largestUnit is not one of "year", "month", or "week", then
  373. if (smallest_unit == "week"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv)) {
  374. // a. Throw a RangeError exception.
  375. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  376. }
  377. // 4. If smallestUnit is "day" and largestUnit is not one of "year", "month", "week", or "day", then
  378. if (smallest_unit == "day"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  379. // a. Throw a RangeError exception.
  380. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  381. }
  382. // 5. If smallestUnit is "hour" and largestUnit is not one of "year", "month", "week", "day", or "hour", then
  383. if (smallest_unit == "hour"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv, "hour"sv)) {
  384. // a. Throw a RangeError exception.
  385. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  386. }
  387. // 6. If smallestUnit is "minute" and largestUnit is "second", "millisecond", "microsecond", or "nanosecond", then
  388. if (smallest_unit == "minute"sv && largest_unit.is_one_of("second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  389. // a. Throw a RangeError exception.
  390. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  391. }
  392. // 7. If smallestUnit is "second" and largestUnit is "millisecond", "microsecond", or "nanosecond", then
  393. if (smallest_unit == "second"sv && largest_unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  394. // a. Throw a RangeError exception.
  395. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  396. }
  397. // 8. If smallestUnit is "millisecond" and largestUnit is "microsecond" or "nanosecond", then
  398. if (smallest_unit == "millisecond"sv && largest_unit.is_one_of("microsecond"sv, "nanosecond"sv)) {
  399. // a. Throw a RangeError exception.
  400. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  401. }
  402. // 9. If smallestUnit is "microsecond" and largestUnit is "nanosecond", then
  403. if (smallest_unit == "microsecond"sv && largest_unit == "nanosecond"sv) {
  404. // a. Throw a RangeError exception.
  405. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  406. }
  407. return {};
  408. }
  409. // 13.23 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  410. String larger_of_two_temporal_units(StringView unit1, StringView unit2)
  411. {
  412. // 1. If either u1 or u2 is "year", return "year".
  413. if (unit1 == "year"sv || unit2 == "year"sv)
  414. return "year"sv;
  415. // 2. If either u1 or u2 is "month", return "month".
  416. if (unit1 == "month"sv || unit2 == "month"sv)
  417. return "month"sv;
  418. // 3. If either u1 or u2 is "week", return "week".
  419. if (unit1 == "week"sv || unit2 == "week"sv)
  420. return "week"sv;
  421. // 4. If either u1 or u2 is "day", return "day".
  422. if (unit1 == "day"sv || unit2 == "day"sv)
  423. return "day"sv;
  424. // 5. If either u1 or u2 is "hour", return "hour".
  425. if (unit1 == "hour"sv || unit2 == "hour"sv)
  426. return "hour"sv;
  427. // 6. If either u1 or u2 is "minute", return "minute".
  428. if (unit1 == "minute"sv || unit2 == "minute"sv)
  429. return "minute"sv;
  430. // 7. If either u1 or u2 is "second", return "second".
  431. if (unit1 == "second"sv || unit2 == "second"sv)
  432. return "second"sv;
  433. // 8. If either u1 or u2 is "millisecond", return "millisecond".
  434. if (unit1 == "millisecond"sv || unit2 == "millisecond"sv)
  435. return "millisecond"sv;
  436. // 9. If either u1 or u2 is "microsecond", return "microsecond".
  437. if (unit1 == "microsecond"sv || unit2 == "microsecond"sv)
  438. return "microsecond"sv;
  439. // 10. Return "nanosecond".
  440. return "nanosecond"sv;
  441. }
  442. // 13.25 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  443. Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit)
  444. {
  445. // 1. If unit is "year", "month", "week", or "day", then
  446. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  447. // a. Return undefined.
  448. return {};
  449. }
  450. // 2. If unit is "hour", then
  451. if (unit == "hour"sv) {
  452. // a. Return 24.
  453. return 24;
  454. }
  455. // 3. If unit is "minute" or "second", then
  456. if (unit.is_one_of("minute"sv, "second"sv)) {
  457. // a. Return 60.
  458. return 60;
  459. }
  460. // 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
  461. VERIFY(unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  462. // 5. Return 1000.
  463. return 1000;
  464. }
  465. // 13.26 RejectTemporalCalendarType ( object ), https://tc39.es/proposal-temporal/#sec-temporal-rejecttemporalcalendartype
  466. ThrowCompletionOr<void> reject_temporal_calendar_type(GlobalObject& global_object, Object& object)
  467. {
  468. auto& vm = global_object.vm();
  469. // 1. Assert: Type(object) is Object.
  470. // 2. If object has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  471. if (is<PlainDate>(object) || is<PlainDateTime>(object) || is<PlainMonthDay>(object) || is<PlainTime>(object) || is<PlainYearMonth>(object) || is<ZonedDateTime>(object)) {
  472. // a. Throw a TypeError exception.
  473. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalPlainTimeWithArgumentMustNotHave, "calendar or timeZone");
  474. }
  475. return {};
  476. }
  477. // 13.27 FormatSecondsStringPart ( second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatsecondsstringpart
  478. String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  479. {
  480. // 1. Assert: second, millisecond, microsecond and nanosecond are integers.
  481. // Non-standard sanity check
  482. if (precision.has<StringView>())
  483. VERIFY(precision.get<StringView>().is_one_of("minute"sv, "auto"sv));
  484. // 2. If precision is "minute", return "".
  485. if (precision.has<StringView>() && precision.get<StringView>() == "minute"sv)
  486. return String::empty();
  487. // 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.
  488. auto seconds_string = String::formatted(":{:02}", second);
  489. // 4. Let fraction be millisecond × 10^6 + microsecond × 10^3 + nanosecond.
  490. u32 fraction = millisecond * 1'000'000 + microsecond * 1'000 + nanosecond;
  491. String fraction_string;
  492. // 5. If precision is "auto", then
  493. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  494. // a. If fraction is 0, return secondsString.
  495. if (fraction == 0)
  496. return seconds_string;
  497. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  498. fraction_string = String::formatted("{:09}", fraction);
  499. // c. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  500. fraction_string = fraction_string.trim("0"sv, TrimMode::Right);
  501. }
  502. // 6. Else,
  503. else {
  504. // a. If precision is 0, return secondsString.
  505. if (precision.get<u8>() == 0)
  506. return seconds_string;
  507. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  508. fraction_string = String::formatted("{:09}", fraction);
  509. // c. Set fraction to the substring of fraction from 0 to precision.
  510. fraction_string = fraction_string.substring(0, precision.get<u8>());
  511. }
  512. // 7. Return the string-concatenation of secondsString, the code unit 0x002E (FULL STOP), and fraction.
  513. return String::formatted("{}.{}", seconds_string, fraction_string);
  514. }
  515. // 13.29 ConstrainToRange ( x, minimum, maximum ), https://tc39.es/proposal-temporal/#sec-temporal-constraintorange
  516. double constrain_to_range(double x, double minimum, double maximum)
  517. {
  518. return min(max(x, minimum), maximum);
  519. }
  520. // NOTE: We have two variants of this function, one using doubles and one using BigInts - most of the time
  521. // doubles will be fine, but take care to choose the right one. The spec is not very clear about this, as
  522. // it uses mathematical values which can be arbitrarily (but not infinitely) large.
  523. // Incidentally V8's Temporal implementation does the same :^)
  524. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  525. i64 round_number_to_increment(double x, u64 increment, StringView rounding_mode)
  526. {
  527. // 1. Assert: x and increment are mathematical values.
  528. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  529. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  530. // 3. Let quotient be x / increment.
  531. auto quotient = x / (double)increment;
  532. double rounded;
  533. // 4. If roundingMode is "ceil", then
  534. if (rounding_mode == "ceil"sv) {
  535. // a. Let rounded be −floor(−quotient).
  536. rounded = -floor(-quotient);
  537. }
  538. // 5. Else if roundingMode is "floor", then
  539. else if (rounding_mode == "floor"sv) {
  540. // a. Let rounded be floor(quotient).
  541. rounded = floor(quotient);
  542. }
  543. // 6. Else if roundingMode is "trunc", then
  544. else if (rounding_mode == "trunc"sv) {
  545. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  546. rounded = trunc(quotient);
  547. }
  548. // 7. Else,
  549. else {
  550. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  551. rounded = round(quotient);
  552. }
  553. // 8. Return rounded × increment.
  554. return (i64)rounded * (i64)increment;
  555. }
  556. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  557. BigInt* round_number_to_increment(GlobalObject& global_object, BigInt const& x, u64 increment, StringView rounding_mode)
  558. {
  559. auto& heap = global_object.heap();
  560. // 1. Assert: x and increment are mathematical values.
  561. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  562. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  563. // OPTIMIZATION: If the increment is 1 the number is always rounded
  564. if (increment == 1)
  565. return js_bigint(heap, x.big_integer());
  566. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  567. // 3. Let quotient be x / increment.
  568. auto division_result = x.big_integer().divided_by(increment_big_int);
  569. // OPTIMIZATION: If there's no remainder the number is already rounded
  570. if (division_result.remainder == Crypto::UnsignedBigInteger { 0 })
  571. return js_bigint(heap, x.big_integer());
  572. Crypto::SignedBigInteger rounded = move(division_result.quotient);
  573. // 4. If roundingMode is "ceil", then
  574. if (rounding_mode == "ceil"sv) {
  575. // a. Let rounded be −floor(−quotient).
  576. if (!division_result.remainder.is_negative())
  577. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  578. }
  579. // 5. Else if roundingMode is "floor", then
  580. else if (rounding_mode == "floor"sv) {
  581. // a. Let rounded be floor(quotient).
  582. if (division_result.remainder.is_negative())
  583. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  584. }
  585. // 6. Else if roundingMode is "trunc", then
  586. else if (rounding_mode == "trunc"sv) {
  587. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  588. // NOTE: This is a no-op
  589. }
  590. // 7. Else,
  591. else {
  592. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  593. if (division_result.remainder.multiplied_by(Crypto::UnsignedBigInteger { 2 }).unsigned_value() >= increment_big_int) {
  594. if (division_result.remainder.is_negative())
  595. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  596. else
  597. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  598. }
  599. }
  600. // 8. Return rounded × increment.
  601. return js_bigint(heap, rounded.multiplied_by(increment_big_int));
  602. }
  603. // 13.34 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  604. ThrowCompletionOr<ISODateTime> parse_iso_date_time(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  605. {
  606. auto& vm = global_object.vm();
  607. // 1. Assert: Type(isoString) is String.
  608. // 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.
  609. Optional<StringView> year_part;
  610. Optional<StringView> month_part;
  611. Optional<StringView> day_part;
  612. Optional<StringView> hour_part;
  613. Optional<StringView> minute_part;
  614. Optional<StringView> second_part;
  615. Optional<StringView> fraction_part;
  616. Optional<StringView> calendar_part;
  617. TODO();
  618. // 3. Let year be the part of isoString produced by the DateYear production.
  619. // 4. If the first code unit of year is 0x2212 (MINUS SIGN), replace it with the code unit 0x002D (HYPHEN-MINUS).
  620. String normalized_year;
  621. if (year_part.has_value() && year_part->starts_with("\xE2\x88\x92"sv))
  622. normalized_year = String::formatted("-{}", year_part->substring_view(3));
  623. else
  624. normalized_year = year_part.value_or("");
  625. // 5. Set year to ! ToIntegerOrInfinity(year).
  626. i32 year = MUST(Value(js_string(vm, normalized_year)).to_integer_or_infinity(global_object));
  627. u8 month;
  628. // 6. If month is undefined, then
  629. if (!month_part.has_value()) {
  630. // a. Set month to 1.
  631. month = 1;
  632. }
  633. // 7. Else,
  634. else {
  635. // a. Set month to ! ToIntegerOrInfinity(month).
  636. month = *month_part->to_uint<u8>();
  637. }
  638. u8 day;
  639. // 8. If day is undefined, then
  640. if (!day_part.has_value()) {
  641. // a. Set day to 1.
  642. day = 1;
  643. }
  644. // 9. Else,
  645. else {
  646. // a. Set day to ! ToIntegerOrInfinity(day).
  647. day = *day_part->to_uint<u8>();
  648. }
  649. // 10. Set hour to ! ToIntegerOrInfinity(hour).
  650. u8 hour = hour_part->to_uint<u8>().value_or(0);
  651. // 11. Set minute to ! ToIntegerOrInfinity(minute).
  652. u8 minute = minute_part->to_uint<u8>().value_or(0);
  653. // 12. Set second to ! ToIntegerOrInfinity(second).
  654. u8 second = second_part->to_uint<u8>().value_or(0);
  655. // 13. If second is 60, then
  656. if (second == 60) {
  657. // a. Set second to 59.
  658. second = 59;
  659. }
  660. u16 millisecond;
  661. u16 microsecond;
  662. u16 nanosecond;
  663. // 14. If fraction is not undefined, then
  664. if (fraction_part.has_value()) {
  665. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  666. auto fraction = String::formatted("{}000000000", *fraction_part);
  667. // b. Let millisecond be the String value equal to the substring of fraction from 0 to 3.
  668. // c. Set millisecond to ! ToIntegerOrInfinity(millisecond).
  669. millisecond = *fraction.substring(0, 3).to_uint<u16>();
  670. // d. Let microsecond be the String value equal to the substring of fraction from 3 to 6.
  671. // e. Set microsecond to ! ToIntegerOrInfinity(microsecond).
  672. microsecond = *fraction.substring(3, 3).to_uint<u16>();
  673. // f. Let nanosecond be the String value equal to the substring of fraction from 6 to 9.
  674. // g. Set nanosecond to ! ToIntegerOrInfinity(nanosecond).
  675. nanosecond = *fraction.substring(6, 3).to_uint<u16>();
  676. }
  677. // 15. Else,
  678. else {
  679. // a. Let millisecond be 0.
  680. millisecond = 0;
  681. // b. Let microsecond be 0.
  682. microsecond = 0;
  683. // c. Let nanosecond be 0.
  684. nanosecond = 0;
  685. }
  686. // 16. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  687. if (!is_valid_iso_date(year, month, day))
  688. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidISODate);
  689. // 17. If ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  690. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  691. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTime);
  692. // 18. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond, [[Calendar]]: calendar }.
  693. 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>() };
  694. }
  695. // 13.35 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  696. ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject& global_object, String const& iso_string)
  697. {
  698. // 1. Assert: Type(isoString) is String.
  699. // 2. If isoString does not satisfy the syntax of a TemporalInstantString (see 13.33), then
  700. // a. Throw a RangeError exception.
  701. // TODO
  702. // 3. Let result be ! ParseISODateTime(isoString).
  703. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  704. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  705. auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string));
  706. // 5. Let offsetString be timeZoneResult.[[OffsetString]].
  707. auto offset_string = time_zone_result.offset;
  708. // 6. If timeZoneResult.[[Z]] is true, then
  709. if (time_zone_result.z) {
  710. // a. Set offsetString to "+00:00".
  711. offset_string = "+00:00"sv;
  712. }
  713. // 7. Assert: offsetString is not undefined.
  714. VERIFY(offset_string.has_value());
  715. // 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 }.
  716. 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) };
  717. }
  718. // 13.37 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  719. ThrowCompletionOr<String> parse_temporal_calendar_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  720. {
  721. auto& vm = global_object.vm();
  722. // 1. Assert: Type(isoString) is String.
  723. // 2. If isoString does not satisfy the syntax of a TemporalCalendarString (see 13.33), then
  724. // a. Throw a RangeError exception.
  725. // 3. Let id be the part of isoString produced by the CalendarName production, or undefined if not present.
  726. Optional<StringView> id_part;
  727. TODO();
  728. // 4. If id is undefined, then
  729. if (!id_part.has_value()) {
  730. // a. Return "iso8601".
  731. return { "iso8601"sv };
  732. }
  733. // 5. If ! IsBuiltinCalendar(id) is false, then
  734. if (!is_builtin_calendar(*id_part)) {
  735. // a. Throw a RangeError exception.
  736. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, *id_part);
  737. }
  738. // 6. Return id.
  739. return { id_part.value() };
  740. }
  741. // 13.38 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  742. ThrowCompletionOr<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string)
  743. {
  744. // 1. Assert: Type(isoString) is String.
  745. // 2. If isoString does not satisfy the syntax of a TemporalDateString (see 13.33), then
  746. // a. Throw a RangeError exception.
  747. // TODO
  748. // 3. Let result be ? ParseISODateTime(isoString).
  749. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  750. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  751. return TemporalDate { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  752. }
  753. // 13.39 ParseTemporalDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatetimestring
  754. ThrowCompletionOr<ISODateTime> parse_temporal_date_time_string(GlobalObject& global_object, String const& iso_string)
  755. {
  756. // 1. Assert: Type(isoString) is String.
  757. // 2. If isoString does not satisfy the syntax of a TemporalDateTimeString (see 13.33), then
  758. // a. Throw a RangeError exception.
  759. // TODO
  760. // 3. Let result be ? ParseISODateTime(isoString).
  761. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  762. // 4. Return result.
  763. return result;
  764. }
  765. // 13.40 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  766. ThrowCompletionOr<TemporalDuration> parse_temporal_duration_string(GlobalObject& global_object, String const& iso_string)
  767. {
  768. (void)global_object;
  769. (void)iso_string;
  770. TODO();
  771. }
  772. // 13.43 ParseTemporalTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimestring
  773. ThrowCompletionOr<TemporalTime> parse_temporal_time_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  774. {
  775. // 1. Assert: Type(isoString) is String.
  776. // 2. If isoString does not satisfy the syntax of a TemporalTimeString (see 13.33), then
  777. // a. Throw a RangeError exception.
  778. // TODO
  779. // 3. Let result be ? ParseISODateTime(isoString).
  780. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  781. // 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]] }.
  782. return TemporalTime { .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .calendar = move(result.calendar) };
  783. }
  784. // 13.44 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  785. ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  786. {
  787. auto& vm = global_object.vm();
  788. // 1. Assert: Type(isoString) is String.
  789. // 2. If isoString does not satisfy the syntax of a TemporalTimeZoneString (see 13.33), then
  790. // a. Throw a RangeError exception.
  791. // 3. Let z, sign, hours, minutes, seconds, fraction and name be the parts of isoString produced respectively by the UTCDesignator, TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, TimeZoneUTCOffsetFraction, and TimeZoneIANAName productions, or undefined if not present.
  792. Optional<StringView> z_part;
  793. Optional<StringView> sign_part;
  794. Optional<StringView> hours_part;
  795. Optional<StringView> minutes_part;
  796. Optional<StringView> seconds_part;
  797. Optional<StringView> fraction_part;
  798. Optional<StringView> name_part;
  799. TODO();
  800. // 4. If z is not undefined, then
  801. if (z_part.has_value()) {
  802. // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
  803. return TemporalTimeZone { .z = true, .offset = {}, .name = name_part.has_value() ? String { *name_part } : Optional<String> {} };
  804. }
  805. Optional<String> offset;
  806. // 5. If hours is undefined, then
  807. if (!hours_part.has_value()) {
  808. // a. Let offsetString be undefined.
  809. // NOTE: No-op.
  810. }
  811. // 6. Else,
  812. else {
  813. // a. Assert: sign is not undefined.
  814. VERIFY(sign_part.has_value());
  815. // b. Set hours to ! ToIntegerOrInfinity(hours).
  816. u8 hours = MUST(Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object));
  817. u8 sign;
  818. // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then
  819. if (sign_part->is_one_of("-", "\u2212")) {
  820. // i. Set sign to −1.
  821. sign = -1;
  822. }
  823. // d. Else,
  824. else {
  825. // i. Set sign to 1.
  826. sign = 1;
  827. }
  828. // e. Set minutes to ! ToIntegerOrInfinity(minutes).
  829. u8 minutes = MUST(Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object));
  830. // f. Set seconds to ! ToIntegerOrInfinity(seconds).
  831. u8 seconds = MUST(Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object));
  832. i32 nanoseconds;
  833. // g. If fraction is not undefined, then
  834. if (fraction_part.has_value()) {
  835. // i. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  836. auto fraction = String::formatted("{}000000000", *fraction_part);
  837. // ii. Let nanoseconds be the String value equal to the substring of fraction from 0 to 9.
  838. // iii. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  839. nanoseconds = MUST(Value(js_string(vm, fraction.substring(0, 9))).to_integer_or_infinity(global_object));
  840. }
  841. // h. Else,
  842. else {
  843. // i. Let nanoseconds be 0.
  844. nanoseconds = 0;
  845. }
  846. // i. Let offsetNanoseconds be sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  847. auto offset_nanoseconds = sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  848. // j. Let offsetString be ! FormatTimeZoneOffsetString(offsetNanoseconds).
  849. offset = format_time_zone_offset_string(offset_nanoseconds);
  850. }
  851. Optional<String> name;
  852. // 7. If name is not undefined, then
  853. if (name_part.has_value()) {
  854. // a. If ! IsValidTimeZoneName(name) is false, throw a RangeError exception.
  855. if (!is_valid_time_zone_name(*name_part))
  856. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName);
  857. // b. Set name to ! CanonicalizeTimeZoneName(name).
  858. name = canonicalize_time_zone_name(*name_part);
  859. }
  860. // 8. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
  861. return TemporalTimeZone { .z = false, .offset = offset, .name = name };
  862. }
  863. // 13.45 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
  864. ThrowCompletionOr<TemporalYearMonth> parse_temporal_year_month_string(GlobalObject& global_object, String const& iso_string)
  865. {
  866. // 1. Assert: Type(isoString) is String.
  867. // 2. If isoString does not satisfy the syntax of a TemporalYearMonthString (see 13.33), then
  868. // a. Throw a RangeError exception.
  869. // TODO
  870. // 3. Let result be ? ParseISODateTime(isoString).
  871. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  872. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  873. return TemporalYearMonth { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  874. }
  875. // 13.46 ToPositiveInteger ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveinteger
  876. ThrowCompletionOr<double> to_positive_integer(GlobalObject& global_object, Value argument)
  877. {
  878. auto& vm = global_object.vm();
  879. // 1. Let integer be ? ToIntegerThrowOnInfinity(argument).
  880. auto integer = TRY(to_integer_throw_on_infinity(global_object, argument, ErrorType::TemporalPropertyMustBePositiveInteger));
  881. // 2. If integer ≤ 0, then
  882. if (integer <= 0) {
  883. // a. Throw a RangeError exception.
  884. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalPropertyMustBePositiveInteger);
  885. }
  886. // 3. Return integer.
  887. return integer;
  888. }
  889. // 13.48 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  890. ThrowCompletionOr<Object*> prepare_temporal_fields(GlobalObject& global_object, Object const& fields, Vector<String> const& field_names, Vector<StringView> const& required_fields)
  891. {
  892. auto& vm = global_object.vm();
  893. // 1. Assert: Type(fields) is Object.
  894. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  895. auto* result = Object::create(global_object, global_object.object_prototype());
  896. VERIFY(result);
  897. // 3. For each value property of fieldNames, do
  898. for (auto& property : field_names) {
  899. // a. Let value be ? Get(fields, property).
  900. auto value = TRY(fields.get(property));
  901. // b. If value is undefined, then
  902. if (value.is_undefined()) {
  903. // i. If requiredFields contains property, then
  904. if (required_fields.contains_slow(property)) {
  905. // 1. Throw a TypeError exception.
  906. return vm.throw_completion<TypeError>(global_object, ErrorType::MissingRequiredProperty, property);
  907. }
  908. // ii. If property is in the Property column of Table 13, then
  909. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  910. if (property.is_one_of("hour", "minute", "second", "millisecond", "microsecond", "nanosecond")) {
  911. // 1. Set value to the corresponding Default value of the same row.
  912. value = Value(0);
  913. }
  914. }
  915. // c. Else,
  916. else {
  917. // i. If property is in the Property column of Table 13 and there is a Conversion value in the same row, then
  918. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  919. // 2. Set value to ? Conversion(value).
  920. if (property.is_one_of("year", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond", "eraYear")) {
  921. value = Value(TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite)));
  922. } else if (property.is_one_of("month", "day")) {
  923. value = Value(TRY(to_positive_integer(global_object, value)));
  924. } else if (property.is_one_of("monthCode", "offset", "era")) {
  925. value = TRY(value.to_primitive_string(global_object));
  926. }
  927. }
  928. // d. Perform ! CreateDataPropertyOrThrow(result, property, value).
  929. MUST(result->create_data_property_or_throw(property, value));
  930. }
  931. // 4. Return result.
  932. return result;
  933. }
  934. }