Instant.cpp 17 KB

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