DateTimeFormat.cpp 31 KB

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