Calendar.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@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/CalendarConstructor.h>
  12. #include <LibJS/Runtime/Temporal/PlainDate.h>
  13. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  14. #include <LibJS/Runtime/Value.h>
  15. namespace JS::Temporal {
  16. // 12 Temporal.Calendar Objects, https://tc39.es/proposal-temporal/#sec-temporal-calendar-objects
  17. Calendar::Calendar(String identifier, Object& prototype)
  18. : Object(prototype)
  19. , m_identifier(move(identifier))
  20. {
  21. }
  22. // 12.1.1 CreateTemporalCalendar ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalcalendar
  23. Calendar* create_temporal_calendar(GlobalObject& global_object, String const& identifier, FunctionObject* new_target)
  24. {
  25. auto& vm = global_object.vm();
  26. // 1. Assert: ! IsBuiltinCalendar(identifier) is true.
  27. VERIFY(is_builtin_calendar(identifier));
  28. // 2. If newTarget is not provided, set newTarget to %Temporal.Calendar%.
  29. if (!new_target)
  30. new_target = global_object.temporal_calendar_constructor();
  31. // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.Calendar.prototype%", « [[InitializedTemporalCalendar]], [[Identifier]] »).
  32. // 4. Set object.[[Identifier]] to identifier.
  33. auto* object = ordinary_create_from_constructor<Calendar>(global_object, *new_target, &GlobalObject::temporal_calendar_prototype, identifier);
  34. if (vm.exception())
  35. return {};
  36. // 5. Return object.
  37. return object;
  38. }
  39. // 12.1.2 IsBuiltinCalendar ( id ), https://tc39.es/proposal-temporal/#sec-temporal-isbuiltincalendar
  40. // NOTE: This is the minimum IsBuiltinCalendar implementation for engines without ECMA-402.
  41. bool is_builtin_calendar(String const& identifier)
  42. {
  43. // 1. If id is not "iso8601", return false.
  44. if (identifier != "iso8601"sv)
  45. return false;
  46. // 2. Return true.
  47. return true;
  48. }
  49. // 12.1.3 GetBuiltinCalendar ( id )
  50. Calendar* get_builtin_calendar(GlobalObject& global_object, String const& identifier)
  51. {
  52. auto& vm = global_object.vm();
  53. // 1. If ! IsBuiltinCalendar(id) is false, throw a RangeError exception.
  54. if (!is_builtin_calendar(identifier)) {
  55. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidCalendarIdentifier, identifier);
  56. return {};
  57. }
  58. // 2. Return ? Construct(%Temporal.Calendar%, « id »).
  59. MarkedValueList arguments(vm.heap());
  60. arguments.append(js_string(vm, identifier));
  61. auto calendar = vm.construct(*global_object.temporal_calendar_constructor(), *global_object.temporal_calendar_constructor(), move(arguments));
  62. if (vm.exception())
  63. return {};
  64. return static_cast<Calendar*>(&calendar.as_object());
  65. }
  66. // 12.1.4 GetISO8601Calendar ( )
  67. Calendar* get_iso8601_calendar(GlobalObject& global_object)
  68. {
  69. // 1. Return ? GetBuiltinCalendar("iso8601").
  70. return get_builtin_calendar(global_object, "iso8601");
  71. }
  72. // 12.1.5 CalendarFields ( calendar, fieldNames ), https://tc39.es/proposal-temporal/#sec-temporal-calendarfields
  73. Vector<String> calendar_fields(GlobalObject& global_object, Object& calendar, Vector<StringView> const& field_names)
  74. {
  75. auto& vm = global_object.vm();
  76. // 1. Let fields be ? GetMethod(calendar, "fields").
  77. auto fields = Value(&calendar).get_method(global_object, vm.names.fields);
  78. if (vm.exception())
  79. return {};
  80. // 2. Let fieldsArray be ! CreateArrayFromList(fieldNames).
  81. Vector<Value> field_names_values;
  82. for (auto& field_name : field_names)
  83. field_names_values.append(js_string(vm, field_name));
  84. Value fields_array = Array::create_from(global_object, field_names_values);
  85. // 3. If fields is not undefined, then
  86. if (fields) {
  87. // a. Set fieldsArray to ? Call(fields, calendar, « fieldsArray »).
  88. fields_array = vm.call(*fields, &calendar, fields_array);
  89. if (vm.exception())
  90. return {};
  91. }
  92. // 4. Return ? IterableToListOfType(fieldsArray, « String »).
  93. auto list = iterable_to_list_of_type(global_object, fields_array, { OptionType::String });
  94. if (vm.exception())
  95. return {};
  96. Vector<String> result;
  97. for (auto& value : list)
  98. result.append(value.as_string().string());
  99. return result;
  100. }
  101. // 12.1.9 CalendarYear ( calendar, dateLike ), https://tc39.es/proposal-temporal/#sec-temporal-calendaryear
  102. double calendar_year(GlobalObject& global_object, Object& calendar, Object& date_like)
  103. {
  104. auto& vm = global_object.vm();
  105. // 1. Assert: Type(calendar) is Object.
  106. // 2. Let result be ? Invoke(calendar, "year", « dateLike »).
  107. auto result = calendar.invoke(vm.names.year, &date_like);
  108. if (vm.exception())
  109. return {};
  110. // 3. If result is undefined, throw a RangeError exception.
  111. if (result.is_undefined()) {
  112. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidCalendarFunctionResult, vm.names.year.as_string());
  113. return {};
  114. }
  115. // 4. Return ? ToIntegerOrInfinity(result).
  116. return result.to_integer_or_infinity(global_object);
  117. }
  118. // 12.1.21 ToTemporalCalendar ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendar
  119. Object* to_temporal_calendar(GlobalObject& global_object, Value temporal_calendar_like)
  120. {
  121. auto& vm = global_object.vm();
  122. // 1. If Type(temporalCalendarLike) is Object, then
  123. if (temporal_calendar_like.is_object()) {
  124. auto& temporal_calendar_like_object = temporal_calendar_like.as_object();
  125. // a. If temporalCalendarLike has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  126. // TODO: The rest of the Temporal built-ins
  127. if (is<PlainDate>(temporal_calendar_like_object)) {
  128. // i. Return temporalCalendarLike.[[Calendar]].
  129. return &static_cast<PlainDate&>(temporal_calendar_like_object).calendar();
  130. }
  131. // b. If ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike.
  132. auto has_property = temporal_calendar_like_object.has_property(vm.names.calendar);
  133. if (vm.exception())
  134. return {};
  135. if (!has_property)
  136. return &temporal_calendar_like_object;
  137. // c. Set temporalCalendarLike to ? Get(temporalCalendarLike, "calendar").
  138. temporal_calendar_like = temporal_calendar_like_object.get(vm.names.calendar);
  139. if (vm.exception())
  140. return {};
  141. // d. If Type(temporalCalendarLike) is Object and ? HasProperty(temporalCalendarLike, "calendar") is false, return temporalCalendarLike.
  142. if (temporal_calendar_like.is_object()) {
  143. has_property = temporal_calendar_like.as_object().has_property(vm.names.calendar);
  144. if (vm.exception())
  145. return {};
  146. if (!has_property)
  147. return &temporal_calendar_like.as_object();
  148. }
  149. }
  150. // 2. Let identifier be ? ToString(temporalCalendarLike).
  151. auto identifier = temporal_calendar_like.to_string(global_object);
  152. if (vm.exception())
  153. return {};
  154. // 3. If ! IsBuiltinCalendar(identifier) is false, then
  155. if (!is_builtin_calendar(identifier)) {
  156. // a. Let identifier be ? ParseTemporalCalendarString(identifier).
  157. auto parsed_identifier = parse_temporal_calendar_string(global_object, identifier);
  158. if (vm.exception())
  159. return {};
  160. identifier = move(*parsed_identifier);
  161. }
  162. // 4. Return ? CreateTemporalCalendar(identifier).
  163. return create_temporal_calendar(global_object, identifier);
  164. }
  165. // 12.1.22 ToTemporalCalendarWithISODefault ( temporalCalendarLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalcalendarwithisodefault
  166. Object* to_temporal_calendar_with_iso_default(GlobalObject& global_object, Value temporal_calendar_like)
  167. {
  168. // 1. If temporalCalendarLike is undefined, then
  169. if (temporal_calendar_like.is_undefined()) {
  170. // a. Return ? GetISO8601Calendar().
  171. return get_iso8601_calendar(global_object);
  172. }
  173. // 2. Return ? ToTemporalCalendar(temporalCalendarLike).
  174. return to_temporal_calendar(global_object, temporal_calendar_like);
  175. }
  176. // 12.1.23 GetTemporalCalendarWithISODefault ( item ), https://tc39.es/proposal-temporal/#sec-temporal-gettemporalcalendarwithisodefault
  177. Object* get_temporal_calendar_with_iso_default(GlobalObject& global_object, Object& item)
  178. {
  179. auto& vm = global_object.vm();
  180. // 1. If item has an [[InitializedTemporalDate]], [[InitializedTemporalDateTime]], [[InitializedTemporalMonthDay]], [[InitializedTemporalTime]], [[InitializedTemporalYearMonth]], or [[InitializedTemporalZonedDateTime]] internal slot, then
  181. // TODO: The rest of the Temporal built-ins
  182. if (is<PlainDate>(item)) {
  183. // a. Return item.[[Calendar]].
  184. return &static_cast<PlainDate&>(item).calendar();
  185. }
  186. // 2. Let calendar be ? Get(item, "calendar").
  187. auto calendar = item.get(vm.names.calendar);
  188. if (vm.exception())
  189. return {};
  190. // 3. Return ? ToTemporalCalendarWithISODefault(calendar).
  191. return to_temporal_calendar_with_iso_default(global_object, calendar);
  192. }
  193. // 12.1.24 DateFromFields ( calendar, fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-datefromfields
  194. PlainDate* date_from_fields(GlobalObject& global_object, Object& calendar, Object& fields, Object& options)
  195. {
  196. auto& vm = global_object.vm();
  197. // 1. Assert: Type(calendar) is Object.
  198. // 2. Assert: Type(fields) is Object.
  199. // 3. Let date be ? Invoke(calendar, "dateFromFields", « fields, options »).
  200. auto date = calendar.invoke(vm.names.dateFromFields, &fields, &options);
  201. if (vm.exception())
  202. return {};
  203. // 4. Perform ? RequireInternalSlot(date, [[InitializedTemporalDate]]).
  204. auto* date_object = date.to_object(global_object);
  205. if (!date_object)
  206. return {};
  207. if (!is<PlainDate>(date_object)) {
  208. vm.throw_exception<TypeError>(global_object, ErrorType::NotA, "Temporal.PlainDate");
  209. return {};
  210. }
  211. // 5. Return date.
  212. return static_cast<PlainDate*>(date_object);
  213. }
  214. // 12.1.28 CalendarEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-calendarequals
  215. bool calendar_equals(GlobalObject& global_object, Object& one, Object& two)
  216. {
  217. auto& vm = global_object.vm();
  218. // 1. If one and two are the same Object value, return true.
  219. if (&one == &two)
  220. return true;
  221. // 2. Let calendarOne be ? ToString(one).
  222. auto calendar_one = Value(&one).to_string(global_object);
  223. if (vm.exception())
  224. return {};
  225. // 3. Let calendarTwo be ? ToString(two).
  226. auto calendar_two = Value(&two).to_string(global_object);
  227. if (vm.exception())
  228. return {};
  229. // 4. If calendarOne is calendarTwo, return true.
  230. if (calendar_one == calendar_two)
  231. return true;
  232. // 5. Return false.
  233. return false;
  234. }
  235. // 12.1.30 IsISOLeapYear ( year ), https://tc39.es/proposal-temporal/#sec-temporal-isisoleapyear
  236. bool is_iso_leap_year(i32 year)
  237. {
  238. // 1. Assert: year is an integer.
  239. // 2. If year modulo 4 ≠ 0, return false.
  240. if (year % 4 != 0)
  241. return false;
  242. // 3. If year modulo 400 = 0, return true.
  243. if (year % 400 == 0)
  244. return true;
  245. // 4. If year modulo 100 = 0, return false.
  246. if (year % 100 == 0)
  247. return false;
  248. // 5. Return true.
  249. return true;
  250. }
  251. // 12.1.32 ISODaysInMonth ( year, month ), https://tc39.es/proposal-temporal/#sec-temporal-isodaysinmonth
  252. i32 iso_days_in_month(i32 year, i32 month)
  253. {
  254. // 1. Assert: year is an integer.
  255. // 2. Assert: month is an integer, month ≥ 1, and month ≤ 12.
  256. VERIFY(month >= 1 && month <= 12);
  257. // 3. If month is 1, 3, 5, 7, 8, 10, or 12, return 31.
  258. if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
  259. return 31;
  260. // 4. If month is 4, 6, 9, or 11, return 30.
  261. if (month == 4 || month == 6 || month == 9 || month == 11)
  262. return 30;
  263. // 5. If ! IsISOLeapYear(year) is true, return 29.
  264. if (is_iso_leap_year(year))
  265. return 29;
  266. // 6. Return 28.
  267. return 28;
  268. }
  269. // 12.1.36 BuildISOMonthCode ( month ), https://tc39.es/proposal-temporal/#sec-buildisomonthcode
  270. String build_iso_month_code(i32 month)
  271. {
  272. return String::formatted("M{:02}", month);
  273. }
  274. // 12.1.37 ResolveISOMonth ( fields ), https://tc39.es/proposal-temporal/#sec-temporal-resolveisomonth
  275. double resolve_iso_month(GlobalObject& global_object, Object& fields)
  276. {
  277. auto& vm = global_object.vm();
  278. // 1. Let month be ? Get(fields, "month").
  279. auto month = fields.get(vm.names.month);
  280. if (vm.exception())
  281. return {};
  282. // 2. Let monthCode be ? Get(fields, "monthCode").
  283. auto month_code = fields.get(vm.names.monthCode);
  284. if (vm.exception())
  285. return {};
  286. // 3. If monthCode is undefined, then
  287. if (month_code.is_undefined()) {
  288. // a. If month is undefined, throw a TypeError exception.
  289. if (month.is_undefined()) {
  290. vm.throw_exception<TypeError>(global_object, ErrorType::TemporalMissingRequiredProperty, vm.names.month.as_string());
  291. return {};
  292. }
  293. // b. Return month.
  294. return month.as_double();
  295. }
  296. // 4. Assert: Type(monthCode) is String.
  297. VERIFY(month_code.is_string());
  298. auto& month_code_string = month_code.as_string().string();
  299. // 5. Let monthLength be the length of monthCode.
  300. auto month_length = month_code_string.length();
  301. // 6. If monthLength is not 3, throw a RangeError exception.
  302. if (month_length != 3) {
  303. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidMonthCode);
  304. return {};
  305. }
  306. // 7. Let numberPart be the substring of monthCode from 1.
  307. auto number_part = month_code_string.substring(1);
  308. // 8. Set numberPart to ! ToIntegerOrInfinity(numberPart).
  309. auto number_part_integer = Value(js_string(vm, move(number_part))).to_integer_or_infinity(global_object);
  310. // 9. If numberPart < 1 or numberPart > 12, throw a RangeError exception.
  311. if (number_part_integer < 1 || number_part_integer > 12) {
  312. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidMonthCode);
  313. return {};
  314. }
  315. // 10. If month is not undefined, and month ≠ numberPart, then
  316. if (!month.is_undefined() && month.as_double() != number_part_integer) {
  317. // a. Throw a RangeError exception.
  318. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidMonthCode);
  319. return {};
  320. }
  321. // 11. If ! SameValueNonNumeric(monthCode, ! BuildISOMonthCode(numberPart)) is false, then
  322. if (month_code_string != build_iso_month_code(number_part_integer)) {
  323. // a. Throw a RangeError exception.
  324. vm.throw_exception<RangeError>(global_object, ErrorType::TemporalInvalidMonthCode);
  325. return {};
  326. }
  327. // 12. Return numberPart.
  328. return number_part_integer;
  329. }
  330. // 12.1.38 ISODateFromFields ( fields, options ), https://tc39.es/proposal-temporal/#sec-temporal-isodatefromfields
  331. Optional<TemporalDate> iso_date_from_fields(GlobalObject& global_object, Object& fields, Object& options)
  332. {
  333. auto& vm = global_object.vm();
  334. // 1. Assert: Type(fields) is Object.
  335. // 2. Let overflow be ? ToTemporalOverflow(options).
  336. auto overflow = to_temporal_overflow(global_object, options);
  337. if (vm.exception())
  338. return {};
  339. // 3. Set fields to ? PrepareTemporalFields(fields, « "day", "month", "monthCode", "year" », «»).
  340. auto* prepared_fields = prepare_temporal_fields(global_object, fields, { "day", "month", "monthCode", "year" }, {});
  341. if (vm.exception())
  342. return {};
  343. // 4. Let year be ? Get(fields, "year").
  344. auto year = prepared_fields->get(vm.names.year);
  345. if (vm.exception())
  346. return {};
  347. // 5. If year is undefined, throw a TypeError exception.
  348. if (year.is_undefined()) {
  349. vm.throw_exception<TypeError>(global_object, ErrorType::TemporalMissingRequiredProperty, vm.names.year.as_string());
  350. return {};
  351. }
  352. // 6. Let month be ? ResolveISOMonth(fields).
  353. auto month = resolve_iso_month(global_object, *prepared_fields);
  354. if (vm.exception())
  355. return {};
  356. // 7. Let day be ? Get(fields, "day").
  357. auto day = prepared_fields->get(vm.names.day);
  358. if (vm.exception())
  359. return {};
  360. // 8. If day is undefined, throw a TypeError exception.
  361. if (day.is_undefined()) {
  362. vm.throw_exception<TypeError>(global_object, ErrorType::TemporalMissingRequiredProperty, vm.names.day.as_string());
  363. return {};
  364. }
  365. // 9. Return ? RegulateISODate(year, month, day, overflow).
  366. return regulate_iso_date(global_object, year.as_double(), month, day.as_double(), *overflow);
  367. }
  368. // 12.1.41 ISOYear ( temporalObject ), https://tc39.es/proposal-temporal/#sec-temporal-isoyear
  369. i32 iso_year(Object& temporal_object)
  370. {
  371. // 1. Assert: temporalObject has an [[ISOYear]] internal slot.
  372. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  373. // 2. Return 𝔽(temporalObject.[[ISOYear]]).
  374. // TODO: add the rest of the builtins with a [[ISOYear]] slot (PlainYearMonth, PlainMonthDay)
  375. if (is<PlainDate>(temporal_object))
  376. return static_cast<PlainDate&>(temporal_object).iso_year();
  377. if (is<PlainDateTime>(temporal_object))
  378. return static_cast<PlainDateTime&>(temporal_object).iso_year();
  379. VERIFY_NOT_REACHED();
  380. }
  381. }