AbstractOperations.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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 <LibJS/Runtime/IteratorOperations.h>
  10. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  11. #include <LibJS/Runtime/Temporal/Duration.h>
  12. #include <LibJS/Runtime/Temporal/PlainDate.h>
  13. #include <LibJS/Runtime/Temporal/PlainTime.h>
  14. #include <LibJS/Runtime/Temporal/TimeZone.h>
  15. namespace JS::Temporal {
  16. static Optional<OptionType> to_option_type(Value value)
  17. {
  18. if (value.is_boolean())
  19. return OptionType::Boolean;
  20. if (value.is_string())
  21. return OptionType::String;
  22. if (value.is_number())
  23. return OptionType::Number;
  24. return {};
  25. }
  26. // 13.1 IterableToListOfType ( items, elementTypes ), https://tc39.es/proposal-temporal/#sec-iterabletolistoftype
  27. MarkedValueList iterable_to_list_of_type(GlobalObject& global_object, Value items, Vector<OptionType> const& element_types)
  28. {
  29. auto& vm = global_object.vm();
  30. auto& heap = global_object.heap();
  31. // 1. Let iteratorRecord be ? GetIterator(items, sync).
  32. auto iterator_record = get_iterator(global_object, items, IteratorHint::Sync);
  33. if (vm.exception())
  34. return MarkedValueList { heap };
  35. // 2. Let values be a new empty List.
  36. MarkedValueList values(heap);
  37. // 3. Let next be true.
  38. auto next = true;
  39. // 4. Repeat, while next is not false,
  40. while (next) {
  41. // a. Set next to ? IteratorStep(iteratorRecord).
  42. auto* iterator_result = iterator_step(global_object, *iterator_record);
  43. if (vm.exception())
  44. return MarkedValueList { heap };
  45. next = iterator_result;
  46. // b. If next is not false, then
  47. if (next) {
  48. // i. Let nextValue be ? IteratorValue(next).
  49. auto next_value = iterator_value(global_object, *iterator_result);
  50. if (vm.exception())
  51. return MarkedValueList { heap };
  52. // ii. If Type(nextValue) is not an element of elementTypes, then
  53. if (auto type = to_option_type(next_value); !type.has_value() || !element_types.contains_slow(*type)) {
  54. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  55. vm.throw_exception<TypeError>(global_object, ErrorType::FixmeAddAnErrorString);
  56. // 2. Return ? IteratorClose(iteratorRecord, completion).
  57. iterator_close(*iterator_record);
  58. return MarkedValueList { heap };
  59. }
  60. // iii. Append nextValue to the end of the List values.
  61. values.append(next_value);
  62. }
  63. }
  64. // 5. Return values.
  65. return values;
  66. }
  67. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  68. Object* get_options_object(GlobalObject& global_object, Value options)
  69. {
  70. auto& vm = global_object.vm();
  71. // 1. If options is undefined, then
  72. if (options.is_undefined()) {
  73. // a. Return ! OrdinaryObjectCreate(null).
  74. return Object::create(global_object, nullptr);
  75. }
  76. // 2. If Type(options) is Object, then
  77. if (options.is_object()) {
  78. // a. Return options.
  79. return &options.as_object();
  80. }
  81. // 3. Throw a TypeError exception.
  82. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, "Options");
  83. return {};
  84. }
  85. // 13.3 GetOption ( options, property, types, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  86. Value get_option(GlobalObject& global_object, Object& options, String const& property, Vector<OptionType> const& types, Vector<StringView> const& values, Value fallback)
  87. {
  88. auto& vm = global_object.vm();
  89. // 1. Assert: Type(options) is Object.
  90. // 2. Assert: Each element of types is Boolean, String, or Number.
  91. // 3. Let value be ? Get(options, property).
  92. auto value = options.get(property);
  93. if (vm.exception())
  94. return {};
  95. // 4. If value is undefined, return fallback.
  96. if (value.is_undefined())
  97. return fallback;
  98. OptionType type;
  99. // 5. If types contains Type(value), then
  100. if (auto value_type = to_option_type(value); value_type.has_value() && types.contains_slow(*value_type)) {
  101. // a. Let type be Type(value).
  102. type = *value_type;
  103. }
  104. // 6. Else,
  105. else {
  106. // a. Let type be the last element of types.
  107. type = types.last();
  108. }
  109. // 7. If type is Boolean, then
  110. if (type == OptionType::Boolean) {
  111. // a. Set value to ! ToBoolean(value).
  112. value = Value(value.to_boolean());
  113. }
  114. // 8. Else if type is Number, then
  115. else if (type == OptionType::Number) {
  116. // a. Set value to ? ToNumber(value).
  117. value = value.to_number(global_object);
  118. if (vm.exception())
  119. return {};
  120. // b. If value is NaN, throw a RangeError exception.
  121. if (value.is_nan()) {
  122. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property);
  123. return {};
  124. }
  125. }
  126. // 9. Else,
  127. else {
  128. // a. Set value to ? ToString(value).
  129. value = value.to_primitive_string(global_object);
  130. if (vm.exception())
  131. return {};
  132. }
  133. // 10. If values is not empty, then
  134. if (!values.is_empty()) {
  135. VERIFY(value.is_string());
  136. // a. If values does not contain value, throw a RangeError exception.
  137. if (!values.contains_slow(value.as_string().string())) {
  138. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property);
  139. return {};
  140. }
  141. }
  142. // 11. Return value.
  143. return value;
  144. }
  145. // 13.6 ToTemporalOverflow ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  146. Optional<String> to_temporal_overflow(GlobalObject& global_object, Object& normalized_options)
  147. {
  148. auto& vm = global_object.vm();
  149. // 1. Return ? GetOption(normalizedOptions, "overflow", « String », « "constrain", "reject" », "constrain").
  150. auto option = get_option(global_object, normalized_options, "overflow", { OptionType::String }, { "constrain"sv, "reject"sv }, js_string(vm, "constrain"));
  151. if (vm.exception())
  152. return {};
  153. VERIFY(option.is_string());
  154. return option.as_string().string();
  155. }
  156. // 13.8 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  157. Optional<String> to_temporal_rounding_mode(GlobalObject& global_object, Object& normalized_options, String const& fallback)
  158. {
  159. auto& vm = global_object.vm();
  160. auto option = get_option(global_object, normalized_options, "roundingMode", { OptionType::String }, { "ceil"sv, "floor"sv, "trunc"sv, "halfExpand"sv }, js_string(vm, fallback));
  161. if (vm.exception())
  162. return {};
  163. VERIFY(option.is_string());
  164. return option.as_string().string();
  165. }
  166. // 13.14 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  167. u64 to_temporal_rounding_increment(GlobalObject& global_object, Object& normalized_options, Optional<double> dividend, bool inclusive)
  168. {
  169. auto& vm = global_object.vm();
  170. double maximum;
  171. // 1. If dividend is undefined, then
  172. if (!dividend.has_value()) {
  173. // a. Let maximum be +∞.
  174. maximum = INFINITY;
  175. }
  176. // 2. Else if inclusive is true, then
  177. else if (inclusive) {
  178. // a. Let maximum be dividend.
  179. maximum = *dividend;
  180. }
  181. // 3. Else if dividend is more than 1, then
  182. else if (*dividend > 1) {
  183. // a. Let maximum be dividend − 1.
  184. maximum = *dividend - 1;
  185. }
  186. // 4. Else,
  187. else {
  188. // a. Let maximum be 1.
  189. maximum = 1;
  190. }
  191. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", « Number », empty, 1).
  192. auto increment_value = get_option(global_object, normalized_options, "roundingIncrement", { OptionType::Number }, {}, Value(1));
  193. if (vm.exception())
  194. return {};
  195. VERIFY(increment_value.is_number());
  196. auto increment = increment_value.as_double();
  197. // 6. If increment < 1 or increment > maximum, throw a RangeError exception.
  198. if (increment < 1 || increment > maximum) {
  199. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  200. return {};
  201. }
  202. // 7. Set increment to floor(ℝ(increment)).
  203. auto floored_increment = static_cast<u64>(increment);
  204. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  205. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0) {
  206. // a. Throw a RangeError exception.
  207. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  208. return {};
  209. }
  210. // 9. Return increment.
  211. return floored_increment;
  212. }
  213. // https://tc39.es/proposal-temporal/#table-temporal-singular-and-plural-units
  214. static HashMap<StringView, StringView> plural_to_singular_units = {
  215. { "years"sv, "year"sv },
  216. { "months"sv, "month"sv },
  217. { "weeks"sv, "week"sv },
  218. { "days"sv, "day"sv },
  219. { "hours"sv, "hour"sv },
  220. { "minutes"sv, "minute"sv },
  221. { "seconds"sv, "second"sv },
  222. { "milliseconds"sv, "millisecond"sv },
  223. { "microseconds"sv, "microsecond"sv },
  224. { "nanoseconds"sv, "nanosecond"sv }
  225. };
  226. // 13.18 ToSmallestTemporalUnit ( normalizedOptions, disallowedUnits, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-tosmallesttemporalunit
  227. Optional<String> to_smallest_temporal_unit(GlobalObject& global_object, Object& normalized_options, Vector<StringView> const& disallowed_units, Optional<String> fallback)
  228. {
  229. auto& vm = global_object.vm();
  230. // 1. Assert: disallowedUnits does not contain fallback.
  231. // 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).
  232. auto smallest_unit_value = get_option(global_object, normalized_options, "smallestUnit"sv, { 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());
  233. if (vm.exception())
  234. return {};
  235. // OPTIMIZATION: We skip the following string-only checks for the fallback to tidy up the code a bit
  236. if (smallest_unit_value.is_undefined())
  237. return {};
  238. VERIFY(smallest_unit_value.is_string());
  239. auto smallest_unit = smallest_unit_value.as_string().string();
  240. // 3. If smallestUnit is in the Plural column of Table 12, then
  241. if (auto singular_unit = plural_to_singular_units.get(smallest_unit); singular_unit.has_value()) {
  242. // a. Set smallestUnit to the corresponding Singular value of the same row.
  243. smallest_unit = singular_unit.value();
  244. }
  245. // 4. If disallowedUnits contains smallestUnit, then
  246. if (disallowed_units.contains_slow(smallest_unit)) {
  247. // a. Throw a RangeError exception.
  248. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, smallest_unit, "smallestUnit");
  249. return {};
  250. }
  251. // 5. Return smallestUnit.
  252. return smallest_unit;
  253. }
  254. // 13.29 ConstrainToRange ( x, minimum, maximum ), https://tc39.es/proposal-temporal/#sec-temporal-constraintorange
  255. double constrain_to_range(double x, double minimum, double maximum)
  256. {
  257. return min(max(x, minimum), maximum);
  258. }
  259. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode )
  260. BigInt* round_number_to_increment(GlobalObject& global_object, BigInt const& x, u64 increment, String const& rounding_mode)
  261. {
  262. auto& heap = global_object.heap();
  263. // 1. Assert: x and increment are mathematical values.
  264. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  265. VERIFY(rounding_mode == "ceil" || rounding_mode == "floor" || rounding_mode == "trunc" || rounding_mode == "halfExpand");
  266. // OPTIMIZATION: If the increment is 1 the number is always rounded
  267. if (increment == 1)
  268. return js_bigint(heap, x.big_integer());
  269. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  270. // 3. Let quotient be x / increment.
  271. auto division_result = x.big_integer().divided_by(increment_big_int);
  272. // OPTIMIZATION: If theres no remainder there number is already rounded
  273. if (division_result.remainder == Crypto::UnsignedBigInteger { 0 })
  274. return js_bigint(heap, x.big_integer());
  275. Crypto::SignedBigInteger rounded = move(division_result.quotient);
  276. // 4. If roundingMode is "ceil", then
  277. if (rounding_mode == "ceil") {
  278. // a. Let rounded be −floor(−quotient).
  279. if (!division_result.remainder.is_negative())
  280. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  281. }
  282. // 5. Else if roundingMode is "floor", then
  283. else if (rounding_mode == "floor") {
  284. // a. Let rounded be floor(quotient).
  285. if (division_result.remainder.is_negative())
  286. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  287. }
  288. // 6. Else if roundingMode is "trunc", then
  289. else if (rounding_mode == "trunc") {
  290. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  291. // NOTE: This is a no-op
  292. }
  293. // 7. Else,
  294. else {
  295. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  296. if (division_result.remainder.multiplied_by(Crypto::UnsignedBigInteger { 2 }).unsigned_value() >= increment_big_int) {
  297. if (division_result.remainder.is_negative())
  298. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  299. else
  300. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  301. }
  302. }
  303. // 8. Return rounded × increment.
  304. return js_bigint(heap, rounded.multiplied_by(increment_big_int));
  305. }
  306. // 13.34 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  307. Optional<ISODateTime> parse_iso_date_time(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  308. {
  309. auto& vm = global_object.vm();
  310. // 1. Assert: Type(isoString) is String.
  311. // 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.
  312. Optional<StringView> year_part;
  313. Optional<StringView> month_part;
  314. Optional<StringView> day_part;
  315. Optional<StringView> hour_part;
  316. Optional<StringView> minute_part;
  317. Optional<StringView> second_part;
  318. Optional<StringView> fraction_part;
  319. Optional<StringView> calendar_part;
  320. TODO();
  321. // 3. Let year be the part of isoString produced by the DateYear production.
  322. // 4. If the first code unit of year is 0x2212 (MINUS SIGN), replace it with the code unit 0x002D (HYPHEN-MINUS).
  323. String normalized_year;
  324. if (year_part.has_value() && year_part->starts_with("\xE2\x88\x92"sv))
  325. normalized_year = String::formatted("-{}", year_part->substring_view(3));
  326. else
  327. normalized_year = year_part.value_or("");
  328. // 5. Set year to ! ToIntegerOrInfinity(year).
  329. i32 year = Value(js_string(vm, normalized_year)).to_integer_or_infinity(global_object);
  330. u8 month;
  331. // 6. If month is undefined, then
  332. if (!month_part.has_value()) {
  333. // a. Set month to 1.
  334. month = 1;
  335. }
  336. // 7. Else,
  337. else {
  338. // a. Set month to ! ToIntegerOrInfinity(month).
  339. month = *month_part->to_uint<u8>();
  340. }
  341. u8 day;
  342. // 8. If day is undefined, then
  343. if (!day_part.has_value()) {
  344. // a. Set day to 1.
  345. day = 1;
  346. }
  347. // 9. Else,
  348. else {
  349. // a. Set day to ! ToIntegerOrInfinity(day).
  350. day = *day_part->to_uint<u8>();
  351. }
  352. // 10. Set hour to ! ToIntegerOrInfinity(hour).
  353. u8 hour = hour_part->to_uint<u8>().value_or(0);
  354. // 11. Set minute to ! ToIntegerOrInfinity(minute).
  355. u8 minute = minute_part->to_uint<u8>().value_or(0);
  356. // 12. Set second to ! ToIntegerOrInfinity(second).
  357. u8 second = second_part->to_uint<u8>().value_or(0);
  358. // 13. If second is 60, then
  359. if (second == 60) {
  360. // a. Set second to 59.
  361. second = 59;
  362. }
  363. u16 millisecond;
  364. u16 microsecond;
  365. u16 nanosecond;
  366. // 14. If fraction is not undefined, then
  367. if (fraction_part.has_value()) {
  368. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  369. auto fraction = String::formatted("{}000000000", *fraction_part);
  370. // b. Let millisecond be the String value equal to the substring of fraction from 0 to 3.
  371. // c. Set millisecond to ! ToIntegerOrInfinity(millisecond).
  372. millisecond = *fraction.substring(0, 3).to_uint<u16>();
  373. // d. Let microsecond be the String value equal to the substring of fraction from 3 to 6.
  374. // e. Set microsecond to ! ToIntegerOrInfinity(microsecond).
  375. microsecond = *fraction.substring(3, 3).to_uint<u16>();
  376. // f. Let nanosecond be the String value equal to the substring of fraction from 6 to 9.
  377. // g. Set nanosecond to ! ToIntegerOrInfinity(nanosecond).
  378. nanosecond = *fraction.substring(6, 3).to_uint<u16>();
  379. }
  380. // 15. Else,
  381. else {
  382. // a. Let millisecond be 0.
  383. millisecond = 0;
  384. // b. Let microsecond be 0.
  385. microsecond = 0;
  386. // c. Let nanosecond be 0.
  387. nanosecond = 0;
  388. }
  389. // 16. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  390. if (!is_valid_iso_date(year, month, day)) {
  391. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidISODate);
  392. return {};
  393. }
  394. // 17. If ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  395. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond)) {
  396. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidTime);
  397. return {};
  398. }
  399. // 18. Return the new Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond, [[Calendar]]: calendar }.
  400. 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>() };
  401. }
  402. // 13.35 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  403. Optional<TemporalInstant> parse_temporal_instant_string(GlobalObject& global_object, String const& iso_string)
  404. {
  405. auto& vm = global_object.vm();
  406. // 1. Assert: Type(isoString) is String.
  407. // 2. If isoString does not satisfy the syntax of a TemporalInstantString (see 13.33), then
  408. // a. Throw a RangeError exception.
  409. // TODO
  410. // 3. Let result be ! ParseISODateTime(isoString).
  411. auto result = parse_iso_date_time(global_object, iso_string);
  412. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  413. auto time_zone_result = parse_temporal_time_zone_string(global_object, iso_string);
  414. if (vm.exception())
  415. return {};
  416. // 5. Assert: timeZoneResult.[[OffsetString]] is not undefined.
  417. VERIFY(time_zone_result->offset.has_value());
  418. // 6. Return the new 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]]: timeZoneResult.[[OffsetString]] }.
  419. 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(time_zone_result->offset) };
  420. }
  421. // 13.37 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  422. Optional<String> parse_temporal_calendar_string([[maybe_unused]] GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  423. {
  424. // 1. Assert: Type(isoString) is String.
  425. // 2. If isoString does not satisfy the syntax of a TemporalCalendarString (see 13.33), then
  426. // a. Throw a RangeError exception.
  427. // 3. Let id be the part of isoString produced by the CalendarName production, or undefined if not present.
  428. Optional<StringView> id_part;
  429. TODO();
  430. // 4. If id is undefined, then
  431. if (!id_part.has_value()) {
  432. // a. Return "iso8601".
  433. return "iso8601";
  434. }
  435. // 5. Return id.
  436. return id_part.value();
  437. }
  438. // 13.38 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  439. Optional<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string)
  440. {
  441. auto& vm = global_object.vm();
  442. // 1. Assert: Type(isoString) is String.
  443. // 2. If isoString does not satisfy the syntax of a TemporalDateString (see 13.33), then
  444. // a. Throw a RangeError exception.
  445. // TODO
  446. // 3. Let result be ? ParseISODateTime(isoString).
  447. auto result = parse_iso_date_time(global_object, iso_string);
  448. if (vm.exception())
  449. return {};
  450. // 4. Return the new Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  451. return TemporalDate { .year = result->year, .month = result->month, .day = result->day, .calendar = move(result->calendar) };
  452. }
  453. // 13.40 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  454. Optional<TemporalDuration> parse_temporal_duration_string(GlobalObject& global_object, String const& iso_string)
  455. {
  456. (void)global_object;
  457. (void)iso_string;
  458. TODO();
  459. }
  460. // 13.43 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  461. Optional<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  462. {
  463. auto& vm = global_object.vm();
  464. // 1. Assert: Type(isoString) is String.
  465. // 2. If isoString does not satisfy the syntax of a TemporalTimeZoneString (see 13.33), then
  466. // a. Throw a RangeError exception.
  467. // 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.
  468. Optional<StringView> z_part;
  469. Optional<StringView> sign_part;
  470. Optional<StringView> hours_part;
  471. Optional<StringView> minutes_part;
  472. Optional<StringView> seconds_part;
  473. Optional<StringView> fraction_part;
  474. Optional<StringView> name_part;
  475. TODO();
  476. // 4. If z is not undefined, then
  477. if (z_part.has_value()) {
  478. // a. Return the new Record: { [[Z]]: "Z", [[OffsetString]]: "+00:00", [[Name]]: undefined }.
  479. return TemporalTimeZone { .z = true, .offset = "+00:00", .name = {} };
  480. }
  481. Optional<String> offset;
  482. // 5. If hours is undefined, then
  483. if (!hours_part.has_value()) {
  484. // a. Let offsetString be undefined.
  485. // NOTE: No-op.
  486. }
  487. // 6. Else,
  488. else {
  489. // a. Assert: sign is not undefined.
  490. VERIFY(sign_part.has_value());
  491. // b. Set hours to ! ToIntegerOrInfinity(hours).
  492. u8 hours = Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object);
  493. u8 sign;
  494. // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then
  495. if (sign_part->is_one_of("-", "\u2212")) {
  496. // i. Set sign to −1.
  497. sign = -1;
  498. }
  499. // d. Else,
  500. else {
  501. // i. Set sign to 1.
  502. sign = 1;
  503. }
  504. // e. Set minutes to ! ToIntegerOrInfinity(minutes).
  505. u8 minutes = Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object);
  506. // f. Set seconds to ! ToIntegerOrInfinity(seconds).
  507. u8 seconds = Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object);
  508. i32 nanoseconds;
  509. // g. If fraction is not undefined, then
  510. if (fraction_part.has_value()) {
  511. // i. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  512. auto fraction = String::formatted("{}000000000", *fraction_part);
  513. // ii. Let nanoseconds be the String value equal to the substring of fraction from 0 to 9.
  514. // iii. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  515. nanoseconds = Value(js_string(vm, fraction.substring(0, 9))).to_integer_or_infinity(global_object);
  516. }
  517. // h. Else,
  518. else {
  519. // i. Let nanoseconds be 0.
  520. nanoseconds = 0;
  521. }
  522. // i. Let offsetNanoseconds be sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  523. auto offset_nanoseconds = sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  524. // j. Let offsetString be ! FormatTimeZoneOffsetString(offsetNanoseconds).
  525. offset = format_time_zone_offset_string(offset_nanoseconds);
  526. }
  527. Optional<String> name;
  528. // 7. If name is not undefined, then
  529. if (name_part.has_value()) {
  530. // a. If ! IsValidTimeZoneName(name) is false, throw a RangeError exception.
  531. if (!is_valid_time_zone_name(*name_part)) {
  532. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName);
  533. return {};
  534. }
  535. // b. Set name to ! CanonicalizeTimeZoneName(name).
  536. name = canonicalize_time_zone_name(*name_part);
  537. }
  538. // 8. Return the new Record: { [[Z]]: undefined, [[OffsetString]]: offsetString, [[Name]]: name }.
  539. return TemporalTimeZone { .z = false, .offset = offset, .name = name };
  540. }
  541. // 13.45 ToPositiveIntegerOrInfinity ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveintegerorinfinity
  542. double to_positive_integer_or_infinity(GlobalObject& global_object, Value argument)
  543. {
  544. auto& vm = global_object.vm();
  545. // 1. Let integer be ? ToIntegerOrInfinity(argument).
  546. auto integer = argument.to_integer_or_infinity(global_object);
  547. if (vm.exception())
  548. return {};
  549. // 2. If integer is -∞𝔽, then
  550. if (Value(integer).is_negative_infinity()) {
  551. // a. Throw a RangeError exception.
  552. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalPropertyMustBePositiveInteger);
  553. return {};
  554. }
  555. // 3. If integer ≤ 0, then
  556. if (integer <= 0) {
  557. // a. Throw a RangeError exception.
  558. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalPropertyMustBePositiveInteger);
  559. return {};
  560. }
  561. // 4. Return integer.
  562. return integer;
  563. }
  564. // 13.46 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  565. Object* prepare_temporal_fields(GlobalObject& global_object, Object& fields, Vector<String> const& field_names, Vector<StringView> const& required_fields)
  566. {
  567. auto& vm = global_object.vm();
  568. // 1. Assert: Type(fields) is Object.
  569. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  570. auto* result = Object::create(global_object, global_object.object_prototype());
  571. VERIFY(result);
  572. // 3. For each value property of fieldNames, do
  573. for (auto& property : field_names) {
  574. // a. Let value be ? Get(fields, property).
  575. auto value = fields.get(property);
  576. if (vm.exception())
  577. return {};
  578. // b. If value is undefined, then
  579. if (value.is_undefined()) {
  580. // i. If requiredFields contains property, then
  581. if (required_fields.contains_slow(property)) {
  582. // 1. Throw a TypeError exception.
  583. vm.throw_exception<TypeError>(global_object, ErrorType::TemporalMissingRequiredProperty, property);
  584. return {};
  585. }
  586. // ii. If property is in the Property column of Table 13, then
  587. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  588. if (property.is_one_of("hour", "minute", "second", "millisecond", "microsecond", "nanosecond")) {
  589. // 1. Set value to the corresponding Default value of the same row.
  590. value = Value(0);
  591. }
  592. }
  593. // c. Else,
  594. else {
  595. // i. If property is in the Property column of Table 13 and there is a Conversion value in the same row, then
  596. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  597. // 2. Set value to ? Conversion(value).
  598. if (property.is_one_of("year", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond", "eraYear")) {
  599. value = Value(value.to_integer_or_infinity(global_object));
  600. if (vm.exception())
  601. return {};
  602. } else if (property.is_one_of("month", "day")) {
  603. value = Value(to_positive_integer_or_infinity(global_object, value));
  604. if (vm.exception())
  605. return {};
  606. } else if (property.is_one_of("monthCode", "offset", "era")) {
  607. value = value.to_primitive_string(global_object);
  608. if (vm.exception())
  609. return {};
  610. }
  611. }
  612. // d. Perform ! CreateDataPropertyOrThrow(result, property, value).
  613. result->create_data_property_or_throw(property, value);
  614. }
  615. // 4. Return result.
  616. return result;
  617. }
  618. }