PlainDate.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/TypeCasts.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Completion.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/GlobalObject.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/PlainDateConstructor.h>
  18. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  19. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  20. #include <LibJS/Runtime/Temporal/TimeZone.h>
  21. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  22. namespace JS::Temporal {
  23. JS_DEFINE_ALLOCATOR(PlainDate);
  24. // 3 Temporal.PlainDate Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindate-objects
  25. PlainDate::PlainDate(i32 year, u8 month, u8 day, Object& calendar, Object& prototype)
  26. : Object(ConstructWithPrototypeTag::Tag, prototype)
  27. , m_iso_year(year)
  28. , m_iso_month(month)
  29. , m_iso_day(day)
  30. , m_calendar(calendar)
  31. {
  32. }
  33. void PlainDate::visit_edges(Visitor& visitor)
  34. {
  35. Base::visit_edges(visitor);
  36. visitor.visit(m_calendar);
  37. }
  38. // 3.5.2 CreateISODateRecord ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-create-iso-date-record
  39. ISODateRecord create_iso_date_record(i32 year, u8 month, u8 day)
  40. {
  41. // 1. Assert: IsValidISODate(year, month, day) is true.
  42. VERIFY(is_valid_iso_date(year, month, day));
  43. // 2. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  44. return { .year = year, .month = month, .day = day };
  45. }
  46. // 3.5.1 CreateTemporalDate ( isoYear, isoMonth, isoDay, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldate
  47. ThrowCompletionOr<PlainDate*> create_temporal_date(VM& vm, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject const* new_target)
  48. {
  49. auto& realm = *vm.current_realm();
  50. // 1. Assert: isoYear is an integer.
  51. // 2. Assert: isoMonth is an integer.
  52. // 3. Assert: isoDay is an integer.
  53. // 4. Assert: Type(calendar) is Object.
  54. // 5. If IsValidISODate(isoYear, isoMonth, isoDay) is false, throw a RangeError exception.
  55. if (!is_valid_iso_date(iso_year, iso_month, iso_day))
  56. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDate);
  57. // 6. If ISODateTimeWithinLimits(isoYear, isoMonth, isoDay, 12, 0, 0, 0, 0, 0) is false, throw a RangeError exception.
  58. if (!iso_date_time_within_limits(iso_year, iso_month, iso_day, 12, 0, 0, 0, 0, 0))
  59. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDate);
  60. // 7. If newTarget is not present, set newTarget to %Temporal.PlainDate%.
  61. if (!new_target)
  62. new_target = realm.intrinsics().temporal_plain_date_constructor();
  63. // 8. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainDate.prototype%", « [[InitializedTemporalDate]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  64. // 9. Set object.[[ISOYear]] to isoYear.
  65. // 10. Set object.[[ISOMonth]] to isoMonth.
  66. // 11. Set object.[[ISODay]] to isoDay.
  67. // 12. Set object.[[Calendar]] to calendar.
  68. auto object = TRY(ordinary_create_from_constructor<PlainDate>(vm, *new_target, &Intrinsics::temporal_plain_date_prototype, iso_year, iso_month, iso_day, calendar));
  69. return object.ptr();
  70. }
  71. // 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate
  72. ThrowCompletionOr<PlainDate*> to_temporal_date(VM& vm, Value item, Object const* options)
  73. {
  74. // 1. If options is not present, set options to undefined.
  75. // 2. Assert: Type(options) is Object or Undefined.
  76. // 3. If Type(item) is Object, then
  77. if (item.is_object()) {
  78. auto& item_object = item.as_object();
  79. // a. If item has an [[InitializedTemporalDate]] internal slot, then
  80. if (is<PlainDate>(item_object)) {
  81. // i. Return item.
  82. return static_cast<PlainDate*>(&item_object);
  83. }
  84. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  85. if (is<ZonedDateTime>(item_object)) {
  86. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  87. // i. Perform ? ToTemporalOverflow(options).
  88. (void)TRY(to_temporal_overflow(vm, options));
  89. // ii. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  90. auto* instant = create_temporal_instant(vm, zoned_date_time.nanoseconds()).release_value();
  91. // iii. Let plainDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  92. auto* plain_date_time = TRY(builtin_time_zone_get_plain_date_time_for(vm, &zoned_date_time.time_zone(), *instant, zoned_date_time.calendar()));
  93. // iv. Return ! CreateTemporalDate(plainDateTime.[[ISOYear]], plainDateTime.[[ISOMonth]], plainDateTime.[[ISODay]], plainDateTime.[[Calendar]]).
  94. return create_temporal_date(vm, plain_date_time->iso_year(), plain_date_time->iso_month(), plain_date_time->iso_day(), plain_date_time->calendar());
  95. }
  96. // c. If item has an [[InitializedTemporalDateTime]] internal slot, then
  97. if (is<PlainDateTime>(item_object)) {
  98. auto& date_time_item = static_cast<PlainDateTime&>(item_object);
  99. // i. Perform ? ToTemporalOverflow(options).
  100. (void)TRY(to_temporal_overflow(vm, options));
  101. // ii. Return ! CreateTemporalDate(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], item.[[Calendar]]).
  102. return create_temporal_date(vm, date_time_item.iso_year(), date_time_item.iso_month(), date_time_item.iso_day(), date_time_item.calendar());
  103. }
  104. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  105. auto* calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object));
  106. // e. Let fieldNames be ? CalendarFields(calendar, « "day", "month", "monthCode", "year" »).
  107. auto field_names = TRY(calendar_fields(vm, *calendar, { "day"sv, "month"sv, "monthCode"sv, "year"sv }));
  108. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  109. auto* fields = TRY(prepare_temporal_fields(vm, item_object, field_names, Vector<StringView> {}));
  110. // g. Return ? CalendarDateFromFields(calendar, fields, options).
  111. return calendar_date_from_fields(vm, *calendar, *fields, options);
  112. }
  113. // 4. Perform ? ToTemporalOverflow(options).
  114. (void)TRY(to_temporal_overflow(vm, options));
  115. // 5. Let string be ? ToString(item).
  116. auto string = TRY(item.to_string(vm));
  117. // 6. Let result be ? ParseTemporalDateString(string).
  118. auto result = TRY(parse_temporal_date_string(vm, string));
  119. // 7. Assert: IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  120. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  121. // 8. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  122. auto* calendar = TRY(to_temporal_calendar_with_iso_default(vm, result.calendar.has_value() ? PrimitiveString::create(vm, *result.calendar) : js_undefined()));
  123. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  124. return create_temporal_date(vm, result.year, result.month, result.day, *calendar);
  125. }
  126. // 3.5.3 DifferenceISODate ( y1, m1, d1, y2, m2, d2, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-differenceisodate
  127. DateDurationRecord difference_iso_date(VM& vm, i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2, StringView largest_unit)
  128. {
  129. VERIFY(largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv));
  130. // 1. If largestUnit is "year" or "month", then
  131. if (largest_unit.is_one_of("year"sv, "month"sv)) {
  132. // a. Let sign be -(! CompareISODate(y1, m1, d1, y2, m2, d2)).
  133. auto sign = -compare_iso_date(year1, month1, day1, year2, month2, day2);
  134. // b. If sign is 0, return ! CreateDateDurationRecord(0, 0, 0, 0).
  135. if (sign == 0)
  136. return create_date_duration_record(0, 0, 0, 0);
  137. // c. Let start be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  138. auto start = ISODateRecord { .year = year1, .month = month1, .day = day1 };
  139. // d. Let end be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  140. auto end = ISODateRecord { .year = year2, .month = month2, .day = day2 };
  141. // e. Let years be end.[[Year]] - start.[[Year]].
  142. double years = end.year - start.year;
  143. // f. Let mid be ! AddISODate(y1, m1, d1, years, 0, 0, 0, "constrain").
  144. auto mid = MUST(add_iso_date(vm, year1, month1, day1, years, 0, 0, 0, "constrain"sv));
  145. // g. Let midSign be -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  146. auto mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  147. // h. If midSign is 0, then
  148. if (mid_sign == 0) {
  149. // i. If largestUnit is "year", return ! CreateDateDurationRecord(years, 0, 0, 0).
  150. if (largest_unit == "year"sv)
  151. return create_date_duration_record(years, 0, 0, 0);
  152. // ii. Return ! CreateDateDurationRecord(0, years × 12, 0, 0).
  153. return create_date_duration_record(0, years * 12, 0, 0);
  154. }
  155. // i. Let months be end.[[Month]] - start.[[Month]].
  156. double months = end.month - start.month;
  157. // j. If midSign is not equal to sign, then
  158. if (mid_sign != sign) {
  159. // i. Set years to years - sign.
  160. years -= sign;
  161. // ii. Set months to months + sign × 12.
  162. months += sign * 12;
  163. }
  164. // k. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  165. mid = MUST(add_iso_date(vm, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  166. // l. Set midSign to -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  167. mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  168. // m. If midSign is 0, then
  169. if (mid_sign == 0) {
  170. // i. If largestUnit is "year", return ! CreateDateDurationRecord(years, months, 0, 0).
  171. if (largest_unit == "year"sv)
  172. return create_date_duration_record(years, months, 0, 0);
  173. // ii. Return ! CreateDateDurationRecord(0, months + years × 12, 0, 0).
  174. return create_date_duration_record(0, months + years * 12, 0, 0);
  175. }
  176. // n. If midSign is not equal to sign, then
  177. if (mid_sign != sign) {
  178. // i. Set months to months - sign.
  179. months -= sign;
  180. // ii. If months is equal to -sign, then
  181. if (months == -sign) {
  182. // 1. Set years to years - sign.
  183. years -= sign;
  184. // 2. Set months to 11 × sign.
  185. months = 11 * sign;
  186. }
  187. // iii. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  188. mid = MUST(add_iso_date(vm, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  189. }
  190. double days;
  191. // o. If mid.[[Month]] = end.[[Month]], then
  192. if (mid.month == end.month) {
  193. // i. Assert: mid.[[Year]] = end.[[Year]].
  194. VERIFY(mid.year == end.year);
  195. // ii. Let days be end.[[Day]] - mid.[[Day]].
  196. days = end.day - mid.day;
  197. }
  198. // p. Else if sign < 0, let days be -mid.[[Day]] - (! ISODaysInMonth(end.[[Year]], end.[[Month]]) - end.[[Day]]).
  199. else if (sign < 0) {
  200. days = -mid.day - (iso_days_in_month(end.year, end.month) - end.day);
  201. }
  202. // q. Else, let days be end.[[Day]] + (! ISODaysInMonth(mid.[[Year]], mid.[[Month]]) - mid.[[Day]]).
  203. else {
  204. days = end.day + (iso_days_in_month(mid.year, mid.month) - mid.day);
  205. }
  206. // r. If largestUnit is "month", then
  207. if (largest_unit == "month"sv) {
  208. // i. Set months to months + years × 12.
  209. months += years * 12;
  210. // ii. Set years to 0.
  211. years = 0;
  212. }
  213. // s. Return ! CreateDateDurationRecord(years, months, 0, days).
  214. return create_date_duration_record(years, months, 0, days);
  215. }
  216. // 2. Else,
  217. else {
  218. // a. Assert: largestUnit is "day" or "week".
  219. VERIFY(largest_unit.is_one_of("day"sv, "week"sv));
  220. // b. Let epochDays1 be MakeDay(𝔽(y1), 𝔽(m1 - 1), 𝔽(d1)).
  221. auto epoch_days_1 = make_day(year1, month1 - 1, day1);
  222. // c. Assert: epochDays1 is finite.
  223. VERIFY(isfinite(epoch_days_1));
  224. // d. Let epochDays2 be MakeDay(𝔽(y2), 𝔽(m2 - 1), 𝔽(d2)).
  225. auto epoch_days_2 = make_day(year2, month2 - 1, day2);
  226. // e. Assert: epochDays2 is finite.
  227. VERIFY(isfinite(epoch_days_2));
  228. // f. Let days be ℝ(epochDays2) - ℝ(epochDays1).
  229. auto days = epoch_days_2 - epoch_days_1;
  230. // g. Let weeks be 0.
  231. double weeks = 0;
  232. // h. If largestUnit is "week", then
  233. if (largest_unit == "week"sv) {
  234. // i. Set weeks to truncate(days / 7).
  235. weeks = trunc(days / 7);
  236. // ii. Set days to remainder(days, 7).
  237. days = fmod(days, 7);
  238. }
  239. // i. Return ! CreateDateDurationRecord(0, 0, weeks, days).
  240. return create_date_duration_record(0, 0, weeks, days);
  241. }
  242. }
  243. // 3.5.4 RegulateISODate ( year, month, day, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisodate
  244. ThrowCompletionOr<ISODateRecord> regulate_iso_date(VM& vm, double year, double month, double day, StringView overflow)
  245. {
  246. VERIFY(year == trunc(year) && month == trunc(month) && day == trunc(day));
  247. // 1. If overflow is "constrain", then
  248. if (overflow == "constrain"sv) {
  249. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat this double as normal integer from this point onwards. This
  250. // does not change the exposed behavior as the parent's call to CreateTemporalDate will immediately check that this value is a valid
  251. // ISO value for years: -273975 - 273975, which is a subset of this check.
  252. if (!AK::is_within_range<i32>(year))
  253. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDate);
  254. // a. Set month to the result of clamping month between 1 and 12.
  255. month = clamp(month, 1, 12);
  256. // b. Let daysInMonth be ! ISODaysInMonth(year, month).
  257. auto days_in_month = iso_days_in_month(static_cast<i32>(year), static_cast<u8>(month));
  258. // c. Set day to the result of clamping day between 1 and daysInMonth.
  259. day = clamp(day, 1, days_in_month);
  260. // d. Return CreateISODateRecord(year, month, day).
  261. return create_iso_date_record(static_cast<i32>(year), static_cast<u8>(month), static_cast<u8>(day));
  262. }
  263. // 2. Else,
  264. else {
  265. // a. Assert: overflow is "reject".
  266. VERIFY(overflow == "reject"sv);
  267. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  268. // This does not change the exposed behavior as the call to IsValidISODate will immediately check that these values are valid ISO
  269. // values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check.
  270. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month) || !AK::is_within_range<u8>(day))
  271. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDate);
  272. auto y = static_cast<i32>(year);
  273. auto m = static_cast<u8>(month);
  274. auto d = static_cast<u8>(day);
  275. // b. If IsValidISODate(year, month, day) is false, throw a RangeError exception.
  276. if (!is_valid_iso_date(y, m, d))
  277. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainDate);
  278. // c. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  279. return ISODateRecord { .year = y, .month = m, .day = d };
  280. }
  281. }
  282. // 3.5.5 IsValidISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisodate
  283. bool is_valid_iso_date(i32 year, u8 month, u8 day)
  284. {
  285. // 1. If month < 1 or month > 12, then
  286. if (month < 1 || month > 12) {
  287. // a. Return false.
  288. return false;
  289. }
  290. // 2. Let daysInMonth be ! ISODaysInMonth(year, month).
  291. auto days_in_month = iso_days_in_month(year, month);
  292. // 3. If day < 1 or day > daysInMonth, then
  293. if (day < 1 || day > days_in_month) {
  294. // a. Return false.
  295. return false;
  296. }
  297. // 4. Return true.
  298. return true;
  299. }
  300. // 3.5.6 DifferenceDate ( calendarRec, one, two, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencedate
  301. ThrowCompletionOr<NonnullGCPtr<Duration>> difference_date(VM& vm, CalendarMethods const& calendar_record, PlainDate const& one, PlainDate const& two, Object const& options)
  302. {
  303. // FIXME: 1. Assert: one.[[Calendar]] and two.[[Calendar]] have been determined to be equivalent as with CalendarEquals.
  304. // FIXME: 2. Assert: options is an ordinary Object.
  305. // 3. Assert: options.[[Prototype]] is null.
  306. VERIFY(!options.prototype());
  307. // 4. Assert: options has a "largestUnit" data property.
  308. VERIFY(MUST(options.has_own_property(vm.names.largestUnit)));
  309. // 5. If one.[[ISOYear]] = two.[[ISOYear]] and one.[[ISOMonth]] = two.[[ISOMonth]] and one.[[ISODay]] = two.[[ISODay]], then
  310. if (one.iso_year() == two.iso_year() && one.iso_month() == two.iso_month() && one.iso_day() == two.iso_day()) {
  311. // a. Return ! CreateTemporalDuration(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  312. return MUST(create_temporal_duration(vm, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  313. }
  314. // 6. If ! Get(options, "largestUnit") is "day", then
  315. auto largest_unit = MUST(options.get(vm.names.largestUnit));
  316. if (largest_unit.is_string() && largest_unit.as_string().utf8_string_view() == "day"sv) {
  317. // a. Let days be DaysUntil(one, two).
  318. auto days = days_until(one, two);
  319. // b. Return ! CreateTemporalDuration(0, 0, 0, days, 0, 0, 0, 0, 0, 0).
  320. return MUST(create_temporal_duration(vm, 0, 0, 0, days, 0, 0, 0, 0, 0, 0));
  321. }
  322. // 7. Return ? CalendarDateUntil(calendarRec, one, two, options).
  323. return TRY(calendar_date_until(vm, calendar_record, Value { &one }, Value { &two }, options));
  324. }
  325. // 3.5.6 BalanceISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodate
  326. ISODateRecord balance_iso_date(double year, double month, double day)
  327. {
  328. // 1. Let epochDays be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  329. auto epoch_days = make_day(year, month - 1, day);
  330. // 2. Assert: epochDays is finite.
  331. VERIFY(isfinite(epoch_days));
  332. // 3. Let ms be MakeDate(epochDays, +0𝔽).
  333. auto ms = make_date(epoch_days, 0);
  334. // 4. Return CreateISODateRecord(ℝ(YearFromTime(ms)), ℝ(MonthFromTime(ms)) + 1, ℝ(DateFromTime(ms))).
  335. return create_iso_date_record(year_from_time(ms), static_cast<u8>(month_from_time(ms) + 1), date_from_time(ms));
  336. }
  337. // 3.5.7 PadISOYear ( y ), https://tc39.es/proposal-temporal/#sec-temporal-padisoyear
  338. ThrowCompletionOr<String> pad_iso_year(VM& vm, i32 y)
  339. {
  340. // 1. Assert: y is an integer.
  341. // 2. If y ≥ 0 and y ≤ 9999, then
  342. if (y >= 0 && y <= 9999) {
  343. // a. Return ToZeroPaddedDecimalString(y, 4).
  344. return TRY_OR_THROW_OOM(vm, String::formatted("{:04}", y));
  345. }
  346. // 3. If y > 0, let yearSign be "+"; otherwise, let yearSign be "-".
  347. auto year_sign = y > 0 ? '+' : '-';
  348. // 4. Let year be ToZeroPaddedDecimalString(abs(y), 6).
  349. // 5. Return the string-concatenation of yearSign and year.
  350. return TRY_OR_THROW_OOM(vm, String::formatted("{}{:06}", year_sign, abs(y)));
  351. }
  352. // 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring
  353. ThrowCompletionOr<String> temporal_date_to_string(VM& vm, PlainDate& temporal_date, StringView show_calendar)
  354. {
  355. // 1. Assert: Type(temporalDate) is Object.
  356. // 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot.
  357. // 3. Let year be ! PadISOYear(temporalDate.[[ISOYear]]).
  358. auto year = MUST_OR_THROW_OOM(pad_iso_year(vm, temporal_date.iso_year()));
  359. // 4. Let month be ToZeroPaddedDecimalString(monthDay.[[ISOMonth]], 2).
  360. auto month = TRY_OR_THROW_OOM(vm, String::formatted("{:02}", temporal_date.iso_month()));
  361. // 5. Let day be ToZeroPaddedDecimalString(monthDay.[[ISODay]], 2).
  362. auto day = TRY_OR_THROW_OOM(vm, String::formatted("{:02}", temporal_date.iso_day()));
  363. // 6. Let calendar be ? MaybeFormatCalendarAnnotation(temporalDate.[[Calendar]], showCalendar).
  364. auto calendar = TRY(maybe_format_calendar_annotation(vm, &temporal_date.calendar(), show_calendar));
  365. // 7. Return the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), month, the code unit 0x002D (HYPHEN-MINUS), day, and calendar.
  366. return TRY_OR_THROW_OOM(vm, String::formatted("{}-{}-{}{}", year, month, day, calendar));
  367. }
  368. // 3.5.9 AddISODate ( year, month, day, years, months, weeks, days, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-addisodate
  369. ThrowCompletionOr<ISODateRecord> add_iso_date(VM& vm, i32 year, u8 month, u8 day, double years, double months, double weeks, double days, StringView overflow)
  370. {
  371. // 1. Assert: year, month, day, years, months, weeks, and days are integers.
  372. VERIFY(years == trunc(years) && months == trunc(months) && weeks == trunc(weeks) && days == trunc(days));
  373. // 2. Assert: overflow is either "constrain" or "reject".
  374. VERIFY(overflow == "constrain"sv || overflow == "reject"sv);
  375. // 3. Let intermediate be ! BalanceISOYearMonth(year + years, month + months).
  376. auto intermediate_year_month = balance_iso_year_month(year + years, month + months);
  377. // 4. Let intermediate be ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], day, overflow).
  378. auto intermediate = TRY(regulate_iso_date(vm, intermediate_year_month.year, intermediate_year_month.month, day, overflow));
  379. // 5. Set days to days + 7 × weeks.
  380. days += 7 * weeks;
  381. // 6. Let d be intermediate.[[Day]] + days.
  382. auto d = intermediate.day + days;
  383. // 7. Return BalanceISODate(intermediate.[[Year]], intermediate.[[Month]], d).
  384. return balance_iso_date(intermediate.year, intermediate.month, d);
  385. }
  386. // 3.5.10 CompareISODate ( y1, m1, d1, y2, m2, d2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodate
  387. i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2)
  388. {
  389. // 1. Assert: y1, m1, d1, y2, m2, and d2 are integers.
  390. // 2. If y1 > y2, return 1.
  391. if (year1 > year2)
  392. return 1;
  393. // 3. If y1 < y2, return -1.
  394. if (year1 < year2)
  395. return -1;
  396. // 4. If m1 > m2, return 1.
  397. if (month1 > month2)
  398. return 1;
  399. // 5. If m1 < m2, return -1.
  400. if (month1 < month2)
  401. return -1;
  402. // 6. If d1 > d2, return 1.
  403. if (day1 > day2)
  404. return 1;
  405. // 7. If d1 < d2, return -1.
  406. if (day1 < day2)
  407. return -1;
  408. // 8. Return 0.
  409. return 0;
  410. }
  411. // 3.5.11 DifferenceTemporalPlainDate ( operation, temporalDate, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalplaindate
  412. ThrowCompletionOr<NonnullGCPtr<Duration>> difference_temporal_plain_date(VM& vm, DifferenceOperation operation, PlainDate& temporal_date, Value other_value, Value options)
  413. {
  414. // 1. If operation is SINCE, let sign be -1. Otherwise, let sign be 1.
  415. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  416. // 2. Set other to ? ToTemporalDate(other).
  417. auto* other = TRY(to_temporal_date(vm, other_value));
  418. // 3. If ? CalendarEquals(temporalDate.[[Calendar]], other.[[Calendar]]) is false, throw a RangeError exception.
  419. if (!TRY(calendar_equals(vm, temporal_date.calendar(), other->calendar())))
  420. return vm.throw_completion<RangeError>(ErrorType::TemporalDifferentCalendars);
  421. // 4. Let resolvedOptions be ? SnapshotOwnProperties(? GetOptionsObject(options), null).
  422. auto resolved_options = TRY(TRY(get_options_object(vm, options))->snapshot_own_properties(vm, nullptr));
  423. // 5. Let settings be ? GetDifferenceSettings(operation, resolvedOptions, DATE, « », "day", "day").
  424. auto settings = TRY(get_difference_settings(vm, operation, resolved_options, UnitGroup::Date, {}, { "day"sv }, "day"sv));
  425. // 6. If temporalDate.[[ISOYear]] = other.[[ISOYear]], and temporalDate.[[ISOMonth]] = other.[[ISOMonth]], and temporalDate.[[ISODay]] = other.[[ISODay]], then
  426. if (temporal_date.iso_year() == other->iso_year() && temporal_date.iso_month() == other->iso_month() && temporal_date.iso_day() == other->iso_day()) {
  427. // a. Return ! CreateTemporalDuration(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  428. return MUST(create_temporal_duration(vm, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
  429. }
  430. // 7. Let calendarRec be ? CreateCalendarMethodsRecord(temporalDate.[[Calendar]], « DATE-ADD, DATE-UNTIL »).
  431. // FIXME: The type of calendar in PlainDate does not align with latest spec
  432. auto calendar_record = TRY(create_calendar_methods_record(vm, NonnullGCPtr<Object> { temporal_date.calendar() }, { { CalendarMethod::DateAdd, CalendarMethod::DateUntil } }));
  433. // 8. Perform ! CreateDataPropertyOrThrow(resolvedOptions, "largestUnit", settings.[[LargestUnit]]).
  434. MUST(resolved_options->create_data_property_or_throw(vm.names.largestUnit, PrimitiveString::create(vm, settings.largest_unit)));
  435. // 9. Let result be ? DifferenceDate(calendarRec, temporalDate, other, resolvedOptions).
  436. auto result = TRY(difference_date(vm, calendar_record, temporal_date, *other, resolved_options));
  437. // 10. If settings.[[SmallestUnit]] is "day" and settings.[[RoundingIncrement]] = 1, let roundingGranularityIsNoop be true; else let roundingGranularityIsNoop be false.
  438. bool rounding_granularity_is_noop = settings.smallest_unit == "day"sv && settings.rounding_increment == 1;
  439. // 11. If roundingGranularityIsNoop is false, then
  440. if (!rounding_granularity_is_noop) {
  441. // a. Let roundRecord be ? RoundDuration(result.[[Years]], result.[[Months]], result.[[Weeks]], result.[[Days]], ZeroTimeDuration(), settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]], temporalDate, calendarRec).
  442. auto round_record = TRY(round_duration(vm, result->years(), result->months(), result->weeks(), result->days(), 0, 0, 0, 0, 0, 0, settings.rounding_increment, settings.smallest_unit, settings.rounding_mode, &temporal_date, calendar_record)).duration_record;
  443. // FIXME: b. Let roundResult be roundRecord.[[NormalizedDuration]].
  444. // FIXME: c. Set result to ? BalanceDateDurationRelative(roundResult.[[Years]], roundResult.[[Months]], roundResult.[[Weeks]], roundResult.[[Days]], settings.[[LargestUnit]], settings.[[SmallestUnit]], temporalDate, calendarRec).
  445. result = MUST(create_temporal_duration(vm, round_record.years, round_record.months, round_record.weeks, round_record.days, 0, 0, 0, 0, 0, 0));
  446. }
  447. // 16. Return ! CreateTemporalDuration(sign × result.[[Years]], sign × result.[[Months]], sign × result.[[Weeks]], sign × result.[[Days]], 0, 0, 0, 0, 0, 0).
  448. return MUST(create_temporal_duration(vm, sign * result->years(), sign * result->months(), sign * result->weeks(), sign * result->days(), 0, 0, 0, 0, 0, 0));
  449. }
  450. }