PlainYearMonth.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Array.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  10. #include <LibJS/Runtime/Temporal/Calendar.h>
  11. #include <LibJS/Runtime/Temporal/Duration.h>
  12. #include <LibJS/Runtime/Temporal/PlainDate.h>
  13. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  14. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  15. namespace JS::Temporal {
  16. // 9 Temporal.PlainYearMonth Objects, https://tc39.es/proposal-temporal/#sec-temporal-plainyearmonth-objects
  17. PlainYearMonth::PlainYearMonth(i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, Object& prototype)
  18. : Object(prototype)
  19. , m_iso_year(iso_year)
  20. , m_iso_month(iso_month)
  21. , m_iso_day(iso_day)
  22. , m_calendar(calendar)
  23. {
  24. }
  25. void PlainYearMonth::visit_edges(Visitor& visitor)
  26. {
  27. Base::visit_edges(visitor);
  28. visitor.visit(&m_calendar);
  29. }
  30. // 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth
  31. ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object const* options)
  32. {
  33. auto& vm = global_object.vm();
  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(global_object, item_object));
  46. // c. Let fieldNames be ? CalendarFields(calendar, « "month", "monthCode", "year" »).
  47. auto field_names = TRY(calendar_fields(global_object, *calendar, { "month"sv, "monthCode"sv, "year"sv }));
  48. // d. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  49. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, {}));
  50. // e. Return ? CalendarYearMonthFromFields(calendar, fields, options).
  51. return calendar_year_month_from_fields(global_object, *calendar, *fields, options);
  52. }
  53. // 4. Perform ? ToTemporalOverflow(options).
  54. (void)TRY(to_temporal_overflow(global_object, options));
  55. // 5. Let string be ? ToString(item).
  56. auto string = TRY(item.to_string(global_object));
  57. // 6. Let result be ? ParseTemporalYearMonthString(string).
  58. auto result = TRY(parse_temporal_year_month_string(global_object, string));
  59. // 7. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  60. auto* calendar = TRY(to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(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(global_object, 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(global_object, *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(GlobalObject& global_object, double year, double month, StringView overflow)
  69. {
  70. auto& vm = global_object.vm();
  71. // 1. Assert: year and month are integers.
  72. VERIFY(year == trunc(year) && month == trunc(month));
  73. // 2. Assert: overflow is either "constrain" or "reject".
  74. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  75. // 3. If overflow is "constrain", then
  76. if (overflow == "constrain"sv) {
  77. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat `year` (a double) as normal integer from this point onwards.
  78. // This does not change the exposed behavior as the subsequent call to CreateTemporalYearMonth will check that its value is a valid ISO
  79. // values (for years: -273975 - 273975) which is a subset of this check.
  80. // If RegulateISOYearMonth is ever used outside ISOYearMonthFromFields, this may need to be changed.
  81. if (!AK::is_within_range<i32>(year))
  82. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  83. // a. Return ! ConstrainISOYearMonth(year, month).
  84. return constrain_iso_year_month(year, month);
  85. }
  86. // 4. If overflow is "reject", then
  87. if (overflow == "reject"sv) {
  88. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  89. // This does not change the exposed behavior as the call to IsValidISOMonth and subsequent call to CreateTemporalDateTime will check
  90. // that these values are valid ISO values (for years: -273975 - 273975, for months: 1 - 12) all of which are subsets of this check.
  91. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month))
  92. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  93. // a. If ! IsValidISOMonth(month) is false, throw a RangeError exception.
  94. if (!is_valid_iso_month(month))
  95. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  96. // b. Return the Record { [[Year]]: year, [[Month]]: month }.
  97. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  98. }
  99. VERIFY_NOT_REACHED();
  100. }
  101. // 9.5.3 IsValidISOMonth ( month ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisomonth
  102. bool is_valid_iso_month(u8 month)
  103. {
  104. // 1. Assert: month is an integer.
  105. // 2. If month < 1 or month > 12, then
  106. if (month < 1 || month > 12) {
  107. // a.Return false.
  108. return false;
  109. }
  110. // 3. Return true.
  111. return true;
  112. }
  113. // 9.5.4 ISOYearMonthWithinLimits ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthwithinlimits
  114. bool iso_year_month_within_limits(i32 year, u8 month)
  115. {
  116. // 1. Assert: year and month are integers.
  117. // 2. If year < -271821 or year > 275760, then
  118. if (year < -271821 || year > 275760) {
  119. // a. Return false.
  120. return false;
  121. }
  122. // 3. If year is -271821 and month < 4, then
  123. if (year == -271821 && month < 4) {
  124. // a. Return false.
  125. return false;
  126. }
  127. // 4. If year is 275760 and month > 9, then
  128. if (year == 275760 && month > 9) {
  129. // a. Return false.
  130. return false;
  131. }
  132. // 5. Return true.
  133. return true;
  134. }
  135. // 9.5.5 BalanceISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisoyearmonth
  136. ISOYearMonth balance_iso_year_month(double year, double month)
  137. {
  138. // 1. Assert: year and month are integers.
  139. VERIFY(year == trunc(year) && month == trunc(month));
  140. // 2. Set year to year + floor((month - 1) / 12).
  141. year += floor((month - 1) / 12);
  142. // 3. Set month to (month - 1) modulo 12 + 1.
  143. month = modulo(month - 1, 12) + 1;
  144. // 4. Return the Record { [[Year]]: year, [[Month]]: month }.
  145. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  146. }
  147. // 9.5.6 ConstrainISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-constrainisoyearmonth
  148. ISOYearMonth constrain_iso_year_month(double year, double month)
  149. {
  150. // 1. Assert: year and month are integers.
  151. VERIFY(year == trunc(year) && month == trunc(month));
  152. // 2. Set month to the result of clamping month between 1 and 12.
  153. month = clamp(month, 1, 12);
  154. // 3. Return the Record { [[Year]]: year, [[Month]]: month }.
  155. // NOTE: `year` is known to be in the i32 range.
  156. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  157. }
  158. // 9.5.7 CreateTemporalYearMonth ( isoYear, isoMonth, calendar, referenceISODay [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalyearmonth
  159. ThrowCompletionOr<PlainYearMonth*> create_temporal_year_month(GlobalObject& global_object, i32 iso_year, u8 iso_month, Object& calendar, u8 reference_iso_day, FunctionObject const* new_target)
  160. {
  161. auto& vm = global_object.vm();
  162. // 1. Assert: isoYear, isoMonth, and referenceISODay are integers.
  163. // 2. Assert: Type(calendar) is Object.
  164. // 3. If IsValidISODate(isoYear, isoMonth, referenceISODay) is false, throw a RangeError exception.
  165. if (!is_valid_iso_date(iso_year, iso_month, reference_iso_day))
  166. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  167. // 4. If ! ISOYearMonthWithinLimits(isoYear, isoMonth) is false, throw a RangeError exception.
  168. if (!iso_year_month_within_limits(iso_year, iso_month))
  169. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  170. // 5. If newTarget is not present, set newTarget to %Temporal.PlainYearMonth%.
  171. if (!new_target)
  172. new_target = global_object.temporal_plain_year_month_constructor();
  173. // 6. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainYearMonth.prototype%", « [[InitializedTemporalYearMonth]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  174. // 7. Set object.[[ISOYear]] to isoYear.
  175. // 8. Set object.[[ISOMonth]] to isoMonth.
  176. // 9. Set object.[[Calendar]] to calendar.
  177. // 10. Set object.[[ISODay]] to referenceISODay.
  178. auto* object = TRY(ordinary_create_from_constructor<PlainYearMonth>(global_object, *new_target, &GlobalObject::temporal_plain_year_month_prototype, iso_year, iso_month, reference_iso_day, calendar));
  179. // 11. Return object.
  180. return object;
  181. }
  182. // 9.5.8 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring
  183. ThrowCompletionOr<String> temporal_year_month_to_string(GlobalObject& global_object, PlainYearMonth& year_month, StringView show_calendar)
  184. {
  185. // 1. Assert: Type(yearMonth) is Object.
  186. // 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot.
  187. // 3. Let year be ! PadISOYear(yearMonth.[[ISOYear]]).
  188. // 4. Let month be ToZeroPaddedDecimalString(yearMonth.[[ISOMonth]], 2).
  189. // 5. Let result be the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), and month.
  190. auto result = String::formatted("{}-{:02}", pad_iso_year(year_month.iso_year()), year_month.iso_month());
  191. // 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]).
  192. auto calendar_id = TRY(Value(&year_month.calendar()).to_string(global_object));
  193. // 7. If showCalendar is "always" or if calendarID is not "iso8601", then
  194. if (show_calendar == "always"sv || calendar_id != "iso8601") {
  195. // a. Let day be ToZeroPaddedDecimalString(yearMonth.[[ISODay]], 2).
  196. // b. Set result to the string-concatenation of result, the code unit 0x002D (HYPHEN-MINUS), and day.
  197. result = String::formatted("{}-{:02}", result, year_month.iso_day());
  198. }
  199. // 8. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  200. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  201. // 9. Set result to the string-concatenation of result and calendarString.
  202. // 10. Return result.
  203. return String::formatted("{}{}", result, calendar_string);
  204. }
  205. // 9.5.9 AddDurationToOrSubtractDurationFromPlainYearMonth ( operation, yearMonth, temporalDurationLike, options ), https://tc39.es/proposal-temporal/#sec-temporal-addtemporalplainyearmonth
  206. ThrowCompletionOr<PlainYearMonth*> add_duration_to_or_subtract_duration_from_plain_year_month(GlobalObject& global_object, ArithmeticOperation operation, PlainYearMonth& year_month, Value temporal_duration_like, Value options_value)
  207. {
  208. auto& vm = global_object.vm();
  209. // 1. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  210. auto duration = TRY(to_temporal_duration_record(global_object, temporal_duration_like));
  211. // 2. If operation is subtract, then
  212. if (operation == ArithmeticOperation::Subtract) {
  213. // a. Set duration to ! CreateNegatedTemporalDuration(duration).
  214. // FIXME: According to the spec CreateNegatedTemporalDuration takes a Temporal.Duration object,
  215. // not a record, so we have to do some trickery. If they want to accept anything that has
  216. // the required internal slots, this should be updated in the AO's description.
  217. // We also have to convert back to a Duration Record afterwards to match the initial type.
  218. auto* actual_duration = MUST(create_temporal_duration(global_object, duration.years, duration.months, duration.weeks, duration.days, duration.hours, duration.minutes, duration.seconds, duration.milliseconds, duration.microseconds, duration.nanoseconds));
  219. auto* negated_duration = create_negated_temporal_duration(global_object, *actual_duration);
  220. duration = MUST(to_temporal_duration_record(global_object, negated_duration));
  221. }
  222. // 3. Let balanceResult be ? BalanceDuration(duration.[[Days]], duration.[[Hours]], duration.[[Minutes]], duration.[[Seconds]], duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]], "day").
  223. auto balance_result = TRY(balance_duration(global_object, duration.days, duration.hours, duration.minutes, duration.seconds, duration.milliseconds, duration.microseconds, Crypto::SignedBigInteger::create_from((i64)duration.nanoseconds), "day"sv));
  224. // 4. Set options to ? GetOptionsObject(options).
  225. auto* options = TRY(get_options_object(global_object, options_value));
  226. // 5. Let calendar be yearMonth.[[Calendar]].
  227. auto& calendar = year_month.calendar();
  228. // 6. Let fieldNames be ? CalendarFields(calendar, « "monthCode", "year" »).
  229. auto field_names = TRY(calendar_fields(global_object, calendar, { "monthCode"sv, "year"sv }));
  230. // 7. Let fields be ? PrepareTemporalFields(yearMonth, fieldNames, «»).
  231. auto* fields = TRY(prepare_temporal_fields(global_object, year_month, field_names, {}));
  232. // 8. Set sign to ! DurationSign(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], balanceResult.[[Days]], 0, 0, 0, 0, 0, 0).
  233. auto sign = duration_sign(duration.years, duration.months, duration.weeks, balance_result.days, 0, 0, 0, 0, 0, 0);
  234. double day;
  235. // 9. If sign < 0, then
  236. if (sign < 0) {
  237. // a. Let dayFromCalendar be ? CalendarDaysInMonth(calendar, yearMonth).
  238. auto day_from_calendar = TRY(calendar_days_in_month(global_object, calendar, year_month));
  239. // b. Let day be ? ToPositiveInteger(dayFromCalendar).
  240. day = TRY(to_positive_integer(global_object, day_from_calendar));
  241. }
  242. // 10. Else,
  243. else {
  244. // a. Let day be 1.
  245. day = 1;
  246. }
  247. // 11. Perform ! CreateDataPropertyOrThrow(fields, "day", day).
  248. MUST(fields->create_data_property_or_throw(vm.names.day, Value(day)));
  249. // 12. Let date be ? CalendarDateFromFields(calendar, fields, undefined).
  250. auto* date = TRY(calendar_date_from_fields(global_object, calendar, *fields, nullptr));
  251. // 13. Let durationToAdd be ! CreateTemporalDuration(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], balanceResult.[[Days]], 0, 0, 0, 0, 0, 0).
  252. auto* duration_to_add = MUST(create_temporal_duration(global_object, duration.years, duration.months, duration.weeks, balance_result.days, 0, 0, 0, 0, 0, 0));
  253. // 14. Let optionsCopy be OrdinaryObjectCreate(%Object.prototype%).
  254. auto* options_copy = Object::create(global_object, global_object.object_prototype());
  255. // 15. Let entries be ? EnumerableOwnPropertyNames(options, key+value).
  256. auto entries = TRY(options->enumerable_own_property_names(Object::PropertyKind::KeyAndValue));
  257. // 16. For each element nextEntry of entries, do
  258. for (auto& next_entry : entries) {
  259. auto key = MUST(next_entry.as_array().get_without_side_effects(0).to_property_key(global_object));
  260. auto value = next_entry.as_array().get_without_side_effects(1);
  261. // a. Perform ! CreateDataPropertyOrThrow(optionsCopy, nextEntry[0], nextEntry[1]).
  262. MUST(options_copy->create_data_property_or_throw(key, value));
  263. }
  264. // 17. Let addedDate be ? CalendarDateAdd(calendar, date, durationToAdd, options).
  265. auto* added_date = TRY(calendar_date_add(global_object, calendar, date, *duration_to_add, options));
  266. // 18. Let addedDateFields be ? PrepareTemporalFields(addedDate, fieldNames, «»).
  267. auto* added_date_fields = TRY(prepare_temporal_fields(global_object, *added_date, field_names, {}));
  268. // 19. Return ? CalendarYearMonthFromFields(calendar, addedDateFields, optionsCopy).
  269. return calendar_year_month_from_fields(global_object, calendar, *added_date_fields, options_copy);
  270. }
  271. }