Instant.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Variant.h>
  8. #include <LibCrypto/BigInt/SignedBigInteger.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  14. #include <LibJS/Runtime/Temporal/Calendar.h>
  15. #include <LibJS/Runtime/Temporal/Instant.h>
  16. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  17. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  18. #include <LibJS/Runtime/Temporal/TimeZone.h>
  19. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  20. namespace JS::Temporal {
  21. // 8 Temporal.Instant Objects, https://tc39.es/proposal-temporal/#sec-temporal-instant-objects
  22. Instant::Instant(BigInt const& nanoseconds, Object& prototype)
  23. : Object(prototype)
  24. , m_nanoseconds(nanoseconds)
  25. {
  26. }
  27. void Instant::visit_edges(Cell::Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(&m_nanoseconds);
  31. }
  32. // 8.5.1 IsValidEpochNanoseconds ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidepochnanoseconds
  33. bool is_valid_epoch_nanoseconds(BigInt const& epoch_nanoseconds)
  34. {
  35. return is_valid_epoch_nanoseconds(epoch_nanoseconds.big_integer());
  36. }
  37. // 8.5.1 IsValidEpochNanoseconds ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidepochnanoseconds
  38. bool is_valid_epoch_nanoseconds(Crypto::SignedBigInteger const& epoch_nanoseconds)
  39. {
  40. // 1. Assert: Type(epochNanoseconds) is BigInt.
  41. // 2. If ℝ(epochNanoseconds) < nsMinInstant or ℝ(epochNanoseconds) > nsMaxInstant, then
  42. if (epoch_nanoseconds < ns_min_instant || epoch_nanoseconds > ns_max_instant) {
  43. // a. Return false.
  44. return false;
  45. }
  46. // 3. Return true.
  47. return true;
  48. }
  49. // 8.5.2 CreateTemporalInstant ( epochNanoseconds [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalinstant
  50. ThrowCompletionOr<Instant*> create_temporal_instant(VM& vm, BigInt const& epoch_nanoseconds, FunctionObject const* new_target)
  51. {
  52. auto& realm = *vm.current_realm();
  53. // 1. Assert: Type(epochNanoseconds) is BigInt.
  54. // 2. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  55. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  56. // 3. If newTarget is not present, set newTarget to %Temporal.Instant%.
  57. if (!new_target)
  58. new_target = realm.intrinsics().temporal_instant_constructor();
  59. // 4. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Instant.prototype%", « [[InitializedTemporalInstant]], [[Nanoseconds]] »).
  60. // 5. Set object.[[Nanoseconds]] to epochNanoseconds.
  61. auto* object = TRY(ordinary_create_from_constructor<Instant>(vm, *new_target, &Intrinsics::temporal_instant_prototype, epoch_nanoseconds));
  62. // 6. Return object.
  63. return object;
  64. }
  65. // 8.5.3 ToTemporalInstant ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalinstant
  66. ThrowCompletionOr<Instant*> to_temporal_instant(VM& vm, Value item)
  67. {
  68. // 1. If Type(item) is Object, then
  69. if (item.is_object()) {
  70. // a. If item has an [[InitializedTemporalInstant]] internal slot, then
  71. if (is<Instant>(item.as_object())) {
  72. // i. Return item.
  73. return &static_cast<Instant&>(item.as_object());
  74. }
  75. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  76. if (is<ZonedDateTime>(item.as_object())) {
  77. auto& zoned_date_time = static_cast<ZonedDateTime&>(item.as_object());
  78. // i. Return ! CreateTemporalInstant(item.[[Nanoseconds]]).
  79. return create_temporal_instant(vm, zoned_date_time.nanoseconds());
  80. }
  81. }
  82. // 2. Let string be ? ToString(item).
  83. auto string = TRY(item.to_string(vm));
  84. // 3. Let epochNanoseconds be ? ParseTemporalInstant(string).
  85. auto* epoch_nanoseconds = TRY(parse_temporal_instant(vm, string));
  86. // 4. Return ! CreateTemporalInstant(ℤ(epochNanoseconds)).
  87. return create_temporal_instant(vm, *epoch_nanoseconds);
  88. }
  89. // 8.5.4 ParseTemporalInstant ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstant
  90. ThrowCompletionOr<BigInt*> parse_temporal_instant(VM& vm, String const& iso_string)
  91. {
  92. // 1. Assert: Type(isoString) is String.
  93. // 2. Let result be ? ParseTemporalInstantString(isoString).
  94. auto result = TRY(parse_temporal_instant_string(vm, iso_string));
  95. // 3. Let offsetString be result.[[TimeZoneOffsetString]].
  96. auto& offset_string = result.time_zone_offset;
  97. // 4. Assert: offsetString is not undefined.
  98. VERIFY(offset_string.has_value());
  99. // 5. Let utc be GetUTCEpochNanoseconds(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]).
  100. auto utc = get_utc_epoch_nanoseconds(result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond);
  101. // 6. If IsTimeZoneOffsetString(offsetString) is false, throw a RangeError exception.
  102. if (!is_time_zone_offset_string(*offset_string))
  103. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidTimeZoneName, *offset_string);
  104. // 7. Let offsetNanoseconds be ParseTimeZoneOffsetString(offsetString).
  105. auto offset_nanoseconds = parse_time_zone_offset_string(*offset_string);
  106. // 7. Let result be utc - ℤ(offsetNanoseconds).
  107. auto result_ns = utc.minus(Crypto::SignedBigInteger { offset_nanoseconds });
  108. // 8. If ! IsValidEpochNanoseconds(result) is false, then
  109. if (!is_valid_epoch_nanoseconds(result_ns)) {
  110. // a. Throw a RangeError exception.
  111. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  112. }
  113. // 9. Return result.
  114. return js_bigint(vm, move(result_ns));
  115. }
  116. // 8.5.5 CompareEpochNanoseconds ( epochNanosecondsOne, epochNanosecondsTwo ), https://tc39.es/proposal-temporal/#sec-temporal-compareepochnanoseconds
  117. i32 compare_epoch_nanoseconds(BigInt const& epoch_nanoseconds_one, BigInt const& epoch_nanoseconds_two)
  118. {
  119. // 1. If epochNanosecondsOne > epochNanosecondsTwo, return 1.
  120. if (epoch_nanoseconds_one.big_integer() > epoch_nanoseconds_two.big_integer())
  121. return 1;
  122. // 2. If epochNanosecondsOne < epochNanosecondsTwo, return -1.
  123. if (epoch_nanoseconds_one.big_integer() < epoch_nanoseconds_two.big_integer())
  124. return -1;
  125. // 3. Return 0.
  126. return 0;
  127. }
  128. // 8.5.6 AddInstant ( epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addinstant
  129. ThrowCompletionOr<BigInt*> add_instant(VM& vm, BigInt const& epoch_nanoseconds, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  130. {
  131. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  132. // 1. Let result be epochNanoseconds + ℤ(nanoseconds) + ℤ(microseconds) × 1000ℤ + ℤ(milliseconds) × 10^6ℤ + ℤ(seconds) × 10^9ℤ + ℤ(minutes) × 60ℤ × 10^9ℤ + ℤ(hours) × 3600ℤ × 10^9ℤ.
  133. auto* result = js_bigint(vm,
  134. epoch_nanoseconds.big_integer()
  135. .plus(Crypto::SignedBigInteger { nanoseconds })
  136. .plus(Crypto::SignedBigInteger { microseconds }.multiplied_by(Crypto::SignedBigInteger { 1'000 }))
  137. .plus(Crypto::SignedBigInteger { milliseconds }.multiplied_by(Crypto::SignedBigInteger { 1'000'000 }))
  138. .plus(Crypto::SignedBigInteger { seconds }.multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  139. .plus(Crypto::SignedBigInteger { minutes }.multiplied_by(Crypto::SignedBigInteger { 60 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  140. .plus(Crypto::SignedBigInteger { hours }.multiplied_by(Crypto::SignedBigInteger { 3600 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 })));
  141. // 2. If ! IsValidEpochNanoseconds(result) is false, throw a RangeError exception.
  142. if (!is_valid_epoch_nanoseconds(*result))
  143. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  144. // 3. Return result.
  145. return result;
  146. }
  147. // 8.5.7 DifferenceInstant ( ns1, ns2, roundingIncrement, smallestUnit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-differenceinstant
  148. BigInt* difference_instant(VM& vm, BigInt const& nanoseconds1, BigInt const& nanoseconds2, u64 rounding_increment, StringView smallest_unit, StringView rounding_mode)
  149. {
  150. // 1. Assert: Type(ns1) is BigInt.
  151. // 2. Assert: Type(ns2) is BigInt.
  152. // 3. Return ! RoundTemporalInstant(ns2 - ns1, roundingIncrement, smallestUnit, roundingMode).
  153. return round_temporal_instant(vm, *js_bigint(vm, nanoseconds2.big_integer().minus(nanoseconds1.big_integer())), rounding_increment, smallest_unit, rounding_mode);
  154. }
  155. // 8.5.8 RoundTemporalInstant ( ns, increment, unit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundtemporalinstant
  156. BigInt* round_temporal_instant(VM& vm, BigInt const& nanoseconds, u64 increment, StringView unit, StringView rounding_mode)
  157. {
  158. // 1. Assert: Type(ns) is BigInt.
  159. u64 increment_nanoseconds;
  160. // 2. If unit is "hour", then
  161. if (unit == "hour"sv) {
  162. // a. Let incrementNs be increment × 3.6 × 10^12.
  163. increment_nanoseconds = increment * 3600000000000;
  164. }
  165. // 3. Else if unit is "minute", then
  166. else if (unit == "minute"sv) {
  167. // a. Let incrementNs be increment × 6 × 10^10.
  168. increment_nanoseconds = increment * 60000000000;
  169. }
  170. // 4. Else if unit is "second", then
  171. else if (unit == "second"sv) {
  172. // a. Let incrementNs be increment × 10^9.
  173. increment_nanoseconds = increment * 1000000000;
  174. }
  175. // 5. Else if unit is "millisecond", then
  176. else if (unit == "millisecond"sv) {
  177. // a. Let incrementNs be increment × 10^6.
  178. increment_nanoseconds = increment * 1000000;
  179. }
  180. // 6. Else if unit is "microsecond", then
  181. else if (unit == "microsecond"sv) {
  182. // a. Let incrementNs be increment × 10^3.
  183. increment_nanoseconds = increment * 1000;
  184. }
  185. // 7. Else,
  186. else {
  187. // a. Assert: unit is "nanosecond".
  188. VERIFY(unit == "nanosecond"sv);
  189. // b. Let incrementNs be increment.
  190. increment_nanoseconds = increment;
  191. }
  192. // 8. Return RoundNumberToIncrementAsIfPositive(ℝ(ns), incrementNs, roundingMode).
  193. return js_bigint(vm, round_number_to_increment_as_if_positive(nanoseconds.big_integer(), increment_nanoseconds, rounding_mode));
  194. }
  195. // 8.5.9 TemporalInstantToString ( instant, timeZone, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporalinstanttostring
  196. ThrowCompletionOr<String> temporal_instant_to_string(VM& vm, Instant& instant, Value time_zone, Variant<StringView, u8> const& precision)
  197. {
  198. // 1. Assert: Type(instant) is Object.
  199. // 2. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  200. // 3. Let outputTimeZone be timeZone.
  201. auto output_time_zone = time_zone;
  202. // 4. If outputTimeZone is undefined, then
  203. if (output_time_zone.is_undefined()) {
  204. // a. Set outputTimeZone to ! CreateTemporalTimeZone("UTC").
  205. output_time_zone = MUST(create_temporal_time_zone(vm, "UTC"sv));
  206. }
  207. // 5. Let isoCalendar be ! GetISO8601Calendar().
  208. auto* iso_calendar = get_iso8601_calendar(vm);
  209. // 6. Let dateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(outputTimeZone, instant, isoCalendar).
  210. auto* date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, output_time_zone, instant, *iso_calendar));
  211. // 7. Let dateTimeString be ? TemporalDateTimeToString(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], undefined, precision, "never").
  212. auto date_time_string = TRY(temporal_date_time_to_string(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(), nullptr, precision, "never"sv));
  213. String time_zone_string;
  214. // 8. If timeZone is undefined, then
  215. if (time_zone.is_undefined()) {
  216. // a. Let timeZoneString be "Z".
  217. time_zone_string = "Z"sv;
  218. }
  219. // 9. Else,
  220. else {
  221. // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
  222. auto offset_ns = TRY(get_offset_nanoseconds_for(vm, time_zone, instant));
  223. // b. Let timeZoneString be ! FormatISOTimeZoneOffsetString(offsetNs).
  224. time_zone_string = format_iso_time_zone_offset_string(offset_ns);
  225. }
  226. // 10. Return the string-concatenation of dateTimeString and timeZoneString.
  227. return String::formatted("{}{}", date_time_string, time_zone_string);
  228. }
  229. // 8.5.10 DifferenceTemporalInstant ( operation, instant, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalinstant
  230. ThrowCompletionOr<Duration*> difference_temporal_instant(VM& vm, DifferenceOperation operation, Instant const& instant, Value other_value, Value options_value)
  231. {
  232. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  233. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  234. // 2. Set other to ? ToTemporalInstant(other).
  235. auto* other = TRY(to_temporal_instant(vm, other_value));
  236. // 3. Let settings be ? GetDifferenceSettings(operation, options, time, « », "nanosecond", "second").
  237. auto settings = TRY(get_difference_settings(vm, operation, options_value, UnitGroup::Time, {}, { "nanosecond"sv }, "second"sv));
  238. // 4. Let roundedNs be ! DifferenceInstant(instant.[[Nanoseconds]], other.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]]).
  239. auto* rounded_ns = difference_instant(vm, instant.nanoseconds(), other->nanoseconds(), settings.rounding_increment, settings.smallest_unit, settings.rounding_mode);
  240. // 5. Assert: The following steps cannot fail due to overflow in the Number domain because abs(roundedNs) ≤ 2 × nsMaxInstant.
  241. // 6. Let result be ! BalanceDuration(0, 0, 0, 0, 0, 0, roundedNs, settings.[[LargestUnit]]).
  242. auto result = MUST(balance_duration(vm, 0, 0, 0, 0, 0, 0, rounded_ns->big_integer(), settings.largest_unit));
  243. // 7. Return ! CreateTemporalDuration(0, 0, 0, 0, sign × result.[[Hours]], sign × result.[[Minutes]], sign × result.[[Seconds]], sign × result.[[Milliseconds]], sign × result.[[Microseconds]], sign × result.[[Nanoseconds]]).
  244. return MUST(create_temporal_duration(vm, 0, 0, 0, 0, sign * result.hours, sign * result.minutes, sign * result.seconds, sign * result.milliseconds, sign * result.microseconds, sign * result.nanoseconds));
  245. }
  246. // 8.5.11 AddDurationToOrSubtractDurationFromInstant ( operation, instant, temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfrominstant
  247. ThrowCompletionOr<Instant*> add_duration_to_or_subtract_duration_from_instant(VM& vm, ArithmeticOperation operation, Instant const& instant, Value temporal_duration_like)
  248. {
  249. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  250. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  251. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  252. auto duration = TRY(to_temporal_duration_record(vm, temporal_duration_like));
  253. // 3. If duration.[[Days]] is not 0, throw a RangeError exception.
  254. if (duration.days != 0)
  255. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "days", duration.days);
  256. // 4. If duration.[[Months]] is not 0, throw a RangeError exception.
  257. if (duration.months != 0)
  258. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "months", duration.months);
  259. // 5. If duration.[[Weeks]] is not 0, throw a RangeError exception.
  260. if (duration.weeks != 0)
  261. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "weeks", duration.weeks);
  262. // 6. If duration.[[Years]] is not 0, throw a RangeError exception.
  263. if (duration.years != 0)
  264. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "years", duration.years);
  265. // 7. Let ns be ? AddInstant(instant.[[Nanoseconds]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]]).
  266. auto* ns = TRY(add_instant(vm, instant.nanoseconds(), sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds));
  267. // 8. Return ! CreateTemporalInstant(ns).
  268. return MUST(create_temporal_instant(vm, *ns));
  269. }
  270. }