Instant.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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/GlobalObject.h>
  12. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  13. #include <LibJS/Runtime/Temporal/Calendar.h>
  14. #include <LibJS/Runtime/Temporal/Instant.h>
  15. #include <LibJS/Runtime/Temporal/InstantConstructor.h>
  16. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  17. #include <LibJS/Runtime/Temporal/TimeZone.h>
  18. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  19. namespace JS::Temporal {
  20. // 8 Temporal.Instant Objects, https://tc39.es/proposal-temporal/#sec-temporal-instant-objects
  21. Instant::Instant(BigInt const& nanoseconds, Object& prototype)
  22. : Object(prototype)
  23. , m_nanoseconds(nanoseconds)
  24. {
  25. }
  26. void Instant::visit_edges(Cell::Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(&m_nanoseconds);
  30. }
  31. // 8.5.1 IsValidEpochNanoseconds ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidepochnanoseconds
  32. bool is_valid_epoch_nanoseconds(BigInt const& epoch_nanoseconds)
  33. {
  34. // 1. Assert: Type(epochNanoseconds) is BigInt.
  35. // 2. If ℝ(epochNanoseconds) < nsMinInstant or ℝ(epochNanoseconds) > nsMaxInstant, then
  36. if (epoch_nanoseconds.big_integer() < ns_min_instant || epoch_nanoseconds.big_integer() > ns_max_instant) {
  37. // a. Return false.
  38. return false;
  39. }
  40. // 3. Return true.
  41. return true;
  42. }
  43. // 8.5.2 CreateTemporalInstant ( epochNanoseconds [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalinstant
  44. ThrowCompletionOr<Instant*> create_temporal_instant(GlobalObject& global_object, BigInt const& epoch_nanoseconds, FunctionObject const* new_target)
  45. {
  46. // 1. Assert: Type(epochNanoseconds) is BigInt.
  47. // 2. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  48. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  49. // 3. If newTarget is not present, set newTarget to %Temporal.Instant%.
  50. if (!new_target)
  51. new_target = global_object.temporal_instant_constructor();
  52. // 4. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Instant.prototype%", « [[InitializedTemporalInstant]], [[Nanoseconds]] »).
  53. // 5. Set object.[[Nanoseconds]] to epochNanoseconds.
  54. auto* object = TRY(ordinary_create_from_constructor<Instant>(global_object, *new_target, &GlobalObject::temporal_instant_prototype, epoch_nanoseconds));
  55. // 6. Return object.
  56. return object;
  57. }
  58. // 8.5.3 ToTemporalInstant ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalinstant
  59. ThrowCompletionOr<Instant*> to_temporal_instant(GlobalObject& global_object, Value item)
  60. {
  61. // 1. If Type(item) is Object, then
  62. if (item.is_object()) {
  63. // a. If item has an [[InitializedTemporalInstant]] internal slot, then
  64. if (is<Instant>(item.as_object())) {
  65. // i. Return item.
  66. return &static_cast<Instant&>(item.as_object());
  67. }
  68. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  69. if (is<ZonedDateTime>(item.as_object())) {
  70. auto& zoned_date_time = static_cast<ZonedDateTime&>(item.as_object());
  71. // i. Return ! CreateTemporalInstant(item.[[Nanoseconds]]).
  72. return create_temporal_instant(global_object, zoned_date_time.nanoseconds());
  73. }
  74. }
  75. // 2. Let string be ? ToString(item).
  76. auto string = TRY(item.to_string(global_object));
  77. // 3. Let epochNanoseconds be ? ParseTemporalInstant(string).
  78. auto* epoch_nanoseconds = TRY(parse_temporal_instant(global_object, string));
  79. // 4. Return ! CreateTemporalInstant(ℤ(epochNanoseconds)).
  80. return create_temporal_instant(global_object, *epoch_nanoseconds);
  81. }
  82. // 8.5.4 ParseTemporalInstant ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstant
  83. ThrowCompletionOr<BigInt*> parse_temporal_instant(GlobalObject& global_object, String const& iso_string)
  84. {
  85. auto& vm = global_object.vm();
  86. // 1. Assert: Type(isoString) is String.
  87. // 2. Let result be ? ParseTemporalInstantString(isoString).
  88. auto result = TRY(parse_temporal_instant_string(global_object, iso_string));
  89. // 3. Let offsetString be result.[[TimeZoneOffsetString]].
  90. auto& offset_string = result.time_zone_offset;
  91. // 4. Assert: offsetString is not undefined.
  92. VERIFY(offset_string.has_value());
  93. // 5. Let utc be GetEpochFromISOParts(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]).
  94. auto* utc = get_epoch_from_iso_parts(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond);
  95. // 6. If ℝ(utc) < -8.64 × 10^21 or ℝ(utc) > 8.64 × 10^21, then
  96. if (utc->big_integer() < ns_min_instant || utc->big_integer() > ns_max_instant) {
  97. // a. Throw a RangeError exception.
  98. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  99. }
  100. // 7. Let offsetNanoseconds be ? ParseTimeZoneOffsetString(offsetString).
  101. auto offset_nanoseconds = TRY(parse_time_zone_offset_string(global_object, *offset_string));
  102. // 8. Let result be utc - ℤ(offsetNanoseconds).
  103. auto* result_ns = js_bigint(vm, utc->big_integer().minus(Crypto::SignedBigInteger::create_from(offset_nanoseconds)));
  104. // 9. If ! IsValidEpochNanoseconds(result) is false, then
  105. if (!is_valid_epoch_nanoseconds(*result_ns)) {
  106. // a. Throw a RangeError exception.
  107. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  108. }
  109. // 10. Return result.
  110. return result_ns;
  111. }
  112. // 8.5.5 CompareEpochNanoseconds ( epochNanosecondsOne, epochNanosecondsTwo ), https://tc39.es/proposal-temporal/#sec-temporal-compareepochnanoseconds
  113. i32 compare_epoch_nanoseconds(BigInt const& epoch_nanoseconds_one, BigInt const& epoch_nanoseconds_two)
  114. {
  115. // 1. If epochNanosecondsOne > epochNanosecondsTwo, return 1.
  116. if (epoch_nanoseconds_one.big_integer() > epoch_nanoseconds_two.big_integer())
  117. return 1;
  118. // 2. If epochNanosecondsOne < epochNanosecondsTwo, return -1.
  119. if (epoch_nanoseconds_one.big_integer() < epoch_nanoseconds_two.big_integer())
  120. return -1;
  121. // 3. Return 0.
  122. return 0;
  123. }
  124. // 8.5.6 AddInstant ( epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addinstant
  125. ThrowCompletionOr<BigInt*> add_instant(GlobalObject& global_object, BigInt const& epoch_nanoseconds, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  126. {
  127. auto& vm = global_object.vm();
  128. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  129. // 1. Let result be epochNanoseconds + ℤ(nanoseconds) + ℤ(microseconds) × 1000ℤ + ℤ(milliseconds) × 10^6ℤ + ℤ(seconds) × 10^9ℤ + ℤ(minutes) × 60ℤ × 10^9ℤ + ℤ(hours) × 3600ℤ × 10^9ℤ.
  130. // FIXME: Pretty sure i64's are not sufficient for the extreme cases.
  131. auto* result = js_bigint(vm,
  132. epoch_nanoseconds.big_integer()
  133. .plus(Crypto::SignedBigInteger::create_from((i64)nanoseconds))
  134. .plus(Crypto::SignedBigInteger::create_from((i64)microseconds).multiplied_by(Crypto::SignedBigInteger { 1'000 }))
  135. .plus(Crypto::SignedBigInteger::create_from((i64)milliseconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000 }))
  136. .plus(Crypto::SignedBigInteger::create_from((i64)seconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  137. .plus(Crypto::SignedBigInteger::create_from((i64)minutes).multiplied_by(Crypto::SignedBigInteger { 60 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  138. .plus(Crypto::SignedBigInteger::create_from((i64)hours).multiplied_by(Crypto::SignedBigInteger { 3600 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 })));
  139. // 2. If ! IsValidEpochNanoseconds(result) is false, throw a RangeError exception.
  140. if (!is_valid_epoch_nanoseconds(*result))
  141. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  142. // 3. Return result.
  143. return result;
  144. }
  145. // 8.5.7 DifferenceInstant ( ns1, ns2, roundingIncrement, smallestUnit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-differenceinstant
  146. BigInt* difference_instant(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, u64 rounding_increment, StringView smallest_unit, StringView rounding_mode)
  147. {
  148. auto& vm = global_object.vm();
  149. // 1. Assert: Type(ns1) is BigInt.
  150. // 2. Assert: Type(ns2) is BigInt.
  151. // 3. Return ! RoundTemporalInstant(ns2 - ns1, roundingIncrement, smallestUnit, roundingMode).
  152. return round_temporal_instant(global_object, *js_bigint(vm, nanoseconds2.big_integer().minus(nanoseconds1.big_integer())), rounding_increment, smallest_unit, rounding_mode);
  153. }
  154. // 8.5.8 RoundTemporalInstant ( ns, increment, unit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundtemporalinstant
  155. BigInt* round_temporal_instant(GlobalObject& global_object, BigInt const& nanoseconds, u64 increment, StringView unit, StringView rounding_mode)
  156. {
  157. // 1. Assert: Type(ns) is BigInt.
  158. u64 increment_nanoseconds;
  159. // 2. If unit is "hour", then
  160. if (unit == "hour"sv) {
  161. // a. Let incrementNs be increment × 3.6 × 10^12.
  162. increment_nanoseconds = increment * 3600000000000;
  163. }
  164. // 3. Else if unit is "minute", then
  165. else if (unit == "minute"sv) {
  166. // a. Let incrementNs be increment × 6 × 10^10.
  167. increment_nanoseconds = increment * 60000000000;
  168. }
  169. // 4. Else if unit is "second", then
  170. else if (unit == "second"sv) {
  171. // a. Let incrementNs be increment × 10^9.
  172. increment_nanoseconds = increment * 1000000000;
  173. }
  174. // 5. Else if unit is "millisecond", then
  175. else if (unit == "millisecond"sv) {
  176. // a. Let incrementNs be increment × 10^6.
  177. increment_nanoseconds = increment * 1000000;
  178. }
  179. // 6. Else if unit is "microsecond", then
  180. else if (unit == "microsecond"sv) {
  181. // a. Let incrementNs be increment × 10^3.
  182. increment_nanoseconds = increment * 1000;
  183. }
  184. // 7. Else,
  185. else {
  186. // a. Assert: unit is "nanosecond".
  187. VERIFY(unit == "nanosecond"sv);
  188. // b. Let incrementNs be increment.
  189. increment_nanoseconds = increment;
  190. }
  191. // 8. Return ! RoundNumberToIncrement(ℝ(ns), incrementNs, roundingMode).
  192. return round_number_to_increment(global_object, nanoseconds, increment_nanoseconds, rounding_mode);
  193. }
  194. // 8.5.9 TemporalInstantToString ( instant, timeZone, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporalinstanttostring
  195. ThrowCompletionOr<String> temporal_instant_to_string(GlobalObject& global_object, Instant& instant, Value time_zone, Variant<StringView, u8> const& precision)
  196. {
  197. // 1. Assert: Type(instant) is Object.
  198. // 2. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  199. // 3. Let outputTimeZone be timeZone.
  200. auto output_time_zone = time_zone;
  201. // 4. If outputTimeZone is undefined, then
  202. if (output_time_zone.is_undefined()) {
  203. // a. Set outputTimeZone to ! CreateTemporalTimeZone("UTC").
  204. output_time_zone = MUST(create_temporal_time_zone(global_object, "UTC"sv));
  205. }
  206. // 5. Let isoCalendar be ! GetISO8601Calendar().
  207. auto* iso_calendar = get_iso8601_calendar(global_object);
  208. // 6. Let dateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(outputTimeZone, instant, isoCalendar).
  209. auto* date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, output_time_zone, instant, *iso_calendar));
  210. // 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").
  211. auto date_time_string = TRY(temporal_date_time_to_string(global_object, 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(), js_undefined(), precision, "never"sv));
  212. String time_zone_string;
  213. // 8. If timeZone is undefined, then
  214. if (time_zone.is_undefined()) {
  215. // a. Let timeZoneString be "Z".
  216. time_zone_string = "Z"sv;
  217. }
  218. // 9. Else,
  219. else {
  220. // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
  221. auto offset_ns = TRY(get_offset_nanoseconds_for(global_object, time_zone, instant));
  222. // b. Let timeZoneString be ! FormatISOTimeZoneOffsetString(offsetNs).
  223. time_zone_string = format_iso_time_zone_offset_string(offset_ns);
  224. }
  225. // 10. Return the string-concatenation of dateTimeString and timeZoneString.
  226. return String::formatted("{}{}", date_time_string, time_zone_string);
  227. }
  228. // 8.5.10 AddDurationToOrSubtractDurationFromInstant ( operation, instant, temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfrominstant
  229. ThrowCompletionOr<Instant*> add_duration_to_or_subtract_duration_from_instant(GlobalObject& global_object, ArithmeticOperation operation, Instant const& instant, Value temporal_duration_like)
  230. {
  231. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  232. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  233. // 2. Let duration be ? ToLimitedTemporalDuration(temporalDurationLike, « "years", "months", "weeks", "days" »).
  234. auto duration = TRY(to_limited_temporal_duration(global_object, temporal_duration_like, { "years"sv, "months"sv, "weeks"sv, "days"sv }));
  235. // 3. Let ns be ? AddInstant(instant.[[Nanoseconds]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]]).
  236. auto* ns = TRY(add_instant(global_object, instant.nanoseconds(), sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds));
  237. // 4. Return ! CreateTemporalInstant(ns).
  238. return MUST(create_temporal_instant(global_object, *ns));
  239. }
  240. }