PlainDate.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 = item.to_string(global_object);
  103. if (auto* exception = vm.exception())
  104. return throw_completion(exception->value());
  105. // 6. Let result be ? ParseTemporalDateString(string).
  106. auto result = TRY(parse_temporal_date_string(global_object, string));
  107. // 7. Assert: ! IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  108. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  109. // 8. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  110. auto* calendar = TRY(to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()));
  111. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  112. return create_temporal_date(global_object, result.year, result.month, result.day, *calendar);
  113. }
  114. // 3.5.4 RegulateISODate ( year, month, day, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisodate
  115. ThrowCompletionOr<ISODate> regulate_iso_date(GlobalObject& global_object, double year, double month, double day, StringView overflow)
  116. {
  117. auto& vm = global_object.vm();
  118. // 1. Assert: year, month, and day are integers.
  119. VERIFY(year == trunc(year) && month == trunc(month) && day == trunc(day));
  120. // 2. Assert: overflow is either "constrain" or "reject".
  121. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  122. // 3. If overflow is "reject", then
  123. if (overflow == "reject"sv) {
  124. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  125. // This does not change the exposed behavior as the call to IsValidISODate will immediately check that these values are valid ISO
  126. // values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check.
  127. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month) || !AK::is_within_range<u8>(day))
  128. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  129. auto y = static_cast<i32>(year);
  130. auto m = static_cast<u8>(month);
  131. auto d = static_cast<u8>(day);
  132. // a. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  133. if (!is_valid_iso_date(y, m, d))
  134. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  135. // b. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  136. return ISODate { .year = y, .month = m, .day = d };
  137. }
  138. // 4. If overflow is "constrain", then
  139. else if (overflow == "constrain"sv) {
  140. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat this double as normal integer from this point onwards. This
  141. // does not change the exposed behavior as the parent's call to CreateTemporalDate will immediately check that this value is a valid
  142. // ISO value for years: -273975 - 273975, which is a subset of this check.
  143. if (!AK::is_within_range<i32>(year))
  144. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  145. auto y = static_cast<i32>(year);
  146. // a. Set month to ! ConstrainToRange(month, 1, 12).
  147. month = constrain_to_range(month, 1, 12);
  148. // b. Set day to ! ConstrainToRange(day, 1, ! ISODaysInMonth(year, month)).
  149. day = constrain_to_range(day, 1, iso_days_in_month(y, month));
  150. // c. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  151. return ISODate { .year = y, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  152. }
  153. VERIFY_NOT_REACHED();
  154. }
  155. // 3.5.5 IsValidISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisodate
  156. bool is_valid_iso_date(i32 year, u8 month, u8 day)
  157. {
  158. // 1. Assert: year, month, and day are integers.
  159. // 2. If month < 1 or month > 12, then
  160. if (month < 1 || month > 12) {
  161. // a. Return false.
  162. return false;
  163. }
  164. // 3. Let daysInMonth be ! ISODaysInMonth(year, month).
  165. auto days_in_month = iso_days_in_month(year, month);
  166. // 4. If day < 1 or day > daysInMonth, then
  167. if (day < 1 || day > days_in_month) {
  168. // a. Return false.
  169. return false;
  170. }
  171. // 5. Return true.
  172. return true;
  173. }
  174. // 3.5.6 BalanceISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodate
  175. ISODate balance_iso_date(double year_, double month_, double day)
  176. {
  177. // 1. Assert: year, month, and day are integers.
  178. // 2. Let balancedYearMonth be ! BalanceISOYearMonth(year, month).
  179. auto balanced_year_month = balance_iso_year_month(year_, month_);
  180. // 3. Set month to balancedYearMonth.[[Month]].
  181. auto month = balanced_year_month.month;
  182. // 4. Set year to balancedYearMonth.[[Year]].
  183. auto year = balanced_year_month.year;
  184. // 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.
  185. i32 test_year;
  186. // 6. If month > 2, then
  187. if (month > 2) {
  188. // a. Let testYear be year.
  189. test_year = year;
  190. }
  191. // 7. Else,
  192. else {
  193. // a. Let testYear be year − 1.
  194. test_year = year - 1;
  195. }
  196. // 8. Repeat, while day < −1 × ! ISODaysInYear(testYear),
  197. while (day < -1 * iso_days_in_year(test_year)) {
  198. // a.Set day to day + !ISODaysInYear(testYear).
  199. day += iso_days_in_year(test_year);
  200. // b.Set year to year − 1.
  201. year--;
  202. // c.Set testYear to testYear − 1.
  203. test_year--;
  204. }
  205. // 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.
  206. // 10. Let testYear be year + 1.
  207. test_year = year + 1;
  208. // 11. Repeat, while day > ! ISODaysInYear(testYear),
  209. while (day > iso_days_in_year(test_year)) {
  210. // a. Set day to day − ! ISODaysInYear(testYear).
  211. day -= iso_days_in_year(test_year);
  212. // b. Set year to year + 1.
  213. year++;
  214. // c. Set testYear to testYear + 1.
  215. test_year++;
  216. }
  217. // 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.
  218. // 13. Repeat, while day < 1,
  219. while (day < 1) {
  220. // a. Set balancedYearMonth to ! BalanceISOYearMonth(year, month − 1).
  221. balanced_year_month = balance_iso_year_month(year, month - 1);
  222. // b. Set year to balancedYearMonth.[[Year]].
  223. year = balanced_year_month.year;
  224. // c. Set month to balancedYearMonth.[[Month]].
  225. month = balanced_year_month.month;
  226. // d. Set day to day + ! ISODaysInMonth(year, month).
  227. day += iso_days_in_month(year, month);
  228. }
  229. // 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.
  230. // 15. Repeat, while day > ! ISODaysInMonth(year, month),
  231. while (day > iso_days_in_month(year, month)) {
  232. // a. Set day to day − ! ISODaysInMonth(year, month).
  233. day -= iso_days_in_month(year, month);
  234. // b. Set balancedYearMonth to ! BalanceISOYearMonth(year, month + 1).
  235. balanced_year_month = balance_iso_year_month(year, month + 1);
  236. // c. Set year to balancedYearMonth.[[Year]].
  237. year = balanced_year_month.year;
  238. // d. Set month to balancedYearMonth.[[Month]].
  239. month = balanced_year_month.month;
  240. }
  241. // 16. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  242. return ISODate { .year = year, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  243. }
  244. // 3.5.7 PadISOYear ( y ), https://tc39.es/proposal-temporal/#sec-temporal-padisoyear
  245. String pad_iso_year(i32 y)
  246. {
  247. // 1. Assert: y is an integer.
  248. // 2. If y > 999 and y ≤ 9999, then
  249. if (y > 999 && y <= 9999) {
  250. // a. Return y formatted as a four-digit decimal number.
  251. return String::number(y);
  252. }
  253. // 3. If y ≥ 0, let yearSign be "+"; otherwise, let yearSign be "-".
  254. auto year_sign = y >= 0 ? '+' : '-';
  255. // 4. Let year be abs(y), formatted as a six-digit decimal number, padded to the left with zeroes as necessary.
  256. // 5. Return the string-concatenation of yearSign and year.
  257. return String::formatted("{}{:06}", year_sign, abs(y));
  258. }
  259. // 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring
  260. ThrowCompletionOr<String> temporal_date_to_string(GlobalObject& global_object, PlainDate& temporal_date, StringView show_calendar)
  261. {
  262. auto& vm = global_object.vm();
  263. // 1. Assert: Type(temporalDate) is Object.
  264. // 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot.
  265. // 3. Let year be ! PadISOYear(temporalDate.[[ISOYear]]).
  266. auto year = pad_iso_year(temporal_date.iso_year());
  267. // 4. Let month be temporalDate.[[ISOMonth]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  268. auto month = String::formatted("{:02}", temporal_date.iso_month());
  269. // 5. Let day be temporalDate.[[ISODay]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  270. auto day = String::formatted("{:02}", temporal_date.iso_day());
  271. // 6. Let calendarID be ? ToString(temporalDate.[[Calendar]]).
  272. auto calendar_id = Value(&temporal_date.calendar()).to_string(global_object);
  273. if (auto* exception = vm.exception())
  274. return throw_completion(exception->value());
  275. // 7. Let calendar be ! FormatCalendarAnnotation(calendarID, showCalendar).
  276. auto calendar = format_calendar_annotation(calendar_id, show_calendar);
  277. // 8. Return the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), month, the code unit 0x002D (HYPHEN-MINUS), day, and calendar.
  278. return String::formatted("{}-{}-{}{}", year, month, day, calendar);
  279. }
  280. // 3.5.9 AddISODate ( year, month, day, years, months, weeks, days, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-addisodate
  281. ThrowCompletionOr<ISODate> add_iso_date(GlobalObject& global_object, i32 year, u8 month, u8 day, double years, double months, double weeks, double days, StringView overflow)
  282. {
  283. // 1. Assert: year, month, day, years, months, weeks, and days are integers.
  284. VERIFY(years == trunc(years) && months == trunc(months) && weeks == trunc(weeks) && days == trunc(days));
  285. // 2. Assert: overflow is either "constrain" or "reject".
  286. VERIFY(overflow == "constrain"sv || overflow == "reject"sv);
  287. // 3. Let intermediate be ! BalanceISOYearMonth(year + years, month + months).
  288. auto intermediate_year_month = balance_iso_year_month(year + years, month + months);
  289. // 4. Let intermediate be ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], day, overflow).
  290. auto intermediate_date = TRY(regulate_iso_date(global_object, intermediate_year_month.year, intermediate_year_month.month, day, overflow));
  291. // 5. Set days to days + 7 × weeks.
  292. days += 7 * weeks;
  293. // 6. Let d be intermediate.[[Day]] + days.
  294. auto d = intermediate_date.day + days;
  295. // 7. Let intermediate be ! BalanceISODate(intermediate.[[Year]], intermediate.[[Month]], d).
  296. auto intermediate = balance_iso_date(intermediate_date.year, intermediate_date.month, d);
  297. // 8. Return ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], intermediate.[[Day]], overflow).
  298. return regulate_iso_date(global_object, intermediate.year, intermediate.month, intermediate.day, overflow);
  299. }
  300. // 3.5.10 CompareISODate ( y1, m1, d1, y2, m2, d2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodate
  301. i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2)
  302. {
  303. // 1. Assert: y1, m1, d1, y2, m2, and d2 are integers.
  304. // 2. If y1 > y2, return 1.
  305. if (year1 > year2)
  306. return 1;
  307. // 3. If y1 < y2, return -1.
  308. if (year1 < year2)
  309. return -1;
  310. // 4. If m1 > m2, return 1.
  311. if (month1 > month2)
  312. return 1;
  313. // 5. If m1 < m2, return -1.
  314. if (month1 < month2)
  315. return -1;
  316. // 6. If d1 > d2, return 1.
  317. if (day1 > day2)
  318. return 1;
  319. // 7. If d1 < d2, return -1.
  320. if (day1 < day2)
  321. return -1;
  322. // 8. Return 0.
  323. return 0;
  324. }
  325. }