Instant.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (c) 2021, 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 < −86400ℤ × 10^17ℤ or epochNanoseconds > 86400ℤ × 10^17ℤ, then
  36. if (epoch_nanoseconds.big_integer() < INSTANT_NANOSECONDS_MIN || epoch_nanoseconds.big_integer() > INSTANT_NANOSECONDS_MAX) {
  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 it 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() < INSTANT_NANOSECONDS_MIN || utc->big_integer() > INSTANT_NANOSECONDS_MAX) {
  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. Return utc − offsetNanoseconds.
  103. return js_bigint(vm, utc->big_integer().minus(Crypto::SignedBigInteger::create_from(offset_nanoseconds)));
  104. }
  105. // 8.5.5 CompareEpochNanoseconds ( epochNanosecondsOne, epochNanosecondsTwo ), https://tc39.es/proposal-temporal/#sec-temporal-compareepochnanoseconds
  106. i32 compare_epoch_nanoseconds(BigInt const& epoch_nanoseconds_one, BigInt const& epoch_nanoseconds_two)
  107. {
  108. // 1. If epochNanosecondsOne > epochNanosecondsTwo, return 1.
  109. if (epoch_nanoseconds_one.big_integer() > epoch_nanoseconds_two.big_integer())
  110. return 1;
  111. // 2. If epochNanosecondsOne < epochNanosecondsTwo, return -1.
  112. if (epoch_nanoseconds_one.big_integer() < epoch_nanoseconds_two.big_integer())
  113. return -1;
  114. // 3. Return 0.
  115. return 0;
  116. }
  117. // 8.5.6 AddInstant ( epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addinstant
  118. ThrowCompletionOr<BigInt*> add_instant(GlobalObject& global_object, BigInt const& epoch_nanoseconds, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  119. {
  120. auto& vm = global_object.vm();
  121. // 1. Assert: hours, minutes, seconds, milliseconds, microseconds, and nanoseconds are integer Number values.
  122. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  123. // 2. Let result be epochNanoseconds + ℤ(nanoseconds) + ℤ(microseconds) × 1000ℤ + ℤ(milliseconds) × 10^6ℤ + ℤ(seconds) × 10^9ℤ + ℤ(minutes) × 60ℤ × 10^9ℤ + ℤ(hours) × 3600ℤ × 10^9ℤ.
  124. // FIXME: Pretty sure i64's are not sufficient for the extreme cases.
  125. auto* result = js_bigint(vm,
  126. epoch_nanoseconds.big_integer()
  127. .plus(Crypto::SignedBigInteger::create_from((i64)nanoseconds))
  128. .plus(Crypto::SignedBigInteger::create_from((i64)microseconds).multiplied_by(Crypto::SignedBigInteger { 1'000 }))
  129. .plus(Crypto::SignedBigInteger::create_from((i64)milliseconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000 }))
  130. .plus(Crypto::SignedBigInteger::create_from((i64)seconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  131. .plus(Crypto::SignedBigInteger::create_from((i64)minutes).multiplied_by(Crypto::SignedBigInteger { 60 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  132. .plus(Crypto::SignedBigInteger::create_from((i64)hours).multiplied_by(Crypto::SignedBigInteger { 3600 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 })));
  133. // If ! IsValidEpochNanoseconds(result) is false, throw a RangeError exception.
  134. if (!is_valid_epoch_nanoseconds(*result))
  135. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  136. // 4. Return result.
  137. return result;
  138. }
  139. // 8.5.7 DifferenceInstant ( ns1, ns2, roundingIncrement, smallestUnit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-differenceinstant
  140. BigInt* difference_instant(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, u64 rounding_increment, StringView smallest_unit, StringView rounding_mode)
  141. {
  142. auto& vm = global_object.vm();
  143. // 1. Assert: Type(ns1) is BigInt.
  144. // 2. Assert: Type(ns2) is BigInt.
  145. // 3. Return ! RoundTemporalInstant(ns2 − ns1, roundingIncrement, smallestUnit, roundingMode).
  146. return round_temporal_instant(global_object, *js_bigint(vm, nanoseconds2.big_integer().minus(nanoseconds1.big_integer())), rounding_increment, smallest_unit, rounding_mode);
  147. }
  148. // 8.5.8 RoundTemporalInstant ( ns, increment, unit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundtemporalinstant
  149. BigInt* round_temporal_instant(GlobalObject& global_object, BigInt const& nanoseconds, u64 increment, StringView unit, StringView rounding_mode)
  150. {
  151. // 1. Assert: Type(ns) is BigInt.
  152. u64 increment_nanoseconds;
  153. // 2. If unit is "hour", then
  154. if (unit == "hour"sv) {
  155. // a. Let incrementNs be increment × 3.6 × 10^12.
  156. increment_nanoseconds = increment * 3600000000000;
  157. }
  158. // 3. Else if unit is "minute", then
  159. else if (unit == "minute"sv) {
  160. // a. Let incrementNs be increment × 6 × 10^10.
  161. increment_nanoseconds = increment * 60000000000;
  162. }
  163. // 4. Else if unit is "second", then
  164. else if (unit == "second"sv) {
  165. // a. Let incrementNs be increment × 10^9.
  166. increment_nanoseconds = increment * 1000000000;
  167. }
  168. // 5. Else if unit is "millisecond", then
  169. else if (unit == "millisecond"sv) {
  170. // a. Let incrementNs be increment × 10^6.
  171. increment_nanoseconds = increment * 1000000;
  172. }
  173. // 6. Else if unit is "microsecond", then
  174. else if (unit == "microsecond"sv) {
  175. // a. Let incrementNs be increment × 10^3.
  176. increment_nanoseconds = increment * 1000;
  177. }
  178. // 7. Else,
  179. else {
  180. // a. Assert: unit is "nanosecond".
  181. VERIFY(unit == "nanosecond"sv);
  182. // b. Let incrementNs be increment.
  183. increment_nanoseconds = increment;
  184. }
  185. // 8. Return ! RoundNumberToIncrement(ℝ(ns), incrementNs, roundingMode).
  186. return round_number_to_increment(global_object, nanoseconds, increment_nanoseconds, rounding_mode);
  187. }
  188. // 8.5.9 TemporalInstantToString ( instant, timeZone, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporalinstanttostring
  189. ThrowCompletionOr<String> temporal_instant_to_string(GlobalObject& global_object, Instant& instant, Value time_zone, Variant<StringView, u8> const& precision)
  190. {
  191. // 1. Assert: Type(instant) is Object.
  192. // 2. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  193. // 3. Let outputTimeZone be timeZone.
  194. auto output_time_zone = time_zone;
  195. // 4. If outputTimeZone is undefined, then
  196. if (output_time_zone.is_undefined()) {
  197. // TODO: Can this really throw...?
  198. // a. Set outputTimeZone to ? CreateTemporalTimeZone("UTC").
  199. output_time_zone = TRY(create_temporal_time_zone(global_object, "UTC"sv));
  200. }
  201. // 5. Let isoCalendar be ! GetISO8601Calendar().
  202. auto* iso_calendar = get_iso8601_calendar(global_object);
  203. // 6. Let dateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(outputTimeZone, instant, isoCalendar).
  204. auto* date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, output_time_zone, instant, *iso_calendar));
  205. // 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").
  206. 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));
  207. String time_zone_string;
  208. // 8. If timeZone is undefined, then
  209. if (time_zone.is_undefined()) {
  210. // a. Let timeZoneString be "Z".
  211. time_zone_string = "Z"sv;
  212. }
  213. // 9. Else,
  214. else {
  215. // a. Let timeZoneString be ? BuiltinTimeZoneGetOffsetStringFor(timeZone, instant).
  216. time_zone_string = TRY(builtin_time_zone_get_offset_string_for(global_object, time_zone, instant));
  217. }
  218. // 10. Return the string-concatenation of dateTimeString and timeZoneString.
  219. return String::formatted("{}{}", date_time_string, time_zone_string);
  220. }
  221. }