ZonedDateTime.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Date.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Temporal/Calendar.h>
  11. #include <LibJS/Runtime/Temporal/Duration.h>
  12. #include <LibJS/Runtime/Temporal/Instant.h>
  13. #include <LibJS/Runtime/Temporal/PlainDate.h>
  14. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  15. #include <LibJS/Runtime/Temporal/TimeZone.h>
  16. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  17. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  18. namespace JS::Temporal {
  19. // 6 Temporal.ZonedDateTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-zoneddatetime-objects
  20. ZonedDateTime::ZonedDateTime(BigInt const& nanoseconds, Object& time_zone, Object& calendar, Object& prototype)
  21. : Object(prototype)
  22. , m_nanoseconds(nanoseconds)
  23. , m_time_zone(time_zone)
  24. , m_calendar(calendar)
  25. {
  26. }
  27. void ZonedDateTime::visit_edges(Cell::Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(&m_nanoseconds);
  31. visitor.visit(&m_time_zone);
  32. visitor.visit(&m_calendar);
  33. }
  34. // 6.5.1 InterpretISODateTimeOffset ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, offsetBehaviour, offsetNanoseconds, timeZone, disambiguation, offsetOption, matchBehaviour ), https://tc39.es/proposal-temporal/#sec-temporal-interpretisodatetimeoffset
  35. ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(VM& vm, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, OffsetBehavior offset_behavior, double offset_nanoseconds, Value time_zone, StringView disambiguation, StringView offset_option, MatchBehavior match_behavior)
  36. {
  37. // 1. Let calendar be ! GetISO8601Calendar().
  38. auto* calendar = get_iso8601_calendar(vm);
  39. // 2. Let dateTime be ? CreateTemporalDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar).
  40. auto* date_time = TRY(create_temporal_date_time(vm, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, *calendar));
  41. // 3. If offsetBehaviour is wall or offsetOption is "ignore", then
  42. if (offset_behavior == OffsetBehavior::Wall || offset_option == "ignore"sv) {
  43. // a. Let instant be ? BuiltinTimeZoneGetInstantFor(timeZone, dateTime, disambiguation).
  44. auto* instant = TRY(builtin_time_zone_get_instant_for(vm, time_zone, *date_time, disambiguation));
  45. // b. Return instant.[[Nanoseconds]].
  46. return &instant->nanoseconds();
  47. }
  48. // 4. If offsetBehaviour is exact or offsetOption is "use", then
  49. if (offset_behavior == OffsetBehavior::Exact || offset_option == "use"sv) {
  50. // a. Let epochNanoseconds be GetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond).
  51. auto epoch_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  52. // b. Set epochNanoseconds to epochNanoseconds - ℤ(offsetNanoseconds).
  53. epoch_nanoseconds = epoch_nanoseconds.minus(Crypto::SignedBigInteger { offset_nanoseconds });
  54. // c. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception.
  55. if (!is_valid_epoch_nanoseconds(epoch_nanoseconds))
  56. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  57. // d. Return epochNanoseconds.
  58. return js_bigint(vm, move(epoch_nanoseconds));
  59. }
  60. // 5. Assert: offsetBehaviour is option.
  61. VERIFY(offset_behavior == OffsetBehavior::Option);
  62. // 6. Assert: offsetOption is "prefer" or "reject".
  63. VERIFY(offset_option.is_one_of("prefer"sv, "reject"sv));
  64. // 7. Let possibleInstants be ? GetPossibleInstantsFor(timeZone, dateTime).
  65. auto possible_instants = TRY(get_possible_instants_for(vm, time_zone, *date_time));
  66. // 8. For each element candidate of possibleInstants, do
  67. for (auto* candidate : possible_instants) {
  68. // a. Let candidateNanoseconds be ? GetOffsetNanosecondsFor(timeZone, candidate).
  69. auto candidate_nanoseconds = TRY(get_offset_nanoseconds_for(vm, time_zone, *candidate));
  70. // b. If candidateNanoseconds = offsetNanoseconds, then
  71. if (candidate_nanoseconds == offset_nanoseconds) {
  72. // i. Return candidate.[[Nanoseconds]].
  73. return &candidate->nanoseconds();
  74. }
  75. // c. If matchBehaviour is match minutes, then
  76. if (match_behavior == MatchBehavior::MatchMinutes) {
  77. // i. Let roundedCandidateNanoseconds be RoundNumberToIncrement(candidateNanoseconds, 60 × 10^9, "halfExpand").
  78. auto rounded_candidate_nanoseconds = round_number_to_increment(candidate_nanoseconds, 60000000000, "halfExpand"sv);
  79. // ii. If roundedCandidateNanoseconds = offsetNanoseconds, then
  80. if (rounded_candidate_nanoseconds == offset_nanoseconds) {
  81. // 1. Return candidate.[[Nanoseconds]].
  82. return &candidate->nanoseconds();
  83. }
  84. }
  85. }
  86. // 9. If offsetOption is "reject", throw a RangeError exception.
  87. if (offset_option == "reject"sv)
  88. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidZonedDateTimeOffset);
  89. // 10. Let instant be ? DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation).
  90. auto* instant = TRY(disambiguate_possible_instants(vm, possible_instants, time_zone, *date_time, disambiguation));
  91. // 11. Return instant.[[Nanoseconds]].
  92. return &instant->nanoseconds();
  93. }
  94. // 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime
  95. ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(VM& vm, Value item, Object const* options)
  96. {
  97. // 1. If options is not present, set options to undefined.
  98. // 2. Assert: Type(options) is Object or Undefined.
  99. // 3. Let offsetBehaviour be option.
  100. auto offset_behavior = OffsetBehavior::Option;
  101. // 4. Let matchBehaviour be match exactly.
  102. auto match_behavior = MatchBehavior::MatchExactly;
  103. Object* calendar = nullptr;
  104. Object* time_zone = nullptr;
  105. Optional<String> offset_string;
  106. ISODateTime result;
  107. // 5. If Type(item) is Object, then
  108. if (item.is_object()) {
  109. auto& item_object = item.as_object();
  110. // a. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  111. if (is<ZonedDateTime>(item_object)) {
  112. // i. Return item.
  113. return &static_cast<ZonedDateTime&>(item_object);
  114. }
  115. // b. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  116. calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object));
  117. // c. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  118. 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 }));
  119. // d. Append "timeZone" to fieldNames.
  120. field_names.append("timeZone");
  121. // e. Append "offset" to fieldNames.
  122. field_names.append("offset");
  123. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, « "timeZone" »).
  124. auto* fields = TRY(prepare_temporal_fields(vm, item_object, field_names, Vector<StringView> { "timeZone"sv }));
  125. // g. Let timeZone be ! Get(fields, "timeZone").
  126. auto time_zone_value = MUST(fields->get(vm.names.timeZone));
  127. // h. Set timeZone to ? ToTemporalTimeZone(timeZone).
  128. time_zone = TRY(to_temporal_time_zone(vm, time_zone_value));
  129. // i. Let offsetString be ! Get(fields, "offset").
  130. auto offset_string_value = MUST(fields->get(vm.names.offset));
  131. // j. If offsetString is undefined, then
  132. if (offset_string_value.is_undefined()) {
  133. // i. Set offsetBehaviour to wall.
  134. offset_behavior = OffsetBehavior::Wall;
  135. }
  136. // k. Else,
  137. else {
  138. // i. Set offsetString to ? ToString(offsetString).
  139. offset_string = TRY(offset_string_value.to_string(vm));
  140. }
  141. // l. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
  142. result = TRY(interpret_temporal_date_time_fields(vm, *calendar, *fields, *options));
  143. }
  144. // 6. Else,
  145. else {
  146. // a. Perform ? ToTemporalOverflow(options).
  147. (void)TRY(to_temporal_overflow(vm, options));
  148. // b. Let string be ? ToString(item).
  149. auto string = TRY(item.to_string(vm));
  150. // c. Let result be ? ParseTemporalZonedDateTimeString(string).
  151. result = TRY(parse_temporal_zoned_date_time_string(vm, string));
  152. // d. Let timeZoneName be result.[[TimeZone]].[[Name]].
  153. auto time_zone_name = result.time_zone.name;
  154. // e. Assert: timeZoneName is not undefined.
  155. VERIFY(time_zone_name.has_value());
  156. // f. If IsTimeZoneOffsetString(timeZoneName) is false, then
  157. if (!is_time_zone_offset_string(*time_zone_name)) {
  158. // i. If IsValidTimeZoneName(timeZoneName) is false, throw a RangeError exception.
  159. if (!is_valid_time_zone_name(*time_zone_name))
  160. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, *time_zone_name);
  161. // ii. Set timeZoneName to ! CanonicalizeTimeZoneName(timeZoneName).
  162. time_zone_name = canonicalize_time_zone_name(*time_zone_name);
  163. }
  164. // g. Let offsetString be result.[[TimeZone]].[[OffsetString]].
  165. offset_string = move(result.time_zone.offset_string);
  166. // h. If result.[[TimeZone]].[[Z]] is true, then
  167. if (result.time_zone.z) {
  168. // i. Set offsetBehaviour to exact.
  169. offset_behavior = OffsetBehavior::Exact;
  170. }
  171. // i. Else if offsetString is undefined, then
  172. else if (!offset_string.has_value()) {
  173. // i. Set offsetBehaviour to wall.
  174. offset_behavior = OffsetBehavior::Wall;
  175. }
  176. // j. Let timeZone be ! CreateTemporalTimeZone(timeZoneName).
  177. time_zone = MUST(create_temporal_time_zone(vm, *time_zone_name));
  178. // k. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  179. auto temporal_calendar_like = result.calendar.has_value()
  180. ? js_string(vm, result.calendar.value())
  181. : js_undefined();
  182. calendar = TRY(to_temporal_calendar_with_iso_default(vm, temporal_calendar_like));
  183. // l. Set matchBehaviour to match minutes.
  184. match_behavior = MatchBehavior::MatchMinutes;
  185. }
  186. // 7. Let offsetNanoseconds be 0.
  187. double offset_nanoseconds = 0;
  188. // 8. If offsetBehaviour is option, then
  189. if (offset_behavior == OffsetBehavior::Option) {
  190. // a. If IsTimeZoneOffsetString(offsetString) is false, throw a RangeError exception.
  191. if (!is_time_zone_offset_string(*offset_string))
  192. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, *offset_string);
  193. // a. Set offsetNanoseconds to ? ParseTimeZoneOffsetString(offsetString).
  194. offset_nanoseconds = parse_time_zone_offset_string(*offset_string);
  195. }
  196. // 9. Let disambiguation be ? ToTemporalDisambiguation(options).
  197. auto disambiguation = TRY(to_temporal_disambiguation(vm, options));
  198. // 10. Let offsetOption be ? ToTemporalOffset(options, "reject").
  199. auto offset_option = TRY(to_temporal_offset(vm, options, "reject"));
  200. // 11. Let epochNanoseconds be ? InterpretISODateTimeOffset(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], offsetBehaviour, offsetNanoseconds, timeZone, disambiguation, offsetOption, matchBehaviour).
  201. 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_nanoseconds, time_zone, disambiguation, offset_option, match_behavior));
  202. // 12. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  203. return MUST(create_temporal_zoned_date_time(vm, *epoch_nanoseconds, *time_zone, *calendar));
  204. }
  205. // 6.5.3 CreateTemporalZonedDateTime ( epochNanoseconds, timeZone, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalzoneddatetime
  206. ThrowCompletionOr<ZonedDateTime*> create_temporal_zoned_date_time(VM& vm, BigInt const& epoch_nanoseconds, Object& time_zone, Object& calendar, FunctionObject const* new_target)
  207. {
  208. auto& realm = *vm.current_realm();
  209. // 1. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  210. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  211. // 2. If newTarget is not present, set newTarget to %Temporal.ZonedDateTime%.
  212. if (!new_target)
  213. new_target = realm.intrinsics().temporal_zoned_date_time_constructor();
  214. // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.ZonedDateTime.prototype%", « [[InitializedTemporalZonedDateTime]], [[Nanoseconds]], [[TimeZone]], [[Calendar]] »).
  215. // 4. Set object.[[Nanoseconds]] to epochNanoseconds.
  216. // 5. Set object.[[TimeZone]] to timeZone.
  217. // 6. Set object.[[Calendar]] to calendar.
  218. auto* object = TRY(ordinary_create_from_constructor<ZonedDateTime>(vm, *new_target, &Intrinsics::temporal_time_zone_prototype, epoch_nanoseconds, time_zone, calendar));
  219. // 7. Return object.
  220. return object;
  221. }
  222. // 6.5.4 TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar, showTimeZone, showOffset [ , increment, unit, roundingMode ] ), https://tc39.es/proposal-temporal/#sec-temporal-temporalzoneddatetimetostring
  223. ThrowCompletionOr<String> temporal_zoned_date_time_to_string(VM& vm, ZonedDateTime& zoned_date_time, Variant<StringView, u8> const& precision, StringView show_calendar, StringView show_time_zone, StringView show_offset, Optional<u64> increment, Optional<StringView> unit, Optional<StringView> rounding_mode)
  224. {
  225. // 1. If increment is not present, set increment to 1.
  226. if (!increment.has_value())
  227. increment = 1;
  228. // 2. If unit is not present, set unit to "nanosecond".
  229. if (!unit.has_value())
  230. unit = "nanosecond"sv;
  231. // 3. If roundingMode is not present, set roundingMode to "trunc".
  232. if (!rounding_mode.has_value())
  233. rounding_mode = "trunc"sv;
  234. // 4. Let ns be ! RoundTemporalInstant(zonedDateTime.[[Nanoseconds]], increment, unit, roundingMode).
  235. auto* ns = round_temporal_instant(vm, zoned_date_time.nanoseconds(), *increment, *unit, *rounding_mode);
  236. // 5. Let timeZone be zonedDateTime.[[TimeZone]].
  237. auto& time_zone = zoned_date_time.time_zone();
  238. // 6. Let instant be ! CreateTemporalInstant(ns).
  239. auto* instant = MUST(create_temporal_instant(vm, *ns));
  240. // 7. Let isoCalendar be ! GetISO8601Calendar().
  241. auto* iso_calendar = get_iso8601_calendar(vm);
  242. // 8. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, isoCalendar).
  243. auto* temporal_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &time_zone, *instant, *iso_calendar));
  244. // 9. Let dateTimeString be ? TemporalDateTimeToString(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], isoCalendar, precision, "never").
  245. auto date_time_string = TRY(temporal_date_time_to_string(vm, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), iso_calendar, precision, "never"sv));
  246. String offset_string;
  247. // 10. If showOffset is "never", then
  248. if (show_offset == "never"sv) {
  249. // a. Let offsetString be the empty String.
  250. offset_string = String::empty();
  251. }
  252. // 11. Else,
  253. else {
  254. // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
  255. auto offset_ns = TRY(get_offset_nanoseconds_for(vm, &time_zone, *instant));
  256. // b. Let offsetString be ! FormatISOTimeZoneOffsetString(offsetNs).
  257. offset_string = format_iso_time_zone_offset_string(offset_ns);
  258. }
  259. String time_zone_string;
  260. // 12. If showTimeZone is "never", then
  261. if (show_time_zone == "never"sv) {
  262. // a. Let timeZoneString be the empty String.
  263. time_zone_string = String::empty();
  264. }
  265. // 13. Else,
  266. else {
  267. // a. Let timeZoneID be ? ToString(timeZone).
  268. auto time_zone_id = TRY(Value(&time_zone).to_string(vm));
  269. // b. Let timeZoneString be the string-concatenation of the code unit 0x005B (LEFT SQUARE BRACKET), timeZoneID, and the code unit 0x005D (RIGHT SQUARE BRACKET).
  270. time_zone_string = String::formatted("[{}]", time_zone_id);
  271. }
  272. // 14. Let calendarString be ? MaybeFormatCalendarAnnotation(zonedDateTime.[[Calendar]], showCalendar).
  273. auto calendar_string = TRY(maybe_format_calendar_annotation(vm, &zoned_date_time.calendar(), show_calendar));
  274. // 15. Return the string-concatenation of dateTimeString, offsetString, timeZoneString, and calendarString.
  275. return String::formatted("{}{}{}{}", date_time_string, offset_string, time_zone_string, calendar_string);
  276. }
  277. // 6.5.5 AddZonedDateTime ( epochNanoseconds, timeZone, calendar, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-addzoneddatetime
  278. ThrowCompletionOr<BigInt*> add_zoned_date_time(VM& vm, BigInt const& epoch_nanoseconds, Value time_zone, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options)
  279. {
  280. // 1. If options is not present, set options to undefined.
  281. // 2. Assert: Type(options) is Object or Undefined.
  282. // 3. If all of years, months, weeks, and days are 0, then
  283. if (years == 0 && months == 0 && weeks == 0 && days == 0) {
  284. // a. Return ? AddInstant(epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  285. return add_instant(vm, epoch_nanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  286. }
  287. // 4. Let instant be ! CreateTemporalInstant(epochNanoseconds).
  288. auto* instant = MUST(create_temporal_instant(vm, epoch_nanoseconds));
  289. // 5. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar).
  290. auto* temporal_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, time_zone, *instant, calendar));
  291. // 6. Let datePart be ! CreateTemporalDate(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], calendar).
  292. auto* date_part = MUST(create_temporal_date(vm, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), calendar));
  293. // 7. Let dateDuration be ! CreateTemporalDuration(years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  294. auto* date_duration = MUST(create_temporal_duration(vm, years, months, weeks, days, 0, 0, 0, 0, 0, 0));
  295. // 8. Let addedDate be ? CalendarDateAdd(calendar, datePart, dateDuration, options).
  296. auto* added_date = TRY(calendar_date_add(vm, calendar, date_part, *date_duration, options));
  297. // 9. Let intermediateDateTime be ? CreateTemporalDateTime(addedDate.[[ISOYear]], addedDate.[[ISOMonth]], addedDate.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], calendar).
  298. auto* intermediate_date_time = TRY(create_temporal_date_time(vm, added_date->iso_year(), added_date->iso_month(), added_date->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), calendar));
  299. // 10. Let intermediateInstant be ? BuiltinTimeZoneGetInstantFor(timeZone, intermediateDateTime, "compatible").
  300. auto* intermediate_instant = TRY(builtin_time_zone_get_instant_for(vm, time_zone, *intermediate_date_time, "compatible"sv));
  301. // 11. Return ? AddInstant(intermediateInstant.[[Nanoseconds]], hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  302. return add_instant(vm, intermediate_instant->nanoseconds(), hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  303. }
  304. // 6.5.6 DifferenceZonedDateTime ( ns1, ns2, timeZone, calendar, largestUnit, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencezoneddatetime
  305. ThrowCompletionOr<DurationRecord> difference_zoned_date_time(VM& vm, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object const& options)
  306. {
  307. // 1. If ns1 is ns2, then
  308. if (nanoseconds1.big_integer() == nanoseconds2.big_integer()) {
  309. // a. Return ! CreateDurationRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  310. return create_duration_record(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  311. }
  312. // 2. Let startInstant be ! CreateTemporalInstant(ns1).
  313. auto* start_instant = MUST(create_temporal_instant(vm, nanoseconds1));
  314. // 3. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, startInstant, calendar).
  315. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &time_zone, *start_instant, calendar));
  316. // 4. Let endInstant be ! CreateTemporalInstant(ns2).
  317. auto* end_instant = MUST(create_temporal_instant(vm, nanoseconds2));
  318. // 5. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, endInstant, calendar).
  319. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &time_zone, *end_instant, calendar));
  320. // 6. Let dateDifference be ? DifferenceISODateTime(startDateTime.[[ISOYear]], startDateTime.[[ISOMonth]], startDateTime.[[ISODay]], startDateTime.[[ISOHour]], startDateTime.[[ISOMinute]], startDateTime.[[ISOSecond]], startDateTime.[[ISOMillisecond]], startDateTime.[[ISOMicrosecond]], startDateTime.[[ISONanosecond]], endDateTime.[[ISOYear]], endDateTime.[[ISOMonth]], endDateTime.[[ISODay]], endDateTime.[[ISOHour]], endDateTime.[[ISOMinute]], endDateTime.[[ISOSecond]], endDateTime.[[ISOMillisecond]], endDateTime.[[ISOMicrosecond]], endDateTime.[[ISONanosecond]], calendar, largestUnit, options).
  321. auto date_difference = TRY(difference_iso_date_time(vm, start_date_time->iso_year(), start_date_time->iso_month(), start_date_time->iso_day(), start_date_time->iso_hour(), start_date_time->iso_minute(), start_date_time->iso_second(), start_date_time->iso_millisecond(), start_date_time->iso_microsecond(), start_date_time->iso_nanosecond(), end_date_time->iso_year(), end_date_time->iso_month(), end_date_time->iso_day(), end_date_time->iso_hour(), end_date_time->iso_minute(), end_date_time->iso_second(), end_date_time->iso_millisecond(), end_date_time->iso_microsecond(), end_date_time->iso_nanosecond(), calendar, largest_unit, options));
  322. // 7. Let intermediateNs be ? AddZonedDateTime(ns1, timeZone, calendar, dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], 0, 0, 0, 0, 0, 0, 0).
  323. auto* intermediate_ns = TRY(add_zoned_date_time(vm, nanoseconds1, &time_zone, calendar, date_difference.years, date_difference.months, date_difference.weeks, 0, 0, 0, 0, 0, 0, 0));
  324. // 8. Let timeRemainderNs be ns2 - intermediateNs.
  325. auto time_remainder_ns = nanoseconds2.big_integer().minus(intermediate_ns->big_integer());
  326. // 9. Let intermediate be ! CreateTemporalZonedDateTime(intermediateNs, timeZone, calendar).
  327. auto* intermediate = MUST(create_temporal_zoned_date_time(vm, *intermediate_ns, time_zone, calendar));
  328. // 10. Let result be ? NanosecondsToDays(timeRemainderNs, intermediate).
  329. auto result = TRY(nanoseconds_to_days(vm, time_remainder_ns, intermediate));
  330. // 11. Let timeDifference be ! BalanceDuration(0, 0, 0, 0, 0, 0, result.[[Nanoseconds]], "hour").
  331. auto time_difference = MUST(balance_duration(vm, 0, 0, 0, 0, 0, 0, result.nanoseconds, "hour"sv));
  332. // 12. Return ! CreateDurationRecord(dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], result.[[Days]], timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]]).
  333. return create_duration_record(date_difference.years, date_difference.months, date_difference.weeks, result.days, time_difference.hours, time_difference.minutes, time_difference.seconds, time_difference.milliseconds, time_difference.microseconds, time_difference.nanoseconds);
  334. }
  335. // 6.5.7 NanosecondsToDays ( nanoseconds, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-nanosecondstodays
  336. ThrowCompletionOr<NanosecondsToDaysResult> nanoseconds_to_days(VM& vm, Crypto::SignedBigInteger nanoseconds, Value relative_to_value)
  337. {
  338. auto& realm = *vm.current_realm();
  339. // 1. Let dayLengthNs be nsPerDay.
  340. auto day_length_ns = ns_per_day_bigint;
  341. // 2. If nanoseconds = 0, then
  342. if (nanoseconds.is_zero()) {
  343. // a. Return the Record { [[Days]]: 0, [[Nanoseconds]]: 0, [[DayLength]]: dayLengthNs }.
  344. return NanosecondsToDaysResult { .days = 0, .nanoseconds = "0"_sbigint, .day_length = day_length_ns.to_double() };
  345. }
  346. // 3. If nanoseconds < 0, let sign be -1; else, let sign be 1.
  347. auto sign = nanoseconds.is_negative() ? -1 : 1;
  348. // 4. If Type(relativeTo) is not Object or relativeTo does not have an [[InitializedTemporalZonedDateTime]] internal slot, then
  349. if (!relative_to_value.is_object() || !is<ZonedDateTime>(relative_to_value.as_object())) {
  350. // a. Return the Record { [[Days]]: truncate(nanoseconds / dayLengthNs), [[Nanoseconds]]: (abs(nanoseconds) modulo dayLengthNs) × sign, [[DayLength]]: dayLengthNs }.
  351. return NanosecondsToDaysResult {
  352. .days = nanoseconds.divided_by(day_length_ns).quotient.to_double(),
  353. .nanoseconds = Crypto::SignedBigInteger { nanoseconds.unsigned_value() }.divided_by(day_length_ns).remainder.multiplied_by(Crypto::SignedBigInteger { sign }),
  354. .day_length = day_length_ns.to_double()
  355. };
  356. }
  357. auto& relative_to = static_cast<ZonedDateTime&>(relative_to_value.as_object());
  358. // 5. Let startNs be ℝ(relativeTo.[[Nanoseconds]]).
  359. auto& start_ns = relative_to.nanoseconds().big_integer();
  360. // 6. Let startInstant be ! CreateTemporalInstant(ℤ(startNs)).
  361. auto* start_instant = MUST(create_temporal_instant(vm, *js_bigint(vm, start_ns)));
  362. // 7. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], startInstant, relativeTo.[[Calendar]]).
  363. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &relative_to.time_zone(), *start_instant, relative_to.calendar()));
  364. // 8. Let endNs be startNs + nanoseconds.
  365. auto end_ns = start_ns.plus(nanoseconds);
  366. auto* end_ns_bigint = js_bigint(vm, end_ns);
  367. // 9. If ! IsValidEpochNanoseconds(ℤ(endNs)) is false, throw a RangeError exception.
  368. if (!is_valid_epoch_nanoseconds(*end_ns_bigint))
  369. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  370. // 10. Let endInstant be ! CreateTemporalInstant(ℤ(endNs)).
  371. auto* end_instant = MUST(create_temporal_instant(vm, *end_ns_bigint));
  372. // 11. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], endInstant, relativeTo.[[Calendar]]).
  373. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &relative_to.time_zone(), *end_instant, relative_to.calendar()));
  374. // 12. Let dateDifference be ? DifferenceISODateTime(startDateTime.[[ISOYear]], startDateTime.[[ISOMonth]], startDateTime.[[ISODay]], startDateTime.[[ISOHour]], startDateTime.[[ISOMinute]], startDateTime.[[ISOSecond]], startDateTime.[[ISOMillisecond]], startDateTime.[[ISOMicrosecond]], startDateTime.[[ISONanosecond]], endDateTime.[[ISOYear]], endDateTime.[[ISOMonth]], endDateTime.[[ISODay]], endDateTime.[[ISOHour]], endDateTime.[[ISOMinute]], endDateTime.[[ISOSecond]], endDateTime.[[ISOMillisecond]], endDateTime.[[ISOMicrosecond]], endDateTime.[[ISONanosecond]], relativeTo.[[Calendar]], "day", OrdinaryObjectCreate(null)).
  375. auto date_difference = TRY(difference_iso_date_time(vm, start_date_time->iso_year(), start_date_time->iso_month(), start_date_time->iso_day(), start_date_time->iso_hour(), start_date_time->iso_minute(), start_date_time->iso_second(), start_date_time->iso_millisecond(), start_date_time->iso_microsecond(), start_date_time->iso_nanosecond(), end_date_time->iso_year(), end_date_time->iso_month(), end_date_time->iso_day(), end_date_time->iso_hour(), end_date_time->iso_minute(), end_date_time->iso_second(), end_date_time->iso_millisecond(), end_date_time->iso_microsecond(), end_date_time->iso_nanosecond(), relative_to.calendar(), "day"sv, *Object::create(realm, nullptr)));
  376. // 13. Let days be dateDifference.[[Days]].
  377. auto days = date_difference.days;
  378. // 14. Let intermediateNs be ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  379. auto intermediate_ns = TRY(add_zoned_date_time(vm, *js_bigint(vm, start_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, days, 0, 0, 0, 0, 0, 0))->big_integer();
  380. // 15. If sign is 1, then
  381. if (sign == 1) {
  382. // a. Repeat, while days > 0 and intermediateNs > endNs,
  383. while (days > 0 && intermediate_ns > end_ns) {
  384. // i. Set days to days - 1.
  385. days--;
  386. // ii. Set intermediateNs to ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  387. intermediate_ns = TRY(add_zoned_date_time(vm, *js_bigint(vm, start_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, days, 0, 0, 0, 0, 0, 0))->big_integer();
  388. }
  389. }
  390. // 16. Set nanoseconds to endNs - intermediateNs.
  391. nanoseconds = end_ns.minus(intermediate_ns);
  392. // 17. Let done be false.
  393. // 18. Repeat, while done is false,
  394. while (true) {
  395. // a. Let oneDayFartherNs be ℝ(? AddZonedDateTime(ℤ(intermediateNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, sign, 0, 0, 0, 0, 0, 0)).
  396. auto one_day_farther_ns = TRY(add_zoned_date_time(vm, *js_bigint(vm, intermediate_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, sign, 0, 0, 0, 0, 0, 0))->big_integer();
  397. // b. Set dayLengthNs to oneDayFartherNs - intermediateNs.
  398. day_length_ns = one_day_farther_ns.minus(intermediate_ns);
  399. // c. If (nanoseconds - dayLengthNs) × sign ≥ 0, then
  400. if (nanoseconds.minus(day_length_ns).multiplied_by(Crypto::SignedBigInteger { sign }) >= "0"_sbigint) {
  401. // i. Set nanoseconds to nanoseconds - dayLengthNs.
  402. nanoseconds = nanoseconds.minus(day_length_ns);
  403. // ii. Set intermediateNs to oneDayFartherNs.
  404. intermediate_ns = move(one_day_farther_ns);
  405. // iii. Set days to days + sign.
  406. days += sign;
  407. }
  408. // d. Else,
  409. else {
  410. // i. Set done to true.
  411. break;
  412. }
  413. }
  414. // 19. Return the Record { [[Days]]: days, [[Nanoseconds]]: nanoseconds, [[DayLength]]: abs(dayLengthNs) }.
  415. return NanosecondsToDaysResult { .days = days, .nanoseconds = move(nanoseconds), .day_length = fabs(day_length_ns.to_double()) };
  416. }
  417. // 6.5.8 DifferenceTemporalZonedDateTime ( operation, zonedDateTime, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalzoneddatetime
  418. ThrowCompletionOr<Duration*> difference_temporal_zoned_date_time(VM& vm, DifferenceOperation operation, ZonedDateTime& zoned_date_time, Value other_value, Value options_value)
  419. {
  420. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  421. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  422. // 2. Set other to ? ToTemporalZonedDateTime(other).
  423. auto* other = TRY(to_temporal_zoned_date_time(vm, other_value));
  424. // 3. If ? CalendarEquals(zonedDateTime.[[Calendar]], other.[[Calendar]]) is false, then
  425. if (!TRY(calendar_equals(vm, zoned_date_time.calendar(), other->calendar()))) {
  426. // a. Throw a RangeError exception.
  427. return vm.throw_completion<RangeError>(ErrorType::TemporalDifferentCalendars);
  428. }
  429. // 4. Let settings be ? GetDifferenceSettings(operation, options, datetime, « », "nanosecond", "hour").
  430. auto settings = TRY(get_difference_settings(vm, operation, options_value, UnitGroup::DateTime, {}, { "nanosecond"sv }, "hour"sv));
  431. // 5. If settings.[[LargestUnit]] is not one of "year", "month", "week", or "day", then
  432. if (!settings.largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  433. // a. Let differenceNs be ! DifferenceInstant(zonedDateTime.[[Nanoseconds]], other.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]]).
  434. auto* difference_ns = difference_instant(vm, zoned_date_time.nanoseconds(), other->nanoseconds(), settings.rounding_increment, settings.smallest_unit, settings.rounding_mode);
  435. // b. Assert: The following steps cannot fail due to overflow in the Number domain because abs(differenceNs) ≤ 2 × nsMaxInstant.
  436. // c. Let balanceResult be ! BalanceDuration(0, 0, 0, 0, 0, 0, differenceNs, settings.[[LargestUnit]]).
  437. auto balance_result = MUST(balance_duration(vm, 0, 0, 0, 0, 0, 0, difference_ns->big_integer(), settings.largest_unit));
  438. // d. Return ! CreateTemporalDuration(0, 0, 0, 0, sign × balanceResult.[[Hours]], sign × balanceResult.[[Minutes]], sign × balanceResult.[[Seconds]], sign × balanceResult.[[Milliseconds]], sign × balanceResult.[[Microseconds]], sign × balanceResult.[[Nanoseconds]]).
  439. return MUST(create_temporal_duration(vm, 0, 0, 0, 0, sign * balance_result.hours, sign * balance_result.minutes, sign * balance_result.seconds, sign * balance_result.milliseconds, sign * balance_result.microseconds, sign * balance_result.nanoseconds));
  440. }
  441. // 6. If ? TimeZoneEquals(zonedDateTime.[[TimeZone]], other.[[TimeZone]]) is false, then
  442. if (!TRY(time_zone_equals(vm, zoned_date_time.time_zone(), other->time_zone()))) {
  443. // a. Throw a RangeError exception.
  444. return vm.throw_completion<RangeError>(ErrorType::TemporalDifferentTimeZones);
  445. }
  446. // 7. Let untilOptions be ? MergeLargestUnitOption(settings.[[Options]], settings.[[LargestUnit]]).
  447. auto* until_options = TRY(merge_largest_unit_option(vm, settings.options, settings.largest_unit));
  448. // 8. Let difference be ? DifferenceZonedDateTime(zonedDateTime.[[Nanoseconds]], other.[[Nanoseconds]], zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]], settings.[[LargestUnit]], untilOptions).
  449. auto difference = TRY(difference_zoned_date_time(vm, zoned_date_time.nanoseconds(), other->nanoseconds(), zoned_date_time.time_zone(), zoned_date_time.calendar(), settings.largest_unit, *until_options));
  450. // 9. Let roundResult be (? RoundDuration(difference.[[Years]], difference.[[Months]], difference.[[Weeks]], difference.[[Days]], difference.[[Hours]], difference.[[Minutes]], difference.[[Seconds]], difference.[[Milliseconds]], difference.[[Microseconds]], difference.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]], zonedDateTime)).[[DurationRecord]].
  451. auto round_result = TRY(round_duration(vm, difference.years, difference.months, difference.weeks, difference.days, difference.hours, difference.minutes, difference.seconds, difference.milliseconds, difference.microseconds, difference.nanoseconds, settings.rounding_increment, settings.smallest_unit, settings.rounding_mode, &zoned_date_time)).duration_record;
  452. // 10. Let result be ? AdjustRoundedDurationDays(roundResult.[[Years]], roundResult.[[Months]], roundResult.[[Weeks]], roundResult.[[Days]], roundResult.[[Hours]], roundResult.[[Minutes]], roundResult.[[Seconds]], roundResult.[[Milliseconds]], roundResult.[[Microseconds]], roundResult.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]], zonedDateTime).
  453. auto result = TRY(adjust_rounded_duration_days(vm, round_result.years, round_result.months, round_result.weeks, round_result.days, round_result.hours, round_result.minutes, round_result.seconds, round_result.milliseconds, round_result.microseconds, round_result.nanoseconds, settings.rounding_increment, settings.smallest_unit, settings.rounding_mode, &zoned_date_time));
  454. // 11. Return ! CreateTemporalDuration(sign × result.[[Years]], sign × result.[[Months]], sign × result.[[Weeks]], sign × result.[[Days]], sign × result.[[Hours]], sign × result.[[Minutes]], sign × result.[[Seconds]], sign × result.[[Milliseconds]], sign × result.[[Microseconds]], sign × result.[[Nanoseconds]]).
  455. return MUST(create_temporal_duration(vm, sign * result.years, sign * result.months, sign * result.weeks, sign * result.days, sign * result.hours, sign * result.minutes, sign * result.seconds, sign * result.milliseconds, sign * result.microseconds, sign * result.nanoseconds));
  456. }
  457. // 6.5.9 AddDurationToOrSubtractDurationFromZonedDateTime ( operation, zonedDateTime, temporalDurationLike, options ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoOrsubtractdurationfromzoneddatetime
  458. ThrowCompletionOr<ZonedDateTime*> add_duration_to_or_subtract_duration_from_zoned_date_time(VM& vm, ArithmeticOperation operation, ZonedDateTime& zoned_date_time, Value temporal_duration_like, Value options_value)
  459. {
  460. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  461. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  462. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  463. auto duration = TRY(to_temporal_duration_record(vm, temporal_duration_like));
  464. // 3. Set options to ? GetOptionsObject(options).
  465. auto* options = TRY(get_options_object(vm, options_value));
  466. // 4. Let timeZone be zonedDateTime.[[TimeZone]].
  467. auto& time_zone = zoned_date_time.time_zone();
  468. // 5. Let calendar be zonedDateTime.[[Calendar]].
  469. auto& calendar = zoned_date_time.calendar();
  470. // 6. Let epochNanoseconds be ? AddZonedDateTime(zonedDateTime.[[Nanoseconds]], timeZone, calendar, sign × duration.[[Years]], sign × duration.[[Months]], sign × duration.[[Weeks]], sign × duration.[[Days]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]], options).
  471. auto* epoch_nanoseconds = TRY(add_zoned_date_time(vm, zoned_date_time.nanoseconds(), &time_zone, calendar, sign * duration.years, sign * duration.months, sign * duration.weeks, sign * duration.days, sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds, options));
  472. // 7. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  473. return MUST(create_temporal_zoned_date_time(vm, *epoch_nanoseconds, time_zone, calendar));
  474. }
  475. }