AbstractOperations.cpp 52 KB

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