AbstractOperations.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  1. /*
  2. * Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2022, 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/AbstractOperations.h>
  13. #include <LibJS/Runtime/Completion.h>
  14. #include <LibJS/Runtime/Date.h>
  15. #include <LibJS/Runtime/IteratorOperations.h>
  16. #include <LibJS/Runtime/PropertyKey.h>
  17. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  18. #include <LibJS/Runtime/Temporal/Calendar.h>
  19. #include <LibJS/Runtime/Temporal/Duration.h>
  20. #include <LibJS/Runtime/Temporal/ISO8601.h>
  21. #include <LibJS/Runtime/Temporal/PlainDate.h>
  22. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  23. #include <LibJS/Runtime/Temporal/PlainTime.h>
  24. #include <LibJS/Runtime/Temporal/TimeZone.h>
  25. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  26. #include <stdlib.h>
  27. namespace JS::Temporal {
  28. static Optional<OptionType> to_option_type(Value value)
  29. {
  30. if (value.is_boolean())
  31. return OptionType::Boolean;
  32. if (value.is_string())
  33. return OptionType::String;
  34. if (value.is_number())
  35. return OptionType::Number;
  36. return {};
  37. }
  38. // 13.1 IterableToListOfType ( items, elementTypes ), https://tc39.es/proposal-temporal/#sec-iterabletolistoftype
  39. ThrowCompletionOr<MarkedVector<Value>> iterable_to_list_of_type(VM& vm, Value items, Vector<OptionType> const& element_types)
  40. {
  41. // 1. Let iteratorRecord be ? GetIterator(items, sync).
  42. auto iterator_record = TRY(get_iterator(vm, items, IteratorHint::Sync));
  43. // 2. Let values be a new empty List.
  44. MarkedVector<Value> values(vm.heap());
  45. // 3. Let next be true.
  46. auto next = true;
  47. // 4. Repeat, while next is not false,
  48. while (next) {
  49. // a. Set next to ? IteratorStep(iteratorRecord).
  50. auto* iterator_result = TRY(iterator_step(vm, iterator_record));
  51. next = iterator_result;
  52. // b. If next is not false, then
  53. if (next) {
  54. // i. Let nextValue be ? IteratorValue(next).
  55. auto next_value = TRY(iterator_value(vm, *iterator_result));
  56. // ii. If Type(nextValue) is not an element of elementTypes, then
  57. if (auto type = to_option_type(next_value); !type.has_value() || !element_types.contains_slow(*type)) {
  58. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  59. auto completion = vm.throw_completion<TypeError>(ErrorType::IterableToListOfTypeInvalidValue, next_value.to_string_without_side_effects());
  60. // 2. Return ? IteratorClose(iteratorRecord, completion).
  61. return iterator_close(vm, iterator_record, move(completion));
  62. }
  63. // iii. Append nextValue to the end of the List values.
  64. values.append(next_value);
  65. }
  66. }
  67. // 5. Return values.
  68. return { move(values) };
  69. }
  70. // 13.2 GetOptionsObject ( options ), https://tc39.es/proposal-temporal/#sec-getoptionsobject
  71. ThrowCompletionOr<Object*> get_options_object(VM& vm, Value options)
  72. {
  73. auto& realm = *vm.current_realm();
  74. // 1. If options is undefined, then
  75. if (options.is_undefined()) {
  76. // a. Return OrdinaryObjectCreate(null).
  77. return Object::create(realm, nullptr);
  78. }
  79. // 2. If Type(options) is Object, then
  80. if (options.is_object()) {
  81. // a. Return options.
  82. return &options.as_object();
  83. }
  84. // 3. Throw a TypeError exception.
  85. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, "Options");
  86. }
  87. // 13.3 GetOption ( options, property, type, values, fallback ), https://tc39.es/proposal-temporal/#sec-getoption
  88. ThrowCompletionOr<Value> get_option(VM& vm, Object const& options, PropertyKey const& property, OptionType type, Span<StringView const> values, OptionDefault const& default_)
  89. {
  90. VERIFY(property.is_string());
  91. // 1. Let value be ? Get(options, property).
  92. auto value = TRY(options.get(property));
  93. // 2. If value is undefined, then
  94. if (value.is_undefined()) {
  95. // a. If default is required, throw a RangeError exception.
  96. if (default_.has<GetOptionRequired>())
  97. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, "undefined"sv, property.as_string());
  98. // b. Return default.
  99. return default_.visit(
  100. [](GetOptionRequired) -> Value { VERIFY_NOT_REACHED(); },
  101. [](Empty) { return js_undefined(); },
  102. [](bool b) { return Value(b); },
  103. [](double d) { return Value(d); },
  104. [&vm](StringView s) { return Value(js_string(vm, s)); });
  105. }
  106. // 5. If type is "boolean", then
  107. if (type == OptionType::Boolean) {
  108. // a. Set value to ToBoolean(value).
  109. value = Value(value.to_boolean());
  110. }
  111. // 6. Else if type is "number", then
  112. else if (type == OptionType::Number) {
  113. // a. Set value to ? ToNumber(value).
  114. value = TRY(value.to_number(vm));
  115. // b. If value is NaN, throw a RangeError exception.
  116. if (value.is_nan())
  117. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, vm.names.NaN.as_string(), property.as_string());
  118. }
  119. // 7. Else,
  120. else {
  121. // a. Assert: type is "string".
  122. VERIFY(type == OptionType::String);
  123. // b. Set value to ? ToString(value).
  124. value = TRY(value.to_primitive_string(vm));
  125. }
  126. // 8. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
  127. if (!values.is_empty()) {
  128. // NOTE: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  129. VERIFY(value.is_string());
  130. if (!values.contains_slow(value.as_string().string()))
  131. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value.as_string().string(), property.as_string());
  132. }
  133. // 9. Return value.
  134. return value;
  135. }
  136. // 13.4 ToTemporalOverflow ( options ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloverflow
  137. ThrowCompletionOr<String> to_temporal_overflow(VM& vm, Object const* options)
  138. {
  139. // 1. If options is undefined, return "constrain".
  140. if (options == nullptr)
  141. return "constrain"sv;
  142. // 2. Return ? GetOption(options, "overflow", "string", « "constrain", "reject" », "constrain").
  143. auto option = TRY(get_option(vm, *options, vm.names.overflow, OptionType::String, { "constrain"sv, "reject"sv }, "constrain"sv));
  144. VERIFY(option.is_string());
  145. return option.as_string().string();
  146. }
  147. // 13.5 ToTemporalDisambiguation ( options ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldisambiguation
  148. ThrowCompletionOr<String> to_temporal_disambiguation(VM& vm, Object const* options)
  149. {
  150. // 1. If options is undefined, return "compatible".
  151. if (options == nullptr)
  152. return "compatible"sv;
  153. // 2. Return ? GetOption(options, "disambiguation", "string", « "compatible", "earlier", "later", "reject" », "compatible").
  154. auto option = TRY(get_option(vm, *options, vm.names.disambiguation, OptionType::String, { "compatible"sv, "earlier"sv, "later"sv, "reject"sv }, "compatible"sv));
  155. VERIFY(option.is_string());
  156. return option.as_string().string();
  157. }
  158. // 13.6 ToTemporalRoundingMode ( normalizedOptions, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingmode
  159. ThrowCompletionOr<String> to_temporal_rounding_mode(VM& vm, Object const& normalized_options, String const& fallback)
  160. {
  161. // 1. Return ? GetOption(normalizedOptions, "roundingMode", "string", « "ceil", "floor", "trunc", "halfExpand" », fallback).
  162. auto option = TRY(get_option(vm, normalized_options, vm.names.roundingMode, OptionType::String, { "ceil"sv, "floor"sv, "trunc"sv, "halfExpand"sv }, fallback.view()));
  163. VERIFY(option.is_string());
  164. return option.as_string().string();
  165. }
  166. // 13.7 NegateTemporalRoundingMode ( roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-negatetemporalroundingmode
  167. StringView negate_temporal_rounding_mode(String const& rounding_mode)
  168. {
  169. // 1. If roundingMode is "ceil", return "floor".
  170. if (rounding_mode == "ceil"sv)
  171. return "floor"sv;
  172. // 2. If roundingMode is "floor", return "ceil".
  173. if (rounding_mode == "floor"sv)
  174. return "ceil"sv;
  175. // 3. Return roundingMode.
  176. return rounding_mode;
  177. }
  178. // 13.8 ToTemporalOffset ( options, fallback ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaloffset
  179. ThrowCompletionOr<String> to_temporal_offset(VM& vm, Object const* options, String const& fallback)
  180. {
  181. // 1. If options is undefined, return fallback.
  182. if (options == nullptr)
  183. return fallback;
  184. // 2. Return ? GetOption(options, "offset", "string", « "prefer", "use", "ignore", "reject" », fallback).
  185. auto option = TRY(get_option(vm, *options, vm.names.offset, OptionType::String, { "prefer"sv, "use"sv, "ignore"sv, "reject"sv }, fallback.view()));
  186. VERIFY(option.is_string());
  187. return option.as_string().string();
  188. }
  189. // 13.9 ToShowCalendarOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowcalendaroption
  190. ThrowCompletionOr<String> to_show_calendar_option(VM& vm, Object const& normalized_options)
  191. {
  192. // 1. Return ? GetOption(normalizedOptions, "calendarName", "string", « "auto", "always", "never" », "auto").
  193. auto option = TRY(get_option(vm, normalized_options, vm.names.calendarName, OptionType::String, { "auto"sv, "always"sv, "never"sv }, "auto"sv));
  194. VERIFY(option.is_string());
  195. return option.as_string().string();
  196. }
  197. // 13.10 ToShowTimeZoneNameOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowtimezonenameoption
  198. ThrowCompletionOr<String> to_show_time_zone_name_option(VM& vm, Object const& normalized_options)
  199. {
  200. // 1. Return ? GetOption(normalizedOptions, "timeZoneName", "string, « "auto", "never" », "auto").
  201. auto option = TRY(get_option(vm, normalized_options, vm.names.timeZoneName, OptionType::String, { "auto"sv, "never"sv }, "auto"sv));
  202. VERIFY(option.is_string());
  203. return option.as_string().string();
  204. }
  205. // 13.11 ToShowOffsetOption ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-toshowoffsetoption
  206. ThrowCompletionOr<String> to_show_offset_option(VM& vm, Object const& normalized_options)
  207. {
  208. // 1. Return ? GetOption(normalizedOptions, "offset", "string", « "auto", "never" », "auto").
  209. auto option = TRY(get_option(vm, normalized_options, vm.names.offset, OptionType::String, { "auto"sv, "never"sv }, "auto"sv));
  210. VERIFY(option.is_string());
  211. return option.as_string().string();
  212. }
  213. // 13.12 ToTemporalRoundingIncrement ( normalizedOptions, dividend, inclusive ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalroundingincrement
  214. ThrowCompletionOr<u64> to_temporal_rounding_increment(VM& vm, Object const& normalized_options, Optional<double> dividend, bool inclusive)
  215. {
  216. double maximum;
  217. // 1. If dividend is undefined, then
  218. if (!dividend.has_value()) {
  219. // a. Let maximum be +∞𝔽.
  220. maximum = INFINITY;
  221. }
  222. // 2. Else if inclusive is true, then
  223. else if (inclusive) {
  224. // a. Let maximum be 𝔽(dividend).
  225. maximum = *dividend;
  226. }
  227. // 3. Else if dividend is more than 1, then
  228. else if (*dividend > 1) {
  229. // a. Let maximum be 𝔽(dividend - 1).
  230. maximum = *dividend - 1;
  231. }
  232. // 4. Else,
  233. else {
  234. // a. Let maximum be 1𝔽.
  235. maximum = 1;
  236. }
  237. // 5. Let increment be ? GetOption(normalizedOptions, "roundingIncrement", "number", undefined, 1𝔽).
  238. auto increment_value = TRY(get_option(vm, normalized_options, vm.names.roundingIncrement, OptionType::Number, {}, 1.0));
  239. VERIFY(increment_value.is_number());
  240. auto increment = increment_value.as_double();
  241. // 6. If increment < 1𝔽 or increment > maximum, throw a RangeError exception.
  242. if (increment < 1 || increment > maximum)
  243. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  244. // 7. Set increment to floor(ℝ(increment)).
  245. auto floored_increment = static_cast<u64>(increment);
  246. // 8. If dividend is not undefined and dividend modulo increment is not zero, then
  247. if (dividend.has_value() && static_cast<u64>(*dividend) % floored_increment != 0)
  248. // a. Throw a RangeError exception.
  249. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, increment, "roundingIncrement");
  250. // 9. Return increment.
  251. return floored_increment;
  252. }
  253. // 13.13 ToTemporalDateTimeRoundingIncrement ( normalizedOptions, smallestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetimeroundingincrement
  254. ThrowCompletionOr<u64> to_temporal_date_time_rounding_increment(VM& vm, Object const& normalized_options, StringView smallest_unit)
  255. {
  256. u16 maximum;
  257. // 1. If smallestUnit is "day", then
  258. if (smallest_unit == "day"sv) {
  259. // a. Let maximum be 1.
  260. maximum = 1;
  261. }
  262. // 2. Else,
  263. else {
  264. // a. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  265. // b. Assert: maximum is not undefined.
  266. maximum = *maximum_temporal_duration_rounding_increment(smallest_unit);
  267. }
  268. // 3. Return ? ToTemporalRoundingIncrement(normalizedOptions, maximum, false).
  269. return to_temporal_rounding_increment(vm, normalized_options, maximum, false);
  270. }
  271. // 13.14 ToSecondsStringPrecision ( normalizedOptions ), https://tc39.es/proposal-temporal/#sec-temporal-tosecondsstringprecision
  272. ThrowCompletionOr<SecondsStringPrecision> to_seconds_string_precision(VM& vm, Object const& normalized_options)
  273. {
  274. // 1. Let smallestUnit be ? GetTemporalUnit(normalizedOptions, "smallestUnit", time, undefined).
  275. auto smallest_unit = TRY(get_temporal_unit(vm, normalized_options, vm.names.smallestUnit, UnitGroup::Time, Optional<StringView> {}));
  276. // 2. If smallestUnit is "hour", throw a RangeError exception.
  277. if (smallest_unit == "hour"sv)
  278. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *smallest_unit, "smallestUnit"sv);
  279. // 3. If smallestUnit is "minute", then
  280. if (smallest_unit == "minute"sv) {
  281. // a. Return the Record { [[Precision]]: "minute", [[Unit]]: "minute", [[Increment]]: 1 }.
  282. return SecondsStringPrecision { .precision = "minute"sv, .unit = "minute"sv, .increment = 1 };
  283. }
  284. // 4. If smallestUnit is "second", then
  285. if (smallest_unit == "second"sv) {
  286. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  287. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  288. }
  289. // 5. If smallestUnit is "millisecond", then
  290. if (smallest_unit == "millisecond"sv) {
  291. // a. Return the Record { [[Precision]]: 3, [[Unit]]: "millisecond", [[Increment]]: 1 }.
  292. return SecondsStringPrecision { .precision = 3, .unit = "millisecond"sv, .increment = 1 };
  293. }
  294. // 6. If smallestUnit is "microsecond", then
  295. if (smallest_unit == "microsecond"sv) {
  296. // a. Return the Record { [[Precision]]: 6, [[Unit]]: "microsecond", [[Increment]]: 1 }.
  297. return SecondsStringPrecision { .precision = 6, .unit = "microsecond"sv, .increment = 1 };
  298. }
  299. // 7. If smallestUnit is "nanosecond", then
  300. if (smallest_unit == "nanosecond"sv) {
  301. // a. Return the Record { [[Precision]]: 9, [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  302. return SecondsStringPrecision { .precision = 9, .unit = "nanosecond"sv, .increment = 1 };
  303. }
  304. // 8. Assert: smallestUnit is undefined.
  305. VERIFY(!smallest_unit.has_value());
  306. // 9. Let fractionalDigitsVal be ? Get(normalizedOptions, "fractionalSecondDigits").
  307. auto fractional_digits_value = TRY(normalized_options.get(vm.names.fractionalSecondDigits));
  308. // 10. If Type(fractionalDigitsVal) is not Number, then
  309. if (!fractional_digits_value.is_number()) {
  310. // a. If fractionalDigitsVal is not undefined, then
  311. if (!fractional_digits_value.is_undefined()) {
  312. // i. If ? ToString(fractionalDigitsVal) is not "auto", throw a RangeError exception.
  313. if (TRY(fractional_digits_value.to_string(vm)) != "auto"sv)
  314. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  315. }
  316. // b. Return the Record { [[Precision]]: "auto", [[Unit]]: "nanosecond", [[Increment]]: 1 }.
  317. return SecondsStringPrecision { .precision = "auto"sv, .unit = "nanosecond"sv, .increment = 1 };
  318. }
  319. // 11. If fractionalDigitsVal is NaN, +∞𝔽, or -∞𝔽, throw a RangeError exception.
  320. if (fractional_digits_value.is_nan() || fractional_digits_value.is_infinity())
  321. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  322. // 12. Let fractionalDigitCount be truncate(ℝ(fractionalDigitsVal)).
  323. auto fractional_digit_count_unchecked = trunc(fractional_digits_value.as_double());
  324. // 13. If fractionalDigitCount < 0 or fractionalDigitCount > 9, throw a RangeError exception.
  325. if (fractional_digit_count_unchecked < 0 || fractional_digit_count_unchecked > 9)
  326. return vm.template throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, fractional_digits_value, "fractionalSecondDigits"sv);
  327. auto fractional_digit_count = static_cast<u8>(fractional_digit_count_unchecked);
  328. // 14. If fractionalDigitCount is 0, then
  329. if (fractional_digit_count == 0) {
  330. // a. Return the Record { [[Precision]]: 0, [[Unit]]: "second", [[Increment]]: 1 }.
  331. return SecondsStringPrecision { .precision = 0, .unit = "second"sv, .increment = 1 };
  332. }
  333. // 15. If fractionalDigitCount is 1, 2, or 3, then
  334. if (fractional_digit_count == 1 || fractional_digit_count == 2 || fractional_digit_count == 3) {
  335. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "millisecond", [[Increment]]: 10^(3 - fractionalDigitCount) }.
  336. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "millisecond"sv, .increment = (u32)pow(10, 3 - fractional_digit_count) };
  337. }
  338. // 16. If fractionalDigitCount is 4, 5, or 6, then
  339. if (fractional_digit_count == 4 || fractional_digit_count == 5 || fractional_digit_count == 6) {
  340. // a. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "microsecond", [[Increment]]: 10^(6 - fractionalDigitCount) }.
  341. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "microsecond"sv, .increment = (u32)pow(10, 6 - fractional_digit_count) };
  342. }
  343. // 17. Assert: fractionalDigitCount is 7, 8, or 9.
  344. VERIFY(fractional_digit_count == 7 || fractional_digit_count == 8 || fractional_digit_count == 9);
  345. // 18. Return the Record { [[Precision]]: fractionalDigitCount, [[Unit]]: "nanosecond", [[Increment]]: 10^(9 - fractionalDigitCount) }.
  346. return SecondsStringPrecision { .precision = fractional_digit_count, .unit = "nanosecond"sv, .increment = (u32)pow(10, 9 - fractional_digit_count) };
  347. }
  348. struct TemporalUnit {
  349. StringView singular;
  350. StringView plural;
  351. UnitGroup category;
  352. };
  353. // https://tc39.es/proposal-temporal/#table-temporal-units
  354. static Vector<TemporalUnit> temporal_units = {
  355. { "year"sv, "years"sv, UnitGroup::Date },
  356. { "month"sv, "months"sv, UnitGroup::Date },
  357. { "week"sv, "weeks"sv, UnitGroup::Date },
  358. { "day"sv, "days"sv, UnitGroup::Date },
  359. { "hour"sv, "hours"sv, UnitGroup::Time },
  360. { "minute"sv, "minutes"sv, UnitGroup::Time },
  361. { "second"sv, "seconds"sv, UnitGroup::Time },
  362. { "millisecond"sv, "milliseconds"sv, UnitGroup::Time },
  363. { "microsecond"sv, "microseconds"sv, UnitGroup::Time },
  364. { "nanosecond"sv, "nanoseconds"sv, UnitGroup::Time }
  365. };
  366. // 13.15 GetTemporalUnit ( normalizedOptions, key, unitGroup, default [ , extraValues ] ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalunit
  367. ThrowCompletionOr<Optional<String>> get_temporal_unit(VM& vm, Object const& normalized_options, PropertyKey const& key, UnitGroup unit_group, TemporalUnitDefault const& default_, Vector<StringView> const& extra_values)
  368. {
  369. // 1. Let singularNames be a new empty List.
  370. Vector<StringView> singular_names;
  371. // 2. For each row of Table 13, except the header row, in table order, do
  372. for (auto const& row : temporal_units) {
  373. // a. Let unit be the value in the Singular column of the row.
  374. auto unit = row.singular;
  375. // b. If the Category column of the row is date and unitGroup is date or datetime, append unit to singularNames.
  376. if (row.category == UnitGroup::Date && (unit_group == UnitGroup::Date || unit_group == UnitGroup::DateTime))
  377. singular_names.append(unit);
  378. // c. Else if the Category column of the row is time and unitGroup is time or datetime, append unit to singularNames.
  379. else if (row.category == UnitGroup::Time && (unit_group == UnitGroup::Time || unit_group == UnitGroup::DateTime))
  380. singular_names.append(unit);
  381. }
  382. // 3. If extraValues is present, then
  383. if (!extra_values.is_empty()) {
  384. // a. Set singularNames to the list-concatenation of singularNames and extraValues.
  385. singular_names.extend(extra_values);
  386. }
  387. OptionDefault default_value;
  388. // 4. If default is required, then
  389. if (default_.has<TemporalUnitRequired>()) {
  390. // a. Let defaultValue be undefined.
  391. default_value = {};
  392. }
  393. // 5. Else,
  394. else {
  395. auto default_string = default_.get<Optional<StringView>>();
  396. // a. Let defaultValue be default.
  397. default_value = default_string.has_value() ? OptionDefault { *default_string } : OptionDefault {};
  398. // b. If defaultValue is not undefined and singularNames does not contain defaultValue, then
  399. if (default_string.has_value() && !singular_names.contains_slow(*default_string)) {
  400. // i. Append defaultValue to singularNames.
  401. singular_names.append(*default_string);
  402. }
  403. }
  404. // 6. Let allowedValues be a copy of singularNames.
  405. auto allowed_values = singular_names;
  406. // 7. For each element singularName of singularNames, do
  407. for (auto const& singular_name : singular_names) {
  408. for (auto const& row : temporal_units) {
  409. // a. If singularName is listed in the Singular column of Table 13, then
  410. if (singular_name == row.singular) {
  411. // i. Let pluralName be the value in the Plural column of the corresponding row.
  412. auto plural_name = row.plural;
  413. // ii. Append pluralName to allowedValues.
  414. allowed_values.append(plural_name);
  415. }
  416. }
  417. }
  418. // 8. NOTE: For each singular Temporal unit name that is contained within allowedValues, the corresponding plural name is also contained within it.
  419. // 9. Let value be ? GetOption(normalizedOptions, key, "string", allowedValues, defaultValue).
  420. auto option_value = TRY(get_option(vm, normalized_options, key, OptionType::String, allowed_values.span(), default_value));
  421. // 10. If value is undefined and default is required, throw a RangeError exception.
  422. if (option_value.is_undefined() && default_.has<TemporalUnitRequired>())
  423. return vm.throw_completion<RangeError>(ErrorType::IsUndefined, String::formatted("{} option value", key.as_string()));
  424. Optional<String> value = option_value.is_undefined()
  425. ? Optional<String> {}
  426. : option_value.as_string().string();
  427. // 11. If value is listed in the Plural column of Table 13, then
  428. for (auto const& row : temporal_units) {
  429. if (row.plural == value) {
  430. // a. Set value to the value in the Singular column of the corresponding row.
  431. value = row.singular;
  432. }
  433. }
  434. // 12. Return value.
  435. return value;
  436. }
  437. // 13.16 ToRelativeTemporalObject ( options ), https://tc39.es/proposal-temporal/#sec-temporal-torelativetemporalobject
  438. ThrowCompletionOr<Value> to_relative_temporal_object(VM& vm, Object const& options)
  439. {
  440. auto& realm = *vm.current_realm();
  441. // 1. Assert: Type(options) is Object.
  442. // 2. Let value be ? Get(options, "relativeTo").
  443. auto value = TRY(options.get(vm.names.relativeTo));
  444. // 3. If value is undefined, then
  445. if (value.is_undefined()) {
  446. // a. Return value.
  447. return value;
  448. }
  449. // 4. Let offsetBehaviour be option.
  450. auto offset_behavior = OffsetBehavior::Option;
  451. // 5. Let matchBehaviour be match exactly.
  452. auto match_behavior = MatchBehavior::MatchExactly;
  453. ISODateTime result;
  454. Value offset_string;
  455. Value time_zone;
  456. Object* calendar = nullptr;
  457. // 6. If Type(value) is Object, then
  458. if (value.is_object()) {
  459. auto& value_object = value.as_object();
  460. // a. If value has either an [[InitializedTemporalDate]] or [[InitializedTemporalZonedDateTime]] internal slot, then
  461. if (is<PlainDate>(value_object) || is<ZonedDateTime>(value_object)) {
  462. // i. Return value.
  463. return value;
  464. }
  465. // b. If value has an [[InitializedTemporalDateTime]] internal slot, then
  466. if (is<PlainDateTime>(value_object)) {
  467. auto& plain_date_time = static_cast<PlainDateTime&>(value_object);
  468. // i. Return ? CreateTemporalDate(value.[[ISOYear]], value.[[ISOMonth]], value.[[ISODay]], 0, 0, 0, 0, 0, 0, value.[[Calendar]]).
  469. return TRY(create_temporal_date(vm, plain_date_time.iso_year(), plain_date_time.iso_month(), plain_date_time.iso_day(), plain_date_time.calendar()));
  470. }
  471. // c. Let calendar be ? GetTemporalCalendarWithISODefault(value).
  472. calendar = TRY(get_temporal_calendar_with_iso_default(vm, value_object));
  473. // d. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  474. auto field_names = TRY(calendar_fields(vm, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv }));
  475. // e. Let fields be ? PrepareTemporalFields(value, fieldNames, «»).
  476. auto* fields = TRY(prepare_temporal_fields(vm, value_object, field_names, Vector<StringView> {}));
  477. // f. Let dateOptions be OrdinaryObjectCreate(null).
  478. auto* date_options = Object::create(realm, nullptr);
  479. // g. Perform ! CreateDataPropertyOrThrow(dateOptions, "overflow", "constrain").
  480. MUST(date_options->create_data_property_or_throw(vm.names.overflow, js_string(vm, "constrain"sv)));
  481. // h. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, dateOptions).
  482. result = TRY(interpret_temporal_date_time_fields(vm, *calendar, *fields, *date_options));
  483. // i. Let offsetString be ? Get(value, "offset").
  484. offset_string = TRY(value_object.get(vm.names.offset));
  485. // j. Let timeZone be ? Get(value, "timeZone").
  486. time_zone = TRY(value_object.get(vm.names.timeZone));
  487. // k. If timeZone is not undefined, then
  488. if (!time_zone.is_undefined()) {
  489. // i. Set timeZone to ? ToTemporalTimeZone(timeZone).
  490. time_zone = TRY(to_temporal_time_zone(vm, time_zone));
  491. }
  492. // l. If offsetString is undefined, then
  493. if (offset_string.is_undefined()) {
  494. // i. Set offsetBehaviour to wall.
  495. offset_behavior = OffsetBehavior::Wall;
  496. }
  497. }
  498. // 7. Else,
  499. else {
  500. // a. Let string be ? ToString(value).
  501. auto string = TRY(value.to_string(vm));
  502. // b. Let result be ? ParseTemporalRelativeToString(string).
  503. result = TRY(parse_temporal_relative_to_string(vm, string));
  504. // c. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  505. calendar = TRY(to_temporal_calendar_with_iso_default(vm, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()));
  506. // d. Let offsetString be result.[[TimeZone]].[[OffsetString]].
  507. offset_string = result.time_zone.offset_string.has_value() ? js_string(vm, *result.time_zone.offset_string) : js_undefined();
  508. // e. Let timeZoneName be result.[[TimeZone]].[[Name]].
  509. auto time_zone_name = result.time_zone.name;
  510. // f. If timeZoneName is undefined, then
  511. if (!time_zone_name.has_value()) {
  512. // i. Let timeZone be undefined.
  513. time_zone = js_undefined();
  514. }
  515. // g. Else,
  516. else {
  517. // i. If IsTimeZoneOffsetString(timeZoneName) is false, then
  518. if (!is_time_zone_offset_string(*time_zone_name)) {
  519. // 1. If IsValidTimeZoneName(timeZoneName) is false, throw a RangeError exception.
  520. if (!is_valid_time_zone_name(*time_zone_name))
  521. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, *time_zone_name);
  522. // 2. Set timeZoneName to ! CanonicalizeTimeZoneName(timeZoneName).
  523. time_zone_name = canonicalize_time_zone_name(*time_zone_name);
  524. }
  525. // ii. Let timeZone be ! CreateTemporalTimeZone(timeZoneName).
  526. time_zone = MUST(create_temporal_time_zone(vm, *time_zone_name));
  527. // iii. If result.[[TimeZone]].[[Z]] is true, then
  528. if (result.time_zone.z) {
  529. // 1. Set offsetBehaviour to exact.
  530. offset_behavior = OffsetBehavior::Exact;
  531. }
  532. // iv. Else if offsetString is undefined, then
  533. else if (offset_string.is_undefined()) {
  534. // 1. Set offsetBehaviour to wall.
  535. offset_behavior = OffsetBehavior::Wall;
  536. }
  537. // v. Set matchBehaviour to match minutes.
  538. match_behavior = MatchBehavior::MatchMinutes;
  539. }
  540. }
  541. // 8. If timeZone is not undefined, then
  542. if (!time_zone.is_undefined()) {
  543. double offset_ns;
  544. // a. If offsetBehaviour is option, then
  545. if (offset_behavior == OffsetBehavior::Option) {
  546. // i. Set offsetString to ? ToString(offsetString).
  547. // 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.
  548. auto actual_offset_string = TRY(offset_string.to_string(vm));
  549. // b. If IsTimeZoneOffsetString(offsetString) is false, throw a RangeError exception.
  550. if (!is_time_zone_offset_string(actual_offset_string))
  551. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, actual_offset_string);
  552. // c. Let offsetNs be ParseTimeZoneOffsetString(offsetString).
  553. offset_ns = parse_time_zone_offset_string(actual_offset_string);
  554. }
  555. // b. Else,
  556. else {
  557. // i. Let offsetNs be 0.
  558. offset_ns = 0;
  559. }
  560. // c. 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).
  561. auto* epoch_nanoseconds = TRY(interpret_iso_date_time_offset(vm, 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));
  562. // d. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  563. return MUST(create_temporal_zoned_date_time(vm, *epoch_nanoseconds, time_zone.as_object(), *calendar));
  564. }
  565. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  566. return TRY(create_temporal_date(vm, result.year, result.month, result.day, *calendar));
  567. }
  568. // 13.17 LargerOfTwoTemporalUnits ( u1, u2 ), https://tc39.es/proposal-temporal/#sec-temporal-largeroftwotemporalunits
  569. StringView larger_of_two_temporal_units(StringView unit1, StringView unit2)
  570. {
  571. // 1. Assert: Both u1 and u2 are listed in the Singular column of Table 13.
  572. // 2. For each row of Table 13, except the header row, in table order, do
  573. for (auto const& row : temporal_units) {
  574. // a. Let unit be the value in the Singular column of the row.
  575. auto unit = row.singular;
  576. // b. If SameValue(u1, unit) is true, return unit.
  577. if (unit1 == unit)
  578. return unit;
  579. // c. If SameValue(u2, unit) is true, return unit.
  580. if (unit2 == unit)
  581. return unit;
  582. }
  583. VERIFY_NOT_REACHED();
  584. }
  585. // 13.18 MergeLargestUnitOption ( options, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-mergelargestunitoption
  586. ThrowCompletionOr<Object*> merge_largest_unit_option(VM& vm, Object const& options, String largest_unit)
  587. {
  588. auto& realm = *vm.current_realm();
  589. // 1. Let merged be OrdinaryObjectCreate(null).
  590. auto* merged = Object::create(realm, nullptr);
  591. // 2. Let keys be ? EnumerableOwnPropertyNames(options, key).
  592. auto keys = TRY(options.enumerable_own_property_names(Object::PropertyKind::Key));
  593. // 3. For each element nextKey of keys, do
  594. for (auto& key : keys) {
  595. auto next_key = MUST(PropertyKey::from_value(vm, key));
  596. // a. Let propValue be ? Get(options, nextKey).
  597. auto prop_value = TRY(options.get(next_key));
  598. // b. Perform ! CreateDataPropertyOrThrow(merged, nextKey, propValue).
  599. MUST(merged->create_data_property_or_throw(next_key, prop_value));
  600. }
  601. // 4. Perform ! CreateDataPropertyOrThrow(merged, "largestUnit", largestUnit).
  602. MUST(merged->create_data_property_or_throw(vm.names.largestUnit, js_string(vm, move(largest_unit))));
  603. // 5. Return merged.
  604. return merged;
  605. }
  606. // 13.19 MaximumTemporalDurationRoundingIncrement ( unit ), https://tc39.es/proposal-temporal/#sec-temporal-maximumtemporaldurationroundingincrement
  607. Optional<u16> maximum_temporal_duration_rounding_increment(StringView unit)
  608. {
  609. // 1. If unit is "year", "month", "week", or "day", then
  610. if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  611. // a. Return undefined.
  612. return {};
  613. }
  614. // 2. If unit is "hour", then
  615. if (unit == "hour"sv) {
  616. // a. Return 24.
  617. return 24;
  618. }
  619. // 3. If unit is "minute" or "second", then
  620. if (unit.is_one_of("minute"sv, "second"sv)) {
  621. // a. Return 60.
  622. return 60;
  623. }
  624. // 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
  625. VERIFY(unit.is_one_of("millisecond"sv, "microsecond"sv, "nanosecond"sv));
  626. // 5. Return 1000.
  627. return 1000;
  628. }
  629. // 13.20 RejectObjectWithCalendarOrTimeZone ( object ), https://tc39.es/proposal-temporal/#sec-temporal-rejectobjectwithcalendarortimezone
  630. ThrowCompletionOr<void> reject_object_with_calendar_or_time_zone(VM& vm, Object& object)
  631. {
  632. // 1. Assert: Type(object) is Object.
  633. // 2. If object has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  634. if (is<PlainDate>(object) || is<PlainDateTime>(object) || is<PlainMonthDay>(object) || is<PlainTime>(object) || is<PlainYearMonth>(object) || is<ZonedDateTime>(object)) {
  635. // a. Throw a TypeError exception.
  636. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "calendar or timeZone");
  637. }
  638. // 3. Let calendarProperty be ? Get(object, "calendar").
  639. auto calendar_property = TRY(object.get(vm.names.calendar));
  640. // 4. If calendarProperty is not undefined, then
  641. if (!calendar_property.is_undefined()) {
  642. // a. Throw a TypeError exception.
  643. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "calendar");
  644. }
  645. // 5. Let timeZoneProperty be ? Get(object, "timeZone").
  646. auto time_zone_property = TRY(object.get(vm.names.timeZone));
  647. // 6. If timeZoneProperty is not undefined, then
  648. if (!time_zone_property.is_undefined()) {
  649. // a. Throw a TypeError exception.
  650. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustNotHave, "timeZone");
  651. }
  652. return {};
  653. }
  654. // 13.21 FormatSecondsStringPart ( second, millisecond, microsecond, nanosecond, precision ), https://tc39.es/proposal-temporal/#sec-temporal-formatsecondsstringpart
  655. String format_seconds_string_part(u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Variant<StringView, u8> const& precision)
  656. {
  657. // 1. Assert: second, millisecond, microsecond, and nanosecond are integers.
  658. // Non-standard sanity check
  659. if (precision.has<StringView>())
  660. VERIFY(precision.get<StringView>().is_one_of("minute"sv, "auto"sv));
  661. // 2. If precision is "minute", return "".
  662. if (precision.has<StringView>() && precision.get<StringView>() == "minute"sv)
  663. return String::empty();
  664. // 3. Let secondsString be the string-concatenation of the code unit 0x003A (COLON) and ToZeroPaddedDecimalString(second, 2).
  665. auto seconds_string = String::formatted(":{:02}", second);
  666. // 4. Let fraction be millisecond × 10^6 + microsecond × 10^3 + nanosecond.
  667. u32 fraction = millisecond * 1'000'000 + microsecond * 1'000 + nanosecond;
  668. String fraction_string;
  669. // 5. If precision is "auto", then
  670. if (precision.has<StringView>() && precision.get<StringView>() == "auto"sv) {
  671. // a. If fraction is 0, return secondsString.
  672. if (fraction == 0)
  673. return seconds_string;
  674. // b. Set fraction to ToZeroPaddedDecimalString(fraction, 9).
  675. fraction_string = String::formatted("{:09}", fraction);
  676. // c. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  677. fraction_string = fraction_string.trim("0"sv, TrimMode::Right);
  678. }
  679. // 6. Else,
  680. else {
  681. // a. If precision is 0, return secondsString.
  682. if (precision.get<u8>() == 0)
  683. return seconds_string;
  684. // b. Set fraction to ToZeroPaddedDecimalString(fraction, 9)
  685. fraction_string = String::formatted("{:09}", fraction);
  686. // c. Set fraction to the substring of fraction from 0 to precision.
  687. fraction_string = fraction_string.substring(0, precision.get<u8>());
  688. }
  689. // 7. Return the string-concatenation of secondsString, the code unit 0x002E (FULL STOP), and fraction.
  690. return String::formatted("{}.{}", seconds_string, fraction_string);
  691. }
  692. // 13.23 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/proposal-temporal/#sec-temporal-getunsignedroundingmode
  693. UnsignedRoundingMode get_unsigned_rounding_mode(StringView rounding_mode, bool is_negative)
  694. {
  695. // 1. If isNegative is true, return the specification type in the third column of Table 14 where the first column is roundingMode and the second column is "negative".
  696. if (is_negative) {
  697. if (rounding_mode == "ceil"sv)
  698. return UnsignedRoundingMode::Zero;
  699. if (rounding_mode == "floor"sv)
  700. return UnsignedRoundingMode::Infinity;
  701. if (rounding_mode == "expand"sv)
  702. return UnsignedRoundingMode::Infinity;
  703. if (rounding_mode == "trunc"sv)
  704. return UnsignedRoundingMode::Zero;
  705. if (rounding_mode == "halfCeil"sv)
  706. return UnsignedRoundingMode::HalfZero;
  707. if (rounding_mode == "halfFloor"sv)
  708. return UnsignedRoundingMode::HalfInfinity;
  709. if (rounding_mode == "halfExpand"sv)
  710. return UnsignedRoundingMode::HalfInfinity;
  711. if (rounding_mode == "halfTrunc"sv)
  712. return UnsignedRoundingMode::HalfZero;
  713. if (rounding_mode == "halfEven"sv)
  714. return UnsignedRoundingMode::HalfEven;
  715. VERIFY_NOT_REACHED();
  716. }
  717. // 2. Else, return the specification type in the third column of Table 14 where the first column is roundingMode and the second column is "positive".
  718. else {
  719. if (rounding_mode == "ceil"sv)
  720. return UnsignedRoundingMode::Infinity;
  721. if (rounding_mode == "floor"sv)
  722. return UnsignedRoundingMode::Zero;
  723. if (rounding_mode == "expand"sv)
  724. return UnsignedRoundingMode::Infinity;
  725. if (rounding_mode == "trunc"sv)
  726. return UnsignedRoundingMode::Zero;
  727. if (rounding_mode == "halfCeil"sv)
  728. return UnsignedRoundingMode::HalfInfinity;
  729. if (rounding_mode == "halfFloor"sv)
  730. return UnsignedRoundingMode::HalfZero;
  731. if (rounding_mode == "halfExpand"sv)
  732. return UnsignedRoundingMode::HalfInfinity;
  733. if (rounding_mode == "halfTrunc"sv)
  734. return UnsignedRoundingMode::HalfZero;
  735. if (rounding_mode == "halfEven"sv)
  736. return UnsignedRoundingMode::HalfEven;
  737. VERIFY_NOT_REACHED();
  738. }
  739. }
  740. // NOTE: We have two variants of these functions, one using doubles and one using BigInts - most of the time
  741. // doubles will be fine, but take care to choose the right one. The spec is not very clear about this, as
  742. // it uses mathematical values which can be arbitrarily (but not infinitely) large.
  743. // Incidentally V8's Temporal implementation does the same :^)
  744. // 13.24 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-applyunsignedroundingmode
  745. double apply_unsigned_rounding_mode(double x, double r1, double r2, Optional<UnsignedRoundingMode> const& unsigned_rounding_mode)
  746. {
  747. // 1. If x is equal to r1, return r1.
  748. if (x == r1)
  749. return r1;
  750. // 2. Assert: r1 < x < r2.
  751. VERIFY(r1 < x && x < r2);
  752. // 3. Assert: unsignedRoundingMode is not undefined.
  753. VERIFY(unsigned_rounding_mode.has_value());
  754. // 4. If unsignedRoundingMode is zero, return r1.
  755. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  756. return r1;
  757. // 5. If unsignedRoundingMode is infinity, return r2.
  758. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  759. return r2;
  760. // 6. Let d1 be x – r1.
  761. auto d1 = x - r1;
  762. // 7. Let d2 be r2 – x.
  763. auto d2 = r2 - x;
  764. // 8. If d1 < d2, return r1.
  765. if (d1 < d2)
  766. return r1;
  767. // 9. If d2 < d1, return r2.
  768. if (d2 < d1)
  769. return r2;
  770. // 10. Assert: d1 is equal to d2.
  771. VERIFY(d1 == d2);
  772. // 11. If unsignedRoundingMode is half-zero, return r1.
  773. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  774. return r1;
  775. // 12. If unsignedRoundingMode is half-infinity, return r2.
  776. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  777. return r2;
  778. // 13. Assert: unsignedRoundingMode is half-even.
  779. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  780. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  781. auto cardinality = modulo((r1 / (r2 - r1)), 2);
  782. // 15. If cardinality is 0, return r1.
  783. if (cardinality == 0)
  784. return r1;
  785. // 16. Return r2.
  786. return r2;
  787. }
  788. // 13.24 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-applyunsignedroundingmode
  789. Crypto::SignedBigInteger apply_unsigned_rounding_mode(Crypto::SignedDivisionResult const& x, Crypto::SignedBigInteger const& r1, Crypto::SignedBigInteger const& r2, Optional<UnsignedRoundingMode> const& unsigned_rounding_mode, Crypto::UnsignedBigInteger const& increment)
  790. {
  791. // 1. If x is equal to r1, return r1.
  792. if (x.quotient == r1 && x.remainder.unsigned_value().is_zero())
  793. return r1;
  794. // 2. Assert: r1 < x < r2.
  795. // NOTE: Skipped for the sake of performance
  796. // 3. Assert: unsignedRoundingMode is not undefined.
  797. VERIFY(unsigned_rounding_mode.has_value());
  798. // 4. If unsignedRoundingMode is zero, return r1.
  799. if (unsigned_rounding_mode == UnsignedRoundingMode::Zero)
  800. return r1;
  801. // 5. If unsignedRoundingMode is infinity, return r2.
  802. if (unsigned_rounding_mode == UnsignedRoundingMode::Infinity)
  803. return r2;
  804. // 6. Let d1 be x – r1.
  805. auto d1 = x.remainder.unsigned_value();
  806. // 7. Let d2 be r2 – x.
  807. auto d2 = increment.minus(x.remainder.unsigned_value());
  808. // 8. If d1 < d2, return r1.
  809. if (d1 < d2)
  810. return r1;
  811. // 9. If d2 < d1, return r2.
  812. if (d2 < d1)
  813. return r2;
  814. // 10. Assert: d1 is equal to d2.
  815. // NOTE: Skipped for the sake of performance
  816. // 11. If unsignedRoundingMode is half-zero, return r1.
  817. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfZero)
  818. return r1;
  819. // 12. If unsignedRoundingMode is half-infinity, return r2.
  820. if (unsigned_rounding_mode == UnsignedRoundingMode::HalfInfinity)
  821. return r2;
  822. // 13. Assert: unsignedRoundingMode is half-even.
  823. VERIFY(unsigned_rounding_mode == UnsignedRoundingMode::HalfEven);
  824. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  825. auto cardinality = modulo(r1.divided_by(r2.minus(r1)).quotient, "2"_bigint);
  826. // 15. If cardinality is 0, return r1.
  827. if (cardinality.unsigned_value().is_zero())
  828. return r1;
  829. // 16. Return r2.
  830. return r2;
  831. }
  832. // 13.25 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  833. double round_number_to_increment(double x, u64 increment, StringView rounding_mode)
  834. {
  835. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  836. // 1. Let quotient be x / increment.
  837. auto quotient = x / static_cast<double>(increment);
  838. bool is_negative;
  839. // 2. If quotient < 0, then
  840. if (quotient < 0) {
  841. // a. Let isNegative be true.
  842. is_negative = true;
  843. // b. Set quotient to -quotient.
  844. quotient = -quotient;
  845. }
  846. // 3. Else,
  847. else {
  848. // a. Let isNegative be false.
  849. is_negative = false;
  850. }
  851. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  852. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  853. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  854. auto r1 = floor(quotient);
  855. // 6. Let r2 be the smallest integer such that r2 > quotient.
  856. auto r2 = ceil(quotient);
  857. if (quotient == r2)
  858. r2++;
  859. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  860. auto rounded = apply_unsigned_rounding_mode(quotient, r1, r2, unsigned_rounding_mode);
  861. // 8. If isNegative is true, set rounded to -rounded.
  862. if (is_negative)
  863. rounded = -rounded;
  864. // 9. Return rounded × increment.
  865. return rounded * static_cast<double>(increment);
  866. }
  867. // 13.25 RoundNumberToIncrement ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrement
  868. Crypto::SignedBigInteger round_number_to_increment(Crypto::SignedBigInteger const& x, u64 increment, StringView rounding_mode)
  869. {
  870. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  871. // OPTIMIZATION: If the increment is 1 the number is always rounded
  872. if (increment == 1)
  873. return x;
  874. auto increment_big_int = Crypto::UnsignedBigInteger { increment };
  875. // 1. Let quotient be x / increment.
  876. auto division_result = x.divided_by(increment_big_int);
  877. // OPTIMIZATION: If there's no remainder the number is already rounded
  878. if (division_result.remainder.unsigned_value().is_zero())
  879. return x;
  880. bool is_negative;
  881. // 2. If quotient < 0, then
  882. if (division_result.quotient.is_negative()) {
  883. // a. Let isNegative be true.
  884. is_negative = true;
  885. // b. Set quotient to -quotient.
  886. division_result.quotient.negate();
  887. division_result.remainder.negate();
  888. }
  889. // 3. Else,
  890. else {
  891. // a. Let isNegative be false.
  892. is_negative = false;
  893. }
  894. // 4. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
  895. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, is_negative);
  896. // 5. Let r1 be the largest integer such that r1 ≤ quotient.
  897. auto r1 = division_result.quotient;
  898. // 6. Let r2 be the smallest integer such that r2 > quotient.
  899. auto r2 = division_result.quotient.plus("1"_bigint);
  900. // 7. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  901. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment_big_int);
  902. // 8. If isNegative is true, set rounded to -rounded.
  903. if (is_negative)
  904. rounded.negate();
  905. // 9. Return rounded × increment.
  906. return rounded.multiplied_by(increment_big_int);
  907. }
  908. // 13.26 RoundNumberToIncrementAsIfPositive ( x, increment, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundnumbertoincrementasifpositive
  909. Crypto::SignedBigInteger round_number_to_increment_as_if_positive(Crypto::SignedBigInteger const& x, u64 increment, StringView rounding_mode)
  910. {
  911. VERIFY(rounding_mode == "ceil"sv || rounding_mode == "floor"sv || rounding_mode == "trunc"sv || rounding_mode == "halfExpand"sv);
  912. // OPTIMIZATION: If the increment is 1 the number is always rounded
  913. if (increment == 1)
  914. return x;
  915. auto increment_big_int = Crypto::UnsignedBigInteger { increment };
  916. // 1. Let quotient be x / increment.
  917. auto division_result = x.divided_by(increment_big_int);
  918. // OPTIMIZATION: If there's no remainder the number is already rounded
  919. if (division_result.remainder.unsigned_value().is_zero())
  920. return x;
  921. // 2. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, false).
  922. auto unsigned_rounding_mode = get_unsigned_rounding_mode(rounding_mode, false);
  923. // 3. Let r1 be the largest integer such that r1 ≤ quotient.
  924. auto r1 = division_result.quotient;
  925. // 4. Let r2 be the smallest integer such that r2 > quotient.
  926. auto r2 = division_result.quotient.plus("1"_bigint);
  927. // 5. Let rounded be ApplyUnsignedRoundingMode(quotient, r1, r2, unsignedRoundingMode).
  928. auto rounded = apply_unsigned_rounding_mode(division_result, r1, r2, unsigned_rounding_mode, increment_big_int);
  929. // 6. Return rounded × increment.
  930. return rounded.multiplied_by(increment_big_int);
  931. }
  932. // 13.28 ParseISODateTime ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parseisodatetime
  933. ThrowCompletionOr<ISODateTime> parse_iso_date_time(VM& vm, ParseResult const& parse_result)
  934. {
  935. // 1. Let parseResult be empty.
  936. // 2. For each nonterminal goal of « TemporalDateTimeString, TemporalInstantString, TemporalMonthDayString, TemporalTimeString, TemporalYearMonthString, TemporalZonedDateTimeString », do
  937. // a. If parseResult is not a Parse Node, set parseResult to ParseText(StringToCodePoints(isoString), goal).
  938. // 3. Assert: parseResult is a Parse Node.
  939. // NOTE: All of this is done by receiving an already parsed ISO string (ParseResult).
  940. // 4. Let each of year, month, day, hour, minute, second, fSeconds, and calendar be the source text matched by the respective DateYear, DateMonth, DateDay, TimeHour, TimeMinute, TimeSecond, TimeFraction, and CalendarName Parse Node contained within parseResult, or an empty sequence of code points if not present.
  941. auto year = parse_result.date_year;
  942. auto month = parse_result.date_month;
  943. auto day = parse_result.date_day;
  944. auto hour = parse_result.time_hour;
  945. auto minute = parse_result.time_minute;
  946. auto second = parse_result.time_second;
  947. auto f_seconds = parse_result.time_fraction;
  948. auto calendar = parse_result.calendar_name;
  949. // 5. If the first code point of year is U+2212 (MINUS SIGN), replace the first code point with U+002D (HYPHEN-MINUS).
  950. Optional<String> normalized_year;
  951. if (year.has_value()) {
  952. normalized_year = year->starts_with("\xE2\x88\x92"sv)
  953. ? String::formatted("-{}", year->substring_view(3))
  954. : String { *year };
  955. }
  956. // 6. Let yearMV be ! ToIntegerOrInfinity(CodePointsToString(year)).
  957. auto year_mv = *normalized_year.value_or("0"sv).to_int<i32>();
  958. // 7. If month is empty, then
  959. // a. Let monthMV be 1.
  960. // 8. Else,
  961. // a. Let monthMV be ! ToIntegerOrInfinity(CodePointsToString(month)).
  962. auto month_mv = *month.value_or("1"sv).to_uint<u8>();
  963. // 9. If day is empty, then
  964. // a. Let dayMV be 1.
  965. // 10. Else,
  966. // a. Let dayMV be ! ToIntegerOrInfinity(CodePointsToString(day)).
  967. auto day_mv = *day.value_or("1"sv).to_uint<u8>();
  968. // 11. Let hourMV be ! ToIntegerOrInfinity(CodePointsToString(hour)).
  969. auto hour_mv = *hour.value_or("0"sv).to_uint<u8>();
  970. // 12. Let minuteMV be ! ToIntegerOrInfinity(CodePointsToString(minute)).
  971. auto minute_mv = *minute.value_or("0"sv).to_uint<u8>();
  972. // 13. Let secondMV be ! ToIntegerOrInfinity(CodePointsToString(second)).
  973. auto second_mv = *second.value_or("0"sv).to_uint<u8>();
  974. // 14. If secondMV is 60, then
  975. if (second_mv == 60) {
  976. // a. Set secondMV to 59.
  977. second_mv = 59;
  978. }
  979. u16 millisecond_mv;
  980. u16 microsecond_mv;
  981. u16 nanosecond_mv;
  982. // 15. If fSeconds is not empty, then
  983. if (f_seconds.has_value()) {
  984. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  985. auto f_seconds_digits = f_seconds->substring_view(1);
  986. // b. Let fSecondsDigitsExtended be the string-concatenation of fSecondsDigits and "000000000".
  987. auto f_seconds_digits_extended = String::formatted("{}000000000", f_seconds_digits);
  988. // c. Let millisecond be the substring of fSecondsDigitsExtended from 0 to 3.
  989. auto millisecond = f_seconds_digits_extended.substring(0, 3);
  990. // d. Let microsecond be the substring of fSecondsDigitsExtended from 3 to 6.
  991. auto microsecond = f_seconds_digits_extended.substring(3, 3);
  992. // e. Let nanosecond be the substring of fSecondsDigitsExtended from 6 to 9.
  993. auto nanosecond = f_seconds_digits_extended.substring(6, 3);
  994. // f. Let millisecondMV be ! ToIntegerOrInfinity(millisecond).
  995. millisecond_mv = *millisecond.to_uint<u16>();
  996. // g. Let microsecondMV be ! ToIntegerOrInfinity(microsecond).
  997. microsecond_mv = *microsecond.to_uint<u16>();
  998. // h. Let nanosecondMV be ! ToIntegerOrInfinity(nanosecond).
  999. nanosecond_mv = *nanosecond.to_uint<u16>();
  1000. }
  1001. // 16. Else,
  1002. else {
  1003. // a. Let millisecondMV be 0.
  1004. millisecond_mv = 0;
  1005. // b. Let microsecondMV be 0.
  1006. microsecond_mv = 0;
  1007. // c. Let nanosecondMV be 0.
  1008. nanosecond_mv = 0;
  1009. }
  1010. // 17. If IsValidISODate(yearMV, monthMV, dayMV) is false, throw a RangeError exception.
  1011. if (!is_valid_iso_date(year_mv, month_mv, day_mv))
  1012. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidISODate);
  1013. // 18. If IsValidTime(hourMV, minuteMV, secondMV, millisecondMV, microsecondMV, nanosecondMV) is false, throw a RangeError exception.
  1014. if (!is_valid_time(hour_mv, minute_mv, second_mv, millisecond_mv, microsecond_mv, nanosecond_mv))
  1015. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTime);
  1016. // 19. Let timeZoneResult be the Record { [[Z]]: false, [[OffsetString]]: undefined, [[Name]]: undefined }.
  1017. auto time_zone_result = TemporalTimeZone { .z = false, .offset_string = {}, .name = {} };
  1018. // 20. If parseResult contains a TimeZoneIdentifier Parse Node, then
  1019. if (parse_result.time_zone_identifier.has_value()) {
  1020. // a. Let name be the source text matched by the TimeZoneIdentifier Parse Node contained within parseResult.
  1021. auto name = parse_result.time_zone_identifier;
  1022. // b. Set timeZoneResult.[[Name]] to CodePointsToString(name).
  1023. time_zone_result.name = *name;
  1024. }
  1025. // 21. If parseResult contains a UTCDesignator Parse Node, then
  1026. if (parse_result.utc_designator.has_value()) {
  1027. // a. Set timeZoneResult.[[Z]] to true.
  1028. time_zone_result.z = true;
  1029. }
  1030. // 22. Else,
  1031. else {
  1032. // a. If parseResult contains a TimeZoneNumericUTCOffset Parse Node, then
  1033. if (parse_result.time_zone_numeric_utc_offset.has_value()) {
  1034. // i. Let offset be the source text matched by the TimeZoneNumericUTCOffset Parse Node contained within parseResult.
  1035. auto offset = parse_result.time_zone_numeric_utc_offset;
  1036. // ii. Set timeZoneResult.[[OffsetString]] to CodePointsToString(offset).
  1037. time_zone_result.offset_string = *offset;
  1038. }
  1039. }
  1040. Optional<String> calendar_val;
  1041. // 23. If calendar is empty, then
  1042. if (!calendar.has_value()) {
  1043. // a. Let calendarVal be undefined.
  1044. calendar_val = {};
  1045. }
  1046. // 24. Else,
  1047. else {
  1048. // a. Let calendarVal be CodePointsToString(calendar).
  1049. // NOTE: This turns the StringView into a String.
  1050. calendar_val = *calendar;
  1051. }
  1052. // 25. Return the Record { [[Year]]: yearMV, [[Month]]: monthMV, [[Day]]: dayMV, [[Hour]]: hourMV, [[Minute]]: minuteMV, [[Second]]: secondMV, [[Millisecond]]: millisecondMV, [[Microsecond]]: microsecondMV, [[Nanosecond]]: nanosecondMV, [[TimeZone]]: timeZoneResult, [[Calendar]]: calendarVal, }.
  1053. return ISODateTime { .year = year_mv, .month = month_mv, .day = day_mv, .hour = hour_mv, .minute = minute_mv, .second = second_mv, .millisecond = millisecond_mv, .microsecond = microsecond_mv, .nanosecond = nanosecond_mv, .time_zone = move(time_zone_result), .calendar = move(calendar_val) };
  1054. }
  1055. // 13.29 ParseTemporalInstantString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstantstring
  1056. ThrowCompletionOr<TemporalInstant> parse_temporal_instant_string(VM& vm, String const& iso_string)
  1057. {
  1058. // 1. If ParseText(StringToCodePoints(isoString), TemporalInstantString) is a List of errors, throw a RangeError exception.
  1059. auto parse_result = parse_iso8601(Production::TemporalInstantString, iso_string);
  1060. if (!parse_result.has_value())
  1061. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidInstantString, iso_string);
  1062. // 2. Let result be ? ParseISODateTime(isoString).
  1063. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1064. // 3. Let offsetString be result.[[TimeZone]].[[OffsetString]].
  1065. Optional<String> offset_string = result.time_zone.offset_string;
  1066. // 4. If result.[[TimeZone]].[[Z]] is true, then
  1067. if (result.time_zone.z) {
  1068. // a. Set offsetString to "+00:00".
  1069. offset_string = "+00:00"sv;
  1070. }
  1071. // 6. Assert: offsetString is not undefined.
  1072. VERIFY(offset_string.has_value());
  1073. // 7. 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 }.
  1074. 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) };
  1075. }
  1076. // 13.30 ParseTemporalZonedDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalzoneddatetimestring
  1077. ThrowCompletionOr<ISODateTime> parse_temporal_zoned_date_time_string(VM& vm, String const& iso_string)
  1078. {
  1079. // 1. If ParseText(StringToCodePoints(isoString), TemporalZonedDateTimeString) is a List of errors, throw a RangeError exception.
  1080. auto parse_result = parse_iso8601(Production::TemporalZonedDateTimeString, iso_string);
  1081. if (!parse_result.has_value())
  1082. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidZonedDateTimeString, iso_string);
  1083. // 2. Return ? ParseISODateTime(isoString).
  1084. return parse_iso_date_time(vm, *parse_result);
  1085. }
  1086. // 13.31 ParseTemporalCalendarString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalcalendarstring
  1087. ThrowCompletionOr<String> parse_temporal_calendar_string(VM& vm, String const& iso_string)
  1088. {
  1089. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalCalendarString).
  1090. auto parse_result = parse_iso8601(Production::TemporalCalendarString, iso_string);
  1091. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1092. if (!parse_result.has_value())
  1093. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarString, iso_string);
  1094. // 3. Let id be the source text matched by the CalendarName Parse Node contained within parseResult, or an empty sequence of code points if not present.
  1095. auto id = parse_result->calendar_name;
  1096. // 4. If id is empty, then
  1097. if (!id.has_value()) {
  1098. // a. Return "iso8601".
  1099. return "iso8601"sv;
  1100. }
  1101. // 5. Return CodePointsToString(id).
  1102. return id.value();
  1103. }
  1104. // 13.32 ParseTemporalDateString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatestring
  1105. ThrowCompletionOr<TemporalDate> parse_temporal_date_string(VM& vm, String const& iso_string)
  1106. {
  1107. // 1. Let parts be ? ParseTemporalDateTimeString(isoString).
  1108. auto parts = TRY(parse_temporal_date_time_string(vm, iso_string));
  1109. // 2. Return the Record { [[Year]]: parts.[[Year]], [[Month]]: parts.[[Month]], [[Day]]: parts.[[Day]], [[Calendar]]: parts.[[Calendar]] }.
  1110. return TemporalDate { .year = parts.year, .month = parts.month, .day = parts.day, .calendar = move(parts.calendar) };
  1111. }
  1112. // 13.33 ParseTemporalDateTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldatetimestring
  1113. ThrowCompletionOr<ISODateTime> parse_temporal_date_time_string(VM& vm, String const& iso_string)
  1114. {
  1115. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalDateTimeString).
  1116. auto parse_result = parse_iso8601(Production::TemporalDateTimeString, iso_string);
  1117. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1118. if (!parse_result.has_value())
  1119. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeString, iso_string);
  1120. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1121. if (parse_result->utc_designator.has_value())
  1122. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeStringUTCDesignator, iso_string);
  1123. // 4. Return ? ParseISODateTime(isoString).
  1124. return parse_iso_date_time(vm, *parse_result);
  1125. }
  1126. // 13.34 ParseTemporalDurationString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaldurationstring
  1127. ThrowCompletionOr<DurationRecord> parse_temporal_duration_string(VM& vm, String const& iso_string)
  1128. {
  1129. // 1. Let duration be ParseText(StringToCodePoints(isoString), TemporalDurationString).
  1130. auto parse_result = parse_iso8601(Production::TemporalDurationString, iso_string);
  1131. // 2. If duration is a List of errors, throw a RangeError exception.
  1132. if (!parse_result.has_value())
  1133. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationString, iso_string);
  1134. // 3. Let each of sign, years, months, weeks, days, hours, fHours, minutes, fMinutes, seconds, and fSeconds be the source text matched by the respective Sign, DurationYears, DurationMonths, DurationWeeks, DurationDays, DurationWholeHours, DurationHoursFraction, DurationWholeMinutes, DurationMinutesFraction, DurationWholeSeconds, and DurationSecondsFraction Parse Node contained within duration, or an empty sequence of code points if not present.
  1135. auto sign_part = parse_result->sign;
  1136. auto years_part = parse_result->duration_years;
  1137. auto months_part = parse_result->duration_months;
  1138. auto weeks_part = parse_result->duration_weeks;
  1139. auto days_part = parse_result->duration_days;
  1140. auto hours_part = parse_result->duration_whole_hours;
  1141. auto f_hours_part = parse_result->duration_hours_fraction;
  1142. auto minutes_part = parse_result->duration_whole_minutes;
  1143. auto f_minutes_part = parse_result->duration_minutes_fraction;
  1144. auto seconds_part = parse_result->duration_whole_seconds;
  1145. auto f_seconds_part = parse_result->duration_seconds_fraction;
  1146. // FIXME: I can has StringView::to<double>()?
  1147. // 4. Let yearsMV be ! ToIntegerOrInfinity(CodePointsToString(years)).
  1148. auto years = strtod(String { years_part.value_or("0"sv) }.characters(), nullptr);
  1149. // 5. Let monthsMV be ! ToIntegerOrInfinity(CodePointsToString(months)).
  1150. auto months = strtod(String { months_part.value_or("0"sv) }.characters(), nullptr);
  1151. // 6. Let weeksMV be ! ToIntegerOrInfinity(CodePointsToString(weeks)).
  1152. auto weeks = strtod(String { weeks_part.value_or("0"sv) }.characters(), nullptr);
  1153. // 7. Let daysMV be ! ToIntegerOrInfinity(CodePointsToString(days)).
  1154. auto days = strtod(String { days_part.value_or("0"sv) }.characters(), nullptr);
  1155. // 8. Let hoursMV be ! ToIntegerOrInfinity(CodePointsToString(hours)).
  1156. auto hours = strtod(String { hours_part.value_or("0"sv) }.characters(), nullptr);
  1157. double minutes;
  1158. // 9. If fHours is not empty, then
  1159. if (f_hours_part.has_value()) {
  1160. // a. If any of minutes, fMinutes, seconds, fSeconds is not empty, throw a RangeError exception.
  1161. if (minutes_part.has_value() || f_minutes_part.has_value() || seconds_part.has_value() || f_seconds_part.has_value())
  1162. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationStringFractionNotLast, iso_string, "hours"sv, "minutes or seconds"sv);
  1163. // b. Let fHoursDigits be the substring of CodePointsToString(fHours) from 1.
  1164. auto f_hours_digits = f_hours_part->substring_view(1);
  1165. // c. Let fHoursScale be the length of fHoursDigits.
  1166. auto f_hours_scale = (double)f_hours_digits.length();
  1167. // d. Let minutesMV be ! ToIntegerOrInfinity(fHoursDigits) / 10^fHoursScale × 60.
  1168. minutes = strtod(String { f_hours_digits }.characters(), nullptr) / pow(10, f_hours_scale) * 60;
  1169. }
  1170. // 10. Else,
  1171. else {
  1172. // a. Let minutesMV be ! ToIntegerOrInfinity(CodePointsToString(minutes)).
  1173. minutes = strtod(String { minutes_part.value_or("0"sv) }.characters(), nullptr);
  1174. }
  1175. double seconds;
  1176. // 11. If fMinutes is not empty, then
  1177. if (f_minutes_part.has_value()) {
  1178. // a. If any of seconds, fSeconds is not empty, throw a RangeError exception.
  1179. if (seconds_part.has_value() || f_seconds_part.has_value())
  1180. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationStringFractionNotLast, iso_string, "minutes"sv, "seconds"sv);
  1181. // b. Let fMinutesDigits be the substring of CodePointsToString(fMinutes) from 1.
  1182. auto f_minutes_digits = f_minutes_part->substring_view(1);
  1183. // c. Let fMinutesScale be the length of fMinutesDigits.
  1184. auto f_minutes_scale = (double)f_minutes_digits.length();
  1185. // d. Let secondsMV be ! ToIntegerOrInfinity(fMinutesDigits) / 10^fMinutesScale × 60.
  1186. seconds = strtod(String { f_minutes_digits }.characters(), nullptr) / pow(10, f_minutes_scale) * 60;
  1187. }
  1188. // 12. Else if seconds is not empty, then
  1189. else if (seconds_part.has_value()) {
  1190. // a. Let secondsMV be ! ToIntegerOrInfinity(CodePointsToString(seconds)).
  1191. seconds = strtod(String { *seconds_part }.characters(), nullptr);
  1192. }
  1193. // 13. Else,
  1194. else {
  1195. // a. Let secondsMV be remainder(minutesMV, 1) × 60.
  1196. seconds = fmod(minutes, 1) * 60;
  1197. }
  1198. double milliseconds;
  1199. // 14. If fSeconds is not empty, then
  1200. if (f_seconds_part.has_value()) {
  1201. // a. Let fSecondsDigits be the substring of CodePointsToString(fSeconds) from 1.
  1202. auto f_seconds_digits = f_seconds_part->substring_view(1);
  1203. // b. Let fSecondsScale be the length of fSecondsDigits.
  1204. auto f_seconds_scale = (double)f_seconds_digits.length();
  1205. // c. Let millisecondsMV be ! ToIntegerOrInfinity(fSecondsDigits) / 10^fSecondsScale × 1000.
  1206. milliseconds = strtod(String { f_seconds_digits }.characters(), nullptr) / pow(10, f_seconds_scale) * 1000;
  1207. }
  1208. // 15. Else,
  1209. else {
  1210. // a. Let millisecondsMV be remainder(secondsMV, 1) × 1000.
  1211. milliseconds = fmod(seconds, 1) * 1000;
  1212. }
  1213. // FIXME: This suffers from floating point (im)precision issues - e.g. "PT0.0000001S" ends up
  1214. // getting parsed as 99.999999 nanoseconds, which is floor()'d to 99 instead of the
  1215. // expected 100. Oof. This is the reason all of these are suffixed with "MV" in the spec:
  1216. // mathematical values are not supposed to have this issue.
  1217. // 16. Let microsecondsMV be remainder(millisecondsMV, 1) × 1000.
  1218. auto microseconds = fmod(milliseconds, 1) * 1000;
  1219. // 17. Let nanosecondsMV be remainder(microsecondsMV, 1) × 1000.
  1220. auto nanoseconds = fmod(microseconds, 1) * 1000;
  1221. i8 factor;
  1222. // 18. If sign contains the code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
  1223. if (sign_part.has_value() && sign_part->is_one_of("-", "\u2212")) {
  1224. // a. Let factor be -1.
  1225. factor = -1;
  1226. }
  1227. // 19. Else,
  1228. else {
  1229. // a. Let factor be 1.
  1230. factor = 1;
  1231. }
  1232. // 20. Return ? CreateDurationRecord(yearsMV × factor, monthsMV × factor, weeksMV × factor, daysMV × factor, hoursMV × factor, floor(minutesMV) × factor, floor(secondsMV) × factor, floor(millisecondsMV) × factor, floor(microsecondsMV) × factor, floor(nanosecondsMV) × factor).
  1233. return create_duration_record(vm, years * factor, months * factor, weeks * factor, days * factor, hours * factor, floor(minutes) * factor, floor(seconds) * factor, floor(milliseconds) * factor, floor(microseconds) * factor, floor(nanoseconds) * factor);
  1234. }
  1235. // 13.35 ParseTemporalMonthDayString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalmonthdaystring
  1236. ThrowCompletionOr<TemporalMonthDay> parse_temporal_month_day_string(VM& vm, String const& iso_string)
  1237. {
  1238. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalMonthDayString).
  1239. auto parse_result = parse_iso8601(Production::TemporalMonthDayString, iso_string);
  1240. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1241. if (!parse_result.has_value())
  1242. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthDayString, iso_string);
  1243. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1244. if (parse_result->utc_designator.has_value())
  1245. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidMonthDayStringUTCDesignator, iso_string);
  1246. // 4. Let result be ? ParseISODateTime(isoString).
  1247. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1248. // 5. Let year be result.[[Year]].
  1249. Optional<i32> year = result.year;
  1250. // 6. If parseResult does not contain a DateYear Parse Node, then
  1251. if (!parse_result->date_year.has_value()) {
  1252. // a. Set year to undefined.
  1253. year = {};
  1254. }
  1255. // 7. Return the Record { [[Year]]: year, [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1256. return TemporalMonthDay { .year = year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1257. }
  1258. // 13.36 ParseTemporalRelativeToString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalrelativetostring
  1259. ThrowCompletionOr<ISODateTime> parse_temporal_relative_to_string(VM& vm, String const& iso_string)
  1260. {
  1261. // 1. If ParseText(StringToCodePoints(isoString), TemporalDateTimeString) is a List of errors, throw a RangeError exception.
  1262. auto parse_result = parse_iso8601(Production::TemporalDateTimeString, iso_string);
  1263. if (!parse_result.has_value())
  1264. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDateTimeString, iso_string);
  1265. // 2. Return ? ParseISODateTime(isoString).
  1266. return parse_iso_date_time(vm, *parse_result);
  1267. }
  1268. // 13.37 ParseTemporalTimeString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimestring
  1269. ThrowCompletionOr<TemporalTime> parse_temporal_time_string(VM& vm, String const& iso_string)
  1270. {
  1271. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalTimeString).
  1272. auto parse_result = parse_iso8601(Production::TemporalTimeString, iso_string);
  1273. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1274. if (!parse_result.has_value())
  1275. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeString, iso_string);
  1276. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1277. if (parse_result->utc_designator.has_value())
  1278. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeStringUTCDesignator, iso_string);
  1279. // 4. Let result be ? ParseISODateTime(isoString).
  1280. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1281. // 5. Return the Record { [[Hour]]: result.[[Hour]], [[Minute]]: result.[[Minute]], [[Second]]: result.[[Second]], [[Millisecond]]: result.[[Millisecond]], [[Microsecond]]: result.[[Microsecond]], [[Nanosecond]]: result.[[Nanosecond]], [[Calendar]]: result.[[Calendar]] }.
  1282. return TemporalTime { .hour = result.hour, .minute = result.minute, .second = result.second, .millisecond = result.millisecond, .microsecond = result.microsecond, .nanosecond = result.nanosecond, .calendar = move(result.calendar) };
  1283. }
  1284. // 13.38 ParseTemporalTimeZoneString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezonestring
  1285. ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(VM& vm, String const& iso_string)
  1286. {
  1287. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalTimeZoneString).
  1288. auto parse_result = parse_iso8601(Production::TemporalTimeZoneString, iso_string);
  1289. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1290. if (!parse_result.has_value())
  1291. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneString, iso_string);
  1292. // 3. Let each of z, offsetString, and name be the source text matched by the respective UTCDesignator, TimeZoneNumericUTCOffset, and TimeZoneIdentifier Parse Nodes contained within parseResult, or an empty sequence of code points if not present.
  1293. auto z = parse_result->utc_designator;
  1294. auto offset_string = parse_result->time_zone_numeric_utc_offset;
  1295. auto name = parse_result->time_zone_identifier;
  1296. // 4. If name is empty, then
  1297. // a. Set name to undefined.
  1298. // 5. Else,
  1299. // a. Set name to CodePointsToString(name).
  1300. // NOTE: No-op.
  1301. // 6. If z is not empty, then
  1302. if (z.has_value()) {
  1303. // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
  1304. return TemporalTimeZone { .z = true, .offset_string = {}, .name = Optional<String>(move(name)) };
  1305. }
  1306. // 7. If offsetString is empty, then
  1307. // a. Set offsetString to undefined.
  1308. // 8. Else,
  1309. // a. Set offsetString to CodePointsToString(offsetString).
  1310. // NOTE: No-op.
  1311. // 9. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
  1312. return TemporalTimeZone { .z = false, .offset_string = Optional<String>(move(offset_string)), .name = Optional<String>(move(name)) };
  1313. }
  1314. // 13.39 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
  1315. ThrowCompletionOr<TemporalYearMonth> parse_temporal_year_month_string(VM& vm, String const& iso_string)
  1316. {
  1317. // 1. Let parseResult be ParseText(StringToCodePoints(isoString), TemporalYearMonthString).
  1318. auto parse_result = parse_iso8601(Production::TemporalYearMonthString, iso_string);
  1319. // 2. If parseResult is a List of errors, throw a RangeError exception.
  1320. if (!parse_result.has_value())
  1321. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidYearMonthString, iso_string);
  1322. // 3. If parseResult contains a UTCDesignator Parse Node, throw a RangeError exception.
  1323. if (parse_result->utc_designator.has_value())
  1324. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidYearMonthStringUTCDesignator, iso_string);
  1325. // 4. Let result be ? ParseISODateTime(isoString).
  1326. auto result = TRY(parse_iso_date_time(vm, *parse_result));
  1327. // 5. Return the Record { [[Year]]: result.[[Year]], [[Month]]: result.[[Month]], [[Day]]: result.[[Day]], [[Calendar]]: result.[[Calendar]] }.
  1328. return TemporalYearMonth { .year = result.year, .month = result.month, .day = result.day, .calendar = move(result.calendar) };
  1329. }
  1330. // 13.40 ToPositiveInteger ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-topositiveinteger
  1331. ThrowCompletionOr<double> to_positive_integer(VM& vm, Value argument)
  1332. {
  1333. // 1. Let integer be ? ToIntegerThrowOnInfinity(argument).
  1334. auto integer = TRY(to_integer_throw_on_infinity(vm, argument, ErrorType::TemporalPropertyMustBePositiveInteger));
  1335. // 2. If integer ≤ 0, then
  1336. if (integer <= 0) {
  1337. // a. Throw a RangeError exception.
  1338. return vm.throw_completion<RangeError>(ErrorType::TemporalPropertyMustBePositiveInteger);
  1339. }
  1340. // 3. Return integer.
  1341. return integer;
  1342. }
  1343. // 13.43 PrepareTemporalFields ( fields, fieldNames, requiredFields ), https://tc39.es/proposal-temporal/#sec-temporal-preparetemporalfields
  1344. ThrowCompletionOr<Object*> prepare_temporal_fields(VM& vm, Object const& fields, Vector<String> const& field_names, Variant<PrepareTemporalFieldsPartial, Vector<StringView>> const& required_fields)
  1345. {
  1346. auto& realm = *vm.current_realm();
  1347. // 1. Let result be OrdinaryObjectCreate(null).
  1348. auto* result = Object::create(realm, nullptr);
  1349. VERIFY(result);
  1350. // 2. Let any be false.
  1351. auto any = false;
  1352. // 3. For each value property of fieldNames, do
  1353. for (auto& property : field_names) {
  1354. // a. Let value be ? Get(fields, property).
  1355. auto value = TRY(fields.get(property));
  1356. // b. If value is not undefined, then
  1357. if (!value.is_undefined()) {
  1358. // i. Set any to true.
  1359. any = true;
  1360. // ii. If property is in the Property column of Table 15 and there is a Conversion value in the same row, then
  1361. // 1. Let Conversion be the Conversion value of the same row.
  1362. // 2. If Conversion is ToIntegerThrowOnInfinity, then
  1363. if (property.is_one_of("year"sv, "hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv, "eraYear"sv)) {
  1364. // a. Set value to ? ToIntegerThrowOnInfinity(value).
  1365. // b. Set value to 𝔽(value).
  1366. value = Value(TRY(to_integer_throw_on_infinity(vm, value, ErrorType::TemporalPropertyMustBeFinite)));
  1367. }
  1368. // 3. Else if Conversion is ToPositiveInteger, then
  1369. else if (property.is_one_of("month"sv, "day"sv)) {
  1370. // a. Set value to ? ToPositiveInteger(value).
  1371. // b. Set value to 𝔽(value).
  1372. value = Value(TRY(to_positive_integer(vm, value)));
  1373. }
  1374. // 4. Else,
  1375. else if (property.is_one_of("monthCode"sv, "offset"sv, "era"sv)) {
  1376. // a. Assert: Conversion is ToString.
  1377. // b. Set value to ? ToString(value).
  1378. value = TRY(value.to_primitive_string(vm));
  1379. }
  1380. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1381. MUST(result->create_data_property_or_throw(property, value));
  1382. }
  1383. // c. Else if requiredFields is a List, then
  1384. else if (required_fields.has<Vector<StringView>>()) {
  1385. // i. If requiredFields contains property, then
  1386. if (required_fields.get<Vector<StringView>>().contains_slow(property)) {
  1387. // 1. Throw a TypeError exception.
  1388. return vm.throw_completion<TypeError>(ErrorType::MissingRequiredProperty, property);
  1389. }
  1390. // ii. If property is in the Property column of Table 13, then
  1391. // NOTE: The other properties in the table are automatically handled as their default value is undefined
  1392. if (property.is_one_of("hour"sv, "minute"sv, "second"sv, "millisecond"sv, "microsecond"sv, "nanosecond"sv)) {
  1393. // 1. Set value to the corresponding Default value of the same row.
  1394. value = Value(0);
  1395. }
  1396. // iii. Perform ! CreateDataPropertyOrThrow(result, property, value).
  1397. MUST(result->create_data_property_or_throw(property, value));
  1398. }
  1399. }
  1400. // 4. If requiredFields is partial and any is false, then
  1401. if (required_fields.has<PrepareTemporalFieldsPartial>() && !any) {
  1402. // a. Throw a TypeError exception.
  1403. return vm.throw_completion<TypeError>(ErrorType::TemporalObjectMustHaveOneOf, String::join(", "sv, field_names));
  1404. }
  1405. // 5. Return result.
  1406. return result;
  1407. }
  1408. // 13.44 GetDifferenceSettings ( operation, options, unitGroup, disallowedUnits, fallbackSmallestUnit, smallestLargestDefaultUnit ), https://tc39.es/proposal-temporal/#sec-temporal-getdifferencesettings
  1409. ThrowCompletionOr<DifferenceSettings> get_difference_settings(VM& vm, DifferenceOperation operation, Value options_value, UnitGroup unit_group, Vector<StringView> const& disallowed_units, TemporalUnitDefault const& fallback_smallest_unit, StringView smallest_largest_default_unit)
  1410. {
  1411. // 1. Set options to ? GetOptionsObject(options).
  1412. auto* options = TRY(get_options_object(vm, options_value));
  1413. // 2. Let smallestUnit be ? GetTemporalUnit(options, "smallestUnit", unitGroup, fallbackSmallestUnit).
  1414. auto smallest_unit = TRY(get_temporal_unit(vm, *options, vm.names.smallestUnit, unit_group, fallback_smallest_unit));
  1415. // 3. If disallowedUnits contains smallestUnit, throw a RangeError exception.
  1416. if (disallowed_units.contains_slow(*smallest_unit))
  1417. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *smallest_unit, "smallestUnit"sv);
  1418. // 4. Let defaultLargestUnit be ! LargerOfTwoTemporalUnits(smallestLargestDefaultUnit, smallestUnit).
  1419. auto default_largest_unit = larger_of_two_temporal_units(smallest_largest_default_unit, *smallest_unit);
  1420. // 5. Let largestUnit be ? GetTemporalUnit(options, "largestUnit", unitGroup, "auto").
  1421. auto largest_unit = TRY(get_temporal_unit(vm, *options, vm.names.largestUnit, unit_group, { "auto"sv }));
  1422. // 6. If disallowedUnits contains largestUnit, throw a RangeError exception.
  1423. if (disallowed_units.contains_slow(*largest_unit))
  1424. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, *largest_unit, "largestUnit"sv);
  1425. // 7. If largestUnit is "auto", set largestUnit to defaultLargestUnit.
  1426. if (largest_unit == "auto"sv)
  1427. largest_unit = default_largest_unit;
  1428. // 8. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
  1429. if (larger_of_two_temporal_units(*largest_unit, *smallest_unit) != largest_unit)
  1430. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidUnitRange, *smallest_unit, *largest_unit);
  1431. // 9. Let roundingMode be ? ToTemporalRoundingMode(options, "trunc").
  1432. auto rounding_mode = TRY(to_temporal_rounding_mode(vm, *options, "trunc"sv));
  1433. // 10. If operation is since, then
  1434. if (operation == DifferenceOperation::Since) {
  1435. // a. Set roundingMode to ! NegateTemporalRoundingMode(roundingMode).
  1436. rounding_mode = negate_temporal_rounding_mode(rounding_mode);
  1437. }
  1438. // 11. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  1439. auto maximum = maximum_temporal_duration_rounding_increment(*smallest_unit);
  1440. // 12. Let roundingIncrement be ? ToTemporalRoundingIncrement(options, maximum, false).
  1441. auto rounding_increment = TRY(to_temporal_rounding_increment(vm, *options, Optional<double> { maximum }, false));
  1442. // 13. Return the Record { [[SmallestUnit]]: smallestUnit, [[LargestUnit]]: largestUnit, [[RoundingMode]]: roundingMode, [[RoundingIncrement]]: roundingIncrement, [[Options]]: options }.
  1443. return DifferenceSettings {
  1444. .smallest_unit = smallest_unit.release_value(),
  1445. .largest_unit = largest_unit.release_value(),
  1446. .rounding_mode = move(rounding_mode),
  1447. .rounding_increment = rounding_increment,
  1448. .options = *options,
  1449. };
  1450. }
  1451. }