PlainYearMonth.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/GlobalObject.h>
  8. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  9. #include <LibJS/Runtime/Temporal/Calendar.h>
  10. #include <LibJS/Runtime/Temporal/PlainDate.h>
  11. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  12. #include <LibJS/Runtime/Temporal/PlainYearMonthConstructor.h>
  13. namespace JS::Temporal {
  14. // 9 Temporal.PlainYearMonth Objects, https://tc39.es/proposal-temporal/#sec-temporal-plainyearmonth-objects
  15. PlainYearMonth::PlainYearMonth(i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, Object& prototype)
  16. : Object(prototype)
  17. , m_iso_year(iso_year)
  18. , m_iso_month(iso_month)
  19. , m_iso_day(iso_day)
  20. , m_calendar(calendar)
  21. {
  22. }
  23. void PlainYearMonth::visit_edges(Visitor& visitor)
  24. {
  25. Base::visit_edges(visitor);
  26. visitor.visit(&m_calendar);
  27. }
  28. // 9.5.1 ToTemporalYearMonth ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalyearmonth
  29. ThrowCompletionOr<PlainYearMonth*> to_temporal_year_month(GlobalObject& global_object, Value item, Object* options)
  30. {
  31. auto& vm = global_object.vm();
  32. // 1. If options is not present, set options to undefined.
  33. // 2. Assert: Type(options) is Object or Undefined.
  34. // 3. If Type(item) is Object, then
  35. if (item.is_object()) {
  36. auto& item_object = item.as_object();
  37. // a. If item has an [[InitializedTemporalYearMonth]] internal slot, then
  38. if (is<PlainYearMonth>(item_object)) {
  39. // i. Return item.
  40. return static_cast<PlainYearMonth*>(&item_object);
  41. }
  42. // b. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  43. auto* calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  44. // c. Let fieldNames be ? CalendarFields(calendar, « "month", "monthCode", "year" »).
  45. auto field_names = TRY(calendar_fields(global_object, *calendar, { "month"sv, "monthCode"sv, "year"sv }));
  46. // d. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  47. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, {}));
  48. // e. Return ? YearMonthFromFields(calendar, fields, options).
  49. return year_month_from_fields(global_object, *calendar, *fields, options);
  50. }
  51. // 4. Perform ? ToTemporalOverflow(options).
  52. (void)TRY(to_temporal_overflow(global_object, options));
  53. // 5. Let string be ? ToString(item).
  54. auto string = TRY(item.to_string(global_object));
  55. // 6. Let result be ? ParseTemporalYearMonthString(string).
  56. auto result = TRY(parse_temporal_year_month_string(global_object, string));
  57. // 7. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  58. auto* calendar = TRY(to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()));
  59. // 8. Set result to ? CreateTemporalYearMonth(result.[[Year]], result.[[Month]], calendar, result.[[Day]]).
  60. auto* creation_result = TRY(create_temporal_year_month(global_object, result.year, result.month, *calendar, result.day));
  61. // 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.
  62. // 10. Return ? YearMonthFromFields(calendar, result).
  63. return year_month_from_fields(global_object, *calendar, *creation_result);
  64. }
  65. // 9.5.2 RegulateISOYearMonth ( year, month, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisoyearmonth
  66. ThrowCompletionOr<ISOYearMonth> regulate_iso_year_month(GlobalObject& global_object, double year, double month, StringView overflow)
  67. {
  68. auto& vm = global_object.vm();
  69. // 1. Assert: year and month are integers.
  70. VERIFY(year == trunc(year) && month == trunc(month));
  71. // 2. Assert: overflow is either "constrain" or "reject".
  72. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  73. // 3. If overflow is "constrain", then
  74. if (overflow == "constrain"sv) {
  75. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat `year` (a double) as normal integer from this point onwards.
  76. // This does not change the exposed behavior as the subsequent call to CreateTemporalYearMonth will check that its value is a valid ISO
  77. // values (for years: -273975 - 273975) which is a subset of this check.
  78. // If RegulateISOYearMonth is ever used outside ISOYearMonthFromFields, this may need to be changed.
  79. if (!AK::is_within_range<i32>(year))
  80. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  81. // a. Return ! ConstrainISOYearMonth(year, month).
  82. return constrain_iso_year_month(year, month);
  83. }
  84. // 4. If overflow is "reject", then
  85. if (overflow == "reject"sv) {
  86. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  87. // This does not change the exposed behavior as the call to IsValidISOMonth and subsequent call to CreateTemporalDateTime will check
  88. // that these values are valid ISO values (for years: -273975 - 273975, for months: 1 - 12) all of which are subsets of this check.
  89. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month))
  90. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  91. // a. If ! IsValidISOMonth(month) is false, throw a RangeError exception.
  92. if (!is_valid_iso_month(month))
  93. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  94. // b. Return the Record { [[Year]]: year, [[Month]]: month }.
  95. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  96. }
  97. VERIFY_NOT_REACHED();
  98. }
  99. // 9.5.3 IsValidISOMonth ( month ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisomonth
  100. bool is_valid_iso_month(u8 month)
  101. {
  102. // 1. Assert: month is an integer.
  103. // 2. If month < 1 or month > 12, then
  104. if (month < 1 || month > 12) {
  105. // a.Return false.
  106. return false;
  107. }
  108. // 3. Return true.
  109. return true;
  110. }
  111. // 9.5.4 ISOYearMonthWithinLimits ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthwithinlimits
  112. bool iso_year_month_within_limits(i32 year, u8 month)
  113. {
  114. // 1. Assert: year and month are integers.
  115. // 2. If year < −271821 or year > 275760, then
  116. if (year < -271821 || year > 275760) {
  117. // a. Return false.
  118. return false;
  119. }
  120. // 3. If year is −271821 and month < 4, then
  121. if (year == -271821 && month < 4) {
  122. // a. Return false.
  123. return false;
  124. }
  125. // 4. If year is 275760 and month > 9, then
  126. if (year == 275760 && month > 9) {
  127. // a. Return false.
  128. return false;
  129. }
  130. // 5. Return true.
  131. return true;
  132. }
  133. // 9.5.5 BalanceISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisoyearmonth
  134. ISOYearMonth balance_iso_year_month(double year, double month)
  135. {
  136. // 1. Assert: year and month are integers.
  137. VERIFY(year == trunc(year) && month == trunc(month));
  138. // 2. Set year to year + floor((month - 1) / 12).
  139. year += floor((month - 1) / 12);
  140. // 3. Set month to (month − 1) modulo 12 + 1.
  141. month = modulo(month - 1, 12) + 1;
  142. // 4. Return the Record { [[Year]]: year, [[Month]]: month }.
  143. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  144. }
  145. // 9.5.6 ConstrainISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-constrainisoyearmonth
  146. ISOYearMonth constrain_iso_year_month(double year, double month)
  147. {
  148. // 1. Assert: year and month are integers.
  149. VERIFY(year == trunc(year) && month == trunc(month));
  150. // 2. Set month to the result of clamping month between 1 and 12.
  151. month = clamp(month, 1, 12);
  152. // 3. Return the Record { [[Year]]: year, [[Month]]: month }.
  153. // NOTE: `year` is known to be in the i32 range.
  154. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  155. }
  156. // 9.5.7 CreateTemporalYearMonth ( isoYear, isoMonth, calendar, referenceISODay [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalyearmonth
  157. 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)
  158. {
  159. auto& vm = global_object.vm();
  160. // 1. Assert: isoYear, isoMonth, and referenceISODay are integers.
  161. // 2. Assert: Type(calendar) is Object.
  162. // 3. If ! IsValidISODate(isoYear, isoMonth, referenceISODay) is false, throw a RangeError exception.
  163. if (!is_valid_iso_date(iso_year, iso_month, reference_iso_day))
  164. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  165. // 4. If ! ISOYearMonthWithinLimits(isoYear, isoMonth) is false, throw a RangeError exception.
  166. if (!iso_year_month_within_limits(iso_year, iso_month))
  167. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  168. // 5. If newTarget is not present, set newTarget to %Temporal.PlainYearMonth%.
  169. if (!new_target)
  170. new_target = global_object.temporal_plain_year_month_constructor();
  171. // 6. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainYearMonth.prototype%", « [[InitializedTemporalYearMonth]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  172. // 7. Set object.[[ISOYear]] to isoYear.
  173. // 8. Set object.[[ISOMonth]] to isoMonth.
  174. // 9. Set object.[[Calendar]] to calendar.
  175. // 10. Set object.[[ISODay]] to referenceISODay.
  176. 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));
  177. // 11. Return object.
  178. return object;
  179. }
  180. // 9.5.8 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring
  181. ThrowCompletionOr<String> temporal_year_month_to_string(GlobalObject& global_object, PlainYearMonth& year_month, StringView show_calendar)
  182. {
  183. // 1. Assert: Type(yearMonth) is Object.
  184. // 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot.
  185. // 3. Let year be ! PadISOYear(yearMonth.[[ISOYear]]).
  186. // 4. Let month be yearMonth.[[ISOMonth]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  187. // 5. Let result be the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), and month.
  188. auto result = String::formatted("{}-{:02}", pad_iso_year(year_month.iso_year()), year_month.iso_month());
  189. // 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]).
  190. auto calendar_id = TRY(Value(&year_month.calendar()).to_string(global_object));
  191. // 7. If showCalendar is "always" or if calendarID is not "iso8601", then
  192. if (show_calendar == "always"sv || calendar_id != "iso8601") {
  193. // a. Let day be yearMonth.[[ISODay]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  194. // b. Set result to the string-concatenation of result, the code unit 0x002D (HYPHEN-MINUS), and day.
  195. result = String::formatted("{}-{:02}", result, year_month.iso_day());
  196. }
  197. // 8. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  198. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  199. // 9. Set result to the string-concatenation of result and calendarString.
  200. // 10. Return result.
  201. return String::formatted("{}{}", result, calendar_string);
  202. }
  203. }