DateTimeFormatConstructor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@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/Date.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  11. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  12. #include <LibJS/Runtime/Intl/DateTimeFormatConstructor.h>
  13. #include <LibJS/Runtime/Temporal/TimeZone.h>
  14. #include <LibLocale/DateTimeFormat.h>
  15. #include <LibLocale/Locale.h>
  16. namespace JS::Intl {
  17. // 11.1 The Intl.DateTimeFormat Constructor, https://tc39.es/ecma402/#sec-intl-datetimeformat-constructor
  18. DateTimeFormatConstructor::DateTimeFormatConstructor(Realm& realm)
  19. : NativeFunction(realm.vm().names.DateTimeFormat.as_string(), *realm.intrinsics().function_prototype())
  20. {
  21. }
  22. ThrowCompletionOr<void> DateTimeFormatConstructor::initialize(Realm& realm)
  23. {
  24. MUST_OR_THROW_OOM(NativeFunction::initialize(realm));
  25. auto& vm = this->vm();
  26. // 11.2.1 Intl.DateTimeFormat.prototype, https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype
  27. define_direct_property(vm.names.prototype, realm.intrinsics().intl_date_time_format_prototype(), 0);
  28. u8 attr = Attribute::Writable | Attribute::Configurable;
  29. define_native_function(realm, vm.names.supportedLocalesOf, supported_locales_of, 1, attr);
  30. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  31. return {};
  32. }
  33. // 11.1.1 Intl.DateTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat
  34. ThrowCompletionOr<Value> DateTimeFormatConstructor::call()
  35. {
  36. // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget.
  37. return TRY(construct(*this));
  38. }
  39. // 11.1.1 Intl.DateTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat
  40. ThrowCompletionOr<NonnullGCPtr<Object>> DateTimeFormatConstructor::construct(FunctionObject& new_target)
  41. {
  42. auto& vm = this->vm();
  43. auto locales = vm.argument(0);
  44. auto options = vm.argument(1);
  45. // 2. Let dateTimeFormat be ? OrdinaryCreateFromConstructor(newTarget, "%DateTimeFormat.prototype%", « [[InitializedDateTimeFormat]], [[Locale]], [[Calendar]], [[NumberingSystem]], [[TimeZone]], [[Weekday]], [[Era]], [[Year]], [[Month]], [[Day]], [[DayPeriod]], [[Hour]], [[Minute]], [[Second]], [[FractionalSecondDigits]], [[TimeZoneName]], [[HourCycle]], [[Pattern]], [[BoundFormat]] »).
  46. auto date_time_format = TRY(ordinary_create_from_constructor<DateTimeFormat>(vm, new_target, &Intrinsics::intl_date_time_format_prototype));
  47. // 3. Perform ? InitializeDateTimeFormat(dateTimeFormat, locales, options).
  48. TRY(initialize_date_time_format(vm, date_time_format, locales, options));
  49. // 4. If the implementation supports the normative optional constructor mode of 4.3 Note 1, then
  50. // a. Let this be the this value.
  51. // b. Return ? ChainDateTimeFormat(dateTimeFormat, NewTarget, this).
  52. // 5. Return dateTimeFormat.
  53. return date_time_format;
  54. }
  55. // 11.2.2 Intl.DateTimeFormat.supportedLocalesOf ( locales [ , options ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat.supportedlocalesof
  56. JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatConstructor::supported_locales_of)
  57. {
  58. auto locales = vm.argument(0);
  59. auto options = vm.argument(1);
  60. // 1. Let availableLocales be %DateTimeFormat%.[[AvailableLocales]].
  61. // 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  62. auto requested_locales = TRY(canonicalize_locale_list(vm, locales));
  63. // 3. Return ? SupportedLocales(availableLocales, requestedLocales, options).
  64. return TRY(supported_locales(vm, requested_locales, options));
  65. }
  66. // 11.1.2 InitializeDateTimeFormat ( dateTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-initializedatetimeformat
  67. ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(VM& vm, DateTimeFormat& date_time_format, Value locales_value, Value options_value)
  68. {
  69. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  70. auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value));
  71. // 2. Set options to ? ToDateTimeOptions(options, "any", "date").
  72. auto* options = TRY(to_date_time_options(vm, options_value, OptionRequired::Any, OptionDefaults::Date));
  73. // 3. Let opt be a new Record.
  74. LocaleOptions opt {};
  75. // 4. Let matcher be ? GetOption(options, "localeMatcher", string, « "lookup", "best fit" », "best fit").
  76. auto matcher = TRY(get_option(vm, *options, vm.names.localeMatcher, OptionType::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv));
  77. // 5. Set opt.[[localeMatcher]] to matcher.
  78. opt.locale_matcher = matcher;
  79. // 6. Let calendar be ? GetOption(options, "calendar", string, empty, undefined).
  80. auto calendar = TRY(get_option(vm, *options, vm.names.calendar, OptionType::String, {}, Empty {}));
  81. // 7. If calendar is not undefined, then
  82. if (!calendar.is_undefined()) {
  83. // a. If calendar does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  84. if (!::Locale::is_type_identifier(TRY(calendar.as_string().utf8_string_view())))
  85. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, calendar, "calendar"sv);
  86. // 8. Set opt.[[ca]] to calendar.
  87. opt.ca = TRY(calendar.as_string().utf8_string());
  88. }
  89. // 9. Let numberingSystem be ? GetOption(options, "numberingSystem", string, empty, undefined).
  90. auto numbering_system = TRY(get_option(vm, *options, vm.names.numberingSystem, OptionType::String, {}, Empty {}));
  91. // 10. If numberingSystem is not undefined, then
  92. if (!numbering_system.is_undefined()) {
  93. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  94. if (!::Locale::is_type_identifier(TRY(numbering_system.as_string().utf8_string_view())))
  95. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  96. // 11. Set opt.[[nu]] to numberingSystem.
  97. opt.nu = TRY(numbering_system.as_string().utf8_string());
  98. }
  99. // 12. Let hour12 be ? GetOption(options, "hour12", boolean, empty, undefined).
  100. auto hour12 = TRY(get_option(vm, *options, vm.names.hour12, OptionType::Boolean, {}, Empty {}));
  101. // 13. Let hourCycle be ? GetOption(options, "hourCycle", string, « "h11", "h12", "h23", "h24" », undefined).
  102. auto hour_cycle = TRY(get_option(vm, *options, vm.names.hourCycle, OptionType::String, AK::Array { "h11"sv, "h12"sv, "h23"sv, "h24"sv }, Empty {}));
  103. // 14. If hour12 is not undefined, then
  104. if (!hour12.is_undefined()) {
  105. // a. Set hourCycle to null.
  106. hour_cycle = js_null();
  107. }
  108. // 15. Set opt.[[hc]] to hourCycle.
  109. if (!hour_cycle.is_nullish())
  110. opt.hc = TRY(hour_cycle.as_string().utf8_string());
  111. // 16. Let localeData be %DateTimeFormat%.[[LocaleData]].
  112. // 17. Let r be ResolveLocale(%DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]], localeData).
  113. auto result = MUST_OR_THROW_OOM(resolve_locale(vm, requested_locales, opt, DateTimeFormat::relevant_extension_keys()));
  114. // 18. Set dateTimeFormat.[[Locale]] to r.[[locale]].
  115. date_time_format.set_locale(move(result.locale));
  116. // 19. Set resolvedCalendar to r.[[ca]].
  117. // 20. Set dateTimeFormat.[[Calendar]] to resolvedCalendar.
  118. if (result.ca.has_value())
  119. date_time_format.set_calendar(result.ca.release_value());
  120. // 21. Set dateTimeFormat.[[NumberingSystem]] to r.[[nu]].
  121. if (result.nu.has_value())
  122. date_time_format.set_numbering_system(result.nu.release_value());
  123. // 22. Let dataLocale be r.[[dataLocale]].
  124. auto data_locale = move(result.data_locale);
  125. // Non-standard, the data locale is needed for LibUnicode lookups while formatting.
  126. date_time_format.set_data_locale(data_locale);
  127. // 23. Let dataLocaleData be localeData.[[<dataLocale>]].
  128. // 24. Let hcDefault be dataLocaleData.[[hourCycle]].
  129. auto default_hour_cycle = TRY_OR_THROW_OOM(vm, ::Locale::get_default_regional_hour_cycle(data_locale));
  130. // Non-standard, default_hour_cycle will be empty if Unicode data generation is disabled.
  131. if (!default_hour_cycle.has_value()) {
  132. date_time_format.set_time_zone(TRY_OR_THROW_OOM(vm, String::from_utf8(default_time_zone())));
  133. return &date_time_format;
  134. }
  135. Optional<::Locale::HourCycle> hour_cycle_value;
  136. // 25. If hour12 is true, then
  137. if (hour12.is_boolean() && hour12.as_bool()) {
  138. // a. If hcDefault is "h11" or "h23", let hc be "h11". Otherwise, let hc be "h12".
  139. if ((default_hour_cycle == ::Locale::HourCycle::H11) || (default_hour_cycle == ::Locale::HourCycle::H23))
  140. hour_cycle_value = ::Locale::HourCycle::H11;
  141. else
  142. hour_cycle_value = ::Locale::HourCycle::H12;
  143. }
  144. // 26. Else if hour12 is false, then
  145. else if (hour12.is_boolean() && !hour12.as_bool()) {
  146. // a. If hcDefault is "h11" or "h23", let hc be "h23". Otherwise, let hc be "h24".
  147. if ((default_hour_cycle == ::Locale::HourCycle::H11) || (default_hour_cycle == ::Locale::HourCycle::H23))
  148. hour_cycle_value = ::Locale::HourCycle::H23;
  149. else
  150. hour_cycle_value = ::Locale::HourCycle::H24;
  151. }
  152. // 27. Else,
  153. else {
  154. // a. Assert: hour12 is undefined.
  155. VERIFY(hour12.is_undefined());
  156. // b. Let hc be r.[[hc]].
  157. if (result.hc.has_value())
  158. hour_cycle_value = ::Locale::hour_cycle_from_string(*result.hc);
  159. // c. If hc is null, set hc to hcDefault.
  160. if (!hour_cycle_value.has_value())
  161. hour_cycle_value = default_hour_cycle;
  162. }
  163. // 28. Set dateTimeFormat.[[HourCycle]] to hc.
  164. if (hour_cycle_value.has_value())
  165. date_time_format.set_hour_cycle(*hour_cycle_value);
  166. // 29. Let timeZone be ? Get(options, "timeZone").
  167. auto time_zone_value = TRY(options->get(vm.names.timeZone));
  168. String time_zone;
  169. // 30. If timeZone is undefined, then
  170. if (time_zone_value.is_undefined()) {
  171. // a. Set timeZone to DefaultTimeZone().
  172. time_zone = TRY_OR_THROW_OOM(vm, String::from_utf8(default_time_zone()));
  173. }
  174. // 31. Else,
  175. else {
  176. // a. Set timeZone to ? ToString(timeZone).
  177. time_zone = TRY(time_zone_value.to_string(vm));
  178. // b. If IsAvailableTimeZoneName(timeZone) is false, then
  179. if (!Temporal::is_available_time_zone_name(time_zone)) {
  180. // i. Throw a RangeError exception.
  181. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  182. }
  183. // c. Set timeZone to CanonicalizeTimeZoneName(timeZone).
  184. time_zone = MUST_OR_THROW_OOM(Temporal::canonicalize_time_zone_name(vm, time_zone));
  185. }
  186. // 32. Set dateTimeFormat.[[TimeZone]] to timeZone.
  187. date_time_format.set_time_zone(move(time_zone));
  188. // 33. Let formatOptions be a new Record.
  189. ::Locale::CalendarPattern format_options {};
  190. // 34. Set formatOptions.[[hourCycle]] to hc.
  191. format_options.hour_cycle = hour_cycle_value;
  192. // 35. Let hasExplicitFormatComponents be false.
  193. // NOTE: Instead of using a boolean, we track any explicitly provided component name for nicer exception messages.
  194. PropertyKey const* explicit_format_component = nullptr;
  195. // 36. For each row of Table 6, except the header row, in table order, do
  196. TRY(for_each_calendar_field(vm, format_options, [&](auto& option, auto const& property, auto const& values) -> ThrowCompletionOr<void> {
  197. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  198. // a. Let prop be the name given in the Property column of the row.
  199. // b. If prop is "fractionalSecondDigits", then
  200. if constexpr (IsIntegral<ValueType>) {
  201. // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
  202. auto value = TRY(get_number_option(vm, *options, property, 1, 3, {}));
  203. // d. Set formatOptions.[[<prop>]] to value.
  204. if (value.has_value()) {
  205. option = static_cast<ValueType>(value.value());
  206. // e. If value is not undefined, then
  207. // i. Set hasExplicitFormatComponents to true.
  208. explicit_format_component = &property;
  209. }
  210. }
  211. // c. Else,
  212. else {
  213. // i. Let values be a List whose elements are the strings given in the Values column of the row.
  214. // ii. Let value be ? GetOption(options, prop, string, values, undefined).
  215. auto value = TRY(get_option(vm, *options, property, OptionType::String, values, Empty {}));
  216. // d. Set formatOptions.[[<prop>]] to value.
  217. if (!value.is_undefined()) {
  218. option = ::Locale::calendar_pattern_style_from_string(TRY(value.as_string().utf8_string_view()));
  219. // e. If value is not undefined, then
  220. // i. Set hasExplicitFormatComponents to true.
  221. explicit_format_component = &property;
  222. }
  223. }
  224. return {};
  225. }));
  226. // 37. Let matcher be ? GetOption(options, "formatMatcher", string, « "basic", "best fit" », "best fit").
  227. matcher = TRY(get_option(vm, *options, vm.names.formatMatcher, OptionType::String, AK::Array { "basic"sv, "best fit"sv }, "best fit"sv));
  228. // 38. Let dateStyle be ? GetOption(options, "dateStyle", string, « "full", "long", "medium", "short" », undefined).
  229. auto date_style = TRY(get_option(vm, *options, vm.names.dateStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  230. // 39. Set dateTimeFormat.[[DateStyle]] to dateStyle.
  231. if (!date_style.is_undefined())
  232. date_time_format.set_date_style(TRY(date_style.as_string().utf8_string_view()));
  233. // 40. Let timeStyle be ? GetOption(options, "timeStyle", string, « "full", "long", "medium", "short" », undefined).
  234. auto time_style = TRY(get_option(vm, *options, vm.names.timeStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  235. // 41. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
  236. if (!time_style.is_undefined())
  237. date_time_format.set_time_style(TRY(time_style.as_string().utf8_string_view()));
  238. Optional<::Locale::CalendarPattern> best_format {};
  239. // 42. If dateStyle is not undefined or timeStyle is not undefined, then
  240. if (date_time_format.has_date_style() || date_time_format.has_time_style()) {
  241. // a. If hasExplicitFormatComponents is true, then
  242. if (explicit_format_component != nullptr) {
  243. // i. Throw a TypeError exception.
  244. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, *explicit_format_component, "dateStyle or timeStyle"sv);
  245. }
  246. // b. Let styles be dataLocaleData.[[styles]].[[<resolvedCalendar>]].
  247. // c. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles).
  248. best_format = MUST_OR_THROW_OOM(date_time_style_format(vm, data_locale, date_time_format));
  249. }
  250. // 43. Else,
  251. else {
  252. // a. Let formats be dataLocaleData.[[formats]].[[<resolvedCalendar>]].
  253. auto formats = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_available_formats(data_locale, date_time_format.calendar()));
  254. // b. If matcher is "basic", then
  255. if (TRY(matcher.as_string().utf8_string_view()) == "basic"sv) {
  256. // i. Let bestFormat be BasicFormatMatcher(formatOptions, formats).
  257. best_format = basic_format_matcher(format_options, move(formats));
  258. }
  259. // c. Else,
  260. else {
  261. // i. Let bestFormat be BestFitFormatMatcher(formatOptions, formats).
  262. best_format = best_fit_format_matcher(format_options, move(formats));
  263. }
  264. }
  265. // 44. For each row in Table 6, except the header row, in table order, do
  266. date_time_format.for_each_calendar_field_zipped_with(*best_format, [&](auto& date_time_format_field, auto const& best_format_field, auto) {
  267. // a. Let prop be the name given in the Property column of the row.
  268. // b. If bestFormat has a field [[<prop>]], then
  269. if (best_format_field.has_value()) {
  270. // i. Let p be bestFormat.[[<prop>]].
  271. // ii. Set dateTimeFormat's internal slot whose name is the Internal Slot column of the row to p.
  272. date_time_format_field = best_format_field;
  273. }
  274. });
  275. String pattern;
  276. Vector<::Locale::CalendarRangePattern> range_patterns;
  277. // 45. If dateTimeFormat.[[Hour]] is undefined, then
  278. if (!date_time_format.has_hour()) {
  279. // a. Set dateTimeFormat.[[HourCycle]] to undefined.
  280. date_time_format.clear_hour_cycle();
  281. }
  282. // 46. If dateTimeFormat.[[HourCycle]] is "h11" or "h12", then
  283. if ((hour_cycle_value == ::Locale::HourCycle::H11) || (hour_cycle_value == ::Locale::HourCycle::H12)) {
  284. // a. Let pattern be bestFormat.[[pattern12]].
  285. if (best_format->pattern12.has_value()) {
  286. pattern = best_format->pattern12.release_value();
  287. } else {
  288. // Non-standard, LibUnicode only provides [[pattern12]] when [[pattern]] has a day
  289. // period. Other implementations provide [[pattern12]] as a copy of [[pattern]].
  290. pattern = move(best_format->pattern);
  291. }
  292. // b. Let rangePatterns be bestFormat.[[rangePatterns12]].
  293. range_patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_range12_formats(data_locale, date_time_format.calendar(), best_format->skeleton));
  294. }
  295. // 47. Else,
  296. else {
  297. // a. Let pattern be bestFormat.[[pattern]].
  298. pattern = move(best_format->pattern);
  299. // b. Let rangePatterns be bestFormat.[[rangePatterns]].
  300. range_patterns = TRY_OR_THROW_OOM(vm, ::Locale::get_calendar_range_formats(data_locale, date_time_format.calendar(), best_format->skeleton));
  301. }
  302. // 48. Set dateTimeFormat.[[Pattern]] to pattern.
  303. date_time_format.set_pattern(move(pattern));
  304. // 49. Set dateTimeFormat.[[RangePatterns]] to rangePatterns.
  305. date_time_format.set_range_patterns(move(range_patterns));
  306. // 50. Return dateTimeFormat.
  307. return &date_time_format;
  308. }
  309. }