TimeZone.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Time.h>
  8. #include <AK/TypeCasts.h>
  9. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Iterator.h>
  14. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  15. #include <LibJS/Runtime/Temporal/Calendar.h>
  16. #include <LibJS/Runtime/Temporal/Instant.h>
  17. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  18. #include <LibJS/Runtime/Temporal/TimeZone.h>
  19. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  20. #include <LibJS/Runtime/Temporal/TimeZoneMethods.h>
  21. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  22. #include <LibTimeZone/TimeZone.h>
  23. namespace JS::Temporal {
  24. JS_DEFINE_ALLOCATOR(TimeZone);
  25. // 11 Temporal.TimeZone Objects, https://tc39.es/proposal-temporal/#sec-temporal-timezone-objects
  26. TimeZone::TimeZone(Object& prototype)
  27. : Object(ConstructWithPrototypeTag::Tag, prototype)
  28. {
  29. }
  30. // 11.1.1 IsAvailableTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-isavailabletimezonename
  31. bool is_available_time_zone_name(StringView time_zone)
  32. {
  33. // 1. Let timeZones be AvailableTimeZones().
  34. // 2. For each String candidate in timeZones, do
  35. // a. If timeZone is an ASCII-case-insensitive match for candidate, return true.
  36. // 3. Return false.
  37. // NOTE: When LibTimeZone is built without ENABLE_TIME_ZONE_DATA, this only recognizes 'UTC',
  38. // which matches the minimum requirements of the Temporal spec.
  39. return ::TimeZone::time_zone_from_string(time_zone).has_value();
  40. }
  41. // 6.4.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/ecma402/#sec-canonicalizetimezonename
  42. // 11.1.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-canonicalizetimezonename
  43. // 15.1.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sup-canonicalizetimezonename
  44. ThrowCompletionOr<String> canonicalize_time_zone_name(VM& vm, StringView time_zone)
  45. {
  46. // 1. Let ianaTimeZone be the String value of the Zone or Link name of the IANA Time Zone Database that is an ASCII-case-insensitive match of timeZone as described in 6.1.
  47. // 2. If ianaTimeZone is a Link name, let ianaTimeZone be the String value of the corresponding Zone name as specified in the file backward of the IANA Time Zone Database.
  48. auto iana_time_zone = ::TimeZone::canonicalize_time_zone(time_zone);
  49. // 3. If ianaTimeZone is one of "Etc/UTC", "Etc/GMT", or "GMT", return "UTC".
  50. // NOTE: This is already done in canonicalize_time_zone().
  51. // 4. Return ianaTimeZone.
  52. return TRY_OR_THROW_OOM(vm, String::from_utf8(*iana_time_zone));
  53. }
  54. // 11.6.1 CreateTemporalTimeZone ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltimezone
  55. ThrowCompletionOr<TimeZone*> create_temporal_time_zone(VM& vm, String identifier, FunctionObject const* new_target)
  56. {
  57. auto& realm = *vm.current_realm();
  58. // 1. If newTarget is not present, set newTarget to %Temporal.TimeZone%.
  59. if (!new_target)
  60. new_target = realm.intrinsics().temporal_time_zone_constructor();
  61. // 2. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.TimeZone.prototype%", « [[InitializedTemporalTimeZone]], [[Identifier]], [[OffsetNanoseconds]] »).
  62. auto object = TRY(ordinary_create_from_constructor<TimeZone>(vm, *new_target, &Intrinsics::temporal_time_zone_prototype));
  63. // 3. If IsTimeZoneOffsetString(identifier) is true, then
  64. if (is_time_zone_offset_string(identifier)) {
  65. // a. Let offsetNanosecondsResult be ParseTimeZoneOffsetString(identifier).
  66. auto offset_nanoseconds_result = parse_time_zone_offset_string(identifier);
  67. // b. Set object.[[Identifier]] to ! FormatTimeZoneOffsetString(offsetNanosecondsResult).
  68. object->set_identifier(MUST_OR_THROW_OOM(format_time_zone_offset_string(vm, offset_nanoseconds_result)));
  69. // c. Set object.[[OffsetNanoseconds]] to offsetNanosecondsResult.
  70. object->set_offset_nanoseconds(offset_nanoseconds_result);
  71. }
  72. // 4. Else,
  73. else {
  74. // a. Assert: ! CanonicalizeTimeZoneName(identifier) is identifier.
  75. VERIFY(MUST_OR_THROW_OOM(canonicalize_time_zone_name(vm, identifier)) == identifier);
  76. // b. Set object.[[Identifier]] to identifier.
  77. object->set_identifier(move(identifier));
  78. // c. Set object.[[OffsetNanoseconds]] to undefined.
  79. // NOTE: No-op.
  80. }
  81. // 5. Return object.
  82. return object.ptr();
  83. }
  84. // 11.6.2 GetISOPartsFromEpoch ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-getisopartsfromepoch
  85. ISODateTime get_iso_parts_from_epoch(VM& vm, Crypto::SignedBigInteger const& epoch_nanoseconds)
  86. {
  87. // 1. Assert: ! IsValidEpochNanoseconds(ℤ(epochNanoseconds)) is true.
  88. VERIFY(is_valid_epoch_nanoseconds(BigInt::create(vm, epoch_nanoseconds)));
  89. // 2. Let remainderNs be epochNanoseconds modulo 10^6.
  90. auto remainder_ns_bigint = modulo(epoch_nanoseconds, Crypto::UnsignedBigInteger { 1'000'000 });
  91. auto remainder_ns = remainder_ns_bigint.to_double();
  92. // 3. Let epochMilliseconds be 𝔽((epochNanoseconds - remainderNs) / 10^6).
  93. auto epoch_milliseconds_bigint = epoch_nanoseconds.minus(remainder_ns_bigint).divided_by(Crypto::UnsignedBigInteger { 1'000'000 }).quotient;
  94. auto epoch_milliseconds = epoch_milliseconds_bigint.to_double();
  95. // 4. Let year be ℝ(! YearFromTime(epochMilliseconds)).
  96. auto year = year_from_time(epoch_milliseconds);
  97. // 5. Let month be ℝ(! MonthFromTime(epochMilliseconds)) + 1.
  98. auto month = static_cast<u8>(month_from_time(epoch_milliseconds) + 1);
  99. // 6. Let day be ℝ(! DateFromTime(epochMilliseconds)).
  100. auto day = date_from_time(epoch_milliseconds);
  101. // 7. Let hour be ℝ(! HourFromTime(epochMilliseconds)).
  102. auto hour = hour_from_time(epoch_milliseconds);
  103. // 8. Let minute be ℝ(! MinFromTime(epochMilliseconds)).
  104. auto minute = min_from_time(epoch_milliseconds);
  105. // 9. Let second be ℝ(! SecFromTime(epochMilliseconds)).
  106. auto second = sec_from_time(epoch_milliseconds);
  107. // 10. Let millisecond be ℝ(! msFromTime(epochMilliseconds)).
  108. auto millisecond = ms_from_time(epoch_milliseconds);
  109. // 11. Let microsecond be floor(remainderNs / 1000).
  110. auto microsecond = floor(remainder_ns / 1000);
  111. // 12. Assert: microsecond < 1000.
  112. VERIFY(microsecond < 1000);
  113. // 13. Let nanosecond be remainderNs modulo 1000.
  114. auto nanosecond = modulo(remainder_ns, 1000);
  115. // 14. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
  116. return { .year = year, .month = month, .day = day, .hour = hour, .minute = minute, .second = second, .millisecond = millisecond, .microsecond = static_cast<u16>(microsecond), .nanosecond = static_cast<u16>(nanosecond) };
  117. }
  118. // 11.6.3 GetNamedTimeZoneNextTransition ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezonenexttransition
  119. BigInt* get_named_time_zone_next_transition(VM&, [[maybe_unused]] StringView time_zone_identifier, [[maybe_unused]] BigInt const& epoch_nanoseconds)
  120. {
  121. // The implementation-defined abstract operation GetNamedTimeZoneNextTransition takes arguments timeZoneIdentifier (a String) and epochNanoseconds (a BigInt) and returns a BigInt or null.
  122. // The returned value t represents the number of nanoseconds since the Unix epoch in UTC that corresponds to the first time zone transition after epochNanoseconds in the IANA time zone identified by timeZoneIdentifier. The operation returns null if no such transition exists for which t ≤ ℤ(nsMaxInstant).
  123. // Given the same values of epochNanoseconds and timeZoneIdentifier, the result must be the same for the lifetime of the surrounding agent.
  124. // TODO: Implement this
  125. return nullptr;
  126. }
  127. // 11.6.4 GetNamedTimeZonePreviousTransition ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezoneprevioustransition
  128. BigInt* get_named_time_zone_previous_transition(VM&, [[maybe_unused]] StringView time_zone_identifier, [[maybe_unused]] BigInt const& epoch_nanoseconds)
  129. {
  130. // The implementation-defined abstract operation GetNamedTimeZonePreviousTransition takes arguments timeZoneIdentifier (a String) and epochNanoseconds (a BigInt) and returns a BigInt or null.
  131. // The returned value t represents the number of nanoseconds since the Unix epoch in UTC that corresponds to the last time zone transition before epochNanoseconds in the IANA time zone identified by timeZoneIdentifier. The operation returns null if no such transition exists for which t ≥ ℤ(nsMinInstant).
  132. // Given the same values of epochNanoseconds and timeZoneIdentifier, the result must be the same for the lifetime of the surrounding agent.
  133. // TODO: Implement this
  134. return nullptr;
  135. }
  136. // 11.6.5 FormatTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formattimezoneoffsetstring
  137. ThrowCompletionOr<String> format_time_zone_offset_string(VM& vm, double offset_nanoseconds)
  138. {
  139. auto offset = static_cast<i64>(offset_nanoseconds);
  140. // 1. Assert: offsetNanoseconds is an integer.
  141. VERIFY(offset == offset_nanoseconds);
  142. StringBuilder builder;
  143. // 2. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
  144. if (offset >= 0)
  145. builder.append('+');
  146. else
  147. builder.append('-');
  148. // 3. Let _offsetNanoseconds_ be abs(_offsetNanoseconds_).
  149. offset = AK::abs(offset);
  150. // 4. Let nanoseconds be offsetNanoseconds modulo 10^9.
  151. auto nanoseconds = offset % 1000000000;
  152. // 5. Let seconds be floor(offsetNanoseconds / 10^9) modulo 60.
  153. auto seconds = (offset / 1000000000) % 60;
  154. // 6. Let minutes be floor(offsetNanoseconds / (6 × 10^10)) modulo 60.
  155. auto minutes = (offset / 60000000000) % 60;
  156. // 7. Let hours be floor(offsetNanoseconds / (3.6 × 10^12)).
  157. auto hours = offset / 3600000000000;
  158. // 8. Let h be ToZeroPaddedDecimalString(hours, 2).
  159. builder.appendff("{:02}", hours);
  160. // 9. Let m be ToZeroPaddedDecimalString(minutes, 2).
  161. builder.appendff(":{:02}", minutes);
  162. // 10. Let s be ToZeroPaddedDecimalString(seconds, 2).
  163. // NOTE: Handled by steps 11 & 12
  164. // 11. If nanoseconds ≠ 0, then
  165. if (nanoseconds != 0) {
  166. // a. Let fraction be ToZeroPaddedDecimalString(nanoseconds, 9).
  167. auto fraction = TRY_OR_THROW_OOM(vm, String::formatted("{:09}", nanoseconds));
  168. // b. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  169. fraction = TRY_OR_THROW_OOM(vm, fraction.trim("0"sv, TrimMode::Right));
  170. // c. Let post be the string-concatenation of the code unit 0x003A (COLON), s, the code unit 0x002E (FULL STOP), and fraction.
  171. builder.appendff(":{:02}.{}", seconds, fraction);
  172. }
  173. // 12. Else if seconds ≠ 0, then
  174. else if (seconds != 0) {
  175. // a. Let post be the string-concatenation of the code unit 0x003A (COLON) and s.
  176. builder.appendff(":{:02}", seconds);
  177. }
  178. // 13. Else,
  179. // a. Let post be the empty String.
  180. // 14. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), m, and post.
  181. return TRY_OR_THROW_OOM(vm, builder.to_string());
  182. }
  183. // 11.6.6 FormatISOTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formatisotimezoneoffsetstring
  184. ThrowCompletionOr<String> format_iso_time_zone_offset_string(VM& vm, double offset_nanoseconds)
  185. {
  186. // 1. Assert: offsetNanoseconds is an integer.
  187. VERIFY(trunc(offset_nanoseconds) == offset_nanoseconds);
  188. // 2. Set offsetNanoseconds to RoundNumberToIncrement(offsetNanoseconds, 60 × 10^9, "halfExpand").
  189. offset_nanoseconds = round_number_to_increment(offset_nanoseconds, 60000000000, "halfExpand"sv);
  190. // 3. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
  191. auto sign = offset_nanoseconds >= 0 ? "+"sv : "-"sv;
  192. // 4. Set offsetNanoseconds to abs(offsetNanoseconds).
  193. offset_nanoseconds = fabs(offset_nanoseconds);
  194. // 5. Let minutes be offsetNanoseconds / (60 × 10^9) modulo 60.
  195. auto minutes = fmod(offset_nanoseconds / 60000000000, 60);
  196. // 6. Let hours be floor(offsetNanoseconds / (3600 × 10^9)).
  197. auto hours = floor(offset_nanoseconds / 3600000000000);
  198. // 7. Let h be ToZeroPaddedDecimalString(hours, 2).
  199. // 8. Let m be ToZeroPaddedDecimalString(minutes, 2).
  200. // 9. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), and m.
  201. return TRY_OR_THROW_OOM(vm, String::formatted("{}{:02}:{:02}", sign, (u32)hours, (u32)minutes));
  202. }
  203. // 11.6.7 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
  204. ThrowCompletionOr<Object*> to_temporal_time_zone(VM& vm, Value temporal_time_zone_like)
  205. {
  206. // 1. If Type(temporalTimeZoneLike) is Object, then
  207. if (temporal_time_zone_like.is_object()) {
  208. // a. If temporalTimeZoneLike has an [[InitializedTemporalTimeZone]] internal slot, then
  209. if (is<TimeZone>(temporal_time_zone_like.as_object())) {
  210. // i. Return temporalTimeZoneLike.
  211. return &temporal_time_zone_like.as_object();
  212. }
  213. // b. If temporalTimeZoneLike has an [[InitializedTemporalZonedDateTime]] internal slot, then
  214. if (is<ZonedDateTime>(temporal_time_zone_like.as_object())) {
  215. auto& zoned_date_time = static_cast<ZonedDateTime&>(temporal_time_zone_like.as_object());
  216. // i. Return temporalTimeZoneLike.[[TimeZone]].
  217. return &zoned_date_time.time_zone();
  218. }
  219. // c. If temporalTimeZoneLike has an [[InitializedTemporalCalendar]] internal slot, throw a RangeError exception.
  220. if (is<Calendar>(temporal_time_zone_like.as_object()))
  221. return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedCalendarObject);
  222. // d. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
  223. if (!TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone)))
  224. return &temporal_time_zone_like.as_object();
  225. // e. Set temporalTimeZoneLike to ? Get(temporalTimeZoneLike, "timeZone").
  226. temporal_time_zone_like = TRY(temporal_time_zone_like.as_object().get(vm.names.timeZone));
  227. // f. If Type(temporalTimeZoneLike) is Object, then
  228. if (temporal_time_zone_like.is_object()) {
  229. // i. If temporalTimeZoneLike has an [[InitializedTemporalCalendar]] internal slot, throw a RangeError exception.
  230. if (is<Calendar>(temporal_time_zone_like.as_object()))
  231. return vm.throw_completion<RangeError>(ErrorType::TemporalUnexpectedCalendarObject);
  232. // ii. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
  233. if (!TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone)))
  234. return &temporal_time_zone_like.as_object();
  235. }
  236. }
  237. // 2. Let identifier be ? ToString(temporalTimeZoneLike).
  238. auto identifier = TRY(temporal_time_zone_like.to_string(vm));
  239. // 3. Let parseResult be ? ParseTemporalTimeZoneString(identifier).
  240. auto parse_result = TRY(parse_temporal_time_zone_string(vm, identifier));
  241. // 4. If parseResult.[[Name]] is not undefined, then
  242. if (parse_result.name.has_value()) {
  243. // a. Let name be parseResult.[[Name]].
  244. auto name = parse_result.name.release_value();
  245. // b. If IsTimeZoneOffsetString(name) is false, then
  246. if (!is_time_zone_offset_string(name)) {
  247. // i. If IsAvailableTimeZoneName(name) is false, throw a RangeError exception.
  248. if (!is_available_time_zone_name(name))
  249. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, name);
  250. // ii. Set name to ! CanonicalizeTimeZoneName(name).
  251. name = MUST_OR_THROW_OOM(canonicalize_time_zone_name(vm, name));
  252. }
  253. // c. Return ! CreateTemporalTimeZone(name).
  254. return MUST_OR_THROW_OOM(create_temporal_time_zone(vm, move(name)));
  255. }
  256. // 5. If parseResult.[[Z]] is true, return ! CreateTemporalTimeZone("UTC").
  257. if (parse_result.z)
  258. return MUST_OR_THROW_OOM(create_temporal_time_zone(vm, "UTC"_string));
  259. // 6. Return ! CreateTemporalTimeZone(parseResult.[[OffsetString]]).
  260. return MUST_OR_THROW_OOM(create_temporal_time_zone(vm, parse_result.offset_string.release_value()));
  261. }
  262. // 11.5.19 GetOffsetNanosecondsFor ( timeZoneRec, instant ), https://tc39.es/proposal-temporal/#sec-temporal-getoffsetnanosecondsfor
  263. ThrowCompletionOr<double> get_offset_nanoseconds_for(VM& vm, TimeZoneMethods const& time_zone_record, Instant const& instant)
  264. {
  265. // 1. Let offsetNanoseconds be ? TimeZoneMethodsRecordCall(timeZoneRec, GET-OFFSET-NANOSECONDS-FOR, « instant »).
  266. auto offset_nanoseconds_value = TRY(time_zone_methods_record_call(vm, time_zone_record, TimeZoneMethod::GetOffsetNanosecondsFor, { { &instant } }));
  267. // 2. If TimeZoneMethodsRecordIsBuiltin(timeZoneRec), return ℝ(offsetNanoseconds).
  268. if (time_zone_methods_record_is_builtin(time_zone_record))
  269. return offset_nanoseconds_value.as_double();
  270. // 3. If Type(offsetNanoseconds) is not Number, throw a TypeError exception.
  271. if (!offset_nanoseconds_value.is_number())
  272. return vm.throw_completion<TypeError>(ErrorType::IsNotA, "Offset nanoseconds value", "number");
  273. // 4. If IsIntegralNumber(offsetNanoseconds) is false, throw a RangeError exception.
  274. if (!offset_nanoseconds_value.is_integral_number())
  275. return vm.throw_completion<RangeError>(ErrorType::IsNotAn, "Offset nanoseconds value", "integral number");
  276. // 5. Set offsetNanoseconds to ℝ(offsetNanoseconds).
  277. auto offset_nanoseconds = offset_nanoseconds_value.as_double();
  278. // 6. If abs(offsetNanoseconds) ≥ nsPerDay, throw a RangeError exception.
  279. if (fabs(offset_nanoseconds) >= ns_per_day)
  280. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidOffsetNanosecondsValue);
  281. // 7. Return offsetNanoseconds.
  282. return offset_nanoseconds;
  283. }
  284. // 11.6.9 BuiltinTimeZoneGetOffsetStringFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetoffsetstringfor
  285. ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(VM& vm, Value time_zone, Instant& instant)
  286. {
  287. auto time_zone_record = TRY(create_time_zone_methods_record(vm, NonnullGCPtr<Object> { time_zone.as_object() }, { { TimeZoneMethod::GetOffsetNanosecondsFor } }));
  288. // 1. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
  289. auto offset_nanoseconds = TRY(get_offset_nanoseconds_for(vm, time_zone_record, instant));
  290. // 2. Return ! FormatTimeZoneOffsetString(offsetNanoseconds).
  291. return MUST_OR_THROW_OOM(format_time_zone_offset_string(vm, offset_nanoseconds));
  292. }
  293. // 11.6.10 BuiltinTimeZoneGetPlainDateTimeFor ( timeZone, instant, calendar ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetplaindatetimefor
  294. ThrowCompletionOr<PlainDateTime*> builtin_time_zone_get_plain_date_time_for(VM& vm, Value time_zone, Instant& instant, Object& calendar)
  295. {
  296. auto time_zone_record = TRY(create_time_zone_methods_record(vm, NonnullGCPtr<Object> { time_zone.as_object() }, { { TimeZoneMethod::GetOffsetNanosecondsFor } }));
  297. // 1. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  298. // 2. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
  299. auto offset_nanoseconds = TRY(get_offset_nanoseconds_for(vm, time_zone_record, instant));
  300. // 3. Let result be ! GetISOPartsFromEpoch(ℝ(instant.[[Nanoseconds]])).
  301. auto result = get_iso_parts_from_epoch(vm, instant.nanoseconds().big_integer());
  302. // 4. Set result to BalanceISODateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]] + offsetNanoseconds).
  303. result = balance_iso_date_time(result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond + offset_nanoseconds);
  304. // 5. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
  305. return create_temporal_date_time(vm, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, calendar);
  306. }
  307. // 11.6.11 BuiltinTimeZoneGetInstantFor ( timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetinstantfor
  308. ThrowCompletionOr<NonnullGCPtr<Instant>> builtin_time_zone_get_instant_for(VM& vm, Value time_zone, PlainDateTime& date_time, StringView disambiguation)
  309. {
  310. // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
  311. // 2. Let possibleInstants be ? GetPossibleInstantsFor(timeZone, dateTime).
  312. auto time_zone_record = TRY(create_time_zone_methods_record(vm, NonnullGCPtr<Object> { time_zone.as_object() }, { { TimeZoneMethod::GetOffsetNanosecondsFor, TimeZoneMethod::GetPossibleInstantsFor } }));
  313. auto possible_instants = TRY(get_possible_instants_for(vm, time_zone_record, date_time));
  314. // 3. Return ? DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation).
  315. return disambiguate_possible_instants(vm, possible_instants, time_zone_record, date_time, disambiguation);
  316. }
  317. // 11.6.12 DisambiguatePossibleInstants ( possibleInstants, timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-disambiguatepossibleinstants
  318. ThrowCompletionOr<NonnullGCPtr<Instant>> disambiguate_possible_instants(VM& vm, MarkedVector<NonnullGCPtr<Instant>> const& possible_instants, TimeZoneMethods const& time_zone_record, PlainDateTime& date_time, StringView disambiguation)
  319. {
  320. // 1. Assert: TimeZoneMethodsRecordHasLookedUp(timeZoneRec, GET-POSSIBLE-INSTANTS-FOR) is true.
  321. VERIFY(time_zone_methods_record_has_looked_up(time_zone_record, TimeZoneMethod::GetPossibleInstantsFor));
  322. // 2. Assert: If possibleInstants is empty, and disambiguation is not "reject", TimeZoneMethodsRecordHasLookedUp(timeZoneRec, GET-OFFSET-NANOSECONDS-FOR) is true.
  323. if (possible_instants.is_empty() && disambiguation != "reject"sv)
  324. VERIFY(time_zone_methods_record_has_looked_up(time_zone_record, TimeZoneMethod::GetOffsetNanosecondsFor));
  325. // 3. Let n be possibleInstants's length.
  326. auto n = possible_instants.size();
  327. // 4. If n = 1, then
  328. if (n == 1) {
  329. // a. Return possibleInstants[0].
  330. return possible_instants[0];
  331. }
  332. // 5. If n ≠ 0, then
  333. if (n != 0) {
  334. // a. If disambiguation is "earlier" or "compatible", then
  335. if (disambiguation.is_one_of("earlier"sv, "compatible"sv)) {
  336. // i. Return possibleInstants[0].
  337. return possible_instants[0];
  338. }
  339. // b. If disambiguation is "later", then
  340. if (disambiguation == "later"sv) {
  341. // i. Return possibleInstants[n - 1].
  342. return possible_instants[n - 1];
  343. }
  344. // c. Assert: disambiguation is "reject".
  345. VERIFY(disambiguation == "reject"sv);
  346. // d. Throw a RangeError exception.
  347. return vm.throw_completion<RangeError>(ErrorType::TemporalDisambiguatePossibleInstantsRejectMoreThanOne);
  348. }
  349. // 6. Assert: n = 0.
  350. VERIFY(n == 0);
  351. // 7. If disambiguation is "reject", then
  352. if (disambiguation == "reject"sv) {
  353. // a. Throw a RangeError exception.
  354. return vm.throw_completion<RangeError>(ErrorType::TemporalDisambiguatePossibleInstantsRejectZero);
  355. }
  356. // 8. Let epochNanoseconds be GetUTCEpochNanoseconds(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]]).
  357. auto epoch_nanoseconds = get_utc_epoch_nanoseconds(date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond());
  358. // 9. Let dayBeforeNs be epochNanoseconds - ℤ(nsPerDay).
  359. auto day_before_ns = BigInt::create(vm, epoch_nanoseconds.minus(ns_per_day_bigint));
  360. // 10. If IsValidEpochNanoseconds(dayBeforeNs) is false, throw a RangeError exception.
  361. if (!is_valid_epoch_nanoseconds(day_before_ns))
  362. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  363. // 11. Let dayBefore be ! CreateTemporalInstant(dayBeforeNs).
  364. auto* day_before = MUST(create_temporal_instant(vm, day_before_ns));
  365. // 12. Let dayAfterNs be epochNanoseconds + ℤ(nsPerDay).
  366. auto day_after_ns = BigInt::create(vm, epoch_nanoseconds.plus(ns_per_day_bigint));
  367. // 13. If IsValidEpochNanoseconds(dayAfterNs) is false, throw a RangeError exception.
  368. if (!is_valid_epoch_nanoseconds(day_after_ns))
  369. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  370. // 14. Let dayAfter be ! CreateTemporalInstant(dayAfterNs).
  371. auto* day_after = MUST(create_temporal_instant(vm, day_after_ns));
  372. // 15. Let offsetBefore be ? GetOffsetNanosecondsFor(timeZoneRec, dayBefore).
  373. auto offset_before = TRY(get_offset_nanoseconds_for(vm, time_zone_record, *day_before));
  374. // 16. Let offsetAfter be ? GetOffsetNanosecondsFor(timeZoneRec, dayAfter).
  375. auto offset_after = TRY(get_offset_nanoseconds_for(vm, time_zone_record, *day_after));
  376. // 17. Let nanoseconds be offsetAfter - offsetBefore.
  377. auto nanoseconds = offset_after - offset_before;
  378. // 18. If disambiguation is "earlier", then
  379. if (disambiguation == "earlier"sv) {
  380. // a. Let earlier be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], dateTime.[[Calendar]], 0, 0, 0, 0, 0, 0, 0, 0, 0, -nanoseconds, undefined).
  381. auto earlier = TRY(add_date_time(vm, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond(), date_time.calendar(), 0, 0, 0, 0, 0, 0, 0, 0, 0, -nanoseconds, nullptr));
  382. // b. Let earlierDateTime be ! CreateTemporalDateTime(earlier.[[Year]], earlier.[[Month]], earlier.[[Day]], earlier.[[Hour]], earlier.[[Minute]], earlier.[[Second]], earlier.[[Millisecond]], earlier.[[Microsecond]], earlier.[[Nanosecond]], dateTime.[[Calendar]]).
  383. auto* earlier_date_time = MUST(create_temporal_date_time(vm, earlier.year, earlier.month, earlier.day, earlier.hour, earlier.minute, earlier.second, earlier.millisecond, earlier.microsecond, earlier.nanosecond, date_time.calendar()));
  384. // c. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, earlierDateTime).
  385. auto possible_instants_ = TRY(get_possible_instants_for(vm, time_zone_record, *earlier_date_time));
  386. // d. If possibleInstants is empty, throw a RangeError exception.
  387. if (possible_instants_.is_empty())
  388. return vm.throw_completion<RangeError>(ErrorType::TemporalDisambiguatePossibleInstantsEarlierZero);
  389. // e. Return possibleInstants[0].
  390. return possible_instants_[0];
  391. }
  392. // 19. Assert: disambiguation is "compatible" or "later".
  393. VERIFY(disambiguation.is_one_of("compatible"sv, "later"sv));
  394. // 20. Let later be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], dateTime.[[Calendar]], 0, 0, 0, 0, 0, 0, 0, 0, 0, nanoseconds, undefined).
  395. auto later = TRY(add_date_time(vm, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond(), date_time.calendar(), 0, 0, 0, 0, 0, 0, 0, 0, 0, nanoseconds, nullptr));
  396. // 21. Let laterDateTime be ! CreateTemporalDateTime(later.[[Year]], later.[[Month]], later.[[Day]], later.[[Hour]], later.[[Minute]], later.[[Second]], later.[[Millisecond]], later.[[Microsecond]], later.[[Nanosecond]], dateTime.[[Calendar]]).
  397. auto* later_date_time = MUST(create_temporal_date_time(vm, later.year, later.month, later.day, later.hour, later.minute, later.second, later.millisecond, later.microsecond, later.nanosecond, date_time.calendar()));
  398. // 22. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, laterDateTime).
  399. auto possible_instants_ = TRY(get_possible_instants_for(vm, time_zone_record, *later_date_time));
  400. // 23. Set n to possibleInstants's length.
  401. n = possible_instants_.size();
  402. // 24. If n = 0, throw a RangeError exception.
  403. if (n == 0)
  404. return vm.throw_completion<RangeError>(ErrorType::TemporalDisambiguatePossibleInstantsZero);
  405. // 25. Return possibleInstants[n - 1].
  406. return possible_instants_[n - 1];
  407. }
  408. // 11.5.24 GetPossibleInstantsFor ( timeZoneRec, dateTime ), https://tc39.es/proposal-temporal/#sec-temporal-getpossibleinstantsfor
  409. ThrowCompletionOr<MarkedVector<NonnullGCPtr<Instant>>> get_possible_instants_for(VM& vm, TimeZoneMethods const& time_zone_record, PlainDateTime const& date_time)
  410. {
  411. // 1. Let possibleInstants be ? TimeZoneMethodsRecordCall(timeZoneRec, GET-POSSIBLE-INSTANTS-FOR, « dateTime »).
  412. auto possible_instants = TRY(time_zone_methods_record_call(vm, time_zone_record, TimeZoneMethod::GetPossibleInstantsFor, { { &date_time } }));
  413. // 2. If TimeZoneMethodsRecordIsBuiltin(timeZoneRec), return ! CreateListFromArrayLike(possibleInstants, « Object »).
  414. if (time_zone_methods_record_is_builtin(time_zone_record)) {
  415. auto list = MarkedVector<NonnullGCPtr<Instant>> { vm.heap() };
  416. (void)MUST(create_list_from_array_like(vm, possible_instants, [&list](auto value) -> ThrowCompletionOr<void> {
  417. list.append(verify_cast<Instant>(value.as_object()));
  418. return {};
  419. }));
  420. return list;
  421. }
  422. // 3. Let iteratorRecord be ? GetIterator(possibleInstants, SYNC).
  423. auto iterator = TRY(get_iterator(vm, possible_instants, IteratorHint::Sync));
  424. // 4. Let list be a new empty List.
  425. auto list = MarkedVector<NonnullGCPtr<Instant>> { vm.heap() };
  426. // 5. Repeat,
  427. while (true) {
  428. // a. Let value be ? IteratorStepValue(iteratorRecord).
  429. auto value = TRY(iterator_step_value(vm, iterator));
  430. // b. If value is DONE, then
  431. if (!value.has_value()) {
  432. // i. Let numResults be list's length.
  433. auto num_results = list.size();
  434. // ii. If numResults > 1, then
  435. if (num_results > 1) {
  436. // 1. Let epochNs be a new empty List.
  437. // 2. For each value instant in list, do
  438. // a. Append instant.[[EpochNanoseconds]] to the end of the List epochNs.
  439. // FIXME: spec bug? shouldn't [[EpochNanoseconds]] just be called [[Nanoseconds]]?
  440. // 3. Let min be the least element of the List epochNs.
  441. // 4. Let max be the greatest element of the List epochNs.
  442. auto const* min = &list.first()->nanoseconds().big_integer();
  443. auto const* max = &list.first()->nanoseconds().big_integer();
  444. for (auto it = list.begin() + 1; it != list.end(); ++it) {
  445. auto const& value = it->ptr()->nanoseconds().big_integer();
  446. if (value < *min)
  447. min = &value;
  448. else if (value > *max)
  449. max = &value;
  450. }
  451. // 5. If abs(ℝ(max - min)) > nsPerDay, throw a RangeError exception.
  452. if (max->minus(*min).unsigned_value() > ns_per_day_bigint.unsigned_value())
  453. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDuration);
  454. }
  455. // iii. Return list.
  456. return list;
  457. }
  458. // c. If value is not an Object or value does not have an [[InitializedTemporalInstant]] internal slot, then
  459. if (!value->is_object() || !is<Instant>(value->as_object())) {
  460. // i. Let completion be ThrowCompletion(a newly created TypeError object).
  461. auto completion = vm.throw_completion<TypeError>(ErrorType::NotAnObjectOfType, "Temporal.Instant");
  462. // ii. Return ? IteratorClose(iteratorRecord, completion).
  463. return iterator_close(vm, iterator, move(completion));
  464. }
  465. // d. Append value to the end of the List list.
  466. list.append(verify_cast<Instant>(value->as_object()));
  467. }
  468. // 7. Return list.
  469. return { move(list) };
  470. }
  471. // 11.6.14 TimeZoneEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-timezoneequals
  472. ThrowCompletionOr<bool> time_zone_equals(VM& vm, Object& one, Object& two)
  473. {
  474. // 1. If one and two are the same Object value, return true.
  475. if (&one == &two)
  476. return true;
  477. // 2. Let timeZoneOne be ? ToString(one).
  478. auto time_zone_one = TRY(Value(&one).to_string(vm));
  479. // 3. Let timeZoneTwo be ? ToString(two).
  480. auto time_zone_two = TRY(Value(&two).to_string(vm));
  481. // 4. If timeZoneOne is timeZoneTwo, return true.
  482. if (time_zone_one == time_zone_two)
  483. return true;
  484. // 5. Return false.
  485. return false;
  486. }
  487. }