PlainDate.cpp 26 KB

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