PlainDate.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021, 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/GlobalObject.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/PlainDateConstructor.h>
  14. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  15. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  16. #include <LibJS/Runtime/Temporal/TimeZone.h>
  17. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  18. namespace JS::Temporal {
  19. // 3 Temporal.PlainDate Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindate-objects
  20. PlainDate::PlainDate(i32 year, u8 month, u8 day, Object& calendar, Object& prototype)
  21. : Object(prototype)
  22. , m_iso_year(year)
  23. , m_iso_month(month)
  24. , m_iso_day(day)
  25. , m_calendar(calendar)
  26. {
  27. }
  28. void PlainDate::visit_edges(Visitor& visitor)
  29. {
  30. Base::visit_edges(visitor);
  31. visitor.visit(&m_calendar);
  32. }
  33. // 3.5.1 CreateTemporalDate ( isoYear, isoMonth, isoDay, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldate
  34. ThrowCompletionOr<PlainDate*> create_temporal_date(GlobalObject& global_object, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject const* new_target)
  35. {
  36. auto& vm = global_object.vm();
  37. // 1. Assert: isoYear is an integer.
  38. // 2. Assert: isoMonth is an integer.
  39. // 3. Assert: isoDay is an integer.
  40. // 4. Assert: Type(calendar) is Object.
  41. // 5. If ! IsValidISODate(isoYear, isoMonth, isoDay) is false, throw a RangeError exception.
  42. if (!is_valid_iso_date(iso_year, iso_month, iso_day))
  43. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  44. // 6. If ! ISODateTimeWithinLimits(isoYear, isoMonth, isoDay, 12, 0, 0, 0, 0, 0) is false, throw a RangeError exception.
  45. if (!iso_date_time_within_limits(global_object, iso_year, iso_month, iso_day, 12, 0, 0, 0, 0, 0))
  46. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  47. // 7. If newTarget is not present, set it to %Temporal.PlainDate%.
  48. if (!new_target)
  49. new_target = global_object.temporal_plain_date_constructor();
  50. // 8. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainDate.prototype%", « [[InitializedTemporalDate]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  51. // 9. Set object.[[ISOYear]] to isoYear.
  52. // 10. Set object.[[ISOMonth]] to isoMonth.
  53. // 11. Set object.[[ISODay]] to isoDay.
  54. // 12. Set object.[[Calendar]] to calendar.
  55. auto* object = TRY(ordinary_create_from_constructor<PlainDate>(global_object, *new_target, &GlobalObject::temporal_plain_date_prototype, iso_year, iso_month, iso_day, calendar));
  56. return object;
  57. }
  58. // 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate
  59. ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject& global_object, Value item, Object* options)
  60. {
  61. auto& vm = global_object.vm();
  62. // 1. If options is not present, set options to ! OrdinaryObjectCreate(null).
  63. if (!options)
  64. options = Object::create(global_object, nullptr);
  65. // 2. Assert: Type(options) is Object.
  66. // 3. If Type(item) is Object, then
  67. if (item.is_object()) {
  68. auto& item_object = item.as_object();
  69. // a. If item has an [[InitializedTemporalDate]] internal slot, then
  70. if (is<PlainDate>(item_object)) {
  71. // i. Return item.
  72. return static_cast<PlainDate*>(&item_object);
  73. }
  74. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  75. if (is<ZonedDateTime>(item_object)) {
  76. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  77. // i. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  78. auto* instant = create_temporal_instant(global_object, zoned_date_time.nanoseconds()).release_value();
  79. // ii. Let plainDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  80. 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()));
  81. // iii. Return ! CreateTemporalDate(plainDateTime.[[ISOYear]], plainDateTime.[[ISOMonth]], plainDateTime.[[ISODay]], plainDateTime.[[Calendar]]).
  82. 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());
  83. }
  84. // c. If item has an [[InitializedTemporalDateTime]] internal slot, then
  85. if (is<PlainDateTime>(item_object)) {
  86. auto& date_time_item = static_cast<PlainDateTime&>(item_object);
  87. // i. Return ! CreateTemporalDate(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], item.[[Calendar]]).
  88. 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());
  89. }
  90. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  91. auto* calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  92. // e. Let fieldNames be ? CalendarFields(calendar, « "day", "month", "monthCode", "year" »).
  93. auto field_names = TRY(calendar_fields(global_object, *calendar, { "day"sv, "month"sv, "monthCode"sv, "year"sv }));
  94. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  95. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, {}));
  96. // g. Return ? DateFromFields(calendar, fields, options).
  97. return date_from_fields(global_object, *calendar, *fields, *options);
  98. }
  99. // 4. Perform ? ToTemporalOverflow(options).
  100. (void)TRY(to_temporal_overflow(global_object, *options));
  101. // 5. Let string be ? ToString(item).
  102. auto string = TRY(item.to_string(global_object));
  103. // 6. Let result be ? ParseTemporalDateString(string).
  104. auto result = TRY(parse_temporal_date_string(global_object, string));
  105. // 7. Assert: ! IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  106. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  107. // 8. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  108. auto* calendar = TRY(to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()));
  109. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  110. return create_temporal_date(global_object, result.year, result.month, result.day, *calendar);
  111. }
  112. // 3.5.3 DifferenceISODate ( y1, m1, d1, y2, m2, d2, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-differenceisodate
  113. DifferenceISODateResult difference_iso_date(GlobalObject& global_object, i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2, StringView largest_unit)
  114. {
  115. // 1. Assert: largestUnit is one of "year", "month", "week", or "day".
  116. VERIFY(largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv));
  117. // 2. If largestUnit is "year" or "month", then
  118. if (largest_unit.is_one_of("year"sv, "month"sv)) {
  119. // a. Let sign be -(! CompareISODate(y1, m1, d1, y2, m2, d2)).
  120. auto sign = -compare_iso_date(year1, month1, day1, year2, month2, day2);
  121. // b. If sign is 0, return the Record { [[Years]]: 0, [[Months]]: 0, [[Weeks]]: 0, [[Days]]: 0 }.
  122. if (sign == 0)
  123. return { .years = 0, .months = 0, .weeks = 0, .days = 0 };
  124. // c. Let start be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  125. auto start = ISODate { .year = year1, .month = month1, .day = day1 };
  126. // d. Let end be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  127. auto end = ISODate { .year = year2, .month = month2, .day = day2 };
  128. // e. Let years be end.[[Year]] − start.[[Year]].
  129. double years = end.year - start.year;
  130. // f. Let mid be ! AddISODate(y1, m1, d1, years, 0, 0, 0, "constrain").
  131. auto mid = MUST(add_iso_date(global_object, year1, month1, day1, years, 0, 0, 0, "constrain"sv));
  132. // g. Let midSign be -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  133. auto mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  134. // h. If midSign is 0, then
  135. if (mid_sign == 0) {
  136. // i. If largestUnit is "year", return the Record { [[Years]]: years, [[Months]]: 0, [[Weeks]]: 0, [[Days]]: 0 }.
  137. if (largest_unit == "year"sv)
  138. return { .years = years, .months = 0, .weeks = 0, .days = 0 };
  139. // ii. Return the Record { [[Years]]: 0, [[Months]]: years × 12, [[Weeks]]: 0, [[Days]]: 0 }.
  140. return { .years = 0, .months = years * 12, .weeks = 0, .days = 0 };
  141. }
  142. // i. Let months be end.[[Month]] − start.[[Month]].
  143. double months = end.month - start.month;
  144. // j. If midSign is not equal to sign, then
  145. if (mid_sign != sign) {
  146. // i. Set years to years - sign.
  147. years -= sign;
  148. // ii. Set months to months + sign × 12.
  149. months += sign * 12;
  150. }
  151. // k. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  152. mid = MUST(add_iso_date(global_object, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  153. // l. Set midSign to -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  154. mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  155. // m. If midSign is 0, then
  156. if (mid_sign == 0) {
  157. // i. If largestUnit is "year", return the Record { [[Years]]: years, [[Months]]: months, [[Weeks]]: 0, [[Days]]: 0 }.
  158. if (largest_unit == "year"sv)
  159. return { .years = years, .months = months, .weeks = 0, .days = 0 };
  160. // ii. Return the Record { [[Years]]: 0, [[Months]]: months + years × 12, [[Weeks]]: 0, [[Days]]: 0 }.
  161. return { .years = 0, .months = months + years * 12, .weeks = 0, .days = 0 };
  162. }
  163. // n. If midSign is not equal to sign, then
  164. if (mid_sign != sign) {
  165. // i. Set months to months - sign.
  166. months -= sign;
  167. // ii. If months is equal to -sign, then
  168. if (months == -sign) {
  169. // 1. Set years to years - sign.
  170. years -= sign;
  171. // 2. Set months to 11 × sign.
  172. months = 11 * sign;
  173. }
  174. // iii. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  175. mid = MUST(add_iso_date(global_object, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  176. // FIXME: This is not used (spec issue, see https://github.com/tc39/proposal-temporal/issues/1483).
  177. // iv. Set midSign to -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  178. mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  179. }
  180. // o. Let days be 0.
  181. double days = 0;
  182. // p. If mid.[[Month]] = end.[[Month]], then
  183. if (mid.month == end.month) {
  184. // i. Assert: mid.[[Year]] = end.[[Year]].
  185. VERIFY(mid.year == end.year);
  186. // ii. Set days to end.[[Day]] - mid.[[Day]].
  187. days = end.day - mid.day;
  188. }
  189. // q. Else if sign < 0, set days to -mid.[[Day]] - (! ISODaysInMonth(end.[[Year]], end.[[Month]]) - end.[[Day]]).
  190. else if (sign < 0) {
  191. days = -mid.day - (iso_days_in_month(end.year, end.month) - end.day);
  192. }
  193. // r. Else, set days to end.[[Day]] + (! ISODaysInMonth(mid.[[Year]], mid.[[Month]]) - mid.[[Day]]).
  194. else {
  195. days = end.day + (iso_days_in_month(mid.year, mid.month) - mid.day);
  196. }
  197. // s. If largestUnit is "month", then
  198. if (largest_unit == "month"sv) {
  199. // i. Set months to months + years × 12.
  200. months += years * 12;
  201. // ii. Set years to 0.
  202. years = 0;
  203. }
  204. // t. Return the Record { [[Years]]: years, [[Months]]: months, [[Weeks]]: 0, [[Days]]: days }.
  205. return { .years = years, .months = months, .weeks = 0, .days = days };
  206. }
  207. // 3. If largestUnit is "day" or "week", then
  208. else {
  209. ISODate smaller;
  210. ISODate greater;
  211. i8 sign;
  212. // a. If ! CompareISODate(y1, m1, d1, y2, m2, d2) < 0, then
  213. if (compare_iso_date(year1, month1, day1, year2, month2, day2) < 0) {
  214. // i. Let smaller be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  215. smaller = { .year = year1, .month = month1, .day = day1 };
  216. // ii. Let greater be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  217. greater = { .year = year2, .month = month2, .day = day2 };
  218. // iii. Let sign be 1.
  219. sign = 1;
  220. }
  221. // b. Else,
  222. else {
  223. // i. Let smaller be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  224. smaller = { .year = year2, .month = month2, .day = day2 };
  225. // ii. Let greater be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  226. greater = { .year = year1, .month = month1, .day = day1 };
  227. // iii. Let sign be −1.
  228. sign = -1;
  229. }
  230. // c. Let days be ! ToISODayOfYear(greater.[[Year]], greater.[[Month]], greater.[[Day]]) − ! ToISODayOfYear(smaller.[[Year]], smaller.[[Month]], smaller.[[Day]]).
  231. double days = to_iso_day_of_year(greater.year, greater.month, greater.day) - to_iso_day_of_year(smaller.year, smaller.month, smaller.day);
  232. // d. Let year be smaller.[[Year]].
  233. auto year = smaller.year;
  234. // e. Repeat, while year < greater.[[Year]],
  235. while (year < greater.year) {
  236. // i. Set days to days + ! ISODaysInYear(year).
  237. days += iso_days_in_year(year);
  238. // ii. Set year to year + 1.
  239. year++;
  240. }
  241. // f. Let weeks be 0.
  242. double weeks = 0;
  243. // g. If largestUnit is "week", then
  244. if (largest_unit == "week"sv) {
  245. // i. Set weeks to floor(days / 7).
  246. weeks = floor(days / 7);
  247. // ii. Set days to days modulo 7.
  248. days = fmod(days, 7);
  249. }
  250. // h. Return the Record { [[Years]]: 0, [[Months]]: 0, [[Weeks]]: weeks × sign, [[Days]]: days × sign }.
  251. // NOTE: We set weeks and days conditionally to avoid negative zero for 0 * -1.
  252. return { .years = 0, .months = 0, .weeks = (weeks != 0) ? weeks * sign : 0, .days = (days != 0) ? days * sign : 0 };
  253. }
  254. VERIFY_NOT_REACHED();
  255. }
  256. // 3.5.4 RegulateISODate ( year, month, day, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisodate
  257. ThrowCompletionOr<ISODate> regulate_iso_date(GlobalObject& global_object, double year, double month, double day, StringView overflow)
  258. {
  259. auto& vm = global_object.vm();
  260. // 1. Assert: year, month, and day are integers.
  261. VERIFY(year == trunc(year) && month == trunc(month) && day == trunc(day));
  262. // 2. Assert: overflow is either "constrain" or "reject".
  263. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  264. // 3. If overflow is "reject", then
  265. if (overflow == "reject"sv) {
  266. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  267. // This does not change the exposed behavior as the call to IsValidISODate will immediately check that these values are valid ISO
  268. // values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check.
  269. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month) || !AK::is_within_range<u8>(day))
  270. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  271. auto y = static_cast<i32>(year);
  272. auto m = static_cast<u8>(month);
  273. auto d = static_cast<u8>(day);
  274. // a. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  275. if (!is_valid_iso_date(y, m, d))
  276. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  277. // b. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  278. return ISODate { .year = y, .month = m, .day = d };
  279. }
  280. // 4. If overflow is "constrain", then
  281. else if (overflow == "constrain"sv) {
  282. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat this double as normal integer from this point onwards. This
  283. // does not change the exposed behavior as the parent's call to CreateTemporalDate will immediately check that this value is a valid
  284. // ISO value for years: -273975 - 273975, which is a subset of this check.
  285. if (!AK::is_within_range<i32>(year))
  286. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  287. auto y = static_cast<i32>(year);
  288. // a. Set month to ! ConstrainToRange(month, 1, 12).
  289. month = constrain_to_range(month, 1, 12);
  290. // b. Set day to ! ConstrainToRange(day, 1, ! ISODaysInMonth(year, month)).
  291. day = constrain_to_range(day, 1, iso_days_in_month(y, month));
  292. // c. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  293. return ISODate { .year = y, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  294. }
  295. VERIFY_NOT_REACHED();
  296. }
  297. // 3.5.5 IsValidISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisodate
  298. bool is_valid_iso_date(i32 year, u8 month, u8 day)
  299. {
  300. // 1. Assert: year, month, and day are integers.
  301. // 2. If month < 1 or month > 12, then
  302. if (month < 1 || month > 12) {
  303. // a. Return false.
  304. return false;
  305. }
  306. // 3. Let daysInMonth be ! ISODaysInMonth(year, month).
  307. auto days_in_month = iso_days_in_month(year, month);
  308. // 4. If day < 1 or day > daysInMonth, then
  309. if (day < 1 || day > days_in_month) {
  310. // a. Return false.
  311. return false;
  312. }
  313. // 5. Return true.
  314. return true;
  315. }
  316. // 3.5.6 BalanceISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodate
  317. ISODate balance_iso_date(double year_, double month_, double day)
  318. {
  319. // 1. Assert: year, month, and day are integers.
  320. // 2. Let balancedYearMonth be ! BalanceISOYearMonth(year, month).
  321. auto balanced_year_month = balance_iso_year_month(year_, month_);
  322. // 3. Set month to balancedYearMonth.[[Month]].
  323. auto month = balanced_year_month.month;
  324. // 4. Set year to balancedYearMonth.[[Year]].
  325. auto year = balanced_year_month.year;
  326. // 5. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in a year, the following section subtracts years and adds days until the number of days is greater than −366 or −365.
  327. i32 test_year;
  328. // 6. If month > 2, then
  329. if (month > 2) {
  330. // a. Let testYear be year.
  331. test_year = year;
  332. }
  333. // 7. Else,
  334. else {
  335. // a. Let testYear be year − 1.
  336. test_year = year - 1;
  337. }
  338. // 8. Repeat, while day < −1 × ! ISODaysInYear(testYear),
  339. while (day < -1 * iso_days_in_year(test_year)) {
  340. // a.Set day to day + !ISODaysInYear(testYear).
  341. day += iso_days_in_year(test_year);
  342. // b.Set year to year − 1.
  343. year--;
  344. // c.Set testYear to testYear − 1.
  345. test_year--;
  346. }
  347. // 9. NOTE: To deal with numbers of days greater than the number of days in a year, the following section adds years and subtracts days until the number of days is less than 366 or 365.
  348. // 10. Let testYear be year + 1.
  349. test_year = year + 1;
  350. // 11. Repeat, while day > ! ISODaysInYear(testYear),
  351. while (day > iso_days_in_year(test_year)) {
  352. // a. Set day to day − ! ISODaysInYear(testYear).
  353. day -= iso_days_in_year(test_year);
  354. // b. Set year to year + 1.
  355. year++;
  356. // c. Set testYear to testYear + 1.
  357. test_year++;
  358. }
  359. // 12. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in the current month, the following section subtracts months and adds days until the number of days is greater than 0.
  360. // 13. Repeat, while day < 1,
  361. while (day < 1) {
  362. // a. Set balancedYearMonth to ! BalanceISOYearMonth(year, month − 1).
  363. balanced_year_month = balance_iso_year_month(year, month - 1);
  364. // b. Set year to balancedYearMonth.[[Year]].
  365. year = balanced_year_month.year;
  366. // c. Set month to balancedYearMonth.[[Month]].
  367. month = balanced_year_month.month;
  368. // d. Set day to day + ! ISODaysInMonth(year, month).
  369. day += iso_days_in_month(year, month);
  370. }
  371. // 14. NOTE: To deal with numbers of days greater than the number of days in the current month, the following section adds months and subtracts days until the number of days is less than the number of days in the month.
  372. // 15. Repeat, while day > ! ISODaysInMonth(year, month),
  373. while (day > iso_days_in_month(year, month)) {
  374. // a. Set day to day − ! ISODaysInMonth(year, month).
  375. day -= iso_days_in_month(year, month);
  376. // b. Set balancedYearMonth to ! BalanceISOYearMonth(year, month + 1).
  377. balanced_year_month = balance_iso_year_month(year, month + 1);
  378. // c. Set year to balancedYearMonth.[[Year]].
  379. year = balanced_year_month.year;
  380. // d. Set month to balancedYearMonth.[[Month]].
  381. month = balanced_year_month.month;
  382. }
  383. // 16. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  384. return ISODate { .year = year, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  385. }
  386. // 3.5.7 PadISOYear ( y ), https://tc39.es/proposal-temporal/#sec-temporal-padisoyear
  387. String pad_iso_year(i32 y)
  388. {
  389. // 1. Assert: y is an integer.
  390. // 2. If y > 999 and y ≤ 9999, then
  391. if (y > 999 && y <= 9999) {
  392. // a. Return y formatted as a four-digit decimal number.
  393. return String::number(y);
  394. }
  395. // 3. If y ≥ 0, let yearSign be "+"; otherwise, let yearSign be "-".
  396. auto year_sign = y >= 0 ? '+' : '-';
  397. // 4. Let year be abs(y), formatted as a six-digit decimal number, padded to the left with zeroes as necessary.
  398. // 5. Return the string-concatenation of yearSign and year.
  399. return String::formatted("{}{:06}", year_sign, abs(y));
  400. }
  401. // 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring
  402. ThrowCompletionOr<String> temporal_date_to_string(GlobalObject& global_object, PlainDate& temporal_date, StringView show_calendar)
  403. {
  404. // 1. Assert: Type(temporalDate) is Object.
  405. // 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot.
  406. // 3. Let year be ! PadISOYear(temporalDate.[[ISOYear]]).
  407. auto year = pad_iso_year(temporal_date.iso_year());
  408. // 4. Let month be temporalDate.[[ISOMonth]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  409. auto month = String::formatted("{:02}", temporal_date.iso_month());
  410. // 5. Let day be temporalDate.[[ISODay]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  411. auto day = String::formatted("{:02}", temporal_date.iso_day());
  412. // 6. Let calendarID be ? ToString(temporalDate.[[Calendar]]).
  413. auto calendar_id = TRY(Value(&temporal_date.calendar()).to_string(global_object));
  414. // 7. Let calendar be ! FormatCalendarAnnotation(calendarID, showCalendar).
  415. auto calendar = format_calendar_annotation(calendar_id, show_calendar);
  416. // 8. Return the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), month, the code unit 0x002D (HYPHEN-MINUS), day, and calendar.
  417. return String::formatted("{}-{}-{}{}", year, month, day, calendar);
  418. }
  419. // 3.5.9 AddISODate ( year, month, day, years, months, weeks, days, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-addisodate
  420. ThrowCompletionOr<ISODate> add_iso_date(GlobalObject& global_object, i32 year, u8 month, u8 day, double years, double months, double weeks, double days, StringView overflow)
  421. {
  422. // 1. Assert: year, month, day, years, months, weeks, and days are integers.
  423. VERIFY(years == trunc(years) && months == trunc(months) && weeks == trunc(weeks) && days == trunc(days));
  424. // 2. Assert: overflow is either "constrain" or "reject".
  425. VERIFY(overflow == "constrain"sv || overflow == "reject"sv);
  426. // 3. Let intermediate be ! BalanceISOYearMonth(year + years, month + months).
  427. auto intermediate_year_month = balance_iso_year_month(year + years, month + months);
  428. // 4. Let intermediate be ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], day, overflow).
  429. auto intermediate_date = TRY(regulate_iso_date(global_object, intermediate_year_month.year, intermediate_year_month.month, day, overflow));
  430. // 5. Set days to days + 7 × weeks.
  431. days += 7 * weeks;
  432. // 6. Let d be intermediate.[[Day]] + days.
  433. auto d = intermediate_date.day + days;
  434. // 7. Let intermediate be ! BalanceISODate(intermediate.[[Year]], intermediate.[[Month]], d).
  435. auto intermediate = balance_iso_date(intermediate_date.year, intermediate_date.month, d);
  436. // 8. Return ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], intermediate.[[Day]], overflow).
  437. return regulate_iso_date(global_object, intermediate.year, intermediate.month, intermediate.day, overflow);
  438. }
  439. // 3.5.10 CompareISODate ( y1, m1, d1, y2, m2, d2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodate
  440. i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2)
  441. {
  442. // 1. Assert: y1, m1, d1, y2, m2, and d2 are integers.
  443. // 2. If y1 > y2, return 1.
  444. if (year1 > year2)
  445. return 1;
  446. // 3. If y1 < y2, return -1.
  447. if (year1 < year2)
  448. return -1;
  449. // 4. If m1 > m2, return 1.
  450. if (month1 > month2)
  451. return 1;
  452. // 5. If m1 < m2, return -1.
  453. if (month1 < month2)
  454. return -1;
  455. // 6. If d1 > d2, return 1.
  456. if (day1 > day2)
  457. return 1;
  458. // 7. If d1 < d2, return -1.
  459. if (day1 < day2)
  460. return -1;
  461. // 8. Return 0.
  462. return 0;
  463. }
  464. }