PlainYearMonth.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TypeCasts.h>
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Array.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  11. #include <LibJS/Runtime/Temporal/Calendar.h>
  12. #include <LibJS/Runtime/Temporal/Duration.h>
  13. #include <LibJS/Runtime/Temporal/PlainDate.h>
  14. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  15. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  16. namespace JS::Temporal {
  17. // 9 Temporal.PlainYearMonth Objects, https://tc39.es/proposal-temporal/#sec-temporal-plainyearmonth-objects
  18. PlainYearMonth::PlainYearMonth(i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, Object& prototype)
  19. : Object(ConstructWithPrototypeTag::Tag, prototype)
  20. , m_iso_year(iso_year)
  21. , m_iso_month(iso_month)
  22. , m_iso_day(iso_day)
  23. , m_calendar(calendar)
  24. {
  25. }
  26. void PlainYearMonth::visit_edges(Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(&m_calendar);
  30. }
  31. // 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth
  32. ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(VM& vm, Value item, Object const* options)
  33. {
  34. // 1. If options is not present, set options to undefined.
  35. // 2. Assert: Type(options) is Object or Undefined.
  36. // 3. If Type(item) is Object, then
  37. if (item.is_object()) {
  38. auto& item_object = item.as_object();
  39. // a. If item has an [[InitializedTemporalYearMonth]] internal slot, then
  40. if (is<PlainYearMonth>(item_object)) {
  41. // i. Return item.
  42. return static_cast<PlainYearMonth*>(&item_object);
  43. }
  44. // b. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  45. auto* calendar = TRY(get_temporal_calendar_with_iso_default(vm, item_object));
  46. // c. Let fieldNames be ? CalendarFields(calendar, « "month", "monthCode", "year" »).
  47. auto field_names = TRY(calendar_fields(vm, *calendar, { "month"sv, "monthCode"sv, "year"sv }));
  48. // d. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  49. auto* fields = TRY(prepare_temporal_fields(vm, item_object, field_names, Vector<StringView> {}));
  50. // e. Return ? CalendarYearMonthFromFields(calendar, fields, options).
  51. return calendar_year_month_from_fields(vm, *calendar, *fields, options);
  52. }
  53. // 4. Perform ? ToTemporalOverflow(options).
  54. (void)TRY(to_temporal_overflow(vm, options));
  55. // 5. Let string be ? ToString(item).
  56. auto string = TRY(item.to_string(vm));
  57. // 6. Let result be ? ParseTemporalYearMonthString(string).
  58. auto result = TRY(parse_temporal_year_month_string(vm, string));
  59. // 7. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  60. auto* calendar = TRY(to_temporal_calendar_with_iso_default(vm, result.calendar.has_value() ? PrimitiveString::create(vm, *result.calendar) : js_undefined()));
  61. // 8. Set result to ? CreateTemporalYearMonth(result.[[Year]], result.[[Month]], calendar, result.[[Day]]).
  62. auto* creation_result = TRY(create_temporal_year_month(vm, result.year, result.month, *calendar, result.day));
  63. // 9. NOTE: The following operation is called without options, in order for the calendar to store a canonical value in the [[ISODay]] internal slot of the result.
  64. // 10. Return ? CalendarYearMonthFromFields(calendar, result).
  65. return calendar_year_month_from_fields(vm, *calendar, *creation_result);
  66. }
  67. // 9.5.2 RegulateISOYearMonth ( year, month, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisoyearmonth
  68. ThrowCompletionOr<ISOYearMonth> regulate_iso_year_month(VM& vm, double year, double month, StringView overflow)
  69. {
  70. // 1. Assert: year and month are integers.
  71. VERIFY(year == trunc(year) && month == trunc(month));
  72. // 2. Assert: overflow is either "constrain" or "reject".
  73. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  74. // 3. If overflow is "constrain", then
  75. if (overflow == "constrain"sv) {
  76. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat `year` (a double) as normal integer from this point onwards.
  77. // This does not change the exposed behavior as the subsequent call to CreateTemporalYearMonth will check that its value is a valid ISO
  78. // values (for years: -273975 - 273975) which is a subset of this check.
  79. // If RegulateISOYearMonth is ever used outside ISOYearMonthFromFields, this may need to be changed.
  80. if (!AK::is_within_range<i32>(year))
  81. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
  82. // a. Set month to the result of clamping month between 1 and 12.
  83. month = clamp(month, 1, 12);
  84. // b. Return the Record { [[Year]]: year, [[Month]]: month }.
  85. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  86. }
  87. // 4. Else,
  88. else {
  89. // a. Assert: overflow is "reject".
  90. VERIFY(overflow == "reject"sv);
  91. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  92. // This does not change the exposed behavior as the call to IsValidISOMonth and subsequent call to CreateTemporalDateTime will check
  93. // that these values are valid ISO values (for years: -273975 - 273975, for months: 1 - 12) all of which are subsets of this check.
  94. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month))
  95. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
  96. // b. If month < 1 or month > 12, throw a RangeError exception.
  97. if (month < 1 || month > 12)
  98. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
  99. // c. Return the Record { [[Year]]: year, [[Month]]: month }.
  100. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  101. }
  102. }
  103. // 9.5.3 ISOYearMonthWithinLimits ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthwithinlimits
  104. bool iso_year_month_within_limits(i32 year, u8 month)
  105. {
  106. // 1. Assert: year and month are integers.
  107. // 2. If year < -271821 or year > 275760, then
  108. if (year < -271821 || year > 275760) {
  109. // a. Return false.
  110. return false;
  111. }
  112. // 3. If year is -271821 and month < 4, then
  113. if (year == -271821 && month < 4) {
  114. // a. Return false.
  115. return false;
  116. }
  117. // 4. If year is 275760 and month > 9, then
  118. if (year == 275760 && month > 9) {
  119. // a. Return false.
  120. return false;
  121. }
  122. // 5. Return true.
  123. return true;
  124. }
  125. // 9.5.4 BalanceISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisoyearmonth
  126. ISOYearMonth balance_iso_year_month(double year, double month)
  127. {
  128. // 1. Assert: year and month are integers.
  129. VERIFY(year == trunc(year) && month == trunc(month));
  130. // 2. Set year to year + floor((month - 1) / 12).
  131. year += floor((month - 1) / 12);
  132. // 3. Set month to ((month - 1) modulo 12) + 1.
  133. month = modulo(month - 1, 12) + 1;
  134. // 4. Return the Record { [[Year]]: year, [[Month]]: month }.
  135. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  136. }
  137. // 9.5.5 CreateTemporalYearMonth ( isoYear, isoMonth, calendar, referenceISODay [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalyearmonth
  138. ThrowCompletionOr<PlainYearMonth*> create_temporal_year_month(VM& vm, i32 iso_year, u8 iso_month, Object& calendar, u8 reference_iso_day, FunctionObject const* new_target)
  139. {
  140. auto& realm = *vm.current_realm();
  141. // 1. Assert: isoYear, isoMonth, and referenceISODay are integers.
  142. // 2. Assert: Type(calendar) is Object.
  143. // 3. If IsValidISODate(isoYear, isoMonth, referenceISODay) is false, throw a RangeError exception.
  144. if (!is_valid_iso_date(iso_year, iso_month, reference_iso_day))
  145. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
  146. // 4. If ! ISOYearMonthWithinLimits(isoYear, isoMonth) is false, throw a RangeError exception.
  147. if (!iso_year_month_within_limits(iso_year, iso_month))
  148. return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidPlainYearMonth);
  149. // 5. If newTarget is not present, set newTarget to %Temporal.PlainYearMonth%.
  150. if (!new_target)
  151. new_target = realm.intrinsics().temporal_plain_year_month_constructor();
  152. // 6. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainYearMonth.prototype%", « [[InitializedTemporalYearMonth]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  153. // 7. Set object.[[ISOYear]] to isoYear.
  154. // 8. Set object.[[ISOMonth]] to isoMonth.
  155. // 9. Set object.[[Calendar]] to calendar.
  156. // 10. Set object.[[ISODay]] to referenceISODay.
  157. auto object = TRY(ordinary_create_from_constructor<PlainYearMonth>(vm, *new_target, &Intrinsics::temporal_plain_year_month_prototype, iso_year, iso_month, reference_iso_day, calendar));
  158. // 11. Return object.
  159. return object.ptr();
  160. }
  161. // 9.5.6 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring
  162. ThrowCompletionOr<String> temporal_year_month_to_string(VM& vm, PlainYearMonth& year_month, StringView show_calendar)
  163. {
  164. // 1. Assert: Type(yearMonth) is Object.
  165. // 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot.
  166. // 3. Let year be ! PadISOYear(yearMonth.[[ISOYear]]).
  167. // 4. Let month be ToZeroPaddedDecimalString(yearMonth.[[ISOMonth]], 2).
  168. // 5. Let result be the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), and month.
  169. auto result = TRY_OR_THROW_OOM(vm, String::formatted("{}-{:02}", MUST_OR_THROW_OOM(pad_iso_year(vm, year_month.iso_year())), year_month.iso_month()));
  170. // 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]).
  171. auto calendar_id = TRY(Value(&year_month.calendar()).to_string(vm));
  172. // 7. If showCalendar is one of "always" or "critical", or if calendarID is not "iso8601", then
  173. if (show_calendar.is_one_of("always"sv, "critical"sv) || calendar_id != "iso8601") {
  174. // a. Let day be ToZeroPaddedDecimalString(yearMonth.[[ISODay]], 2).
  175. // b. Set result to the string-concatenation of result, the code unit 0x002D (HYPHEN-MINUS), and day.
  176. result = TRY_OR_THROW_OOM(vm, String::formatted("{}-{:02}", result, year_month.iso_day()));
  177. }
  178. // 8. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  179. auto calendar_string = MUST_OR_THROW_OOM(format_calendar_annotation(vm, calendar_id, show_calendar));
  180. // 9. Set result to the string-concatenation of result and calendarString.
  181. // 10. Return result.
  182. return TRY_OR_THROW_OOM(vm, String::formatted("{}{}", result, calendar_string));
  183. }
  184. // 9.5.7 DifferenceTemporalPlainYearMonth ( operation, yearMonth, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalplainyearmonth
  185. ThrowCompletionOr<Duration*> difference_temporal_plain_year_month(VM& vm, DifferenceOperation operation, PlainYearMonth& year_month, Value other_value, Value options_value)
  186. {
  187. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  188. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  189. // 2. Set other to ? ToTemporalYearMonth(other).
  190. auto* other = TRY(to_temporal_year_month(vm, other_value));
  191. // 3. Let calendar be yearMonth.[[Calendar]].
  192. auto& calendar = year_month.calendar();
  193. // 4. If ? CalendarEquals(calendar, other.[[Calendar]]) is false, throw a RangeError exception.
  194. if (!TRY(calendar_equals(vm, calendar, other->calendar())))
  195. return vm.throw_completion<RangeError>(ErrorType::TemporalDifferentCalendars);
  196. // 5. Let settings be ? GetDifferenceSettings(operation, options, date, « "week", "day" », "month", "year").
  197. auto settings = TRY(get_difference_settings(vm, operation, options_value, UnitGroup::Date, { "week"sv, "day"sv }, { "month"sv }, "year"sv));
  198. // 6. Let fieldNames be ? CalendarFields(calendar, « "monthCode", "year" »).
  199. auto field_names = TRY(calendar_fields(vm, calendar, { "monthCode"sv, "year"sv }));
  200. // 7. Let otherFields be ? PrepareTemporalFields(other, fieldNames, «»).
  201. auto* other_fields = TRY(prepare_temporal_fields(vm, *other, field_names, Vector<StringView> {}));
  202. // 8. Perform ! CreateDataPropertyOrThrow(otherFields, "day", 1𝔽).
  203. MUST(other_fields->create_data_property_or_throw(vm.names.day, Value(1)));
  204. // 9. Let otherDate be ? CalendarDateFromFields(calendar, otherFields).
  205. auto* other_date = TRY(calendar_date_from_fields(vm, calendar, *other_fields));
  206. // 10. Let thisFields be ? PrepareTemporalFields(yearMonth, fieldNames, «»).
  207. auto* this_fields = TRY(prepare_temporal_fields(vm, year_month, field_names, Vector<StringView> {}));
  208. // 11. Perform ! CreateDataPropertyOrThrow(thisFields, "day", 1𝔽).
  209. MUST(this_fields->create_data_property_or_throw(vm.names.day, Value(1)));
  210. // 12. Let thisDate be ? CalendarDateFromFields(calendar, thisFields).
  211. auto* this_date = TRY(calendar_date_from_fields(vm, calendar, *this_fields));
  212. // 13. Let untilOptions be ? MergeLargestUnitOption(settings.[[Options]], settings.[[LargestUnit]]).
  213. auto* until_options = TRY(merge_largest_unit_option(vm, settings.options, move(settings.largest_unit)));
  214. // 14. Let result be ? CalendarDateUntil(calendar, thisDate, otherDate, untilOptions).
  215. auto* duration = TRY(calendar_date_until(vm, calendar, this_date, other_date, *until_options));
  216. auto result = DurationRecord { duration->years(), duration->months(), 0, 0, 0, 0, 0, 0, 0, 0 };
  217. // 15. If settings.[[SmallestUnit]] is not "month" or settings.[[RoundingIncrement]] ≠ 1, then
  218. if (settings.smallest_unit != "month"sv || settings.rounding_increment != 1) {
  219. // a. Set result to (? RoundDuration(result.[[Years]], result.[[Months]], 0, 0, 0, 0, 0, 0, 0, 0, settings.[[RoundingIncrement]], settings.[[SmallestUnit]], settings.[[RoundingMode]], thisDate)).[[DurationRecord]].
  220. result = TRY(round_duration(vm, result.years, result.months, 0, 0, 0, 0, 0, 0, 0, 0, settings.rounding_increment, settings.smallest_unit, settings.rounding_mode, this_date)).duration_record;
  221. }
  222. // 16. Return ! CreateTemporalDuration(sign × result.[[Years]], sign × result.[[Months]], 0, 0, 0, 0, 0, 0, 0, 0).
  223. return MUST(create_temporal_duration(vm, sign * result.years, sign * result.months, 0, 0, 0, 0, 0, 0, 0, 0));
  224. }
  225. // 9.5.8 AddDurationToOrSubtractDurationFromPlainYearMonth ( operation, yearMonth, temporalDurationLike, options ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoorsubtractdurationfromplainyearmonth
  226. ThrowCompletionOr<PlainYearMonth*> add_duration_to_or_subtract_duration_from_plain_year_month(VM& vm, ArithmeticOperation operation, PlainYearMonth& year_month, Value temporal_duration_like, Value options_value)
  227. {
  228. auto& realm = *vm.current_realm();
  229. // 1. Let duration be ? ToTemporalDuration(temporalDurationLike).
  230. auto* duration = TRY(to_temporal_duration(vm, temporal_duration_like));
  231. // 2. If operation is subtract, then
  232. if (operation == ArithmeticOperation::Subtract) {
  233. // a. Set duration to ! CreateNegatedTemporalDuration(duration).
  234. duration = create_negated_temporal_duration(vm, *duration);
  235. }
  236. // 3. Let balanceResult be ? BalanceDuration(duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]], "day").
  237. auto balance_result = TRY(balance_duration(vm, duration->days(), duration->hours(), duration->minutes(), duration->seconds(), duration->milliseconds(), duration->microseconds(), Crypto::SignedBigInteger { duration->nanoseconds() }, "day"sv));
  238. // 4. Set options to ? GetOptionsObject(options).
  239. auto* options = TRY(get_options_object(vm, options_value));
  240. // 5. Let calendar be yearMonth.[[Calendar]].
  241. auto& calendar = year_month.calendar();
  242. // 6. Let fieldNames be ? CalendarFields(calendar, « "monthCode", "year" »).
  243. auto field_names = TRY(calendar_fields(vm, calendar, { "monthCode"sv, "year"sv }));
  244. // 7. Let fields be ? PrepareTemporalFields(yearMonth, fieldNames, «»).
  245. auto* fields = TRY(prepare_temporal_fields(vm, year_month, field_names, Vector<StringView> {}));
  246. // 8. Set sign to ! DurationSign(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], balanceResult.[[Days]], 0, 0, 0, 0, 0, 0).
  247. auto sign = duration_sign(duration->years(), duration->months(), duration->weeks(), balance_result.days, 0, 0, 0, 0, 0, 0);
  248. double day;
  249. // 9. If sign < 0, then
  250. if (sign < 0) {
  251. // a. Let day be ? CalendarDaysInMonth(calendar, yearMonth).
  252. day = TRY(calendar_days_in_month(vm, calendar, year_month));
  253. }
  254. // 10. Else,
  255. else {
  256. // a. Let day be 1.
  257. day = 1;
  258. }
  259. // 11. Perform ! CreateDataPropertyOrThrow(fields, "day", 𝔽(day)).
  260. MUST(fields->create_data_property_or_throw(vm.names.day, Value(day)));
  261. // 12. Let date be ? CalendarDateFromFields(calendar, fields).
  262. auto* date = TRY(calendar_date_from_fields(vm, calendar, *fields));
  263. // 13. Let durationToAdd be ! CreateTemporalDuration(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], balanceResult.[[Days]], 0, 0, 0, 0, 0, 0).
  264. auto* duration_to_add = MUST(create_temporal_duration(vm, duration->years(), duration->months(), duration->weeks(), balance_result.days, 0, 0, 0, 0, 0, 0));
  265. // 14. Let optionsCopy be OrdinaryObjectCreate(null).
  266. auto options_copy = Object::create(realm, nullptr);
  267. // 15. Let entries be ? EnumerableOwnPropertyNames(options, key+value).
  268. auto entries = TRY(options->enumerable_own_property_names(Object::PropertyKind::KeyAndValue));
  269. // 16. For each element entry of entries, do
  270. for (auto& entry : entries) {
  271. auto key = MUST(entry.as_array().get_without_side_effects(0).to_property_key(vm));
  272. auto value = entry.as_array().get_without_side_effects(1);
  273. // a. Perform ! CreateDataPropertyOrThrow(optionsCopy, entry[0], entry[1]).
  274. MUST(options_copy->create_data_property_or_throw(key, value));
  275. }
  276. // 17. Let addedDate be ? CalendarDateAdd(calendar, date, durationToAdd, options).
  277. auto* added_date = TRY(calendar_date_add(vm, calendar, date, *duration_to_add, options));
  278. // 18. Let addedDateFields be ? PrepareTemporalFields(addedDate, fieldNames, «»).
  279. auto* added_date_fields = TRY(prepare_temporal_fields(vm, *added_date, field_names, Vector<StringView> {}));
  280. // 19. Return ? CalendarYearMonthFromFields(calendar, addedDateFields, optionsCopy).
  281. return calendar_year_month_from_fields(vm, calendar, *added_date_fields, options_copy);
  282. }
  283. }