Instant.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. auto& vm = global_object.vm();
  62. // 1. If Type(item) is Object, then
  63. if (item.is_object()) {
  64. // a. If item has an [[InitializedTemporalInstant]] internal slot, then
  65. if (is<Instant>(item.as_object())) {
  66. // i. Return item.
  67. return &static_cast<Instant&>(item.as_object());
  68. }
  69. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  70. if (is<ZonedDateTime>(item.as_object())) {
  71. auto& zoned_date_time = static_cast<ZonedDateTime&>(item.as_object());
  72. // i. Return ! CreateTemporalInstant(item.[[Nanoseconds]]).
  73. return create_temporal_instant(global_object, zoned_date_time.nanoseconds());
  74. }
  75. }
  76. // 2. Let string be ? ToString(item).
  77. auto string = item.to_string(global_object);
  78. if (auto* exception = vm.exception())
  79. return throw_completion(exception->value());
  80. // 3. Let epochNanoseconds be ? ParseTemporalInstant(string).
  81. auto* epoch_nanoseconds = TRY(parse_temporal_instant(global_object, string));
  82. // 4. Return ! CreateTemporalInstant(ℤ(epochNanoseconds)).
  83. return create_temporal_instant(global_object, *epoch_nanoseconds);
  84. }
  85. // 8.5.4 ParseTemporalInstant ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstant
  86. ThrowCompletionOr<BigInt*> parse_temporal_instant(GlobalObject& global_object, String const& iso_string)
  87. {
  88. auto& vm = global_object.vm();
  89. // 1. Assert: Type(isoString) is String.
  90. // 2. Let result be ? ParseTemporalInstantString(isoString).
  91. auto result = TRY(parse_temporal_instant_string(global_object, iso_string));
  92. // 3. Let offsetString be result.[[TimeZoneOffsetString]].
  93. auto& offset_string = result.time_zone_offset;
  94. // 4. Assert: offsetString is not undefined.
  95. VERIFY(offset_string.has_value());
  96. // 5. Let utc be ? GetEpochFromISOParts(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]).
  97. 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);
  98. if (auto* exception = vm.exception())
  99. return throw_completion(exception->value());
  100. // 6. If utc < −8.64 × 10^21 or utc > 8.64 × 10^21, then
  101. if (utc->big_integer() < INSTANT_NANOSECONDS_MIN || utc->big_integer() > INSTANT_NANOSECONDS_MAX) {
  102. // a. Throw a RangeError exception.
  103. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  104. }
  105. // 7. Let offsetNanoseconds be ? ParseTimeZoneOffsetString(offsetString).
  106. auto offset_nanoseconds = TRY(parse_time_zone_offset_string(global_object, *offset_string));
  107. // 8. Return utc − offsetNanoseconds.
  108. return js_bigint(vm, utc->big_integer().minus(Crypto::SignedBigInteger::create_from(offset_nanoseconds)));
  109. }
  110. // 8.5.5 CompareEpochNanoseconds ( epochNanosecondsOne, epochNanosecondsTwo ), https://tc39.es/proposal-temporal/#sec-temporal-compareepochnanoseconds
  111. i32 compare_epoch_nanoseconds(BigInt const& epoch_nanoseconds_one, BigInt const& epoch_nanoseconds_two)
  112. {
  113. // 1. If epochNanosecondsOne > epochNanosecondsTwo, return 1.
  114. if (epoch_nanoseconds_one.big_integer() > epoch_nanoseconds_two.big_integer())
  115. return 1;
  116. // 2. If epochNanosecondsOne < epochNanosecondsTwo, return -1.
  117. if (epoch_nanoseconds_one.big_integer() < epoch_nanoseconds_two.big_integer())
  118. return -1;
  119. // 3. Return 0.
  120. return 0;
  121. }
  122. // 8.5.6 AddInstant ( epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addinstant
  123. ThrowCompletionOr<BigInt*> add_instant(GlobalObject& global_object, BigInt const& epoch_nanoseconds, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  124. {
  125. auto& vm = global_object.vm();
  126. // 1. Assert: hours, minutes, seconds, milliseconds, microseconds, and nanoseconds are integer Number values.
  127. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  128. // 2. Let result be epochNanoseconds + ℤ(nanoseconds) + ℤ(microseconds) × 1000ℤ + ℤ(milliseconds) × 10^6ℤ + ℤ(seconds) × 10^9ℤ + ℤ(minutes) × 60ℤ × 10^9ℤ + ℤ(hours) × 3600ℤ × 10^9ℤ.
  129. // FIXME: Pretty sure i64's are not sufficient for the extreme cases.
  130. auto* result = js_bigint(vm,
  131. epoch_nanoseconds.big_integer()
  132. .plus(Crypto::SignedBigInteger::create_from((i64)nanoseconds))
  133. .plus(Crypto::SignedBigInteger::create_from((i64)microseconds).multiplied_by(Crypto::SignedBigInteger { 1'000 }))
  134. .plus(Crypto::SignedBigInteger::create_from((i64)milliseconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000 }))
  135. .plus(Crypto::SignedBigInteger::create_from((i64)seconds).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  136. .plus(Crypto::SignedBigInteger::create_from((i64)minutes).multiplied_by(Crypto::SignedBigInteger { 60 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  137. .plus(Crypto::SignedBigInteger::create_from((i64)hours).multiplied_by(Crypto::SignedBigInteger { 3600 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 })));
  138. // If ! IsValidEpochNanoseconds(result) is false, throw a RangeError exception.
  139. if (!is_valid_epoch_nanoseconds(*result))
  140. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  141. // 4. Return result.
  142. return result;
  143. }
  144. // 8.5.7 DifferenceInstant ( ns1, ns2, roundingIncrement, smallestUnit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-differenceinstant
  145. BigInt* difference_instant(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, u64 rounding_increment, StringView smallest_unit, StringView rounding_mode)
  146. {
  147. auto& vm = global_object.vm();
  148. // 1. Assert: Type(ns1) is BigInt.
  149. // 2. Assert: Type(ns2) is BigInt.
  150. // 3. Return ! RoundTemporalInstant(ns2 − ns1, roundingIncrement, smallestUnit, roundingMode).
  151. return round_temporal_instant(global_object, *js_bigint(vm, nanoseconds2.big_integer().minus(nanoseconds1.big_integer())), rounding_increment, smallest_unit, rounding_mode);
  152. }
  153. // 8.5.8 RoundTemporalInstant ( ns, increment, unit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundtemporalinstant
  154. BigInt* round_temporal_instant(GlobalObject& global_object, BigInt const& nanoseconds, u64 increment, StringView unit, StringView rounding_mode)
  155. {
  156. // 1. Assert: Type(ns) is BigInt.
  157. u64 increment_nanoseconds;
  158. // 2. If unit is "hour", then
  159. if (unit == "hour"sv) {
  160. // a. Let incrementNs be increment × 3.6 × 10^12.
  161. increment_nanoseconds = increment * 3600000000000;
  162. }
  163. // 3. Else if unit is "minute", then
  164. else if (unit == "minute"sv) {
  165. // a. Let incrementNs be increment × 6 × 10^10.
  166. increment_nanoseconds = increment * 60000000000;
  167. }
  168. // 4. Else if unit is "second", then
  169. else if (unit == "second"sv) {
  170. // a. Let incrementNs be increment × 10^9.
  171. increment_nanoseconds = increment * 1000000000;
  172. }
  173. // 5. Else if unit is "millisecond", then
  174. else if (unit == "millisecond"sv) {
  175. // a. Let incrementNs be increment × 10^6.
  176. increment_nanoseconds = increment * 1000000;
  177. }
  178. // 6. Else if unit is "microsecond", then
  179. else if (unit == "microsecond"sv) {
  180. // a. Let incrementNs be increment × 10^3.
  181. increment_nanoseconds = increment * 1000;
  182. }
  183. // 7. Else,
  184. else {
  185. // a. Assert: unit is "nanosecond".
  186. VERIFY(unit == "nanosecond"sv);
  187. // b. Let incrementNs be increment.
  188. increment_nanoseconds = increment;
  189. }
  190. // 8. Return ! RoundNumberToIncrement(ℝ(ns), incrementNs, roundingMode).
  191. return round_number_to_increment(global_object, nanoseconds, increment_nanoseconds, rounding_mode);
  192. }
  193. // 8.5.9 TemporalInstantToString ( instant, timeZone, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporalinstanttostring
  194. ThrowCompletionOr<String> temporal_instant_to_string(GlobalObject& global_object, Instant& instant, Value time_zone, Variant<StringView, u8> const& precision)
  195. {
  196. // 1. Assert: Type(instant) is Object.
  197. // 2. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  198. // 3. Let outputTimeZone be timeZone.
  199. auto output_time_zone = time_zone;
  200. // 4. If outputTimeZone is undefined, then
  201. if (output_time_zone.is_undefined()) {
  202. // TODO: Can this really throw...?
  203. // a. Set outputTimeZone to ? CreateTemporalTimeZone("UTC").
  204. output_time_zone = TRY(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 timeZoneString be ? BuiltinTimeZoneGetOffsetStringFor(timeZone, instant).
  221. time_zone_string = TRY(builtin_time_zone_get_offset_string_for(global_object, time_zone, instant));
  222. }
  223. // 10. Return the string-concatenation of dateTimeString and timeZoneString.
  224. return String::formatted("{}{}", date_time_string, time_zone_string);
  225. }
  226. }