AbstractOperations.cpp 53 KB

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