AbstractOperations.cpp 53 KB

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