PlainDateTime.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Date.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  10. #include <LibJS/Runtime/Temporal/Calendar.h>
  11. #include <LibJS/Runtime/Temporal/Instant.h>
  12. #include <LibJS/Runtime/Temporal/PlainDate.h>
  13. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  14. #include <LibJS/Runtime/Temporal/PlainDateTimeConstructor.h>
  15. #include <LibJS/Runtime/Temporal/PlainTime.h>
  16. #include <LibJS/Runtime/Temporal/TimeZone.h>
  17. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  18. namespace JS::Temporal {
  19. // 5 Temporal.PlainDateTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindatetime-objects
  20. 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)
  21. : Object(prototype)
  22. , m_iso_year(iso_year)
  23. , m_iso_month(iso_month)
  24. , m_iso_day(iso_day)
  25. , m_iso_hour(iso_hour)
  26. , m_iso_minute(iso_minute)
  27. , m_iso_second(iso_second)
  28. , m_iso_millisecond(iso_millisecond)
  29. , m_iso_microsecond(iso_microsecond)
  30. , m_iso_nanosecond(iso_nanosecond)
  31. , m_calendar(calendar)
  32. {
  33. }
  34. void PlainDateTime::visit_edges(Visitor& visitor)
  35. {
  36. Base::visit_edges(visitor);
  37. visitor.visit(&m_calendar);
  38. }
  39. // 5.5.1 GetEpochFromISOParts ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-getepochfromisoparts
  40. BigInt* get_epoch_from_iso_parts(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  41. {
  42. auto& vm = global_object.vm();
  43. // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  44. // 2. Assert: ! IsValidISODate(year, month, day) is true.
  45. VERIFY(is_valid_iso_date(year, month, day));
  46. // 3. Assert: ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is true.
  47. VERIFY(is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond));
  48. // 4. Let date be ! MakeDay(𝔽(year), 𝔽(month − 1), 𝔽(day)).
  49. auto date = make_day(global_object, Value(year), Value(month - 1), Value(day));
  50. // 5. Let time be ! MakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond)).
  51. auto time = make_time(global_object, Value(hour), Value(minute), Value(second), Value(millisecond));
  52. // 6. Let ms be ! MakeDate(date, time).
  53. auto ms = make_date(date, time);
  54. // 7. Assert: ms is finite.
  55. VERIFY(ms.is_finite_number());
  56. // 8. Return ℝ(ms) × 10^6 + microsecond × 10^3 + nanosecond.
  57. return js_bigint(vm, Crypto::SignedBigInteger::create_from(static_cast<i64>(ms.as_double())).multiplied_by(Crypto::UnsignedBigInteger { 1'000'000 }).plus(Crypto::SignedBigInteger::create_from((i64)microsecond * 1000)).plus(Crypto::SignedBigInteger(nanosecond)));
  58. }
  59. // -864 * 10^19 - 864 * 10^11
  60. const auto DATETIME_NANOSECONDS_MIN = "-8640000086400000000000"_sbigint;
  61. // +864 * 10^19 + 864 * 10^11
  62. const auto DATETIME_NANOSECONDS_MAX = "8640000086400000000000"_sbigint;
  63. // 5.5.2 ISODateTimeWithinLimits ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-isodatetimewithinlimits
  64. bool iso_date_time_within_limits(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  65. {
  66. // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  67. // 2. Let ns be ! GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond).
  68. auto ns = get_epoch_from_iso_parts(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  69. // 3. If ns ≤ -8.64 × 10^21 - 8.64 × 10^13, then
  70. if (ns->big_integer() <= DATETIME_NANOSECONDS_MIN) {
  71. // a. Return false.
  72. return false;
  73. }
  74. // 4. If ns ≥ 8.64 × 10^21 + 8.64 × 10^13, then
  75. if (ns->big_integer() >= DATETIME_NANOSECONDS_MAX) {
  76. // a. Return false.
  77. return false;
  78. }
  79. // 5. Return true.
  80. return true;
  81. }
  82. // 5.5.3 InterpretTemporalDateTimeFields ( calendar, fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-interprettemporaldatetimefields
  83. Optional<ISODateTime> interpret_temporal_date_time_fields(GlobalObject& global_object, Object& calendar, Object& fields, Object& options)
  84. {
  85. auto& vm = global_object.vm();
  86. // 1. Let timeResult be ? ToTemporalTimeRecord(fields).
  87. auto unregulated_time_result = to_temporal_time_record(global_object, fields);
  88. if (vm.exception())
  89. return {};
  90. // 2. Let temporalDate be ? DateFromFields(calendar, fields, options).
  91. auto* temporal_date = date_from_fields(global_object, calendar, fields, options);
  92. if (vm.exception())
  93. return {};
  94. // 3. Let overflow be ? ToTemporalOverflow(options).
  95. auto overflow = to_temporal_overflow(global_object, options);
  96. if (vm.exception())
  97. return {};
  98. // 4. Let timeResult be ? RegulateTime(timeResult.[[Hour]], timeResult.[[Minute]], timeResult.[[Second]], timeResult.[[Millisecond]], timeResult.[[Microsecond]], timeResult.[[Nanosecond]], overflow).
  99. auto time_result = regulate_time(global_object, 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);
  100. if (vm.exception())
  101. return {};
  102. // 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]] }.
  103. return ISODateTime {
  104. .year = temporal_date->iso_year(),
  105. .month = temporal_date->iso_month(),
  106. .day = temporal_date->iso_day(),
  107. .hour = time_result->hour,
  108. .minute = time_result->minute,
  109. .second = time_result->second,
  110. .millisecond = time_result->millisecond,
  111. .microsecond = time_result->microsecond,
  112. .nanosecond = time_result->nanosecond,
  113. };
  114. }
  115. // 5.5.4 ToTemporalDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldatetime
  116. PlainDateTime* to_temporal_date_time(GlobalObject& global_object, Value item, Object* options)
  117. {
  118. auto& vm = global_object.vm();
  119. // 1. If options is not present, set options to ! OrdinaryObjectCreate(null).
  120. if (!options)
  121. options = Object::create(global_object, nullptr);
  122. Object* calendar;
  123. ISODateTime result;
  124. // 2. If Type(item) is Object, then
  125. if (item.is_object()) {
  126. auto& item_object = item.as_object();
  127. // a. If item has an [[InitializedTemporalDateTime]] internal slot, then
  128. if (is<PlainDateTime>(item_object)) {
  129. // i. Return item.
  130. return &static_cast<PlainDateTime&>(item_object);
  131. }
  132. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  133. if (is<ZonedDateTime>(item_object)) {
  134. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  135. // i. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  136. auto* instant = create_temporal_instant(global_object, zoned_date_time.nanoseconds());
  137. // ii. Return ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  138. return builtin_time_zone_get_plain_date_time_for(global_object, &zoned_date_time.time_zone(), *instant, zoned_date_time.calendar());
  139. }
  140. // c. If item has an [[InitializedTemporalDate]] internal slot, then
  141. if (is<PlainDate>(item_object)) {
  142. auto& plain_date = static_cast<PlainDate&>(item_object);
  143. // i. Return ? CreateTemporalDateTime(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], 0, 0, 0, 0, 0, 0, item.[[Calendar]]).
  144. return create_temporal_date_time(global_object, plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day(), 0, 0, 0, 0, 0, 0, plain_date.calendar());
  145. }
  146. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  147. calendar = get_temporal_calendar_with_iso_default(global_object, item_object);
  148. if (vm.exception())
  149. return {};
  150. // e. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  151. auto field_names = calendar_fields(global_object, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv });
  152. if (vm.exception())
  153. return {};
  154. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  155. auto* fields = prepare_temporal_fields(global_object, item_object, field_names, {});
  156. if (vm.exception())
  157. return {};
  158. // g. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
  159. auto maybe_result = interpret_temporal_date_time_fields(global_object, *calendar, *fields, *options);
  160. if (vm.exception())
  161. return {};
  162. result = move(*maybe_result);
  163. }
  164. // 3. Else,
  165. else {
  166. // a. Perform ? ToTemporalOverflow(options).
  167. (void)to_temporal_overflow(global_object, *options);
  168. if (vm.exception())
  169. return {};
  170. // b. Let string be ? ToString(item).
  171. auto string = item.to_string(global_object);
  172. if (vm.exception())
  173. return {};
  174. // c. Let result be ? ParseTemporalDateTimeString(string).
  175. auto maybe_result = parse_temporal_date_time_string(global_object, string);
  176. if (vm.exception())
  177. return {};
  178. result = move(*maybe_result);
  179. // d. Assert: ! IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  180. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  181. // e. Assert: ! IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]]) is true.
  182. VERIFY(is_valid_time(result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond));
  183. // f. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  184. calendar = to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined());
  185. if (vm.exception())
  186. return {};
  187. }
  188. // 4. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
  189. return create_temporal_date_time(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, *calendar);
  190. }
  191. // 5.5.5 BalanceISODateTime ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodatetime
  192. ISODateTime balance_iso_date_time(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, i64 nanosecond)
  193. {
  194. // NOTE: The only use of this AO is in BuiltinTimeZoneGetPlainDateTimeFor, where we know that all values
  195. // but `nanosecond` are in their usual range, hence why that's the only outlier here. The range for that
  196. // is -86400000000000 to 86400000000999, so an i32 is not enough.
  197. // 1. Assert: year, month, day, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  198. // 2. Let balancedTime be ! BalanceTime(hour, minute, second, millisecond, microsecond, nanosecond).
  199. auto balanced_time = balance_time(hour, minute, second, millisecond, microsecond, nanosecond);
  200. // 3. Let balancedDate be ! BalanceISODate(year, month, day + balancedTime.[[Days]]).
  201. auto balanced_date = balance_iso_date(year, month, day + balanced_time.days);
  202. // 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]] }.
  203. 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 };
  204. }
  205. // 5.5.6 CreateTemporalDateTime ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldatetime
  206. PlainDateTime* create_temporal_date_time(GlobalObject& global_object, 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)
  207. {
  208. auto& vm = global_object.vm();
  209. // 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  210. // 2. Assert: Type(calendar) is Object.
  211. // 3. If ! IsValidISODate(isoYear, isoMonth, isoDay) is false, throw a RangeError exception.
  212. if (!is_valid_iso_date(iso_year, iso_month, iso_day)) {
  213. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDateTime);
  214. return {};
  215. }
  216. // 4. If ! IsValidTime(hour, minute, second, millisecond, microsecond, nanosecond) is false, throw a RangeError exception.
  217. if (!is_valid_time(hour, minute, second, millisecond, microsecond, nanosecond)) {
  218. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDateTime);
  219. return {};
  220. }
  221. // 5. If ! ISODateTimeWithinLimits(isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond) is false, then
  222. if (!iso_date_time_within_limits(global_object, iso_year, iso_month, iso_day, hour, minute, second, millisecond, microsecond, nanosecond)) {
  223. // a. Throw a RangeError exception.
  224. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainDateTime);
  225. return {};
  226. }
  227. // 6. If newTarget is not present, set it to %Temporal.PlainDateTime%.
  228. if (!new_target)
  229. new_target = global_object.temporal_plain_date_time_constructor();
  230. // 7. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainDateTime.prototype%", « [[InitializedTemporalDateTime]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[ISOHour]], [[ISOMinute]], [[ISOSecond]], [[ISOMillisecond]], [[ISOMicrosecond]], [[ISONanosecond]], [[Calendar]] »).
  231. // 8. Set object.[[ISOYear]] to isoYear.
  232. // 9. Set object.[[ISOMonth]] to isoMonth.
  233. // 10. Set object.[[ISODay]] to isoDay.
  234. // 11. Set object.[[ISOHour]] to hour.
  235. // 12. Set object.[[ISOMinute]] to minute.
  236. // 13. Set object.[[ISOSecond]] to second.
  237. // 14. Set object.[[ISOMillisecond]] to millisecond.
  238. // 15. Set object.[[ISOMicrosecond]] to microsecond.
  239. // 16. Set object.[[ISONanosecond]] to nanosecond.
  240. // 17. Set object.[[Calendar]] to calendar.
  241. auto* object = ordinary_create_from_constructor<PlainDateTime>(global_object, *new_target, &GlobalObject::temporal_plain_date_prototype, iso_year, iso_month, iso_day, hour, minute, second, millisecond, microsecond, nanosecond, calendar);
  242. if (vm.exception())
  243. return {};
  244. // 18. Return object.
  245. return object;
  246. }
  247. // 5.5.7 TemporalDateTimeToString ( isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, nanosecond, calendar, precision, showCalendar ), , https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetimetostring
  248. Optional<String> temporal_date_time_to_string(GlobalObject& global_object, i32 iso_year, u8 iso_month, u8 iso_day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, Value calendar, Variant<StringView, u8> const& precision, StringView show_calendar)
  249. {
  250. auto& vm = global_object.vm();
  251. // 1. Assert: isoYear, isoMonth, isoDay, hour, minute, second, millisecond, microsecond, and nanosecond are integers.
  252. // 2. Let year be ! PadISOYear(isoYear).
  253. // 3. Let month be isoMonth formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  254. // 4. Let day be isoDay formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  255. // 5. Let hour be hour formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  256. // 6. Let minute be minute formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  257. // 7. Let seconds be ! FormatSecondsStringPart(second, millisecond, microsecond, nanosecond, precision).
  258. auto seconds = format_seconds_string_part(second, millisecond, microsecond, nanosecond, precision);
  259. // 8. Let calendarID be ? ToString(calendar).
  260. auto calendar_id = calendar.to_string(global_object);
  261. if (vm.exception())
  262. return {};
  263. // 9. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  264. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  265. // 10. 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.
  266. return String::formatted("{}-{:02}-{:02}T{:02}:{:02}{}{}", pad_iso_year(iso_year), iso_month, iso_day, hour, minute, seconds, calendar_string);
  267. }
  268. // 5.5.8 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
  269. 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)
  270. {
  271. // 1. Assert: y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, and ns2 are integers.
  272. // 2. Let dateResult be ! CompareISODate(y1, mon1, d1, y2, mon2, d2).
  273. auto date_result = compare_iso_date(year1, month1, day1, year2, month2, day2);
  274. // 3. If dateResult is not 0, then
  275. if (date_result != 0) {
  276. // a. Return dateResult.
  277. return date_result;
  278. }
  279. // 4. Return ! CompareTemporalTime(h1, min1, s1, ms1, mus1, ns1, h2, min2, s2, ms2, mus2, ns2).
  280. return compare_temporal_time(hour1, minute1, second1, millisecond1, microsecond1, nanosecond1, hour2, minute2, second2, millisecond2, microsecond2, nanosecond2);
  281. }
  282. }