DateTimeFormatConstructor.cpp 18 KB

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