Instant.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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(VM& vm, BigInt const& epoch_nanoseconds, FunctionObject const* new_target)
  45. {
  46. auto& realm = *vm.current_realm();
  47. // 1. Assert: Type(epochNanoseconds) is BigInt.
  48. // 2. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  49. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  50. // 3. If newTarget is not present, set newTarget to %Temporal.Instant%.
  51. if (!new_target)
  52. new_target = realm.global_object().temporal_instant_constructor();
  53. // 4. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Instant.prototype%", « [[InitializedTemporalInstant]], [[Nanoseconds]] »).
  54. // 5. Set object.[[Nanoseconds]] to epochNanoseconds.
  55. auto* object = TRY(ordinary_create_from_constructor<Instant>(vm, *new_target, &GlobalObject::temporal_instant_prototype, epoch_nanoseconds));
  56. // 6. Return object.
  57. return object;
  58. }
  59. // 8.5.3 ToTemporalInstant ( item ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalinstant
  60. ThrowCompletionOr<Instant*> to_temporal_instant(VM& vm, Value item)
  61. {
  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(vm, zoned_date_time.nanoseconds());
  74. }
  75. }
  76. // 2. Let string be ? ToString(item).
  77. auto string = TRY(item.to_string(vm));
  78. // 3. Let epochNanoseconds be ? ParseTemporalInstant(string).
  79. auto* epoch_nanoseconds = TRY(parse_temporal_instant(vm, string));
  80. // 4. Return ! CreateTemporalInstant(ℤ(epochNanoseconds)).
  81. return create_temporal_instant(vm, *epoch_nanoseconds);
  82. }
  83. // 8.5.4 ParseTemporalInstant ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalinstant
  84. ThrowCompletionOr<BigInt*> parse_temporal_instant(VM& vm, String const& iso_string)
  85. {
  86. // 1. Assert: Type(isoString) is String.
  87. // 2. Let result be ? ParseTemporalInstantString(isoString).
  88. auto result = TRY(parse_temporal_instant_string(vm, 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(vm, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond);
  95. // 6. Let offsetNanoseconds be ? ParseTimeZoneOffsetString(offsetString).
  96. auto offset_nanoseconds = TRY(parse_time_zone_offset_string(vm, *offset_string));
  97. // 7. Let result be utc - ℤ(offsetNanoseconds).
  98. auto* result_ns = js_bigint(vm, utc->big_integer().minus(Crypto::SignedBigInteger { offset_nanoseconds }));
  99. // 8. If ! IsValidEpochNanoseconds(result) is false, then
  100. if (!is_valid_epoch_nanoseconds(*result_ns)) {
  101. // a. Throw a RangeError exception.
  102. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  103. }
  104. // 9. Return result.
  105. return result_ns;
  106. }
  107. // 8.5.5 CompareEpochNanoseconds ( epochNanosecondsOne, epochNanosecondsTwo ), https://tc39.es/proposal-temporal/#sec-temporal-compareepochnanoseconds
  108. i32 compare_epoch_nanoseconds(BigInt const& epoch_nanoseconds_one, BigInt const& epoch_nanoseconds_two)
  109. {
  110. // 1. If epochNanosecondsOne > epochNanosecondsTwo, return 1.
  111. if (epoch_nanoseconds_one.big_integer() > epoch_nanoseconds_two.big_integer())
  112. return 1;
  113. // 2. If epochNanosecondsOne < epochNanosecondsTwo, return -1.
  114. if (epoch_nanoseconds_one.big_integer() < epoch_nanoseconds_two.big_integer())
  115. return -1;
  116. // 3. Return 0.
  117. return 0;
  118. }
  119. // 8.5.6 AddInstant ( epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-addinstant
  120. ThrowCompletionOr<BigInt*> add_instant(VM& vm, BigInt const& epoch_nanoseconds, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds)
  121. {
  122. VERIFY(hours == trunc(hours) && minutes == trunc(minutes) && seconds == trunc(seconds) && milliseconds == trunc(milliseconds) && microseconds == trunc(microseconds) && nanoseconds == trunc(nanoseconds));
  123. // 1. Let result be epochNanoseconds + ℤ(nanoseconds) + ℤ(microseconds) × 1000ℤ + ℤ(milliseconds) × 10^6ℤ + ℤ(seconds) × 10^9ℤ + ℤ(minutes) × 60ℤ × 10^9ℤ + ℤ(hours) × 3600ℤ × 10^9ℤ.
  124. auto* result = js_bigint(vm,
  125. epoch_nanoseconds.big_integer()
  126. .plus(Crypto::SignedBigInteger { nanoseconds })
  127. .plus(Crypto::SignedBigInteger { microseconds }.multiplied_by(Crypto::SignedBigInteger { 1'000 }))
  128. .plus(Crypto::SignedBigInteger { milliseconds }.multiplied_by(Crypto::SignedBigInteger { 1'000'000 }))
  129. .plus(Crypto::SignedBigInteger { seconds }.multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  130. .plus(Crypto::SignedBigInteger { minutes }.multiplied_by(Crypto::SignedBigInteger { 60 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 }))
  131. .plus(Crypto::SignedBigInteger { hours }.multiplied_by(Crypto::SignedBigInteger { 3600 }).multiplied_by(Crypto::SignedBigInteger { 1'000'000'000 })));
  132. // 2. If ! IsValidEpochNanoseconds(result) is false, throw a RangeError exception.
  133. if (!is_valid_epoch_nanoseconds(*result))
  134. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidEpochNanoseconds);
  135. // 3. Return result.
  136. return result;
  137. }
  138. // 8.5.7 DifferenceInstant ( ns1, ns2, roundingIncrement, smallestUnit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-differenceinstant
  139. BigInt* difference_instant(VM& vm, BigInt const& nanoseconds1, BigInt const& nanoseconds2, u64 rounding_increment, StringView smallest_unit, StringView rounding_mode)
  140. {
  141. // 1. Assert: Type(ns1) is BigInt.
  142. // 2. Assert: Type(ns2) is BigInt.
  143. // 3. Return ! RoundTemporalInstant(ns2 - ns1, roundingIncrement, smallestUnit, roundingMode).
  144. return round_temporal_instant(vm, *js_bigint(vm, nanoseconds2.big_integer().minus(nanoseconds1.big_integer())), rounding_increment, smallest_unit, rounding_mode);
  145. }
  146. // 8.5.8 RoundTemporalInstant ( ns, increment, unit, roundingMode ), https://tc39.es/proposal-temporal/#sec-temporal-roundtemporalinstant
  147. BigInt* round_temporal_instant(VM& vm, BigInt const& nanoseconds, u64 increment, StringView unit, StringView rounding_mode)
  148. {
  149. // 1. Assert: Type(ns) is BigInt.
  150. u64 increment_nanoseconds;
  151. // 2. If unit is "hour", then
  152. if (unit == "hour"sv) {
  153. // a. Let incrementNs be increment × 3.6 × 10^12.
  154. increment_nanoseconds = increment * 3600000000000;
  155. }
  156. // 3. Else if unit is "minute", then
  157. else if (unit == "minute"sv) {
  158. // a. Let incrementNs be increment × 6 × 10^10.
  159. increment_nanoseconds = increment * 60000000000;
  160. }
  161. // 4. Else if unit is "second", then
  162. else if (unit == "second"sv) {
  163. // a. Let incrementNs be increment × 10^9.
  164. increment_nanoseconds = increment * 1000000000;
  165. }
  166. // 5. Else if unit is "millisecond", then
  167. else if (unit == "millisecond"sv) {
  168. // a. Let incrementNs be increment × 10^6.
  169. increment_nanoseconds = increment * 1000000;
  170. }
  171. // 6. Else if unit is "microsecond", then
  172. else if (unit == "microsecond"sv) {
  173. // a. Let incrementNs be increment × 10^3.
  174. increment_nanoseconds = increment * 1000;
  175. }
  176. // 7. Else,
  177. else {
  178. // a. Assert: unit is "nanosecond".
  179. VERIFY(unit == "nanosecond"sv);
  180. // b. Let incrementNs be increment.
  181. increment_nanoseconds = increment;
  182. }
  183. // 8. Return RoundNumberToIncrementAsIfPositive(ℝ(ns), incrementNs, roundingMode).
  184. return js_bigint(vm, round_number_to_increment_as_if_positive(nanoseconds.big_integer(), increment_nanoseconds, rounding_mode));
  185. }
  186. // 8.5.9 TemporalInstantToString ( instant, timeZone, precision ), https://tc39.es/proposal-temporal/#sec-temporal-temporalinstanttostring
  187. ThrowCompletionOr<String> temporal_instant_to_string(VM& vm, Instant& instant, Value time_zone, Variant<StringView, u8> const& precision)
  188. {
  189. // 1. Assert: Type(instant) is Object.
  190. // 2. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  191. // 3. Let outputTimeZone be timeZone.
  192. auto output_time_zone = time_zone;
  193. // 4. If outputTimeZone is undefined, then
  194. if (output_time_zone.is_undefined()) {
  195. // a. Set outputTimeZone to ! CreateTemporalTimeZone("UTC").
  196. output_time_zone = MUST(create_temporal_time_zone(vm, "UTC"sv));
  197. }
  198. // 5. Let isoCalendar be ! GetISO8601Calendar().
  199. auto* iso_calendar = get_iso8601_calendar(vm);
  200. // 6. Let dateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(outputTimeZone, instant, isoCalendar).
  201. auto* date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, output_time_zone, instant, *iso_calendar));
  202. // 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").
  203. 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));
  204. String time_zone_string;
  205. // 8. If timeZone is undefined, then
  206. if (time_zone.is_undefined()) {
  207. // a. Let timeZoneString be "Z".
  208. time_zone_string = "Z"sv;
  209. }
  210. // 9. Else,
  211. else {
  212. // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
  213. auto offset_ns = TRY(get_offset_nanoseconds_for(vm, time_zone, instant));
  214. // b. Let timeZoneString be ! FormatISOTimeZoneOffsetString(offsetNs).
  215. time_zone_string = format_iso_time_zone_offset_string(offset_ns);
  216. }
  217. // 10. Return the string-concatenation of dateTimeString and timeZoneString.
  218. return String::formatted("{}{}", date_time_string, time_zone_string);
  219. }
  220. // 8.5.10 DifferenceTemporalInstant ( operation, instant, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalinstant
  221. ThrowCompletionOr<Duration*> difference_temporal_instant(VM& vm, DifferenceOperation operation, Instant const& instant, Value other_value, Value options_value)
  222. {
  223. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  224. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  225. // 2. Set other to ? ToTemporalInstant(other).
  226. auto* other = TRY(to_temporal_instant(vm, other_value));
  227. // 3. Let settings be ? GetDifferenceSettings(operation, options, time, « », "nanosecond", "second").
  228. auto settings = TRY(get_difference_settings(vm, operation, options_value, UnitGroup::Time, {}, { "nanosecond"sv }, "second"sv));
  229. // 4. Let roundedNs be ! DifferenceInstant(instant.[[Nanoseconds]], other.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]]).
  230. auto* rounded_ns = difference_instant(vm, instant.nanoseconds(), other->nanoseconds(), settings.rounding_increment, settings.smallest_unit, settings.rounding_mode);
  231. // 5. Assert: The following steps cannot fail due to overflow in the Number domain because abs(roundedNs) ≤ 2 × nsMaxInstant.
  232. // 6. Let result be ! BalanceDuration(0, 0, 0, 0, 0, 0, roundedNs, settings.[[LargestUnit]]).
  233. auto result = MUST(balance_duration(vm, 0, 0, 0, 0, 0, 0, rounded_ns->big_integer(), settings.largest_unit));
  234. // 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]]).
  235. 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));
  236. }
  237. // 8.5.11 AddDurationToOrSubtractDurationFromInstant ( operation, instant, temporalDurationLike ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfrominstant
  238. ThrowCompletionOr<Instant*> add_duration_to_or_subtract_duration_from_instant(VM& vm, ArithmeticOperation operation, Instant const& instant, Value temporal_duration_like)
  239. {
  240. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  241. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  242. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  243. auto duration = TRY(to_temporal_duration_record(vm, temporal_duration_like));
  244. // 3. If duration.[[Days]] is not 0, throw a RangeError exception.
  245. if (duration.days != 0)
  246. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "days", duration.days);
  247. // 4. If duration.[[Months]] is not 0, throw a RangeError exception.
  248. if (duration.months != 0)
  249. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "months", duration.months);
  250. // 5. If duration.[[Weeks]] is not 0, throw a RangeError exception.
  251. if (duration.weeks != 0)
  252. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "weeks", duration.weeks);
  253. // 6. If duration.[[Years]] is not 0, throw a RangeError exception.
  254. if (duration.years != 0)
  255. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidDurationPropertyValueNonZero, "years", duration.years);
  256. // 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]]).
  257. 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));
  258. // 8. Return ! CreateTemporalInstant(ns).
  259. return MUST(create_temporal_instant(vm, *ns));
  260. }
  261. }