DateTimeFormat.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/NumericLimits.h>
  7. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  8. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  9. #include <LibJS/Runtime/Temporal/TimeZone.h>
  10. #include <LibUnicode/Locale.h>
  11. namespace JS::Intl {
  12. // 11 DateTimeFormat Objects, https://tc39.es/ecma402/#datetimeformat-objects
  13. DateTimeFormat::DateTimeFormat(Object& prototype)
  14. : Object(prototype)
  15. {
  16. }
  17. DateTimeFormat::Style DateTimeFormat::style_from_string(StringView style)
  18. {
  19. if (style == "full"sv)
  20. return Style::Full;
  21. if (style == "long"sv)
  22. return Style::Long;
  23. if (style == "medium"sv)
  24. return Style::Medium;
  25. if (style == "short"sv)
  26. return Style::Short;
  27. VERIFY_NOT_REACHED();
  28. }
  29. StringView DateTimeFormat::style_to_string(Style style)
  30. {
  31. switch (style) {
  32. case Style::Full:
  33. return "full"sv;
  34. case Style::Long:
  35. return "long"sv;
  36. case Style::Medium:
  37. return "medium"sv;
  38. case Style::Short:
  39. return "short"sv;
  40. default:
  41. VERIFY_NOT_REACHED();
  42. }
  43. }
  44. // 11.1.1 InitializeDateTimeFormat ( dateTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-initializedatetimeformat
  45. ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(GlobalObject& global_object, DateTimeFormat& date_time_format, Value locales_value, Value options_value)
  46. {
  47. auto& vm = global_object.vm();
  48. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  49. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  50. // 2. Let options be ? ToDateTimeOptions(options, "any", "date").
  51. auto* options = TRY(to_date_time_options(global_object, options_value, OptionRequired::Any, OptionDefaults::Date));
  52. // 3. Let opt be a new Record.
  53. LocaleOptions opt {};
  54. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  55. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv));
  56. // 5. Set opt.[[localeMatcher]] to matcher.
  57. opt.locale_matcher = matcher;
  58. // 6. Let calendar be ? GetOption(options, "calendar", "string", undefined, undefined).
  59. auto calendar = TRY(get_option(global_object, *options, vm.names.calendar, Value::Type::String, {}, Empty {}));
  60. // 7. If calendar is not undefined, then
  61. if (!calendar.is_undefined()) {
  62. // a. If calendar does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  63. if (!Unicode::is_type_identifier(calendar.as_string().string()))
  64. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, calendar, "calendar"sv);
  65. // 8. Set opt.[[ca]] to calendar.
  66. opt.ca = calendar.as_string().string();
  67. }
  68. // 9. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  69. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  70. // 10. If numberingSystem is not undefined, then
  71. if (!numbering_system.is_undefined()) {
  72. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  73. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  74. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  75. // 11. Set opt.[[nu]] to numberingSystem.
  76. opt.nu = numbering_system.as_string().string();
  77. }
  78. // 12. Let hour12 be ? GetOption(options, "hour12", "boolean", undefined, undefined).
  79. auto hour12 = TRY(get_option(global_object, *options, vm.names.hour12, Value::Type::Boolean, {}, Empty {}));
  80. // 13. Let hourCycle be ? GetOption(options, "hourCycle", "string", « "h11", "h12", "h23", "h24" », undefined).
  81. 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 {}));
  82. // 14. If hour12 is not undefined, then
  83. if (!hour12.is_undefined()) {
  84. // a. Let hourCycle be null.
  85. hour_cycle = js_null();
  86. }
  87. // 15. Set opt.[[hc]] to hourCycle.
  88. if (!hour_cycle.is_nullish())
  89. opt.hc = hour_cycle.as_string().string();
  90. // 16. Let localeData be %DateTimeFormat%.[[LocaleData]].
  91. // 17. Let r be ResolveLocale(%DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]], localeData).
  92. auto result = resolve_locale(requested_locales, opt, DateTimeFormat::relevant_extension_keys());
  93. // 18. Set dateTimeFormat.[[Locale]] to r.[[locale]].
  94. date_time_format.set_locale(move(result.locale));
  95. // 19. Let calendar be r.[[ca]].
  96. // 20. Set dateTimeFormat.[[Calendar]] to calendar.
  97. date_time_format.set_calendar(result.ca.release_value());
  98. // 21. Set dateTimeFormat.[[HourCycle]] to r.[[hc]].
  99. date_time_format.set_hour_cycle(result.hc.release_value());
  100. // 22. Set dateTimeFormat.[[NumberingSystem]] to r.[[nu]].
  101. date_time_format.set_numbering_system(result.nu.release_value());
  102. // 23. Let dataLocale be r.[[dataLocale]].
  103. auto data_locale = move(result.data_locale);
  104. // 24. Let timeZone be ? Get(options, "timeZone").
  105. auto time_zone_value = TRY(options->get(vm.names.timeZone));
  106. String time_zone;
  107. // 25. If timeZone is undefined, then
  108. if (time_zone_value.is_undefined()) {
  109. // a. Let timeZone be DefaultTimeZone().
  110. time_zone = Temporal::default_time_zone();
  111. }
  112. // 26. Else,
  113. else {
  114. // a. Let timeZone be ? ToString(timeZone).
  115. time_zone = TRY(time_zone_value.to_string(global_object));
  116. // b. If the result of IsValidTimeZoneName(timeZone) is false, then
  117. if (!Temporal::is_valid_time_zone_name(time_zone)) {
  118. // i. Throw a RangeError exception.
  119. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  120. }
  121. // c. Let timeZone be CanonicalizeTimeZoneName(timeZone).
  122. time_zone = Temporal::canonicalize_time_zone_name(time_zone);
  123. }
  124. // 27. Set dateTimeFormat.[[TimeZone]] to timeZone.
  125. date_time_format.set_time_zone(move(time_zone));
  126. // 28. Let opt be a new Record.
  127. Unicode::CalendarPattern format_options {};
  128. // 29. For each row of Table 4, except the header row, in table order, do
  129. TRY(for_each_calendar_field(global_object, format_options, [&](auto& option, auto const& property, auto const& defaults) -> ThrowCompletionOr<void> {
  130. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  131. // a. Let prop be the name given in the Property column of the row.
  132. // b. If prop is "fractionalSecondDigits", then
  133. if constexpr (IsIntegral<ValueType>) {
  134. // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
  135. auto value = TRY(get_number_option(global_object, *options, property, 1, 3, {}));
  136. // d. Set opt.[[<prop>]] to value.
  137. if (value.has_value())
  138. option = static_cast<ValueType>(value.value());
  139. }
  140. // c. Else,
  141. else {
  142. // i. Let value be ? GetOption(options, prop, "string", « the strings given in the Values column of the row », undefined).
  143. auto value = TRY(get_option(global_object, *options, property, Value::Type::String, defaults, Empty {}));
  144. // d. Set opt.[[<prop>]] to value.
  145. if (!value.is_undefined())
  146. option = Unicode::calendar_pattern_style_from_string(value.as_string().string());
  147. }
  148. return {};
  149. }));
  150. // 30. Let dataLocaleData be localeData.[[<dataLocale>]].
  151. // 31. Let matcher be ? GetOption(options, "formatMatcher", "string", « "basic", "best fit" », "best fit").
  152. matcher = TRY(get_option(global_object, *options, vm.names.formatMatcher, Value::Type::String, AK::Array { "basic"sv, "best fit"sv }, "best fit"sv));
  153. // 32. Let dateStyle be ? GetOption(options, "dateStyle", "string", « "full", "long", "medium", "short" », undefined).
  154. 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 {}));
  155. // 33. Set dateTimeFormat.[[DateStyle]] to dateStyle.
  156. if (!date_style.is_undefined())
  157. date_time_format.set_date_style(date_style.as_string().string());
  158. // 34. Let timeStyle be ? GetOption(options, "timeStyle", "string", « "full", "long", "medium", "short" », undefined).
  159. 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 {}));
  160. // 35. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
  161. if (!time_style.is_undefined())
  162. date_time_format.set_time_style(time_style.as_string().string());
  163. Optional<Unicode::CalendarPattern> best_format {};
  164. // 36. If dateStyle is not undefined or timeStyle is not undefined, then
  165. if (date_time_format.has_date_style() || date_time_format.has_time_style()) {
  166. // a. For each row in Table 4, except the header row, do
  167. TRY(for_each_calendar_field(global_object, format_options, [&](auto const& option, auto const& property, auto const&) -> ThrowCompletionOr<void> {
  168. // i. Let prop be the name given in the Property column of the row.
  169. // ii. Let p be opt.[[<prop>]].
  170. // iii. If p is not undefined, then
  171. if (option.has_value()) {
  172. // 1. Throw a TypeError exception.
  173. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, property, "dateStyle or timeStyle"sv);
  174. }
  175. return {};
  176. }));
  177. // b. Let styles be dataLocaleData.[[styles]].[[<calendar>]].
  178. // c. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles).
  179. best_format = date_time_style_format(data_locale, date_time_format);
  180. }
  181. // 37. Else,
  182. else {
  183. // a. Let formats be dataLocaleData.[[formats]].[[<calendar>]].
  184. auto formats = Unicode::get_calendar_available_formats(data_locale, date_time_format.calendar());
  185. // b. If matcher is "basic", then
  186. if (matcher.as_string().string() == "basic"sv) {
  187. // i. Let bestFormat be BasicFormatMatcher(opt, formats).
  188. best_format = basic_format_matcher(format_options, move(formats));
  189. }
  190. // c. Else,
  191. else {
  192. // i. Let bestFormat be BestFitFormatMatcher(opt, formats).
  193. best_format = best_fit_format_matcher(format_options, move(formats));
  194. }
  195. }
  196. // Non-standard, best_format will be empty if Unicode data generation is disabled.
  197. if (!best_format.has_value())
  198. return &date_time_format;
  199. // 38. For each row in Table 4, except the header row, in table order, do
  200. date_time_format.for_each_calendar_field_zipped_with(*best_format, [&](auto& date_time_format_field, auto const& best_format_field, auto) {
  201. // a. Let prop be the name given in the Property column of the row.
  202. // b. If bestFormat has a field [[<prop>]], then
  203. if (best_format_field.has_value()) {
  204. // i. Let p be bestFormat.[[<prop>]].
  205. // ii. Set dateTimeFormat's internal slot whose name is the Internal Slot column of the row to p.
  206. date_time_format_field = best_format_field;
  207. }
  208. });
  209. String pattern;
  210. // 39. If dateTimeFormat.[[Hour]] is undefined, then
  211. if (!date_time_format.has_hour()) {
  212. // a. Set dateTimeFormat.[[HourCycle]] to undefined.
  213. date_time_format.clear_hour_cycle();
  214. // b. Let pattern be bestFormat.[[pattern]].
  215. pattern = move(best_format->pattern);
  216. // FIXME: Implement step c when range formats are parsed by LibUnicode.
  217. // c. Let rangePatterns be bestFormat.[[rangePatterns]].
  218. }
  219. // 40. Else,
  220. else {
  221. // a. Let hcDefault be dataLocaleData.[[hourCycle]].
  222. auto default_hour_cycle = Unicode::get_default_regional_hour_cycle(data_locale);
  223. VERIFY(default_hour_cycle.has_value());
  224. // b. Let hc be dateTimeFormat.[[HourCycle]].
  225. // c. If hc is null, then
  226. // i. Set hc to hcDefault.
  227. auto hour_cycle = date_time_format.has_hour_cycle() ? date_time_format.hour_cycle() : *default_hour_cycle;
  228. // d. If hour12 is not undefined, then
  229. if (!hour12.is_undefined()) {
  230. // i. If hour12 is true, then
  231. if (hour12.as_bool()) {
  232. // 1. If hcDefault is "h11" or "h23", then
  233. if ((default_hour_cycle == Unicode::HourCycle::H11) || (default_hour_cycle == Unicode::HourCycle::H23)) {
  234. // a. Set hc to "h11".
  235. hour_cycle = Unicode::HourCycle::H11;
  236. }
  237. // 2. Else,
  238. else {
  239. // a. Set hc to "h12".
  240. hour_cycle = Unicode::HourCycle::H12;
  241. }
  242. }
  243. // ii. Else,
  244. else {
  245. // 1. Assert: hour12 is false.
  246. // 2. If hcDefault is "h11" or "h23", then
  247. if ((default_hour_cycle == Unicode::HourCycle::H11) || (default_hour_cycle == Unicode::HourCycle::H23)) {
  248. // a. Set hc to "h23".
  249. hour_cycle = Unicode::HourCycle::H23;
  250. }
  251. // 3. Else,
  252. else {
  253. // a. Set hc to "h24".
  254. hour_cycle = Unicode::HourCycle::H24;
  255. }
  256. }
  257. }
  258. // e. Set dateTimeFormat.[[HourCycle]] to hc.
  259. date_time_format.set_hour_cycle(hour_cycle);
  260. // FIXME: Implement steps f.ii and g.ii when range formats are parsed by LibUnicode.
  261. // f. If dateTimeformat.[[HourCycle]] is "h11" or "h12", then
  262. if ((hour_cycle == Unicode::HourCycle::H11) || (hour_cycle == Unicode::HourCycle::H12)) {
  263. // i. Let pattern be bestFormat.[[pattern12]].
  264. if (best_format->pattern12.has_value()) {
  265. pattern = best_format->pattern12.release_value();
  266. } else {
  267. // Non-standard, LibUnicode only provides [[pattern12]] when [[pattern]] has a day
  268. // period. Other implementations provide [[pattern12]] as a copy of [[pattern]].
  269. pattern = move(best_format->pattern);
  270. }
  271. // ii. Let rangePatterns be bestFormat.[[rangePatterns12]].
  272. }
  273. // g. Else,
  274. else {
  275. // i. Let pattern be bestFormat.[[pattern]].
  276. pattern = move(best_format->pattern);
  277. // ii. Let rangePatterns be bestFormat.[[rangePatterns]].
  278. }
  279. }
  280. // 41. Set dateTimeFormat.[[Pattern]] to pattern.
  281. date_time_format.set_pattern(move(pattern));
  282. // FIXME: Implement step 42 when range formats are parsed by LibUnicode.
  283. // 42. Set dateTimeFormat.[[RangePatterns]] to rangePatterns.
  284. // 43. Return dateTimeFormat.
  285. return &date_time_format;
  286. }
  287. // 11.1.2 ToDateTimeOptions ( options, required, defaults ), https://tc39.es/ecma402/#sec-todatetimeoptions
  288. ThrowCompletionOr<Object*> to_date_time_options(GlobalObject& global_object, Value options_value, OptionRequired required, OptionDefaults defaults)
  289. {
  290. auto& vm = global_object.vm();
  291. // 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options).
  292. Object* options = nullptr;
  293. if (!options_value.is_undefined())
  294. options = TRY(options_value.to_object(global_object));
  295. // 2. Let options be OrdinaryObjectCreate(options).
  296. options = Object::create(global_object, options);
  297. // 3. Let needDefaults be true.
  298. bool needs_defaults = true;
  299. // 4. If required is "date" or "any", then
  300. if ((required == OptionRequired::Date) || (required == OptionRequired::Any)) {
  301. // a. For each property name prop of « "weekday", "year", "month", "day" », do
  302. for (auto const& property : AK::Array { vm.names.weekday, vm.names.year, vm.names.month, vm.names.day }) {
  303. // i. Let value be ? Get(options, prop).
  304. auto value = TRY(options->get(property));
  305. // ii. If value is not undefined, let needDefaults be false.
  306. if (!value.is_undefined())
  307. needs_defaults = false;
  308. }
  309. }
  310. // 5. If required is "time" or "any", then
  311. if ((required == OptionRequired::Time) || (required == OptionRequired::Any)) {
  312. // a. For each property name prop of « "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits" », do
  313. for (auto const& property : AK::Array { vm.names.dayPeriod, vm.names.hour, vm.names.minute, vm.names.second, vm.names.fractionalSecondDigits }) {
  314. // i. Let value be ? Get(options, prop).
  315. auto value = TRY(options->get(property));
  316. // ii. If value is not undefined, let needDefaults be false.
  317. if (!value.is_undefined())
  318. needs_defaults = false;
  319. }
  320. }
  321. // 6. Let dateStyle be ? Get(options, "dateStyle").
  322. auto date_style = TRY(options->get(vm.names.dateStyle));
  323. // 7. Let timeStyle be ? Get(options, "timeStyle").
  324. auto time_style = TRY(options->get(vm.names.timeStyle));
  325. // 8. If dateStyle is not undefined or timeStyle is not undefined, let needDefaults be false.
  326. if (!date_style.is_undefined() || !time_style.is_undefined())
  327. needs_defaults = false;
  328. // 9. If required is "date" and timeStyle is not undefined, then
  329. if ((required == OptionRequired::Date) && !time_style.is_undefined()) {
  330. // a. Throw a TypeError exception.
  331. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, "timeStyle"sv, "date"sv);
  332. }
  333. // 10. If required is "time" and dateStyle is not undefined, then
  334. if ((required == OptionRequired::Time) && !date_style.is_undefined()) {
  335. // a. Throw a TypeError exception.
  336. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, "dateStyle"sv, "time"sv);
  337. }
  338. // 11. If needDefaults is true and defaults is either "date" or "all", then
  339. if (needs_defaults && ((defaults == OptionDefaults::Date) || (defaults == OptionDefaults::All))) {
  340. // a. For each property name prop of « "year", "month", "day" », do
  341. for (auto const& property : AK::Array { vm.names.year, vm.names.month, vm.names.day }) {
  342. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  343. TRY(options->create_data_property_or_throw(property, js_string(vm, "numeric"sv)));
  344. }
  345. }
  346. // 12. If needDefaults is true and defaults is either "time" or "all", then
  347. if (needs_defaults && ((defaults == OptionDefaults::Time) || (defaults == OptionDefaults::All))) {
  348. // a. For each property name prop of « "hour", "minute", "second" », do
  349. for (auto const& property : AK::Array { vm.names.hour, vm.names.minute, vm.names.second }) {
  350. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  351. TRY(options->create_data_property_or_throw(property, js_string(vm, "numeric"sv)));
  352. }
  353. }
  354. // 13. Return options.
  355. return options;
  356. }
  357. // 11.1.3 DateTimeStyleFormat ( dateStyle, timeStyle, styles ), https://tc39.es/ecma402/#sec-date-time-style-format
  358. Optional<Unicode::CalendarPattern> date_time_style_format(StringView data_locale, DateTimeFormat& date_time_format)
  359. {
  360. Unicode::CalendarPattern time_format {};
  361. Unicode::CalendarPattern date_format {};
  362. auto get_pattern = [&](auto type, auto style) -> Optional<Unicode::CalendarPattern> {
  363. auto formats = Unicode::get_calendar_format(data_locale, date_time_format.calendar(), type);
  364. if (formats.has_value()) {
  365. switch (style) {
  366. case DateTimeFormat::Style::Full:
  367. return formats->full_format;
  368. case DateTimeFormat::Style::Long:
  369. return formats->long_format;
  370. case DateTimeFormat::Style::Medium:
  371. return formats->medium_format;
  372. case DateTimeFormat::Style::Short:
  373. return formats->short_format;
  374. }
  375. }
  376. return {};
  377. };
  378. // 1. If timeStyle is not undefined, then
  379. if (date_time_format.has_time_style()) {
  380. // a. Assert: timeStyle is one of "full", "long", "medium", or "short".
  381. // b. Let timeFormat be styles.[[TimeFormat]].[[<timeStyle>]].
  382. auto pattern = get_pattern(Unicode::CalendarFormatType::Time, date_time_format.time_style());
  383. if (!pattern.has_value())
  384. return {};
  385. time_format = pattern.release_value();
  386. }
  387. // 2. If dateStyle is not undefined, then
  388. if (date_time_format.has_date_style()) {
  389. // a. Assert: dateStyle is one of "full", "long", "medium", or "short".
  390. // b. Let dateFormat be styles.[[DateFormat]].[[<dateStyle>]].
  391. auto pattern = get_pattern(Unicode::CalendarFormatType::Date, date_time_format.date_style());
  392. if (!pattern.has_value())
  393. return {};
  394. date_format = pattern.release_value();
  395. }
  396. // 3. If dateStyle is not undefined and timeStyle is not undefined, then
  397. if (date_time_format.has_date_style() && date_time_format.has_time_style()) {
  398. // a. Let format be a new Record.
  399. Unicode::CalendarPattern format {};
  400. // b. Add to format all fields from dateFormat except [[pattern]] and [[rangePatterns]].
  401. format.for_each_calendar_field_zipped_with(date_format, [](auto& format_field, auto const& date_format_field, auto) {
  402. format_field = date_format_field;
  403. });
  404. // c. Add to format all fields from timeFormat except [[pattern]], [[rangePatterns]], [[pattern12]], and [[rangePatterns12]], if present.
  405. format.for_each_calendar_field_zipped_with(time_format, [](auto& format_field, auto const& time_format_field, auto) {
  406. if (time_format_field.has_value())
  407. format_field = time_format_field;
  408. });
  409. // d. Let connector be styles.[[DateTimeFormat]].[[<dateStyle>]].
  410. auto connector = get_pattern(Unicode::CalendarFormatType::DateTime, date_time_format.date_style());
  411. if (!connector.has_value())
  412. return {};
  413. // e. Let pattern be the string connector with the substring "{0}" replaced with timeFormat.[[pattern]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  414. auto pattern = connector->pattern.replace("{0}"sv, time_format.pattern).replace("{1}"sv, date_format.pattern);
  415. // f. Set format.[[pattern]] to pattern.
  416. format.pattern = move(pattern);
  417. // g. If timeFormat has a [[pattern12]] field, then
  418. if (time_format.pattern12.has_value()) {
  419. // i. Let pattern12 be the string connector with the substring "{0}" replaced with timeFormat.[[pattern12]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  420. auto pattern12 = connector->pattern.replace("{0}"sv, *time_format.pattern12).replace("{1}"sv, date_format.pattern);
  421. // ii. Set format.[[pattern12]] to pattern12.
  422. format.pattern12 = move(pattern12);
  423. }
  424. // FIXME: Implement steps h-j when range formats are parsed by LibUnicode.
  425. // h. Let dateTimeRangeFormat be styles.[[DateTimeRangeFormat]].[[<dateStyle>]].[[<timeStyle>]].
  426. // i. Set format.[[rangePatterns]] to dateTimeRangeFormat.[[rangePatterns]].
  427. // j. If dateTimeRangeFormat has a [[rangePatterns12]] field, then
  428. // i. Set format.[[rangePatterns12]] to dateTimeRangeFormat.[[rangePatterns12]].
  429. // k. Return format.
  430. return format;
  431. }
  432. // 4. If timeStyle is not undefined, then
  433. if (date_time_format.has_time_style()) {
  434. // a. Return timeFormat.
  435. return time_format;
  436. }
  437. // 5. Assert: dateStyle is not undefined.
  438. VERIFY(date_time_format.has_date_style());
  439. // 6. Return dateFormat.
  440. return date_format;
  441. }
  442. // 11.1.4 BasicFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-basicformatmatcher
  443. Optional<Unicode::CalendarPattern> basic_format_matcher(Unicode::CalendarPattern const& options, Vector<Unicode::CalendarPattern> formats)
  444. {
  445. // 1. Let removalPenalty be 120.
  446. constexpr int removal_penalty = 120;
  447. // 2. Let additionPenalty be 20.
  448. constexpr int addition_penalty = 20;
  449. // 3. Let longLessPenalty be 8.
  450. constexpr int long_less_penalty = 8;
  451. // 4. Let longMorePenalty be 6.
  452. constexpr int long_more_penalty = 6;
  453. // 5. Let shortLessPenalty be 6.
  454. constexpr int short_less_penalty = 6;
  455. // 6. Let shortMorePenalty be 3.
  456. constexpr int short_more_penalty = 3;
  457. // 7. Let bestScore be -Infinity.
  458. int best_score = NumericLimits<int>::min();
  459. // 8. Let bestFormat be undefined.
  460. Optional<Unicode::CalendarPattern> best_format;
  461. // 9. Assert: Type(formats) is List.
  462. // 10. For each element format of formats, do
  463. for (auto& format : formats) {
  464. // a. Let score be 0.
  465. int score = 0;
  466. // b. For each property name property shown in Table 4, do
  467. format.for_each_calendar_field_zipped_with(options, [&](auto const& format_prop, auto const& options_prop, auto) {
  468. using ValueType = typename RemoveReference<decltype(options_prop)>::ValueType;
  469. // i. If options has a field [[<property>]], let optionsProp be options.[[<property>]]; else let optionsProp be undefined.
  470. // ii. If format has a field [[<property>]], let formatProp be format.[[<property>]]; else let formatProp be undefined.
  471. // iii. If optionsProp is undefined and formatProp is not undefined, decrease score by additionPenalty.
  472. if (!options_prop.has_value() && format_prop.has_value()) {
  473. score -= addition_penalty;
  474. }
  475. // iv. Else if optionsProp is not undefined and formatProp is undefined, decrease score by removalPenalty.
  476. else if (options_prop.has_value() && !format_prop.has_value()) {
  477. score -= removal_penalty;
  478. }
  479. // v. Else if optionsProp ≠ formatProp, then
  480. else if (options_prop != format_prop) {
  481. using ValuesType = Conditional<IsIntegral<ValueType>, AK::Array<u8, 3>, AK::Array<Unicode::CalendarPatternStyle, 5>>;
  482. ValuesType values {};
  483. // 1. If property is "fractionalSecondDigits", then
  484. if constexpr (IsIntegral<ValueType>) {
  485. // a. Let values be « 1𝔽, 2𝔽, 3𝔽 ».
  486. values = { 1, 2, 3 };
  487. }
  488. // 2. Else,
  489. else {
  490. // a. Let values be « "2-digit", "numeric", "narrow", "short", "long" ».
  491. values = {
  492. Unicode::CalendarPatternStyle::TwoDigit,
  493. Unicode::CalendarPatternStyle::Numeric,
  494. Unicode::CalendarPatternStyle::Narrow,
  495. Unicode::CalendarPatternStyle::Short,
  496. Unicode::CalendarPatternStyle::Long,
  497. };
  498. }
  499. // 3. Let optionsPropIndex be the index of optionsProp within values.
  500. auto options_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *options_prop));
  501. // 4. Let formatPropIndex be the index of formatProp within values.
  502. auto format_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *format_prop));
  503. // 5. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
  504. int delta = max(min(format_prop_index - options_prop_index, 2), -2);
  505. // 6. If delta = 2, decrease score by longMorePenalty.
  506. if (delta == 2)
  507. score -= long_more_penalty;
  508. // 7. Else if delta = 1, decrease score by shortMorePenalty.
  509. else if (delta == 1)
  510. score -= short_more_penalty;
  511. // 8. Else if delta = -1, decrease score by shortLessPenalty.
  512. else if (delta == -1)
  513. score -= short_less_penalty;
  514. // 9. Else if delta = -2, decrease score by longLessPenalty.
  515. else if (delta == -2)
  516. score -= long_less_penalty;
  517. }
  518. });
  519. // c. If score > bestScore, then
  520. if (score > best_score) {
  521. // i. Let bestScore be score.
  522. best_score = score;
  523. // ii. Let bestFormat be format.
  524. best_format = format;
  525. }
  526. }
  527. if (!best_format.has_value())
  528. return {};
  529. // Non-standard, if the user provided options that differ from the best format's options, keep
  530. // the user's options. This is expected by TR-35:
  531. //
  532. // It is not necessary to supply dateFormatItems with skeletons for every field length; fields
  533. // in the skeleton and pattern are expected to be expanded in parallel to handle a request.
  534. // https://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
  535. //
  536. // Rather than generating an prohibitively large amount of nearly-duplicate patterns, which only
  537. // differ by field length, we expand the field lengths here.
  538. best_format->for_each_calendar_field_zipped_with(options, [&](auto& best_format_field, auto const& option_field, auto field_type) {
  539. switch (field_type) {
  540. case Unicode::CalendarPattern::Field::FractionalSecondDigits:
  541. if (best_format->second.has_value() && option_field.has_value())
  542. best_format_field = option_field;
  543. break;
  544. case Unicode::CalendarPattern::Field::Hour:
  545. case Unicode::CalendarPattern::Field::Minute:
  546. case Unicode::CalendarPattern::Field::Second:
  547. break;
  548. default:
  549. if (best_format_field.has_value() && option_field.has_value())
  550. best_format_field = option_field;
  551. break;
  552. }
  553. });
  554. // 11. Return bestFormat.
  555. return best_format;
  556. }
  557. // 11.1.5 BestFitFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-bestfitformatmatcher
  558. Optional<Unicode::CalendarPattern> best_fit_format_matcher(Unicode::CalendarPattern const& options, Vector<Unicode::CalendarPattern> formats)
  559. {
  560. // When the BestFitFormatMatcher abstract operation is called with two arguments options and formats, it performs
  561. // implementation dependent steps, which should return a set of component representations that a typical user of
  562. // the selected locale would perceive as at least as good as the one returned by BasicFormatMatcher.
  563. return basic_format_matcher(options, move(formats));
  564. }
  565. }