AbstractOperations.cpp 51 KB

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