PlainYearMonth.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (c) 2021, 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. 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 ! OrdinaryObjectCreate(null).
  33. if (!options)
  34. options = Object::create(global_object, nullptr);
  35. // 2. Assert: Type(options) is Object.
  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 = get_temporal_calendar_with_iso_default(global_object, item_object);
  46. if (vm.exception())
  47. return {};
  48. // c. Let fieldNames be ? CalendarFields(calendar, « "month", "monthCode", "year" »).
  49. auto field_names = calendar_fields(global_object, *calendar, { "month"sv, "monthCode"sv, "year"sv });
  50. if (vm.exception())
  51. return {};
  52. // d. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  53. auto* fields = prepare_temporal_fields(global_object, item_object, field_names, {});
  54. if (vm.exception())
  55. return {};
  56. // e. Return ? YearMonthFromFields(calendar, fields, options).
  57. return year_month_from_fields(global_object, *calendar, *fields, options);
  58. }
  59. // 4. Perform ? ToTemporalOverflow(options).
  60. (void)to_temporal_overflow(global_object, *options);
  61. if (vm.exception())
  62. return {};
  63. // 5. Let string be ? ToString(item).
  64. auto string = item.to_string(global_object);
  65. if (vm.exception())
  66. return {};
  67. // 6. Let result be ? ParseTemporalYearMonthString(string).
  68. auto result = parse_temporal_year_month_string(global_object, string);
  69. if (vm.exception())
  70. return {};
  71. // 7. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  72. auto* calendar = to_temporal_calendar_with_iso_default(global_object, result->calendar.has_value() ? js_string(vm, *result->calendar) : js_undefined());
  73. if (vm.exception())
  74. return {};
  75. // 8. Set result to ? CreateTemporalYearMonth(result.[[Year]], result.[[Month]], calendar, result.[[Day]]).
  76. auto* creation_result = create_temporal_year_month(global_object, result->year, result->month, *calendar, result->day);
  77. if (vm.exception())
  78. return {};
  79. // 9. Let canonicalYearMonthOptions be ! OrdinaryObjectCreate(null).
  80. auto* canonical_year_month_options = Object::create(global_object, nullptr);
  81. // 10. Return ? YearMonthFromFields(calendar, result, canonicalYearMonthOptions).
  82. return year_month_from_fields(global_object, *calendar, *creation_result, canonical_year_month_options);
  83. }
  84. // 9.5.2 RegulateISOYearMonth ( year, month, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisoyearmonth
  85. Optional<ISOYearMonth> regulate_iso_year_month(GlobalObject& global_object, double year, double month, StringView overflow)
  86. {
  87. auto& vm = global_object.vm();
  88. // 1. Assert: year and month are integers.
  89. VERIFY(year == trunc(year) && month == trunc(month));
  90. // 2. Assert: overflow is either "constrain" or "reject".
  91. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  92. // 3. If overflow is "constrain", then
  93. if (overflow == "constrain"sv) {
  94. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat `year` (a double) as normal integer from this point onwards.
  95. // This does not change the exposed behavior as the subsequent call to CreateTemporalYearMonth will check that its value is a valid ISO
  96. // values (for years: -273975 - 273975) which is a subset of this check.
  97. // If RegulateISOYearMonth is ever used outside ISOYearMonthFromFields, this may need to be changed.
  98. if (!AK::is_within_range<i32>(year)) {
  99. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  100. return {};
  101. }
  102. // a. Return ! ConstrainISOYearMonth(year, month).
  103. return constrain_iso_year_month(year, month);
  104. }
  105. // 4. If overflow is "reject", then
  106. if (overflow == "reject"sv) {
  107. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  108. // This does not change the exposed behavior as the call to IsValidISOMonth and subsequent call to CreateTemporalDateTime will check
  109. // that these values are valid ISO values (for years: -273975 - 273975, for months: 1 - 12) all of which are subsets of this check.
  110. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month)) {
  111. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  112. return {};
  113. }
  114. // a. If ! IsValidISOMonth(month) is false, throw a RangeError exception.
  115. if (!is_valid_iso_month(month)) {
  116. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  117. return {};
  118. }
  119. // b. Return the Record { [[Year]]: year, [[Month]]: month }.
  120. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  121. }
  122. VERIFY_NOT_REACHED();
  123. }
  124. // 9.5.3 IsValidISOMonth ( month ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisomonth
  125. bool is_valid_iso_month(u8 month)
  126. {
  127. // 1. Assert: month is an integer.
  128. // 2. If month < 1 or month > 12, then
  129. if (month < 1 || month > 12) {
  130. // a.Return false.
  131. return false;
  132. }
  133. // 3. Return true.
  134. return true;
  135. }
  136. // 9.5.4 ISOYearMonthWithinLimits ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isoyearmonthwithinlimits
  137. bool iso_year_month_within_limits(i32 year, u8 month)
  138. {
  139. // 1. Assert: year and month are integers.
  140. // 2. If year < −271821 or year > 275760, then
  141. if (year < -271821 || year > 275760) {
  142. // a. Return false.
  143. return false;
  144. }
  145. // 3. If year is −271821 and month < 4, then
  146. if (year == -271821 && month < 4) {
  147. // a. Return false.
  148. return false;
  149. }
  150. // 4. If year is 275760 and month > 9, then
  151. if (year == 275760 && month > 9) {
  152. // a. Return false.
  153. return false;
  154. }
  155. // 5. Return true.
  156. return true;
  157. }
  158. // 9.5.5 BalanceISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisoyearmonth
  159. ISOYearMonth balance_iso_year_month(double year, double month)
  160. {
  161. // 1. Assert: year and month are integers.
  162. VERIFY(year == trunc(year) && month == trunc(month));
  163. // 2. Set year to year + floor((month - 1) / 12).
  164. year += floor((month - 1) / 12);
  165. // 3. Set month to (month − 1) modulo 12 + 1.
  166. month = fmod(month - 1, 12) + 1;
  167. // 4. Return the Record { [[Year]]: year, [[Month]]: month }.
  168. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  169. }
  170. // 9.5.6 ConstrainISOYearMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-constrainisoyearmonth
  171. ISOYearMonth constrain_iso_year_month(double year, double month)
  172. {
  173. // 1. Assert: year and month are integers.
  174. VERIFY(year == trunc(year) && month == trunc(month));
  175. // 2. Set month to ! ConstrainToRange(month, 1, 12).
  176. month = constrain_to_range(month, 1, 12);
  177. // 3. Return the Record { [[Year]]: year, [[Month]]: month }.
  178. // NOTE: `year` is known to be in the i32 range.
  179. return ISOYearMonth { .year = static_cast<i32>(year), .month = static_cast<u8>(month), .reference_iso_day = 0 };
  180. }
  181. // 9.5.7 CreateTemporalYearMonth ( isoYear, isoMonth, calendar, referenceISODay [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalyearmonth
  182. PlainYearMonth* create_temporal_year_month(GlobalObject& global_object, i32 iso_year, u8 iso_month, Object& calendar, u8 reference_iso_day, FunctionObject const* new_target)
  183. {
  184. auto& vm = global_object.vm();
  185. // 1. Assert: isoYear, isoMonth, and referenceISODay are integers.
  186. // 2. Assert: Type(calendar) is Object.
  187. // 3. If ! IsValidISODate(isoYear, isoMonth, referenceISODay) is false, throw a RangeError exception.
  188. if (!is_valid_iso_date(iso_year, iso_month, reference_iso_day)) {
  189. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  190. return {};
  191. }
  192. // 4. If ! ISOYearMonthWithinLimits(isoYear, isoMonth) is false, throw a RangeError exception.
  193. if (!iso_year_month_within_limits(iso_year, iso_month)) {
  194. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidPlainYearMonth);
  195. return {};
  196. }
  197. // 5. If newTarget is not present, set it to %Temporal.PlainYearMonth%.
  198. if (!new_target)
  199. new_target = global_object.temporal_plain_year_month_constructor();
  200. // 6. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainYearMonth.prototype%", « [[InitializedTemporalYearMonth]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  201. // 7. Set object.[[ISOYear]] to isoYear.
  202. // 8. Set object.[[ISOMonth]] to isoMonth.
  203. // 9. Set object.[[Calendar]] to calendar.
  204. // 10. Set object.[[ISODay]] to referenceISODay.
  205. auto* object = ordinary_create_from_constructor<PlainYearMonth>(global_object, *new_target, &GlobalObject::temporal_plain_year_month_prototype, iso_year, iso_month, reference_iso_day, calendar);
  206. if (vm.exception())
  207. return {};
  208. // 11. Return object.
  209. return object;
  210. }
  211. // 9.5.8 TemporalYearMonthToString ( yearMonth, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporalyearmonthtostring
  212. Optional<String> temporal_year_month_to_string(GlobalObject& global_object, PlainYearMonth& year_month, StringView show_calendar)
  213. {
  214. auto& vm = global_object.vm();
  215. // 1. Assert: Type(yearMonth) is Object.
  216. // 2. Assert: yearMonth has an [[InitializedTemporalYearMonth]] internal slot.
  217. // 3. Let year be ! PadISOYear(yearMonth.[[ISOYear]]).
  218. // 4. Let month be yearMonth.[[ISOMonth]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  219. // 5. Let result be the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), and month.
  220. auto result = String::formatted("{}-{:02}", pad_iso_year(year_month.iso_year()), year_month.iso_month());
  221. // 6. Let calendarID be ? ToString(yearMonth.[[Calendar]]).
  222. auto calendar_id = Value(&year_month.calendar()).to_string(global_object);
  223. if (vm.exception())
  224. return {};
  225. // 7. If calendarID is not "iso8601", then
  226. if (calendar_id != "iso8601") {
  227. // a. Let day be yearMonth.[[ISODay]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  228. // b. Set result to the string-concatenation of result, the code unit 0x002D (HYPHEN-MINUS), and day.
  229. result = String::formatted("{}-{:02}", result, year_month.iso_day());
  230. }
  231. // 8. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  232. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  233. // 9. Set result to the string-concatenation of result and calendarString.
  234. // 10. Return result.
  235. return String::formatted("{}{}", result, calendar_string);
  236. }
  237. }