AbstractOperations.cpp 53 KB

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