AbstractOperations.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/DateTimeLexer.h>
  10. #include <AK/TypeCasts.h>
  11. #include <AK/Variant.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibJS/Runtime/IteratorOperations.h>
  14. #include <LibJS/Runtime/PropertyKey.h>
  15. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  16. #include <LibJS/Runtime/Temporal/Calendar.h>
  17. #include <LibJS/Runtime/Temporal/Duration.h>
  18. #include <LibJS/Runtime/Temporal/PlainDate.h>
  19. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  20. #include <LibJS/Runtime/Temporal/PlainTime.h>
  21. #include <LibJS/Runtime/Temporal/TimeZone.h>
  22. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  23. namespace JS::Temporal {
  24. static Optional<OptionType> to_option_type(Value value)
  25. {
  26. if (value.is_boolean())
  27. return OptionType::Boolean;
  28. if (value.is_string())
  29. return OptionType::String;
  30. if (value.is_number())
  31. return OptionType::Number;
  32. return {};
  33. }
  34. // 13.1 IterableToListOfType ( items, elementTypes ), https://tc39.es/proposal-temporal/#sec-iterabletolistoftype
  35. ThrowCompletionOr<MarkedValueList> iterable_to_list_of_type(GlobalObject& global_object, Value items, Vector<OptionType> const& element_types)
  36. {
  37. auto& vm = global_object.vm();
  38. auto& heap = global_object.heap();
  39. // 1. Let iteratorRecord be ? GetIterator(items, sync).
  40. auto iterator_record = TRY(get_iterator(global_object, items, IteratorHint::Sync));
  41. // 2. Let values be a new empty List.
  42. MarkedValueList values(heap);
  43. // 3. Let next be true.
  44. auto next = true;
  45. // 4. Repeat, while next is not false,
  46. while (next) {
  47. // a. Set next to ? IteratorStep(iteratorRecord).
  48. auto* iterator_result = TRY(iterator_step(global_object, *iterator_record));
  49. next = iterator_result;
  50. // b. If next is not false, then
  51. if (next) {
  52. // i. Let nextValue be ? IteratorValue(next).
  53. auto next_value = TRY(iterator_value(global_object, *iterator_result));
  54. // ii. If Type(nextValue) is not an element of elementTypes, then
  55. if (auto type = to_option_type(next_value); !type.has_value() || !element_types.contains_slow(*type)) {
  56. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  57. auto completion = vm.throw_completion<TypeError>(global_object, ErrorType::IterableToListOfTypeInvalidValue, next_value.to_string_without_side_effects());
  58. // 2. Return ? IteratorClose(iteratorRecord, completion).
  59. return iterator_close(*iterator_record, move(completion));
  60. }
  61. // iii. Append nextValue to the end of the List values.
  62. values.append(next_value);
  63. }
  64. }
  65. // 5. Return values.
  66. return { move(values) };
  67. }
  68. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  69. ThrowCompletionOr<Object*> get_options_object(GlobalObject& global_object, Value options)
  70. {
  71. auto& vm = global_object.vm();
  72. // 1. If options is undefined, then
  73. if (options.is_undefined()) {
  74. // a. Return ! OrdinaryObjectCreate(null).
  75. return Object::create(global_object, nullptr);
  76. }
  77. // 2. If Type(options) is Object, then
  78. if (options.is_object()) {
  79. // a. Return options.
  80. return &options.as_object();
  81. }
  82. // 3. Throw a TypeError exception.
  83. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, "Options");
  84. }
  85. // 13.3 GetOption ( options, property, types, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  86. ThrowCompletionOr<Value> get_option(GlobalObject& global_object, Object const& options, PropertyKey const& property, Vector<OptionType> const& types, Vector<StringView> const& values, Value fallback)
  87. {
  88. VERIFY(property.is_string());
  89. auto& vm = global_object.vm();
  90. // 1. Assert: Type(options) is Object.
  91. // 2. Assert: Each element of types is Boolean, String, or Number.
  92. // 3. Let value be ? Get(options, property).
  93. auto value = TRY(options.get(property));
  94. // 4. If value is undefined, return fallback.
  95. if (value.is_undefined())
  96. return fallback;
  97. OptionType type;
  98. // 5. If types contains Type(value), then
  99. if (auto value_type = to_option_type(value); value_type.has_value() && types.contains_slow(*value_type)) {
  100. // a. Let type be Type(value).
  101. type = *value_type;
  102. }
  103. // 6. Else,
  104. else {
  105. // a. Let type be the last element of types.
  106. type = types.last();
  107. }
  108. // 7. If type is Boolean, then
  109. if (type == OptionType::Boolean) {
  110. // a. Set value to ! ToBoolean(value).
  111. value = Value(value.to_boolean());
  112. }
  113. // 8. Else if type is Number, then
  114. else if (type == OptionType::Number) {
  115. // a. Set value to ? ToNumber(value).
  116. value = TRY(value.to_number(global_object));
  117. // b. If value is NaN, throw a RangeError exception.
  118. if (value.is_nan())
  119. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property.as_string());
  120. }
  121. // 9. Else,
  122. else {
  123. // a. Set value to ? ToString(value).
  124. value = TRY(value.to_primitive_string(global_object));
  125. }
  126. // 10. If values is not empty, then
  127. if (!values.is_empty()) {
  128. VERIFY(value.is_string());
  129. // a. If values does not contain value, throw a RangeError exception.
  130. if (!values.contains_slow(value.as_string().string()))
  131. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  132. }
  133. // 11. Return value.
  134. return value;
  135. }
  136. // 13.4 GetStringOrNumberOption ( options, property, stringValues, minimum, maximum, fallback ), https://tc39.es/proposal-temporal/#sec-getstringornumberoption
  137. template<typename NumberType>
  138. ThrowCompletionOr<Variant<String, NumberType>> get_string_or_number_option(GlobalObject& global_object, Object const& options, PropertyKey const& property, Vector<StringView> const& string_values, NumberType minimum, NumberType maximum, Value fallback)
  139. {
  140. auto& vm = global_object.vm();
  141. // 1. Assert: Type(options) is Object.
  142. // 2. Let value be ? GetOption(options, property, « Number, String », empty, fallback).
  143. auto value = TRY(get_option(global_object, options, property, { OptionType::Number, OptionType::String }, {}, fallback));
  144. // 3. If Type(value) is Number, then
  145. if (value.is_number()) {
  146. // a. If value < minimum or value > maximum, throw a RangeError exception.
  147. if (value.as_double() < minimum || value.as_double() > maximum)
  148. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_double(), property.as_string());
  149. // b. Return floor(ℝ(value)).
  150. return static_cast<NumberType>(floor(value.as_double()));
  151. }
  152. // 4. Assert: Type(value) is String.
  153. VERIFY(value.is_string());
  154. // 5. If stringValues does not contain value, throw a RangeError exception.
  155. if (!string_values.contains_slow(value.as_string().string()))
  156. return vm.template throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  157. // 6. Return value.
  158. return value.as_string().string();
  159. }
  160. // 13.6 ToTemporalOverflow ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  161. ThrowCompletionOr<String> to_temporal_overflow(GlobalObject& global_object, Object const& normalized_options)
  162. {
  163. auto& vm = global_object.vm();
  164. // 1. Return ? GetOption(normalizedOptions, "overflow", « String », « "constrain", "reject" », "constrain").
  165. auto option = TRY(get_option(global_object, normalized_options, vm.names.overflow, { OptionType::String }, { "constrain"sv, "reject"sv }, js_string(vm, "constrain")));
  166. VERIFY(option.is_string());
  167. return option.as_string().string();
  168. }
  169. // 13.7 ToTemporalDisambiguation ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldisambiguation
  170. ThrowCompletionOr<String> to_temporal_disambiguation(GlobalObject& global_object, Object const& normalized_options)
  171. {
  172. auto& vm = global_object.vm();
  173. // 1. Return ? GetOption(normalizedOptions, "disambiguation", « String », « "compatible", "earlier", "later", "reject" », "compatible").
  174. auto option = TRY(get_option(global_object, normalized_options, vm.names.disambiguation, { OptionType::String }, { "compatible"sv, "earlier"sv, "later"sv, "reject"sv }, js_string(vm, "compatible")));
  175. VERIFY(option.is_string());
  176. return option.as_string().string();
  177. }
  178. // 13.8 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  179. ThrowCompletionOr<String> to_temporal_rounding_mode(GlobalObject& global_object, Object const& normalized_options, String const& fallback)
  180. {
  181. auto& vm = global_object.vm();
  182. // 1. Return ? GetOption(normalizedOptions, "roundingMode", « String », « "ceil", "floor", "trunc", "halfExpand" », fallback).
  183. 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)));
  184. VERIFY(option.is_string());
  185. return option.as_string().string();
  186. }
  187. // 13.10 ToTemporalOffset ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloffset
  188. ThrowCompletionOr<String> to_temporal_offset(GlobalObject& global_object, Object const& normalized_options, String const& fallback)
  189. {
  190. auto& vm = global_object.vm();
  191. // 1. Return ? GetOption(normalizedOptions, "offset", « String », « "prefer", "use", "ignore", "reject" », fallback).
  192. auto option = TRY(get_option(global_object, normalized_options, vm.names.offset, { OptionType::String }, { "prefer"sv, "use"sv, "ignore"sv, "reject"sv }, js_string(vm, fallback)));
  193. VERIFY(option.is_string());
  194. return option.as_string().string();
  195. }
  196. // 13.11 ToShowCalendarOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowcalendaroption
  197. ThrowCompletionOr<String> to_show_calendar_option(GlobalObject& global_object, Object const& normalized_options)
  198. {
  199. auto& vm = global_object.vm();
  200. // 1. Return ? GetOption(normalizedOptions, "calendarName", « String », « "auto", "always", "never" », "auto").
  201. 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)));
  202. VERIFY(option.is_string());
  203. return option.as_string().string();
  204. }
  205. // 13.12 ToShowTimeZoneNameOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowtimezonenameoption
  206. ThrowCompletionOr<String> to_show_time_zone_name_option(GlobalObject& global_object, Object const& normalized_options)
  207. {
  208. auto& vm = global_object.vm();
  209. // 1. Return ? GetOption(normalizedOptions, "timeZoneName", « String », « "auto", "never" », "auto").
  210. auto option = TRY(get_option(global_object, normalized_options, vm.names.timeZoneName, { OptionType::String }, { "auto"sv, "never"sv }, js_string(vm, "auto"sv)));
  211. VERIFY(option.is_string());
  212. return option.as_string().string();
  213. }
  214. // 13.13 ToShowOffsetOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowoffsetoption
  215. ThrowCompletionOr<String> to_show_offset_option(GlobalObject& global_object, Object const& normalized_options)
  216. {
  217. auto& vm = global_object.vm();
  218. // 1. Return ? GetOption(normalizedOptions, "offset", « String », « "auto", "never" », "auto").
  219. auto option = TRY(get_option(global_object, normalized_options, vm.names.offset, { OptionType::String }, { "auto"sv, "never"sv }, js_string(vm, "auto"sv)));
  220. VERIFY(option.is_string());
  221. return option.as_string().string();
  222. }
  223. // 13.14 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  224. ThrowCompletionOr<u64> to_temporal_rounding_increment(GlobalObject& global_object, Object const& normalized_options, Optional<double> dividend, bool inclusive)
  225. {
  226. auto& vm = global_object.vm();
  227. double maximum;
  228. // 1. If dividend is undefined, then
  229. if (!dividend.has_value()) {
  230. // a. Let maximum be +∞.
  231. maximum = INFINITY;
  232. }
  233. // 2. Else if inclusive is true, then
  234. else if (inclusive) {
  235. // a. Let maximum be dividend.
  236. maximum = *dividend;
  237. }
  238. // 3. Else if dividend is more than 1, then
  239. else if (*dividend > 1) {
  240. // a. Let maximum be dividend − 1.
  241. maximum = *dividend - 1;
  242. }
  243. // 4. Else,
  244. else {
  245. // a. Let maximum be 1.
  246. maximum = 1;
  247. }
  248. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", « Number », empty, 1).
  249. auto increment_value = TRY(get_option(global_object, normalized_options, vm.names.roundingIncrement, { OptionType::Number }, {}, Value(1)));
  250. VERIFY(increment_value.is_number());
  251. auto increment = increment_value.as_double();
  252. // 6. If increment < 1 or increment > maximum, throw a RangeError exception.
  253. if (increment < 1 || increment > maximum)
  254. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  255. // 7. Set increment to floor(ℝ(increment)).
  256. auto floored_increment = static_cast<u64>(increment);
  257. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  258. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0)
  259. // a. Throw a RangeError exception.
  260. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  261. // 9. Return increment.
  262. return floored_increment;
  263. }
  264. // 13.15 ToTemporalDateTimeRoundingIncrement ( normalizedOptions, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetimeroundingincrement
  265. ThrowCompletionOr<u64> to_temporal_date_time_rounding_increment(GlobalObject& global_object, Object const& normalized_options, StringView smallest_unit)
  266. {
  267. double maximum;
  268. // 1. If smallestUnit is "day", then
  269. if (smallest_unit == "day"sv) {
  270. // a. Let maximum be 1.
  271. maximum = 1;
  272. }
  273. // 2. Else if smallestUnit is "hour", then
  274. else if (smallest_unit == "hour"sv) {
  275. // a. Let maximum be 24.
  276. maximum = 24;
  277. }
  278. // 3. Else if smallestUnit is "minute" or "second", then
  279. else if (smallest_unit.is_one_of("minute"sv, "second"sv)) {
  280. // a. Let maximum be 60.
  281. maximum = 60;
  282. }
  283. // 4. Else,
  284. else {
  285. // a. Assert: smallestUnit is "millisecond", "microsecond", or "nanosecond".
  286. VERIFY(smallest_unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  287. // b. Let maximum be 1000.
  288. maximum = 1000;
  289. }
  290. // 5. Return ? ToTemporalRoundingIncrement(normalizedOptions, maximum, false).
  291. return to_temporal_rounding_increment(global_object, normalized_options, maximum, false);
  292. }
  293. // 13.16 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
  294. ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(GlobalObject& global_object, Object const& normalized_options)
  295. {
  296. auto& vm = global_object.vm();
  297. // Let smallestUnit be ? ToSmallestTemporalUnit(normalizedOptions, « "year", "month", "week", "day", "hour" », undefined).
  298. auto smallest_unit = TRY(to_smallest_temporal_unit(global_object, normalized_options, { "year"sv, "month"sv, "week"sv, "day"sv, "hour"sv }, {}));
  299. // 2. If smallestUnit is "minute", then
  300. if (smallest_unit == "minute"sv) {
  301. // a. Return the Record { [[Precision]]: "minute", [[Unit]]: "minute", [[Increment]]: 1 }.
  302. return SecondsStringPrecision { .precision = "minute"sv, .unit = "minute"sv, .increment = 1 };
  303. }
  304. // 3. If smallestUnit is "second", then
  305. if (smallest_unit == "second"sv) {
  306. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  307. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  308. }
  309. // 4. If smallestUnit is "millisecond", then
  310. if (smallest_unit == "millisecond"sv) {
  311. // a. Return the Record { [[Precision]]: 3, [[Unit]]: "millisecond", [[Increment]]: 1 }.
  312. return SecondsStringPrecision { .precision = 3, .unit = "millisecond"sv, .increment = 1 };
  313. }
  314. // 5. If smallestUnit is "microsecond", then
  315. if (smallest_unit == "microsecond"sv) {
  316. // a. Return the Record { [[Precision]]: 6, [[Unit]]: "microsecond", [[Increment]]: 1 }.
  317. return SecondsStringPrecision { .precision = 6, .unit = "microsecond"sv, .increment = 1 };
  318. }
  319. // 6. If smallestUnit is "nanosecond", then
  320. if (smallest_unit == "nanosecond"sv) {
  321. // a. Return the Record { [[Precision]]: 9, [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  322. return SecondsStringPrecision { .precision = 9, .unit = "nanosecond"sv, .increment = 1 };
  323. }
  324. // 7. Assert: smallestUnit is undefined.
  325. VERIFY(!smallest_unit.has_value());
  326. // 8. Let digits be ? GetStringOrNumberOption(normalizedOptions, "fractionalSecondDigits", « "auto" », 0, 9, "auto").
  327. 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)));
  328. // 9. If digits is "auto", then
  329. if (digits_variant.has<String>()) {
  330. VERIFY(digits_variant.get<String>() == "auto"sv);
  331. // a. Return the Record { [[Precision]]: "auto", [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  332. return SecondsStringPrecision { .precision = "auto"sv, .unit = "nanosecond"sv, .increment = 1 };
  333. }
  334. auto digits = digits_variant.get<u8>();
  335. // 10. If digits is 0, then
  336. if (digits == 0) {
  337. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  338. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  339. }
  340. // 11. If digits is 1, 2, or 3, then
  341. if (digits == 1 || digits == 2 || digits == 3) {
  342. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "millisecond", [[Increment]]: 10^(3 − digits) }.
  343. return SecondsStringPrecision { .precision = digits, .unit = "millisecond"sv, .increment = (u32)pow(10, 3 - digits) };
  344. }
  345. // 12. If digits is 4, 5, or 6, then
  346. if (digits == 4 || digits == 5 || digits == 6) {
  347. // a. Return the Record { [[Precision]]: digits, [[Unit]]: "microsecond", [[Increment]]: 10^(6 − digits) }.
  348. return SecondsStringPrecision { .precision = digits, .unit = "microsecond"sv, .increment = (u32)pow(10, 6 - digits) };
  349. }
  350. // 13. Assert: digits is 7, 8, or 9.
  351. VERIFY(digits == 7 || digits == 8 || digits == 9);
  352. // 14. Return the Record { [[Precision]]: digits, [[Unit]]: "nanosecond", [[Increment]]: 10^(9 − digits) }.
  353. return SecondsStringPrecision { .precision = digits, .unit = "nanosecond"sv, .increment = (u32)pow(10, 9 - digits) };
  354. }
  355. // https://tc39.es/proposal-temporal/#table-temporal-singular-and-plural-units
  356. static HashMap<StringView, StringView> plural_to_singular_units = {
  357. { "years"sv, "year"sv },
  358. { "months"sv, "month"sv },
  359. { "weeks"sv, "week"sv },
  360. { "days"sv, "day"sv },
  361. { "hours"sv, "hour"sv },
  362. { "minutes"sv, "minute"sv },
  363. { "seconds"sv, "second"sv },
  364. { "milliseconds"sv, "millisecond"sv },
  365. { "microseconds"sv, "microsecond"sv },
  366. { "nanoseconds"sv, "nanosecond"sv }
  367. };
  368. // 13.17 ToLargestTemporalUnit ( normalizedOptions, disallowedUnits, fallback [ , autoValue ] ), https://tc39.es/proposal-temporal/#sec-temporal-tolargesttemporalunit
  369. 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)
  370. {
  371. auto& vm = global_object.vm();
  372. // 1. Assert: disallowedUnits does not contain fallback.
  373. // 2. Assert: disallowedUnits does not contain "auto".
  374. // 3. Assert: autoValue is not present or fallback is "auto".
  375. VERIFY(!auto_value.has_value() || fallback == "auto"sv);
  376. // 4. Assert: autoValue is not present or disallowedUnits does not contain autoValue.
  377. // 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).
  378. 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)));
  379. auto largest_unit = largest_unit_value.as_string().string();
  380. // 6. If largestUnit is "auto" and autoValue is present, then
  381. if (largest_unit == "auto"sv && auto_value.has_value()) {
  382. // a. Return autoValue.
  383. return *auto_value;
  384. }
  385. // 7. If largestUnit is in the Plural column of Table 12, then
  386. if (auto singular_unit = plural_to_singular_units.get(largest_unit); singular_unit.has_value()) {
  387. // a. Set largestUnit to the corresponding Singular value of the same row.
  388. largest_unit = singular_unit.value();
  389. }
  390. // 8. If disallowedUnits contains largestUnit, then
  391. if (disallowed_units.contains_slow(largest_unit)) {
  392. // a. Throw a RangeError exception.
  393. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, largest_unit, vm.names.largestUnit.as_string());
  394. }
  395. // 9. Return largestUnit.
  396. return largest_unit;
  397. }
  398. // 13.18 ToSmallestTemporalUnit ( normalizedOptions, disallowedUnits, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-tosmallesttemporalunit
  399. ThrowCompletionOr<Optional<String>> to_smallest_temporal_unit(GlobalObject& global_object, Object const& normalized_options, Vector<StringView> const& disallowed_units, Optional<String> fallback)
  400. {
  401. auto& vm = global_object.vm();
  402. // 1. Assert: disallowedUnits does not contain fallback.
  403. // 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).
  404. 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()));
  405. // OPTIMIZATION: We skip the following string-only checks for the fallback to tidy up the code a bit
  406. if (smallest_unit_value.is_undefined())
  407. return Optional<String> {};
  408. VERIFY(smallest_unit_value.is_string());
  409. auto smallest_unit = smallest_unit_value.as_string().string();
  410. // 3. If smallestUnit is in the Plural column of Table 12, then
  411. if (auto singular_unit = plural_to_singular_units.get(smallest_unit); singular_unit.has_value()) {
  412. // a. Set smallestUnit to the corresponding Singular value of the same row.
  413. smallest_unit = singular_unit.value();
  414. }
  415. // 4. If disallowedUnits contains smallestUnit, then
  416. if (disallowed_units.contains_slow(smallest_unit)) {
  417. // a. Throw a RangeError exception.
  418. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, smallest_unit, vm.names.smallestUnit.as_string());
  419. }
  420. // 5. Return smallestUnit.
  421. return smallest_unit;
  422. }
  423. // 13.19 ToTemporalDurationTotalUnit ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldurationtotalunit
  424. ThrowCompletionOr<String> to_temporal_duration_total_unit(GlobalObject& global_object, Object const& normalized_options)
  425. {
  426. auto& vm = global_object.vm();
  427. // 1. Let unit be ? GetOption(normalizedOptions, "unit", « String », « "year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds", "microsecond", "microseconds", "nanosecond", "nanoseconds" », undefined).
  428. auto unit_value = TRY(get_option(global_object, normalized_options, vm.names.unit, { 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 }, js_undefined()));
  429. // 2. If unit is undefined, then
  430. if (unit_value.is_undefined()) {
  431. // a. Throw a RangeError exception.
  432. return vm.throw_completion<RangeError>(global_object, ErrorType::IsUndefined, "unit option value"sv);
  433. }
  434. auto unit = unit_value.as_string().string();
  435. // 3. If unit is in the Plural column of Table 12, then
  436. if (auto singular_unit = plural_to_singular_units.get(unit); singular_unit.has_value()) {
  437. // a. Set unit to the corresponding Singular value of the same row.
  438. unit = *singular_unit;
  439. }
  440. // 4. Return unit.
  441. return unit;
  442. }
  443. // 13.21 ToRelativeTemporalObject ( options ), https://tc39.es/proposal-temporal/#sec-temporal-torelativetemporalobject
  444. ThrowCompletionOr<Value> to_relative_temporal_object(GlobalObject& global_object, Object const& options)
  445. {
  446. auto& vm = global_object.vm();
  447. // 1. Assert: Type(options) is Object.
  448. // 2. Let value be ? Get(options, "relativeTo").
  449. auto value = TRY(options.get(vm.names.relativeTo));
  450. // 3. If value is undefined, then
  451. if (value.is_undefined()) {
  452. // a. Return value.
  453. return value;
  454. }
  455. // 4. Let offsetBehaviour be option.
  456. auto offset_behavior = OffsetBehavior::Option;
  457. // 5. Let matchBehaviour be match exactly.
  458. auto match_behavior = MatchBehavior::MatchExactly;
  459. ISODateTime result;
  460. Value offset_string;
  461. Value time_zone;
  462. Object* calendar = nullptr;
  463. // 6. If Type(value) is Object, then
  464. if (value.is_object()) {
  465. auto& value_object = value.as_object();
  466. // a. If value has either an [[InitializedTemporalDateTime]] or [[InitializedTemporalZonedDateTime]] internal slot, then
  467. if (is<PlainDateTime>(value_object) || is<ZonedDateTime>(value_object)) {
  468. // i. Return value.
  469. return value;
  470. }
  471. // b. If value has an [[InitializedTemporalDate]] internal slot, then
  472. if (is<PlainDate>(value_object)) {
  473. auto& plain_date_object = static_cast<PlainDate&>(value_object);
  474. // i. Return ? CreateTemporalDateTime(value.[[ISOYear]], value.[[ISOMonth]], value.[[ISODay]], 0, 0, 0, 0, 0, 0, value.[[Calendar]]).
  475. return TRY(create_temporal_date_time(global_object, plain_date_object.iso_year(), plain_date_object.iso_month(), plain_date_object.iso_day(), 0, 0, 0, 0, 0, 0, plain_date_object.calendar()));
  476. }
  477. // c. Let calendar be ? GetTemporalCalendarWithISODefault(value).
  478. calendar = TRY(get_temporal_calendar_with_iso_default(global_object, value_object));
  479. // d. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  480. auto field_names = TRY(calendar_fields(global_object, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv }));
  481. // e. Let fields be ? PrepareTemporalFields(value, fieldNames, «»).
  482. auto* fields = TRY(prepare_temporal_fields(global_object, value_object, field_names, {}));
  483. // f. Let dateOptions be ! OrdinaryObjectCreate(null).
  484. auto* date_options = Object::create(global_object, nullptr);
  485. // g. Perform ! CreateDataPropertyOrThrow(dateOptions, "overflow", "constrain").
  486. MUST(date_options->create_data_property_or_throw(vm.names.overflow, js_string(vm, "constrain"sv)));
  487. // h. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, dateOptions).
  488. result = TRY(interpret_temporal_date_time_fields(global_object, *calendar, *fields, *date_options));
  489. // i. Let offsetString be ? Get(value, "offset").
  490. offset_string = TRY(value_object.get(vm.names.offset));
  491. // j. Let timeZone be ? Get(value, "timeZone").
  492. time_zone = TRY(value_object.get(vm.names.timeZone));
  493. // k. If offsetString is undefined, then
  494. if (offset_string.is_undefined()) {
  495. // i. Set offsetBehaviour to wall.
  496. offset_behavior = OffsetBehavior::Wall;
  497. }
  498. }
  499. // 7. Else,
  500. else {
  501. // a. Let string be ? ToString(value).
  502. auto string = TRY(value.to_string(global_object));
  503. // b. Let result be ? ParseTemporalRelativeToString(string).
  504. auto parsed_result = TRY(parse_temporal_relative_to_string(global_object, string));
  505. // NOTE: The ISODateTime struct inside `parsed_result` will be moved into `result` at the end of this path to avoid mismatching names.
  506. // Thus, all remaining references to `result` in this path actually refer to `parsed_result`.
  507. // c. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  508. calendar = TRY(to_temporal_calendar_with_iso_default(global_object, parsed_result.date_time.calendar.has_value() ? js_string(vm, *parsed_result.date_time.calendar) : js_undefined()));
  509. // d. Let offsetString be result.[[TimeZoneOffset]].
  510. offset_string = parsed_result.time_zone.offset.has_value() ? js_string(vm, *parsed_result.time_zone.offset) : js_undefined();
  511. // e. Let timeZone be result.[[TimeZoneIANAName]].
  512. time_zone = parsed_result.time_zone.name.has_value() ? js_string(vm, *parsed_result.time_zone.name) : js_undefined();
  513. // f. If result.[[TimeZoneZ]] is true, then
  514. if (parsed_result.time_zone.z) {
  515. // i. Set offsetBehaviour to exact.
  516. offset_behavior = OffsetBehavior::Exact;
  517. }
  518. // g. Else if offsetString is undefined, then
  519. else if (offset_string.is_undefined()) {
  520. // i. Set offsetBehaviour to wall.
  521. offset_behavior = OffsetBehavior::Wall;
  522. }
  523. // h. Set matchBehaviour to match minutes.
  524. match_behavior = MatchBehavior::MatchMinutes;
  525. // See NOTE above about why this is done.
  526. result = move(parsed_result.date_time);
  527. }
  528. // 8. If timeZone is not undefined, then
  529. if (!time_zone.is_undefined()) {
  530. // a. Set timeZone to ? ToTemporalTimeZone(timeZone).
  531. time_zone = TRY(to_temporal_time_zone(global_object, time_zone));
  532. double offset_ns;
  533. // b. If offsetBehaviour is option, then
  534. if (offset_behavior == OffsetBehavior::Option) {
  535. // i. Set offsetString to ? ToString(offsetString).
  536. // NOTE: offsetString is not used after this path, so we don't need to put this into the original offset_string which is of type JS::Value.
  537. auto actual_offset_string = TRY(offset_string.to_string(global_object));
  538. // ii. Let offsetNs be ? ParseTimeZoneOffsetString(offsetString).
  539. offset_ns = TRY(parse_time_zone_offset_string(global_object, actual_offset_string));
  540. }
  541. // c. Else,
  542. else {
  543. // i. Let offsetNs be 0.
  544. offset_ns = 0;
  545. }
  546. // d. Let epochNanoseconds be ? InterpretISODateTimeOffset(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], offsetBehaviour, offsetNs, timeZone, "compatible", "reject", matchBehaviour).
  547. auto* epoch_nanoseconds = TRY(interpret_iso_date_time_offset(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, offset_behavior, offset_ns, time_zone, "compatible"sv, "reject"sv, match_behavior));
  548. // e. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  549. return MUST(create_temporal_zoned_date_time(global_object, *epoch_nanoseconds, time_zone.as_object(), *calendar));
  550. }
  551. // 9. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
  552. return TRY(create_temporal_date_time(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, *calendar));
  553. }
  554. // 13.22 ValidateTemporalUnitRange ( largestUnit, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-validatetemporalunitrange
  555. ThrowCompletionOr<void> validate_temporal_unit_range(GlobalObject& global_object, StringView largest_unit, StringView smallest_unit)
  556. {
  557. auto& vm = global_object.vm();
  558. // 1. If smallestUnit is "year" and largestUnit is not "year", then
  559. if (smallest_unit == "year"sv && largest_unit != "year"sv) {
  560. // a. Throw a RangeError exception.
  561. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  562. }
  563. // 2. If smallestUnit is "month" and largestUnit is not "year" or "month", then
  564. if (smallest_unit == "month"sv && !largest_unit.is_one_of("year"sv, "month"sv)) {
  565. // a. Throw a RangeError exception.
  566. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  567. }
  568. // 3. If smallestUnit is "week" and largestUnit is not one of "year", "month", or "week", then
  569. if (smallest_unit == "week"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv)) {
  570. // a. Throw a RangeError exception.
  571. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  572. }
  573. // 4. If smallestUnit is "day" and largestUnit is not one of "year", "month", "week", or "day", then
  574. if (smallest_unit == "day"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  575. // a. Throw a RangeError exception.
  576. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  577. }
  578. // 5. If smallestUnit is "hour" and largestUnit is not one of "year", "month", "week", "day", or "hour", then
  579. if (smallest_unit == "hour"sv && !largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv, "hour"sv)) {
  580. // a. Throw a RangeError exception.
  581. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  582. }
  583. // 6. If smallestUnit is "minute" and largestUnit is "second", "millisecond", "microsecond", or "nanosecond", then
  584. if (smallest_unit == "minute"sv && largest_unit.is_one_of("second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  585. // a. Throw a RangeError exception.
  586. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  587. }
  588. // 7. If smallestUnit is "second" and largestUnit is "millisecond", "microsecond", or "nanosecond", then
  589. if (smallest_unit == "second"sv && largest_unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  590. // a. Throw a RangeError exception.
  591. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  592. }
  593. // 8. If smallestUnit is "millisecond" and largestUnit is "microsecond" or "nanosecond", then
  594. if (smallest_unit == "millisecond"sv && largest_unit.is_one_of("microsecond"sv, "nanosecond"sv)) {
  595. // a. Throw a RangeError exception.
  596. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  597. }
  598. // 9. If smallestUnit is "microsecond" and largestUnit is "nanosecond", then
  599. if (smallest_unit == "microsecond"sv && largest_unit == "nanosecond"sv) {
  600. // a. Throw a RangeError exception.
  601. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, smallest_unit, largest_unit);
  602. }
  603. return {};
  604. }
  605. // 13.23 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  606. String larger_of_two_temporal_units(StringView unit1, StringView unit2)
  607. {
  608. // 1. If either u1 or u2 is "year", return "year".
  609. if (unit1 == "year"sv || unit2 == "year"sv)
  610. return "year"sv;
  611. // 2. If either u1 or u2 is "month", return "month".
  612. if (unit1 == "month"sv || unit2 == "month"sv)
  613. return "month"sv;
  614. // 3. If either u1 or u2 is "week", return "week".
  615. if (unit1 == "week"sv || unit2 == "week"sv)
  616. return "week"sv;
  617. // 4. If either u1 or u2 is "day", return "day".
  618. if (unit1 == "day"sv || unit2 == "day"sv)
  619. return "day"sv;
  620. // 5. If either u1 or u2 is "hour", return "hour".
  621. if (unit1 == "hour"sv || unit2 == "hour"sv)
  622. return "hour"sv;
  623. // 6. If either u1 or u2 is "minute", return "minute".
  624. if (unit1 == "minute"sv || unit2 == "minute"sv)
  625. return "minute"sv;
  626. // 7. If either u1 or u2 is "second", return "second".
  627. if (unit1 == "second"sv || unit2 == "second"sv)
  628. return "second"sv;
  629. // 8. If either u1 or u2 is "millisecond", return "millisecond".
  630. if (unit1 == "millisecond"sv || unit2 == "millisecond"sv)
  631. return "millisecond"sv;
  632. // 9. If either u1 or u2 is "microsecond", return "microsecond".
  633. if (unit1 == "microsecond"sv || unit2 == "microsecond"sv)
  634. return "microsecond"sv;
  635. // 10. Return "nanosecond".
  636. return "nanosecond"sv;
  637. }
  638. // 13.24 MergeLargestUnitOption ( options, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-mergelargestunitoption
  639. ThrowCompletionOr<Object*> merge_largest_unit_option(GlobalObject& global_object, Object& options, String largest_unit)
  640. {
  641. auto& vm = global_object.vm();
  642. // 1. Let merged be ! OrdinaryObjectCreate(%Object.prototype%).
  643. auto* merged = Object::create(global_object, global_object.object_prototype());
  644. // 2. Let keys be ? EnumerableOwnPropertyNames(options, key).
  645. auto keys = TRY(options.enumerable_own_property_names(Object::PropertyKind::Key));
  646. // 3. For each element nextKey of keys, do
  647. for (auto& key : keys) {
  648. auto next_key = PropertyKey::from_value(global_object, key);
  649. // a. Let propValue be ? Get(options, nextKey).
  650. auto prop_value = TRY(options.get(next_key));
  651. // b. Perform ! CreateDataPropertyOrThrow(merged, nextKey, propValue).
  652. MUST(merged->create_data_property_or_throw(next_key, prop_value));
  653. }
  654. // 4. Perform ! CreateDataPropertyOrThrow(merged, "largestUnit", largestUnit).
  655. MUST(merged->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, move(largest_unit))));
  656. // 5. Return merged.
  657. return merged;
  658. }
  659. // 13.25 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  660. Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit)
  661. {
  662. // 1. If unit is "year", "month", "week", or "day", then
  663. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  664. // a. Return undefined.
  665. return {};
  666. }
  667. // 2. If unit is "hour", then
  668. if (unit == "hour"sv) {
  669. // a. Return 24.
  670. return 24;
  671. }
  672. // 3. If unit is "minute" or "second", then
  673. if (unit.is_one_of("minute"sv, "second"sv)) {
  674. // a. Return 60.
  675. return 60;
  676. }
  677. // 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
  678. VERIFY(unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  679. // 5. Return 1000.
  680. return 1000;
  681. }
  682. // 13.26 RejectObjectWithCalendarOrTimeZone ( object ), https://tc39.es/proposal-temporal/#sec-temporal-rejectobjectwithcalendarortimezone
  683. ThrowCompletionOr<void> reject_object_with_calendar_or_time_zone(GlobalObject& global_object, Object& object)
  684. {
  685. auto& vm = global_object.vm();
  686. // 1. Assert: Type(object) is Object.
  687. // 2. If object has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  688. if (is<PlainDate>(object) || is<PlainDateTime>(object) || is<PlainMonthDay>(object) || is<PlainTime>(object) || is<PlainYearMonth>(object) || is<ZonedDateTime>(object)) {
  689. // a. Throw a TypeError exception.
  690. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "calendar or timeZone");
  691. }
  692. // 3. Let calendarProperty be ? Get(object, "calendar").
  693. auto calendar_property = TRY(object.get(vm.names.calendar));
  694. // 4. If calendarProperty is not undefined, then
  695. if (!calendar_property.is_undefined()) {
  696. // a. Throw a TypeError exception.
  697. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "calendar");
  698. }
  699. // 5. Let timeZoneProperty be ? Get(object, "timeZone").
  700. auto time_zone_property = TRY(object.get(vm.names.timeZone));
  701. // 6. If timeZoneProperty is not undefined, then
  702. if (!time_zone_property.is_undefined()) {
  703. // a. Throw a TypeError exception.
  704. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustNotHave, "timeZone");
  705. }
  706. return {};
  707. }
  708. // 13.27 FormatSecondsStringPart ( second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatsecondsstringpart
  709. String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  710. {
  711. // 1. Assert: second, millisecond, microsecond and nanosecond are integers.
  712. // Non-standard sanity check
  713. if (precision.has<StringView>())
  714. VERIFY(precision.get<StringView>().is_one_of("minute"sv, "auto"sv));
  715. // 2. If precision is "minute", return "".
  716. if (precision.has<StringView>() && precision.get<StringView>() == "minute"sv)
  717. return String::empty();
  718. // 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.
  719. auto seconds_string = String::formatted(":{:02}", second);
  720. // 4. Let fraction be millisecond × 10^6 + microsecond × 10^3 + nanosecond.
  721. u32 fraction = millisecond * 1'000'000 + microsecond * 1'000 + nanosecond;
  722. String fraction_string;
  723. // 5. If precision is "auto", then
  724. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  725. // a. If fraction is 0, return secondsString.
  726. if (fraction == 0)
  727. return seconds_string;
  728. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  729. fraction_string = String::formatted("{:09}", fraction);
  730. // c. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  731. fraction_string = fraction_string.trim("0"sv, TrimMode::Right);
  732. }
  733. // 6. Else,
  734. else {
  735. // a. If precision is 0, return secondsString.
  736. if (precision.get<u8>() == 0)
  737. return seconds_string;
  738. // b. Set fraction to fraction formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  739. fraction_string = String::formatted("{:09}", fraction);
  740. // c. Set fraction to the substring of fraction from 0 to precision.
  741. fraction_string = fraction_string.substring(0, precision.get<u8>());
  742. }
  743. // 7. Return the string-concatenation of secondsString, the code unit 0x002E (FULL STOP), and fraction.
  744. return String::formatted("{}.{}", seconds_string, fraction_string);
  745. }
  746. // 13.28 Sign ( n ), https://tc39.es/proposal-temporal/#sec-temporal-sign
  747. double sign(double n)
  748. {
  749. // 1. If n is NaN, n is +0𝔽, or n is −0𝔽, return n.
  750. if (isnan(n) || n == 0)
  751. return n;
  752. // 2. If n < +0𝔽, return −1𝔽.
  753. if (n < 0)
  754. return -1;
  755. // 3. Return 1𝔽.
  756. return 1;
  757. }
  758. // 13.29 ConstrainToRange ( x, minimum, maximum ), https://tc39.es/proposal-temporal/#sec-temporal-constraintorange
  759. double constrain_to_range(double x, double minimum, double maximum)
  760. {
  761. // 1. Assert: x, minimum and maximum are mathematical values.
  762. // 2. Return min(max(x, minimum), maximum).
  763. return min(max(x, minimum), maximum);
  764. }
  765. // NOTE: We have two variants of this function, one using doubles and one using BigInts - most of the time
  766. // doubles will be fine, but take care to choose the right one. The spec is not very clear about this, as
  767. // it uses mathematical values which can be arbitrarily (but not infinitely) large.
  768. // Incidentally V8's Temporal implementation does the same :^)
  769. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  770. i64 round_number_to_increment(double x, u64 increment, StringView rounding_mode)
  771. {
  772. // 1. Assert: x and increment are mathematical values.
  773. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  774. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  775. // 3. Let quotient be x / increment.
  776. auto quotient = x / (double)increment;
  777. double rounded;
  778. // 4. If roundingMode is "ceil", then
  779. if (rounding_mode == "ceil"sv) {
  780. // a. Let rounded be −floor(−quotient).
  781. rounded = -floor(-quotient);
  782. }
  783. // 5. Else if roundingMode is "floor", then
  784. else if (rounding_mode == "floor"sv) {
  785. // a. Let rounded be floor(quotient).
  786. rounded = floor(quotient);
  787. }
  788. // 6. Else if roundingMode is "trunc", then
  789. else if (rounding_mode == "trunc"sv) {
  790. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  791. rounded = trunc(quotient);
  792. }
  793. // 7. Else,
  794. else {
  795. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  796. rounded = round(quotient);
  797. }
  798. // 8. Return rounded × increment.
  799. return (i64)rounded * (i64)increment;
  800. }
  801. // 13.32 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  802. BigInt* round_number_to_increment(GlobalObject& global_object, BigInt const& x, u64 increment, StringView rounding_mode)
  803. {
  804. auto& heap = global_object.heap();
  805. // 1. Assert: x and increment are mathematical values.
  806. // 2. Assert: roundingMode is "ceil", "floor", "trunc", or "halfExpand".
  807. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  808. // OPTIMIZATION: If the increment is 1 the number is always rounded
  809. if (increment == 1)
  810. return js_bigint(heap, x.big_integer());
  811. auto increment_big_int = Crypto::UnsignedBigInteger::create_from(increment);
  812. // 3. Let quotient be x / increment.
  813. auto division_result = x.big_integer().divided_by(increment_big_int);
  814. // OPTIMIZATION: If there's no remainder the number is already rounded
  815. if (division_result.remainder == Crypto::UnsignedBigInteger { 0 })
  816. return js_bigint(heap, x.big_integer());
  817. Crypto::SignedBigInteger rounded = move(division_result.quotient);
  818. // 4. If roundingMode is "ceil", then
  819. if (rounding_mode == "ceil"sv) {
  820. // a. Let rounded be −floor(−quotient).
  821. if (!division_result.remainder.is_negative())
  822. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  823. }
  824. // 5. Else if roundingMode is "floor", then
  825. else if (rounding_mode == "floor"sv) {
  826. // a. Let rounded be floor(quotient).
  827. if (division_result.remainder.is_negative())
  828. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  829. }
  830. // 6. Else if roundingMode is "trunc", then
  831. else if (rounding_mode == "trunc"sv) {
  832. // a. Let rounded be the integral part of quotient, removing any fractional digits.
  833. // NOTE: This is a no-op
  834. }
  835. // 7. Else,
  836. else {
  837. // a. Let rounded be ! RoundHalfAwayFromZero(quotient).
  838. if (division_result.remainder.multiplied_by(Crypto::UnsignedBigInteger { 2 }).unsigned_value() >= increment_big_int) {
  839. if (division_result.remainder.is_negative())
  840. rounded = rounded.minus(Crypto::UnsignedBigInteger { 1 });
  841. else
  842. rounded = rounded.plus(Crypto::UnsignedBigInteger { 1 });
  843. }
  844. }
  845. // 8. Return rounded × increment.
  846. return js_bigint(heap, rounded.multiplied_by(increment_big_int));
  847. }
  848. // 13.34 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  849. ThrowCompletionOr<ISODateTime> parse_iso_date_time(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  850. {
  851. auto& vm = global_object.vm();
  852. // 1. Assert: Type(isoString) is String.
  853. // 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.
  854. Optional<StringView> year_part;
  855. Optional<StringView> month_part;
  856. Optional<StringView> day_part;
  857. Optional<StringView> hour_part;
  858. Optional<StringView> minute_part;
  859. Optional<StringView> second_part;
  860. Optional<StringView> fraction_part;
  861. Optional<StringView> calendar_part;
  862. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseISODateTime");
  863. // 3. Let year be the part of isoString produced by the DateYear production.
  864. // 4. If the first code unit of year is 0x2212 (MINUS SIGN), replace it with the code unit 0x002D (HYPHEN-MINUS).
  865. String normalized_year;
  866. if (year_part.has_value() && year_part->starts_with("\xE2\x88\x92"sv))
  867. normalized_year = String::formatted("-{}", year_part->substring_view(3));
  868. else
  869. normalized_year = year_part.value_or("");
  870. // 5. Set year to ! ToIntegerOrInfinity(year).
  871. i32 year = MUST(Value(js_string(vm, normalized_year)).to_integer_or_infinity(global_object));
  872. u8 month;
  873. // 6. If month is undefined, then
  874. if (!month_part.has_value()) {
  875. // a. Set month to 1.
  876. month = 1;
  877. }
  878. // 7. Else,
  879. else {
  880. // a. Set month to ! ToIntegerOrInfinity(month).
  881. month = *month_part->to_uint<u8>();
  882. }
  883. u8 day;
  884. // 8. If day is undefined, then
  885. if (!day_part.has_value()) {
  886. // a. Set day to 1.
  887. day = 1;
  888. }
  889. // 9. Else,
  890. else {
  891. // a. Set day to ! ToIntegerOrInfinity(day).
  892. day = *day_part->to_uint<u8>();
  893. }
  894. // 10. Set hour to ! ToIntegerOrInfinity(hour).
  895. u8 hour = hour_part->to_uint<u8>().value_or(0);
  896. // 11. Set minute to ! ToIntegerOrInfinity(minute).
  897. u8 minute = minute_part->to_uint<u8>().value_or(0);
  898. // 12. Set second to ! ToIntegerOrInfinity(second).
  899. u8 second = second_part->to_uint<u8>().value_or(0);
  900. // 13. If second is 60, then
  901. if (second == 60) {
  902. // a. Set second to 59.
  903. second = 59;
  904. }
  905. u16 millisecond;
  906. u16 microsecond;
  907. u16 nanosecond;
  908. // 14. If fraction is not undefined, then
  909. if (fraction_part.has_value()) {
  910. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  911. auto fraction = String::formatted("{}000000000", *fraction_part);
  912. // b. Let millisecond be the String value equal to the substring of fraction from 0 to 3.
  913. // c. Set millisecond to ! ToIntegerOrInfinity(millisecond).
  914. millisecond = *fraction.substring(0, 3).to_uint<u16>();
  915. // d. Let microsecond be the String value equal to the substring of fraction from 3 to 6.
  916. // e. Set microsecond to ! ToIntegerOrInfinity(microsecond).
  917. microsecond = *fraction.substring(3, 3).to_uint<u16>();
  918. // f. Let nanosecond be the String value equal to the substring of fraction from 6 to 9.
  919. // g. Set nanosecond to ! ToIntegerOrInfinity(nanosecond).
  920. nanosecond = *fraction.substring(6, 3).to_uint<u16>();
  921. }
  922. // 15. Else,
  923. else {
  924. // a. Let millisecond be 0.
  925. millisecond = 0;
  926. // b. Let microsecond be 0.
  927. microsecond = 0;
  928. // c. Let nanosecond be 0.
  929. nanosecond = 0;
  930. }
  931. // 16. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  932. if (!is_valid_iso_date(year, month, day))
  933. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidISODate);
  934. // 17. If ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  935. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  936. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTime);
  937. // 18. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond, [[Calendar]]: calendar }.
  938. 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>() };
  939. }
  940. // 13.35 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  941. ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(GlobalObject& global_object, String const& iso_string)
  942. {
  943. // 1. Assert: Type(isoString) is String.
  944. // 2. If isoString does not satisfy the syntax of a TemporalInstantString (see 13.33), then
  945. // a. Throw a RangeError exception.
  946. // TODO
  947. // 3. Let result be ! ParseISODateTime(isoString).
  948. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  949. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  950. auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string));
  951. // 5. Let offsetString be timeZoneResult.[[OffsetString]].
  952. auto offset_string = time_zone_result.offset;
  953. // 6. If timeZoneResult.[[Z]] is true, then
  954. if (time_zone_result.z) {
  955. // a. Set offsetString to "+00:00".
  956. offset_string = "+00:00"sv;
  957. }
  958. // 7. Assert: offsetString is not undefined.
  959. VERIFY(offset_string.has_value());
  960. // 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 }.
  961. 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) };
  962. }
  963. // 13.36 ParseTemporalZonedDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalzoneddatetimestring
  964. ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_zoned_date_time_string(GlobalObject& global_object, String const& iso_string)
  965. {
  966. // 1. Assert: Type(isoString) is String.
  967. // 2. If isoString does not satisfy the syntax of a TemporalZonedDateTimeString (see 13.33), then
  968. // a. Throw a RangeError exception.
  969. // TODO
  970. // 3. Let result be ! ParseISODateTime(isoString).
  971. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  972. // 4. Let timeZoneResult be ? ParseTemporalTimeZoneString(isoString).
  973. auto time_zone_result = TRY(parse_temporal_time_zone_string(global_object, iso_string));
  974. // 5. 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]], [[Calendar]]: result.[[Calendar]], [[TimeZoneZ]]: timeZoneResult.[[Z]], [[TimeZoneOffsetString]]: timeZoneResult.[[OffsetString]], [[TimeZoneName]]: timeZoneResult.[[Name]] }.
  975. // NOTE: This returns the two structs together instead of separated to avoid a copy in ToTemporalZonedDateTime, as the spec tries to put the result of InterpretTemporalDateTimeFields and ParseTemporalZonedDateTimeString into the same `result` variable.
  976. // InterpretTemporalDateTimeFields returns an ISODateTime, so the moved in `result` here is subsequently moved into ParseTemporalZonedDateTimeString's `result` variable.
  977. return TemporalZonedDateTime { .date_time = move(result), .time_zone = move(time_zone_result) };
  978. }
  979. // 13.37 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  980. ThrowCompletionOr<String> parse_temporal_calendar_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  981. {
  982. auto& vm = global_object.vm();
  983. // 1. Assert: Type(isoString) is String.
  984. // 2. If isoString does not satisfy the syntax of a TemporalCalendarString (see 13.33), then
  985. // a. Throw a RangeError exception.
  986. // 3. Let id be the part of isoString produced by the CalendarName production, or undefined if not present.
  987. Optional<StringView> id_part;
  988. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalCalendarString");
  989. // 4. If id is undefined, then
  990. if (!id_part.has_value()) {
  991. // a. Return "iso8601".
  992. return "iso8601"sv;
  993. }
  994. // 5. If ! IsBuiltinCalendar(id) is false, then
  995. if (!is_builtin_calendar(*id_part)) {
  996. // a. Throw a RangeError exception.
  997. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, *id_part);
  998. }
  999. // 6. Return id.
  1000. return id_part.value();
  1001. }
  1002. // 13.38 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  1003. ThrowCompletionOr<TemporalDate> parse_temporal_date_string(GlobalObject& global_object, String const& iso_string)
  1004. {
  1005. // 1. Assert: Type(isoString) is String.
  1006. // 2. If isoString does not satisfy the syntax of a TemporalDateString (see 13.33), then
  1007. // a. Throw a RangeError exception.
  1008. // TODO
  1009. // 3. Let result be ? ParseISODateTime(isoString).
  1010. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1011. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1012. return TemporalDate { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1013. }
  1014. // 13.39 ParseTemporalDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatetimestring
  1015. ThrowCompletionOr<ISODateTime> parse_temporal_date_time_string(GlobalObject& global_object, String const& iso_string)
  1016. {
  1017. // 1. Assert: Type(isoString) is String.
  1018. // 2. If isoString does not satisfy the syntax of a TemporalDateTimeString (see 13.33), then
  1019. // a. Throw a RangeError exception.
  1020. // TODO
  1021. // 3. Let result be ? ParseISODateTime(isoString).
  1022. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1023. // 4. Return result.
  1024. return result;
  1025. }
  1026. // 13.40 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  1027. ThrowCompletionOr<TemporalDuration> parse_temporal_duration_string(GlobalObject& global_object, String const& iso_string)
  1028. {
  1029. (void)iso_string;
  1030. auto& vm = global_object.vm();
  1031. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalDurationString");
  1032. }
  1033. // 13.41 ParseTemporalMonthDayString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalmonthdaystring
  1034. ThrowCompletionOr<TemporalMonthDay> parse_temporal_month_day_string(GlobalObject& global_object, String const& iso_string)
  1035. {
  1036. // 1. Assert: Type(isoString) is String.
  1037. // 2. If isoString does not satisfy the syntax of a TemporalMonthDayString (see 13.33), then
  1038. // a. Throw a RangeError exception.
  1039. // TODO
  1040. // 3. Let result be ? ParseISODateTime(isoString).
  1041. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1042. // 4. Let year be result.[[Year]].
  1043. Optional<i32> year = result.year;
  1044. // 5. If no part of isoString is produced by the DateYear production, then
  1045. // a. Set year to undefined.
  1046. // TODO (this is the case when TemporalMonthDayString is a DateSpecMonthDay)
  1047. // 6. Return the Record { [[Year]]: year, [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1048. return TemporalMonthDay { .year = year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1049. }
  1050. // 13.42 ParseTemporalRelativeToString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalrelativetostring
  1051. ThrowCompletionOr<TemporalZonedDateTime> parse_temporal_relative_to_string(GlobalObject& global_object, String const& iso_string)
  1052. {
  1053. // 1. Assert: Type(isoString) is String.
  1054. // 2. If isoString does not satisfy the syntax of a TemporalRelativeToString (see 13.33), then
  1055. // a. Throw a RangeError exception.
  1056. // TODO
  1057. // 3. Let result be ! ParseISODateTime(isoString).
  1058. auto result = MUST(parse_iso_date_time(global_object, iso_string));
  1059. bool z;
  1060. Optional<String> offset;
  1061. Optional<String> time_zone;
  1062. // TODO: 4. If isoString satisfies the syntax of a TemporalZonedDateTimeString (see 13.33), then
  1063. // a. Let timeZoneResult be ! ParseTemporalTimeZoneString(isoString).
  1064. // b. Let z be timeZoneResult.[[Z]].
  1065. // c. Let offset be timeZoneResult.[[Offset]].
  1066. // d. Let timeZone be timeZoneResult.[[Name]].
  1067. // TODO: 5. Else,
  1068. // a. Let z be false.
  1069. z = false;
  1070. // b. Let offset be undefined. (NOTE: It already is)
  1071. // c. Let timeZone be undefined. (NOTE: It already is)
  1072. // 6. 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]], [[Calendar]]: result.[[Calendar]], [[TimeZoneZ]]: z, [[TimeZoneOffset]]: offset, [[TimeZoneIANAName]]: timeZone }.
  1073. return TemporalZonedDateTime { .date_time = move(result), .time_zone = { .z = z, .offset = move(offset), .name = move(time_zone) } };
  1074. }
  1075. // 13.43 ParseTemporalTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimestring
  1076. ThrowCompletionOr<TemporalTime> parse_temporal_time_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  1077. {
  1078. // 1. Assert: Type(isoString) is String.
  1079. // 2. If isoString does not satisfy the syntax of a TemporalTimeString (see 13.33), then
  1080. // a. Throw a RangeError exception.
  1081. // TODO
  1082. // 3. Let result be ? ParseISODateTime(isoString).
  1083. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1084. // 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]] }.
  1085. return TemporalTime { .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .calendar = move(result.calendar) };
  1086. }
  1087. // 13.44 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  1088. ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject& global_object, [[maybe_unused]] String const& iso_string)
  1089. {
  1090. auto& vm = global_object.vm();
  1091. // 1. Assert: Type(isoString) is String.
  1092. // 2. If isoString does not satisfy the syntax of a TemporalTimeZoneString (see 13.33), then
  1093. // a. Throw a RangeError exception.
  1094. // 3. Let z, sign, hours, minutes, seconds, fraction and name be the parts of isoString produced respectively by the UTCDesignator, TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, TimeZoneUTCOffsetFractionalPart, and TimeZoneIANAName productions, or undefined if not present.
  1095. Optional<StringView> z_part;
  1096. Optional<StringView> sign_part;
  1097. Optional<StringView> hours_part;
  1098. Optional<StringView> minutes_part;
  1099. Optional<StringView> seconds_part;
  1100. Optional<StringView> fraction_part;
  1101. Optional<StringView> name_part;
  1102. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "ParseTemporalTimeZoneString");
  1103. // 4. If z is not undefined, then
  1104. if (z_part.has_value()) {
  1105. // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
  1106. return TemporalTimeZone { .z = true, .offset = {}, .name = name_part.has_value() ? String { *name_part } : Optional<String> {} };
  1107. }
  1108. Optional<String> offset;
  1109. // 5. If hours is undefined, then
  1110. if (!hours_part.has_value()) {
  1111. // a. Let offsetString be undefined.
  1112. // NOTE: No-op.
  1113. }
  1114. // 6. Else,
  1115. else {
  1116. // a. Assert: sign is not undefined.
  1117. VERIFY(sign_part.has_value());
  1118. // b. Set hours to ! ToIntegerOrInfinity(hours).
  1119. u8 hours = MUST(Value(js_string(vm, *hours_part)).to_integer_or_infinity(global_object));
  1120. u8 sign;
  1121. // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then
  1122. if (sign_part->is_one_of("-", "\u2212")) {
  1123. // i. Set sign to −1.
  1124. sign = -1;
  1125. }
  1126. // d. Else,
  1127. else {
  1128. // i. Set sign to 1.
  1129. sign = 1;
  1130. }
  1131. // e. Set minutes to ! ToIntegerOrInfinity(minutes).
  1132. u8 minutes = MUST(Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object));
  1133. // f. Set seconds to ! ToIntegerOrInfinity(seconds).
  1134. u8 seconds = MUST(Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object));
  1135. i32 nanoseconds;
  1136. // g. If fraction is not undefined, then
  1137. if (fraction_part.has_value()) {
  1138. // i. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  1139. auto fraction = String::formatted("{}000000000", *fraction_part);
  1140. // ii. Let nanoseconds be the String value equal to the substring of fraction from 1 to 10.
  1141. // iii. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  1142. nanoseconds = MUST(Value(js_string(vm, fraction.substring(1, 10))).to_integer_or_infinity(global_object));
  1143. }
  1144. // h. Else,
  1145. else {
  1146. // i. Let nanoseconds be 0.
  1147. nanoseconds = 0;
  1148. }
  1149. // i. Let offsetNanoseconds be sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  1150. auto offset_nanoseconds = sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  1151. // j. Let offsetString be ! FormatTimeZoneOffsetString(offsetNanoseconds).
  1152. offset = format_time_zone_offset_string(offset_nanoseconds);
  1153. }
  1154. Optional<String> name;
  1155. // 7. If name is not undefined, then
  1156. if (name_part.has_value()) {
  1157. // a. If ! IsValidTimeZoneName(name) is false, throw a RangeError exception.
  1158. if (!is_valid_time_zone_name(*name_part))
  1159. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName);
  1160. // b. Set name to ! CanonicalizeTimeZoneName(name).
  1161. name = canonicalize_time_zone_name(*name_part);
  1162. }
  1163. // 8. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
  1164. return TemporalTimeZone { .z = false, .offset = offset, .name = name };
  1165. }
  1166. // 13.45 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
  1167. ThrowCompletionOr<TemporalYearMonth> parse_temporal_year_month_string(GlobalObject& global_object, String const& iso_string)
  1168. {
  1169. // 1. Assert: Type(isoString) is String.
  1170. // 2. If isoString does not satisfy the syntax of a TemporalYearMonthString (see 13.33), then
  1171. // a. Throw a RangeError exception.
  1172. // TODO
  1173. // 3. Let result be ? ParseISODateTime(isoString).
  1174. auto result = TRY(parse_iso_date_time(global_object, iso_string));
  1175. // 4. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1176. return TemporalYearMonth { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1177. }
  1178. // 13.46 ToPositiveInteger ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveinteger
  1179. ThrowCompletionOr<double> to_positive_integer(GlobalObject& global_object, Value argument)
  1180. {
  1181. auto& vm = global_object.vm();
  1182. // 1. Let integer be ? ToIntegerThrowOnInfinity(argument).
  1183. auto integer = TRY(to_integer_throw_on_infinity(global_object, argument, ErrorType::TemporalPropertyMustBePositiveInteger));
  1184. // 2. If integer ≤ 0, then
  1185. if (integer <= 0) {
  1186. // a. Throw a RangeError exception.
  1187. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalPropertyMustBePositiveInteger);
  1188. }
  1189. // 3. Return integer.
  1190. return integer;
  1191. }
  1192. // 13.48 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  1193. ThrowCompletionOr<Object*> prepare_temporal_fields(GlobalObject& global_object, Object const& fields, Vector<String> const& field_names, Vector<StringView> const& required_fields)
  1194. {
  1195. auto& vm = global_object.vm();
  1196. // 1. Assert: Type(fields) is Object.
  1197. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  1198. auto* result = Object::create(global_object, global_object.object_prototype());
  1199. VERIFY(result);
  1200. // 3. For each value property of fieldNames, do
  1201. for (auto& property : field_names) {
  1202. // a. Let value be ? Get(fields, property).
  1203. auto value = TRY(fields.get(property));
  1204. // b. If value is undefined, then
  1205. if (value.is_undefined()) {
  1206. // i. If requiredFields contains property, then
  1207. if (required_fields.contains_slow(property)) {
  1208. // 1. Throw a TypeError exception.
  1209. return vm.throw_completion<TypeError>(global_object, ErrorType::MissingRequiredProperty, property);
  1210. }
  1211. // ii. If property is in the Property column of Table 13, then
  1212. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  1213. if (property.is_one_of("hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  1214. // 1. Set value to the corresponding Default value of the same row.
  1215. value = Value(0);
  1216. }
  1217. }
  1218. // c. Else,
  1219. else {
  1220. // i. If property is in the Property column of Table 13 and there is a Conversion value in the same row, then
  1221. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  1222. // 2. Set value to ? Conversion(value).
  1223. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv))
  1224. value = Value(TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite)));
  1225. else if (property.is_one_of("month"sv, "day"sv))
  1226. value = Value(TRY(to_positive_integer(global_object, value)));
  1227. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv))
  1228. value = TRY(value.to_primitive_string(global_object));
  1229. }
  1230. // d. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1231. MUST(result->create_data_property_or_throw(property, value));
  1232. }
  1233. // 4. Return result.
  1234. return result;
  1235. }
  1236. // 13.49 PreparePartialTemporalFields ( fields, fieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-preparepartialtemporalfields
  1237. ThrowCompletionOr<Object*> prepare_partial_temporal_fields(GlobalObject& global_object, Object const& fields, Vector<String> const& field_names)
  1238. {
  1239. auto& vm = global_object.vm();
  1240. // 1. Assert: Type(fields) is Object.
  1241. // 2. Let result be ! OrdinaryObjectCreate(%Object.prototype%).
  1242. auto* result = Object::create(global_object, global_object.object_prototype());
  1243. // 3. Let any be false.
  1244. auto any = false;
  1245. // 4. For each value property of fieldNames, do
  1246. for (auto& property : field_names) {
  1247. // a. Let value be ? Get(fields, property).
  1248. auto value = TRY(fields.get(property));
  1249. // b. If value is not undefined, then
  1250. if (!value.is_undefined()) {
  1251. // i. Set any to true.
  1252. any = true;
  1253. // ii. If property is in the Property column of Table 13, then
  1254. // 1. Let Conversion represent the abstract operation named by the Conversion value of the same row.
  1255. // 2. Set value to ? Conversion(value).
  1256. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv))
  1257. value = Value(TRY(to_integer_throw_on_infinity(global_object, value, ErrorType::TemporalPropertyMustBeFinite)));
  1258. else if (property.is_one_of("month"sv, "day"sv))
  1259. value = Value(TRY(to_positive_integer(global_object, value)));
  1260. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv))
  1261. value = TRY(value.to_primitive_string(global_object));
  1262. // NOTE: According to the spec this is step 4c, but I believe that's incorrect. See https://github.com/tc39/proposal-temporal/issues/1910.
  1263. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1264. MUST(result->create_data_property_or_throw(property, value));
  1265. }
  1266. }
  1267. // 5. If any is false, then
  1268. if (!any) {
  1269. // a. Throw a TypeError exception.
  1270. return vm.throw_completion<TypeError>(global_object, ErrorType::TemporalObjectMustHaveOneOf, String::join(", "sv, field_names));
  1271. }
  1272. // 6. Return result.
  1273. return result;
  1274. }
  1275. }