PlainDateTime.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/TypeCasts.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/Completion.h>
  10. #include <LibJS/Runtime/Date.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/Duration.h>
  15. #include <LibJS/Runtime/Temporal/Instant.h>
  16. #include <LibJS/Runtime/Temporal/PlainDate.h>
  17. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  18. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  19. #include <LibJS/Runtime/Temporal/PlainTime.h>
  20. #include <LibJS/Runtime/Temporal/TimeZone.h>
  21. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  22. namespace JS::Temporal {
  23. JS_DEFINE_ALLOCATOR(PlainDateTime);
  24. // 5 Temporal.PlainDateTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindatetime-objects
  25. PlainDateTime::PlainDateTime(i32 iso_year, u8 iso_month, u8 iso_day, u8 iso_hour, u8 iso_minute, u8 iso_second, u16 iso_millisecond, u16 iso_microsecond, u16 iso_nanosecond, Object& calendar, Object& prototype)
  26. : Object(ConstructWithPrototypeTag::Tag, prototype)
  27. , m_iso_year(iso_year)
  28. , m_iso_month(iso_month)
  29. , m_iso_day(iso_day)
  30. , m_iso_hour(iso_hour)
  31. , m_iso_minute(iso_minute)
  32. , m_iso_second(iso_second)
  33. , m_iso_millisecond(iso_millisecond)
  34. , m_iso_microsecond(iso_microsecond)
  35. , m_iso_nanosecond(iso_nanosecond)
  36. , m_calendar(calendar)
  37. {
  38. }
  39. void PlainDateTime::visit_edges(Visitor& visitor)
  40. {
  41. Base::visit_edges(visitor);
  42. visitor.visit(m_calendar);
  43. }
  44. // nsMinInstant - nsPerDay
  45. auto const DATETIME_NANOSECONDS_MIN = "-8640000086400000000000"_sbigint;
  46. // nsMaxInstant + nsPerDay
  47. auto const DATETIME_NANOSECONDS_MAX = "8640000086400000000000"_sbigint;
  48. // 5.5.1 ISODateTimeWithinLimits ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetimewithinlimits
  49. bool iso_date_time_within_limits(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  50. {
  51. // 1. Assert: IsValidISODate(year, month, day) is true.
  52. VERIFY(is_valid_iso_date(year, month, day));
  53. // 2. Let ns be ℝ(GetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond)).
  54. auto ns = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  55. // 3. If ns ≤ nsMinInstant - nsPerDay, then
  56. if (ns <= DATETIME_NANOSECONDS_MIN) {
  57. // a. Return false.
  58. return false;
  59. }
  60. // 4. If ns ≥ nsMaxInstant + nsPerDay, then
  61. if (ns >= DATETIME_NANOSECONDS_MAX) {
  62. // a. Return false.
  63. return false;
  64. }
  65. // 5. Return true.
  66. return true;
  67. }
  68. // 5.5.2 InterpretTemporalDateTimeFields ( calendar, fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-interprettemporaldatetimefields
  69. ThrowCompletionOr<ISODateTime> interpret_temporal_date_time_fields(VM& vm, Object& calendar, Object& fields, Object const* options)
  70. {
  71. // 1. Let timeResult be ? ToTemporalTimeRecord(fields).
  72. auto unregulated_time_result = TRY(to_temporal_time_record(vm, fields));
  73. // 2. Let overflow be ? ToTemporalOverflow(options).
  74. auto overflow = TRY(to_temporal_overflow(vm, options));
  75. // 3. Let temporalDate be ? CalendarDateFromFields(calendar, fields, options).
  76. auto* temporal_date = TRY(calendar_date_from_fields(vm, calendar, fields, options));
  77. // 4. Let timeResult be ? RegulateTime(timeResult.[[Hour]], timeResult.[[Minute]], timeResult.[[Second]], timeResult.[[Millisecond]], timeResult.[[Microsecond]], timeResult.[[Nanosecond]], overflow).
  78. auto time_result = TRY(regulate_time(vm, *unregulated_time_result.hour, *unregulated_time_result.minute, *unregulated_time_result.second, *unregulated_time_result.millisecond, *unregulated_time_result.microsecond, *unregulated_time_result.nanosecond, overflow));
  79. // 5. Return the Record { [[Year]]: temporalDate.[[ISOYear]], [[Month]]: temporalDate.[[ISOMonth]], [[Day]]: temporalDate.[[ISODay]], [[Hour]]: timeResult.[[Hour]], [[Minute]]: timeResult.[[Minute]], [[Second]]: timeResult.[[Second]], [[Millisecond]]: timeResult.[[Millisecond]], [[Microsecond]]: timeResult.[[Microsecond]], [[Nanosecond]]: timeResult.[[Nanosecond]] }.
  80. return ISODateTime {
  81. .year = temporal_date->iso_year(),
  82. .month = temporal_date->iso_month(),
  83. .day = temporal_date->iso_day(),
  84. .hour = time_result.hour,
  85. .minute = time_result.minute,
  86. .second = time_result.second,
  87. .millisecond = time_result.millisecond,
  88. .microsecond = time_result.microsecond,
  89. .nanosecond = time_result.nanosecond,
  90. };
  91. }
  92. // 5.5.3 ToTemporalDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetime
  93. ThrowCompletionOr<PlainDateTime*> to_temporal_date_time(VM& vm, Value item, Object const* options)
  94. {
  95. // 1. If options is not present, set options to undefined.
  96. // 2. Assert: Type(options) is Object or Undefined.
  97. Object* calendar;
  98. ISODateTime result;
  99. // 3. If Type(item) is Object, then
  100. if (item.is_object()) {
  101. auto& item_object = item.as_object();
  102. // a. If item has an [[InitializedTemporalDateTime]] internal slot, then
  103. if (is<PlainDateTime>(item_object)) {
  104. // i. Return item.
  105. return &static_cast<PlainDateTime&>(item_object);
  106. }
  107. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  108. if (is<ZonedDateTime>(item_object)) {
  109. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  110. // i. Perform ? ToTemporalOverflow(options).
  111. (void)TRY(to_temporal_overflow(vm, options));
  112. // ii. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  113. auto* instant = create_temporal_instant(vm, zoned_date_time.nanoseconds()).release_value();
  114. // iii. Return ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  115. return builtin_time_zone_get_plain_date_time_for(vm, &zoned_date_time.time_zone(), *instant, zoned_date_time.calendar());
  116. }
  117. // c. If item has an [[InitializedTemporalDate]] internal slot, then
  118. if (is<PlainDate>(item_object)) {
  119. auto& plain_date = static_cast<PlainDate&>(item_object);
  120. // i. Perform ? ToTemporalOverflow(options).
  121. (void)TRY(to_temporal_overflow(vm, options));
  122. // ii. Return ? CreateTemporalDateTime(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], 0, 0, 0, 0, 0, 0, item.[[Calendar]]).
  123. return create_temporal_date_time(vm, plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day(), 0, 0, 0, 0, 0, 0, plain_date.calendar());
  124. }
  125. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  126. calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object));
  127. // e. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  128. auto field_names = TRY(calendar_fields(vm, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv }));
  129. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  130. auto* fields = TRY(prepare_temporal_fields(vm, item_object, field_names, Vector<StringView> {}));
  131. // g. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
  132. result = TRY(interpret_temporal_date_time_fields(vm, *calendar, *fields, options));
  133. }
  134. // 4. Else,
  135. else {
  136. // a. Perform ? ToTemporalOverflow(options).
  137. (void)TRY(to_temporal_overflow(vm, options));
  138. // b. Let string be ? ToString(item).
  139. auto string = TRY(item.to_string(vm));
  140. // c. Let result be ? ParseTemporalDateTimeString(string).
  141. result = TRY(parse_temporal_date_time_string(vm, string));
  142. // d. Assert: IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  143. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  144. // e. Assert: IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]) is true.
  145. VERIFY(is_valid_time(result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond));
  146. // f. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  147. calendar = TRY(to_temporal_calendar_with_iso_default(vm, result.calendar.has_value() ? PrimitiveString::create(vm, *result.calendar) : js_undefined()));
  148. }
  149. // 5. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
  150. return create_temporal_date_time(vm, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, *calendar);
  151. }
  152. // 5.5.4 BalanceISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodatetime
  153. ISODateTime balance_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, i64 nanosecond)
  154. {
  155. // NOTE: The only use of this AO is in BuiltinTimeZoneGetPlainDateTimeFor, where we know that all values
  156. // but `nanosecond` are in their usual range, hence why that's the only outlier here. The range for that
  157. // is -86400000000000 to 86400000000999, so an i32 is not enough.
  158. // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  159. // 2. Let balancedTime be ! BalanceTime(hour, minute, second, millisecond, microsecond, nanosecond).
  160. auto balanced_time = balance_time(hour, minute, second, millisecond, microsecond, nanosecond);
  161. // 3. Let balancedDate be BalanceISODate(year, month, day + balancedTime.[[Days]]).
  162. auto balanced_date = balance_iso_date(year, month, day + balanced_time.days);
  163. // 4. Return the Record { [[Year]]: balancedDate.[[Year]], [[Month]]: balancedDate.[[Month]], [[Day]]: balancedDate.[[Day]], [[Hour]]: balancedTime.[[Hour]], [[Minute]]: balancedTime.[[Minute]], [[Second]]: balancedTime.[[Second]], [[Millisecond]]: balancedTime.[[Millisecond]], [[Microsecond]]: balancedTime.[[Microsecond]], [[Nanosecond]]: balancedTime.[[Nanosecond]] }.
  164. return ISODateTime { .year = balanced_date.year, .month = balanced_date.month, .day = balanced_date.day, .hour = balanced_time.hour, .minute = balanced_time.minute, .second = balanced_time.second, .millisecond = balanced_time.millisecond, .microsecond = balanced_time.microsecond, .nanosecond = balanced_time.nanosecond };
  165. }
  166. // 5.5.5 CreateTemporalDateTime ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldatetime
  167. ThrowCompletionOr<PlainDateTime*> create_temporal_date_time(VM& vm, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, FunctionObject const* new_target)
  168. {
  169. auto& realm = *vm.current_realm();
  170. // 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  171. // 2. Assert: Type(calendar) is Object.
  172. // 3. If IsValidISODate(isoYear, isoMonth, isoDay) is false, throw a RangeError exception.
  173. if (!is_valid_iso_date(iso_year, iso_month, iso_day))
  174. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDateTime);
  175. // 4. If IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  176. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond))
  177. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDateTime);
  178. // 5. If ISODateTimeWithinLimits(isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond) is false, then
  179. if (!iso_date_time_within_limits(iso_year, iso_month, iso_day, hour, minute, second, millisecond, microsecond, nanosecond)) {
  180. // a. Throw a RangeError exception.
  181. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDateTime);
  182. }
  183. // 6. If newTarget is not present, set newTarget to %Temporal.PlainDateTime%.
  184. if (!new_target)
  185. new_target = realm.intrinsics().temporal_plain_date_time_constructor();
  186. // 7. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainDateTime.prototype%", « [[InitializedTemporalDateTime]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[ISOHour]], [[ISOMinute]], [[ISOSecond]], [[ISOMillisecond]], [[ISOMicrosecond]], [[ISONanosecond]], [[Calendar]] »).
  187. // 8. Set object.[[ISOYear]] to isoYear.
  188. // 9. Set object.[[ISOMonth]] to isoMonth.
  189. // 10. Set object.[[ISODay]] to isoDay.
  190. // 11. Set object.[[ISOHour]] to hour.
  191. // 12. Set object.[[ISOMinute]] to minute.
  192. // 13. Set object.[[ISOSecond]] to second.
  193. // 14. Set object.[[ISOMillisecond]] to millisecond.
  194. // 15. Set object.[[ISOMicrosecond]] to microsecond.
  195. // 16. Set object.[[ISONanosecond]] to nanosecond.
  196. // 17. Set object.[[Calendar]] to calendar.
  197. auto object = TRY(ordinary_create_from_constructor<PlainDateTime>(vm, *new_target, &Intrinsics::temporal_plain_date_prototype, iso_year, iso_month, iso_day, hour, minute, second, millisecond, microsecond, nanosecond, calendar));
  198. // 18. Return object.
  199. return object.ptr();
  200. }
  201. // 5.5.6 TemporalDateTimeToString ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar, precision, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetimetostring
  202. ThrowCompletionOr<String> temporal_date_time_to_string(VM& vm, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object const* calendar, Variant<StringView, u8> const& precision, StringView show_calendar)
  203. {
  204. // 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  205. // 2. Let year be ! PadISOYear(isoYear).
  206. // 3. Let month be ToZeroPaddedDecimalString(isoMonth, 2).
  207. // 4. Let day be ToZeroPaddedDecimalString(isoDay, 2).
  208. // 5. Let hour be ToZeroPaddedDecimalString(hour, 2).
  209. // 6. Let minute be ToZeroPaddedDecimalString(minute, 2).
  210. // 7. Let seconds be ! FormatSecondsStringPart(second, millisecond, microsecond, nanosecond, precision).
  211. auto seconds = MUST_OR_THROW_OOM(format_seconds_string_part(vm, second, millisecond, microsecond, nanosecond, precision));
  212. // 8. Let calendarString be ? MaybeFormatCalendarAnnotation(calendar, showCalendar).
  213. auto calendar_string = TRY(maybe_format_calendar_annotation(vm, calendar, show_calendar));
  214. // 9. Return the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), month, the code unit 0x002D (HYPHEN-MINUS), day, 0x0054 (LATIN CAPITAL LETTER T), hour, the code unit 0x003A (COLON), minute, seconds, and calendarString.
  215. return TRY_OR_THROW_OOM(vm, String::formatted("{}-{:02}-{:02}T{:02}:{:02}{}{}", MUST_OR_THROW_OOM(pad_iso_year(vm, iso_year)), iso_month, iso_day, hour, minute, seconds, calendar_string));
  216. }
  217. // 5.5.7 CompareISODateTime ( y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, ns2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodatetime
  218. i8 compare_iso_date_time(i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2)
  219. {
  220. // 1. Assert: y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, and ns2 are integers.
  221. // 2. Let dateResult be ! CompareISODate(y1, mon1, d1, y2, mon2, d2).
  222. auto date_result = compare_iso_date(year1, month1, day1, year2, month2, day2);
  223. // 3. If dateResult is not 0, then
  224. if (date_result != 0) {
  225. // a. Return dateResult.
  226. return date_result;
  227. }
  228. // 4. Return ! CompareTemporalTime(h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, ns2).
  229. return compare_temporal_time(hour1, minute1, second1, millisecond1, microsecond1, nanosecond1, hour2, minute2, second2, millisecond2, microsecond2, nanosecond2);
  230. }
  231. // 5.5.8 AddDateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, options ), https://tc39.es/proposal-temporal/#sec-temporal-adddatetime
  232. ThrowCompletionOr<TemporalPlainDateTime> add_date_time(VM& vm, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options)
  233. {
  234. // 1. Assert: ISODateTimeWithinLimits(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond) is true.
  235. VERIFY(iso_date_time_within_limits(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond));
  236. // 2. Let timeResult be ! AddTime(hour, minute, second, millisecond, microsecond, nanosecond, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  237. auto time_result = add_time(hour, minute, second, millisecond, microsecond, nanosecond, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  238. // 3. Let datePart be ! CreateTemporalDate(year, month, day, calendar).
  239. auto* date_part = MUST(create_temporal_date(vm, year, month, day, calendar));
  240. // 4. Let dateDuration be ? CreateTemporalDuration(years, months, weeks, days + timeResult.[[Days]], 0, 0, 0, 0, 0, 0).
  241. auto date_duration = TRY(create_temporal_duration(vm, years, months, weeks, days + time_result.days, 0, 0, 0, 0, 0, 0));
  242. // 5. Let addedDate be ? CalendarDateAdd(calendar, datePart, dateDuration, options).
  243. auto* added_date = TRY(calendar_date_add(vm, calendar, date_part, *date_duration, options));
  244. // 6. Return the Record { [[Year]]: addedDate.[[ISOYear]], [[Month]]: addedDate.[[ISOMonth]], [[Day]]: addedDate.[[ISODay]], [[Hour]]: timeResult.[[Hour]], [[Minute]]: timeResult.[[Minute]], [[Second]]: timeResult.[[Second]], [[Millisecond]]: timeResult.[[Millisecond]], [[Microsecond]]: timeResult.[[Microsecond]], [[Nanosecond]]: timeResult.[[Nanosecond]] }.
  245. return TemporalPlainDateTime { .year = added_date->iso_year(), .month = added_date->iso_month(), .day = added_date->iso_day(), .hour = time_result.hour, .minute = time_result.minute, .second = time_result.second, .millisecond = time_result.millisecond, .microsecond = time_result.microsecond, .nanosecond = time_result.nanosecond };
  246. }
  247. // 5.5.9 RoundISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode [ , dayLength ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundisodatetime
  248. ISODateTime round_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, u64 increment, StringView unit, StringView rounding_mode, Optional<double> day_length)
  249. {
  250. // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  251. // 2. Assert: ISODateTimeWithinLimits(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond) is true.
  252. VERIFY(iso_date_time_within_limits(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond));
  253. // 3. If dayLength is not present, set dayLength to nsPerDay.
  254. if (!day_length.has_value())
  255. day_length = ns_per_day;
  256. // 4. Let roundedTime be ! RoundTime(hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, roundingMode, dayLength).
  257. auto rounded_time = round_time(hour, minute, second, millisecond, microsecond, nanosecond, increment, unit, rounding_mode, day_length);
  258. // 5. Let balanceResult be BalanceISODate(year, month, day + roundedTime.[[Days]]).
  259. auto balance_result = balance_iso_date(year, month, day + rounded_time.days);
  260. // 6. Return the Record { [[Year]]: balanceResult.[[Year]], [[Month]]: balanceResult.[[Month]], [[Day]]: balanceResult.[[Day]], [[Hour]]: roundedTime.[[Hour]], [[Minute]]: roundedTime.[[Minute]], [[Second]]: roundedTime.[[Second]], [[Millisecond]]: roundedTime.[[Millisecond]], [[Microsecond]]: roundedTime.[[Microsecond]], [[Nanosecond]]: roundedTime.[[Nanosecond]] }.
  261. return ISODateTime { .year = balance_result.year, .month = balance_result.month, .day = balance_result.day, .hour = rounded_time.hour, .minute = rounded_time.minute, .second = rounded_time.second, .millisecond = rounded_time.millisecond, .microsecond = rounded_time.microsecond, .nanosecond = rounded_time.nanosecond };
  262. }
  263. // 5.5.10 DifferenceISODateTime ( y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, ns2, calendar, largestUnit, options ), https://tc39.es/proposal-temporal/#sec-temporal-differenceisodatetime
  264. ThrowCompletionOr<DurationRecord> difference_iso_date_time(VM& vm, i32 year1, u8 month1, u8 day1, u8 hour1, u8 minute1, u8 second1, u16 millisecond1, u16 microsecond1, u16 nanosecond1, i32 year2, u8 month2, u8 day2, u8 hour2, u8 minute2, u8 second2, u16 millisecond2, u16 microsecond2, u16 nanosecond2, Object& calendar, StringView largest_unit, Object const& options)
  265. {
  266. // 1. Assert: ISODateTimeWithinLimits(y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1) is true.
  267. VERIFY(iso_date_time_within_limits(year1, month1, day1, hour1, minute1, second1, millisecond1, microsecond1, nanosecond1));
  268. // 2. Assert: ISODateTimeWithinLimits(y2, mon2, d2, h2, min2, s2, ms2, mus2, ns2) is true.
  269. VERIFY(iso_date_time_within_limits(year2, month2, day2, hour2, minute2, second2, millisecond2, microsecond2, nanosecond2));
  270. // 3. Let timeDifference be ! DifferenceTime(h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, ns2).
  271. auto time_difference = difference_time(vm, hour1, minute1, second1, millisecond1, microsecond1, nanosecond1, hour2, minute2, second2, millisecond2, microsecond2, nanosecond2);
  272. // 4. Let timeSign be ! DurationSign(0, 0, 0, 0, timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]]).
  273. auto time_sign = duration_sign(0, 0, 0, 0, time_difference.hours, time_difference.minutes, time_difference.seconds, time_difference.milliseconds, time_difference.microseconds, time_difference.nanoseconds);
  274. // 5. Let dateSign be ! CompareISODate(y2, mon2, d2, y1, mon1, d1).
  275. auto date_sign = compare_iso_date(year2, month2, day2, year1, month1, day1);
  276. // 6. Let adjustedDate be CreateISODateRecord(y1, mon1, d1).
  277. auto adjusted_date = create_iso_date_record(year1, month1, day1);
  278. // 7. If timeSign is -dateSign, then
  279. if (time_sign == -date_sign) {
  280. // a. Set adjustedDate to BalanceISODate(adjustedDate.[[Year]], adjustedDate.[[Month]], adjustedDate.[[Day]] - timeSign).
  281. adjusted_date = balance_iso_date(adjusted_date.year, adjusted_date.month, adjusted_date.day - time_sign);
  282. // b. Set timeDifference to ! BalanceDuration(-timeSign, timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]], largestUnit).
  283. time_difference = MUST(balance_duration(vm, -time_sign, time_difference.hours, time_difference.minutes, time_difference.seconds, time_difference.milliseconds, time_difference.microseconds, Crypto::SignedBigInteger { time_difference.nanoseconds }, largest_unit));
  284. }
  285. // 8. Let date1 be ! CreateTemporalDate(adjustedDate.[[Year]], adjustedDate.[[Month]], adjustedDate.[[Day]], calendar).
  286. auto* date1 = MUST(create_temporal_date(vm, adjusted_date.year, adjusted_date.month, adjusted_date.day, calendar));
  287. // 9. Let date2 be ! CreateTemporalDate(y2, mon2, d2, calendar).
  288. auto* date2 = MUST(create_temporal_date(vm, year2, month2, day2, calendar));
  289. // 10. Let dateLargestUnit be ! LargerOfTwoTemporalUnits("day", largestUnit).
  290. auto date_largest_unit = larger_of_two_temporal_units("day"sv, largest_unit);
  291. // 11. Let untilOptions be ? MergeLargestUnitOption(options, dateLargestUnit).
  292. auto* until_options = TRY(merge_largest_unit_option(vm, options, TRY_OR_THROW_OOM(vm, String::from_utf8(date_largest_unit))));
  293. // 12. Let dateDifference be ? CalendarDateUntil(calendar, date1, date2, untilOptions).
  294. // FIXME: AD-HOC calendar records use as this AO is not up to date with latest spec
  295. auto calendar_record = TRY(create_calendar_methods_record(vm, NonnullGCPtr<Object> { calendar }, { { CalendarMethod::DateAdd, CalendarMethod::DateUntil } }));
  296. auto date_difference = TRY(calendar_date_until(vm, calendar_record, date1, date2, *until_options));
  297. // 13. Let balanceResult be ? BalanceDuration(dateDifference.[[Days]], timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]], largestUnit).
  298. auto balance_result = TRY(balance_duration(vm, date_difference->days(), time_difference.hours, time_difference.minutes, time_difference.seconds, time_difference.milliseconds, time_difference.microseconds, Crypto::SignedBigInteger { time_difference.nanoseconds }, largest_unit));
  299. // 14. Return ! CreateDurationRecord(dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], balanceResult.[[Days]], balanceResult.[[Hours]], balanceResult.[[Minutes]], balanceResult.[[Seconds]], balanceResult.[[Milliseconds]], balanceResult.[[Microseconds]], balanceResult.[[Nanoseconds]]).
  300. return create_duration_record(date_difference->years(), date_difference->months(), date_difference->weeks(), balance_result.days, balance_result.hours, balance_result.minutes, balance_result.seconds, balance_result.milliseconds, balance_result.microseconds, balance_result.nanoseconds);
  301. }
  302. // 5.5.11 DifferenceTemporalPlainDateTime ( operation, dateTime, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalplaindatetime
  303. ThrowCompletionOr<NonnullGCPtr<Duration>> difference_temporal_plain_date_time(VM& vm, DifferenceOperation operation, PlainDateTime& date_time, Value other_value, Value options_value)
  304. {
  305. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  306. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  307. // 2. Set other to ? ToTemporalDateTime(other).
  308. auto* other = TRY(to_temporal_date_time(vm, other_value));
  309. // 3. If ? CalendarEquals(dateTime.[[Calendar]], other.[[Calendar]]) is false, throw a RangeError exception.
  310. if (!TRY(calendar_equals(vm, date_time.calendar(), other->calendar())))
  311. return vm.throw_completion<RangeError>(ErrorType::TemporalDifferentCalendars);
  312. // 4. Let settings be ? GetDifferenceSettings(operation, options, datetime, « », "nanosecond", "day").
  313. auto settings = TRY(get_difference_settings(vm, operation, options_value, UnitGroup::DateTime, {}, { "nanosecond"sv }, "day"sv));
  314. // 5. Let diff be ? DifferenceISODateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], other.[[ISOYear]], other.[[ISOMonth]], other.[[ISODay]], other.[[ISOHour]], other.[[ISOMinute]], other.[[ISOSecond]], other.[[ISOMillisecond]], other.[[ISOMicrosecond]], other.[[ISONanosecond]], dateTime.[[Calendar]], settings.[[LargestUnit]], settings.[[Options]]).
  315. auto diff = TRY(difference_iso_date_time(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(), other->iso_year(), other->iso_month(), other->iso_day(), other->iso_hour(), other->iso_minute(), other->iso_second(), other->iso_millisecond(), other->iso_microsecond(), other->iso_nanosecond(), date_time.calendar(), settings.largest_unit, settings.options));
  316. // 6. Let relativeTo be ! CreateTemporalDate(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[Calendar]]).
  317. auto* relative_to = MUST(create_temporal_date(vm, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.calendar()));
  318. // 7. Let roundResult be (? RoundDuration(diff.[[Years]], diff.[[Months]], diff.[[Weeks]], diff.[[Days]], diff.[[Hours]], diff.[[Minutes]], diff.[[Seconds]], diff.[[Milliseconds]], diff.[[Microseconds]], diff.[[Nanoseconds]], settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]], relativeTo)).[[DurationRecord]].
  319. // FIXME: AD-HOC calendar records use as this AO is not up to date with latest spec
  320. auto calendar_record = TRY(create_calendar_methods_record(vm, NonnullGCPtr<Object> { date_time.calendar() }, { { CalendarMethod::DateAdd, CalendarMethod::DateUntil } }));
  321. auto round_result = TRY(round_duration(vm, diff.years, diff.months, diff.weeks, diff.days, diff.hours, diff.minutes, diff.seconds, diff.milliseconds, diff.microseconds, diff.nanoseconds, settings.rounding_increment, settings.smallest_unit, settings.rounding_mode, relative_to, calendar_record)).duration_record;
  322. // 8. Let result be ? BalanceDuration(roundResult.[[Days]], roundResult.[[Hours]], roundResult.[[Minutes]], roundResult.[[Seconds]], roundResult.[[Milliseconds]], roundResult.[[Microseconds]], roundResult.[[Nanoseconds]], settings.[[LargestUnit]]).
  323. auto result = MUST(balance_duration(vm, round_result.days, round_result.hours, round_result.minutes, round_result.seconds, round_result.milliseconds, round_result.microseconds, Crypto::SignedBigInteger { round_result.nanoseconds }, settings.largest_unit));
  324. // 9. Return ! CreateTemporalDuration(sign × roundResult.[[Years]], sign × roundResult.[[Months]], sign × roundResult.[[Weeks]], sign × result.[[Days]], sign × result.[[Hours]], sign × result.[[Minutes]], sign × result.[[Seconds]], sign × result.[[Milliseconds]], sign × result.[[Microseconds]], sign × result.[[Nanoseconds]]).
  325. return MUST(create_temporal_duration(vm, sign * round_result.years, sign * round_result.months, sign * round_result.weeks, sign * result.days, sign * result.hours, sign * result.minutes, sign * result.seconds, sign * result.milliseconds, sign * result.microseconds, sign * result.nanoseconds));
  326. }
  327. // 5.5.12 AddDurationToOrSubtractDurationFromPlainDateTime ( operation, dateTime, temporalDurationLike, options ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfromplaindatetime
  328. ThrowCompletionOr<PlainDateTime*> add_duration_to_or_subtract_duration_from_plain_date_time(VM& vm, ArithmeticOperation operation, PlainDateTime& date_time, Value temporal_duration_like, Value options_value)
  329. {
  330. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  331. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  332. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  333. auto duration = TRY(to_temporal_duration_record(vm, temporal_duration_like));
  334. // 3. Set options to ? GetOptionsObject(options).
  335. auto* options = TRY(get_options_object(vm, options_value));
  336. // 4. Let result be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], dateTime.[[Calendar]], sign × duration.[[Years]], sign × duration.[[Months]], sign × duration.[[Weeks]], sign × duration.[[Days]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]], options).
  337. auto result = TRY(add_date_time(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(), date_time.calendar(), sign * duration.years, sign * duration.months, sign * duration.weeks, sign * duration.days, sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds, options));
  338. // 5. Assert: IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  339. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  340. // 6. Assert: IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]) is true.
  341. VERIFY(is_valid_time(result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond));
  342. // 7. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], dateTime.[[Calendar]]).
  343. return create_temporal_date_time(vm, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, date_time.calendar());
  344. }
  345. }