AbstractOperations.cpp 56 KB

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