AbstractOperations.cpp 52 KB

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