DateTimeFormat.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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) {
  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. // ii. Let rangePatterns be bestFormat.[[rangePatterns12]].
  267. }
  268. // g. Else,
  269. else {
  270. // i. Let pattern be bestFormat.[[pattern]].
  271. pattern = move(best_format->pattern);
  272. // ii. Let rangePatterns be bestFormat.[[rangePatterns]].
  273. }
  274. }
  275. // 41. Set dateTimeFormat.[[Pattern]] to pattern.
  276. date_time_format.set_pattern(move(pattern));
  277. // FIXME: Implement step 42 when range formats are parsed by LibUnicode.
  278. // 42. Set dateTimeFormat.[[RangePatterns]] to rangePatterns.
  279. // 43. Return dateTimeFormat.
  280. return &date_time_format;
  281. }
  282. // 11.1.2 ToDateTimeOptions ( options, required, defaults ), https://tc39.es/ecma402/#sec-todatetimeoptions
  283. ThrowCompletionOr<Object*> to_date_time_options(GlobalObject& global_object, Value options_value, OptionRequired required, OptionDefaults defaults)
  284. {
  285. auto& vm = global_object.vm();
  286. // 1. If options is undefined, let options be null; otherwise let options be ? ToObject(options).
  287. Object* options = nullptr;
  288. if (!options_value.is_undefined())
  289. options = TRY(options_value.to_object(global_object));
  290. // 2. Let options be OrdinaryObjectCreate(options).
  291. options = Object::create(global_object, options);
  292. // 3. Let needDefaults be true.
  293. bool needs_defaults = true;
  294. // 4. If required is "date" or "any", then
  295. if ((required == OptionRequired::Date) || (required == OptionRequired::Any)) {
  296. // a. For each property name prop of « "weekday", "year", "month", "day" », do
  297. for (auto const& property : AK::Array { vm.names.weekday, vm.names.year, vm.names.month, vm.names.day }) {
  298. // i. Let value be ? Get(options, prop).
  299. auto value = TRY(options->get(property));
  300. // ii. If value is not undefined, let needDefaults be false.
  301. if (!value.is_undefined())
  302. needs_defaults = false;
  303. }
  304. }
  305. // 5. If required is "time" or "any", then
  306. if ((required == OptionRequired::Time) || (required == OptionRequired::Any)) {
  307. // a. For each property name prop of « "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits" », do
  308. for (auto const& property : AK::Array { vm.names.dayPeriod, vm.names.hour, vm.names.minute, vm.names.second, vm.names.fractionalSecondDigits }) {
  309. // i. Let value be ? Get(options, prop).
  310. auto value = TRY(options->get(property));
  311. // ii. If value is not undefined, let needDefaults be false.
  312. if (!value.is_undefined())
  313. needs_defaults = false;
  314. }
  315. }
  316. // 6. Let dateStyle be ? Get(options, "dateStyle").
  317. auto date_style = TRY(options->get(vm.names.dateStyle));
  318. // 7. Let timeStyle be ? Get(options, "timeStyle").
  319. auto time_style = TRY(options->get(vm.names.timeStyle));
  320. // 8. If dateStyle is not undefined or timeStyle is not undefined, let needDefaults be false.
  321. if (!date_style.is_undefined() || !time_style.is_undefined())
  322. needs_defaults = false;
  323. // 9. If required is "date" and timeStyle is not undefined, then
  324. if ((required == OptionRequired::Date) && !time_style.is_undefined()) {
  325. // a. Throw a TypeError exception.
  326. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, "timeStyle"sv, "date"sv);
  327. }
  328. // 10. If required is "time" and dateStyle is not undefined, then
  329. if ((required == OptionRequired::Time) && !date_style.is_undefined()) {
  330. // a. Throw a TypeError exception.
  331. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, "dateStyle"sv, "time"sv);
  332. }
  333. // 11. If needDefaults is true and defaults is either "date" or "all", then
  334. if (needs_defaults && ((defaults == OptionDefaults::Date) || (defaults == OptionDefaults::All))) {
  335. // a. For each property name prop of « "year", "month", "day" », do
  336. for (auto const& property : AK::Array { vm.names.year, vm.names.month, vm.names.day }) {
  337. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  338. TRY(options->create_data_property_or_throw(property, js_string(vm, "numeric"sv)));
  339. }
  340. }
  341. // 12. If needDefaults is true and defaults is either "time" or "all", then
  342. if (needs_defaults && ((defaults == OptionDefaults::Time) || (defaults == OptionDefaults::All))) {
  343. // a. For each property name prop of « "hour", "minute", "second" », do
  344. for (auto const& property : AK::Array { vm.names.hour, vm.names.minute, vm.names.second }) {
  345. // i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
  346. TRY(options->create_data_property_or_throw(property, js_string(vm, "numeric"sv)));
  347. }
  348. }
  349. // 13. Return options.
  350. return options;
  351. }
  352. // 11.1.3 DateTimeStyleFormat ( dateStyle, timeStyle, styles ), https://tc39.es/ecma402/#sec-date-time-style-format
  353. Optional<Unicode::CalendarPattern> date_time_style_format(StringView data_locale, DateTimeFormat& date_time_format)
  354. {
  355. Unicode::CalendarPattern time_format {};
  356. Unicode::CalendarPattern date_format {};
  357. auto get_pattern = [&](auto type, auto style) -> Optional<Unicode::CalendarPattern> {
  358. auto formats = Unicode::get_calendar_format(data_locale, date_time_format.calendar(), type);
  359. if (formats.has_value()) {
  360. switch (style) {
  361. case DateTimeFormat::Style::Full:
  362. return formats->full_format;
  363. case DateTimeFormat::Style::Long:
  364. return formats->long_format;
  365. case DateTimeFormat::Style::Medium:
  366. return formats->medium_format;
  367. case DateTimeFormat::Style::Short:
  368. return formats->short_format;
  369. }
  370. }
  371. return {};
  372. };
  373. // 1. If timeStyle is not undefined, then
  374. if (date_time_format.has_time_style()) {
  375. // a. Assert: timeStyle is one of "full", "long", "medium", or "short".
  376. // b. Let timeFormat be styles.[[TimeFormat]].[[<timeStyle>]].
  377. auto pattern = get_pattern(Unicode::CalendarFormatType::Time, date_time_format.time_style());
  378. if (!pattern.has_value())
  379. return {};
  380. time_format = pattern.release_value();
  381. }
  382. // 2. If dateStyle is not undefined, then
  383. if (date_time_format.has_date_style()) {
  384. // a. Assert: dateStyle is one of "full", "long", "medium", or "short".
  385. // b. Let dateFormat be styles.[[DateFormat]].[[<dateStyle>]].
  386. auto pattern = get_pattern(Unicode::CalendarFormatType::Date, date_time_format.date_style());
  387. if (!pattern.has_value())
  388. return {};
  389. date_format = pattern.release_value();
  390. }
  391. // 3. If dateStyle is not undefined and timeStyle is not undefined, then
  392. if (date_time_format.has_date_style() && date_time_format.has_time_style()) {
  393. // a. Let format be a new Record.
  394. Unicode::CalendarPattern format {};
  395. // b. Add to format all fields from dateFormat except [[pattern]] and [[rangePatterns]].
  396. format.for_each_calendar_field_zipped_with(date_format, [](auto& format_field, auto const& date_format_field) {
  397. format_field = date_format_field;
  398. });
  399. // c. Add to format all fields from timeFormat except [[pattern]], [[rangePatterns]], [[pattern12]], and [[rangePatterns12]], if present.
  400. format.for_each_calendar_field_zipped_with(time_format, [](auto& format_field, auto const& time_format_field) {
  401. if (time_format_field.has_value())
  402. format_field = time_format_field;
  403. });
  404. // d. Let connector be styles.[[DateTimeFormat]].[[<dateStyle>]].
  405. auto connector = get_pattern(Unicode::CalendarFormatType::DateTime, date_time_format.date_style());
  406. if (!connector.has_value())
  407. return {};
  408. // e. Let pattern be the string connector with the substring "{0}" replaced with timeFormat.[[pattern]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  409. auto pattern = connector->pattern.replace("{0}"sv, time_format.pattern).replace("{1}"sv, date_format.pattern);
  410. // f. Set format.[[pattern]] to pattern.
  411. format.pattern = move(pattern);
  412. // g. If timeFormat has a [[pattern12]] field, then
  413. if (time_format.pattern12.has_value()) {
  414. // i. Let pattern12 be the string connector with the substring "{0}" replaced with timeFormat.[[pattern12]] and the substring "{1}" replaced with dateFormat.[[pattern]].
  415. auto pattern12 = connector->pattern.replace("{0}"sv, *time_format.pattern12).replace("{1}"sv, date_format.pattern);
  416. // ii. Set format.[[pattern12]] to pattern12.
  417. format.pattern12 = move(pattern12);
  418. }
  419. // FIXME: Implement steps h-j when range formats are parsed by LibUnicode.
  420. // h. Let dateTimeRangeFormat be styles.[[DateTimeRangeFormat]].[[<dateStyle>]].[[<timeStyle>]].
  421. // i. Set format.[[rangePatterns]] to dateTimeRangeFormat.[[rangePatterns]].
  422. // j. If dateTimeRangeFormat has a [[rangePatterns12]] field, then
  423. // i. Set format.[[rangePatterns12]] to dateTimeRangeFormat.[[rangePatterns12]].
  424. // k. Return format.
  425. return format;
  426. }
  427. // 4. If timeStyle is not undefined, then
  428. if (date_time_format.has_time_style()) {
  429. // a. Return timeFormat.
  430. return time_format;
  431. }
  432. // 5. Assert: dateStyle is not undefined.
  433. VERIFY(date_time_format.has_date_style());
  434. // 6. Return dateFormat.
  435. return date_format;
  436. }
  437. // 11.1.4 BasicFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-basicformatmatcher
  438. Optional<Unicode::CalendarPattern> basic_format_matcher(Unicode::CalendarPattern const& options, Vector<Unicode::CalendarPattern> formats)
  439. {
  440. // 1. Let removalPenalty be 120.
  441. constexpr int removal_penalty = 120;
  442. // 2. Let additionPenalty be 20.
  443. constexpr int addition_penalty = 20;
  444. // 3. Let longLessPenalty be 8.
  445. constexpr int long_less_penalty = 8;
  446. // 4. Let longMorePenalty be 6.
  447. constexpr int long_more_penalty = 6;
  448. // 5. Let shortLessPenalty be 6.
  449. constexpr int short_less_penalty = 6;
  450. // 6. Let shortMorePenalty be 3.
  451. constexpr int short_more_penalty = 3;
  452. // 7. Let bestScore be -Infinity.
  453. int best_score = NumericLimits<int>::min();
  454. // 8. Let bestFormat be undefined.
  455. Optional<Unicode::CalendarPattern> best_format;
  456. // 9. Assert: Type(formats) is List.
  457. // 10. For each element format of formats, do
  458. for (auto& format : formats) {
  459. // a. Let score be 0.
  460. int score = 0;
  461. // b. For each property name property shown in Table 4, do
  462. format.for_each_calendar_field_zipped_with(options, [&](auto const& format_prop, auto const& options_prop) {
  463. using ValueType = typename RemoveReference<decltype(options_prop)>::ValueType;
  464. // i. If options has a field [[<property>]], let optionsProp be options.[[<property>]]; else let optionsProp be undefined.
  465. // ii. If format has a field [[<property>]], let formatProp be format.[[<property>]]; else let formatProp be undefined.
  466. // iii. If optionsProp is undefined and formatProp is not undefined, decrease score by additionPenalty.
  467. if (!options_prop.has_value() && format_prop.has_value()) {
  468. score -= addition_penalty;
  469. }
  470. // iv. Else if optionsProp is not undefined and formatProp is undefined, decrease score by removalPenalty.
  471. else if (options_prop.has_value() && !format_prop.has_value()) {
  472. score -= removal_penalty;
  473. }
  474. // v. Else if optionsProp ≠ formatProp, then
  475. else if (options_prop != format_prop) {
  476. using ValuesType = Conditional<IsIntegral<ValueType>, AK::Array<u8, 3>, AK::Array<Unicode::CalendarPatternStyle, 5>>;
  477. ValuesType values {};
  478. // 1. If property is "fractionalSecondDigits", then
  479. if constexpr (IsIntegral<ValueType>) {
  480. // a. Let values be « 1𝔽, 2𝔽, 3𝔽 ».
  481. values = { 1, 2, 3 };
  482. }
  483. // 2. Else,
  484. else {
  485. // a. Let values be « "2-digit", "numeric", "narrow", "short", "long" ».
  486. values = {
  487. Unicode::CalendarPatternStyle::TwoDigit,
  488. Unicode::CalendarPatternStyle::Numeric,
  489. Unicode::CalendarPatternStyle::Narrow,
  490. Unicode::CalendarPatternStyle::Short,
  491. Unicode::CalendarPatternStyle::Long,
  492. };
  493. }
  494. // 3. Let optionsPropIndex be the index of optionsProp within values.
  495. auto options_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *options_prop));
  496. // 4. Let formatPropIndex be the index of formatProp within values.
  497. auto format_prop_index = static_cast<int>(find_index(values.begin(), values.end(), *format_prop));
  498. // 5. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
  499. int delta = max(min(format_prop_index - options_prop_index, 2), -2);
  500. // 6. If delta = 2, decrease score by longMorePenalty.
  501. if (delta == 2)
  502. score -= long_more_penalty;
  503. // 7. Else if delta = 1, decrease score by shortMorePenalty.
  504. else if (delta == 1)
  505. score -= short_more_penalty;
  506. // 8. Else if delta = -1, decrease score by shortLessPenalty.
  507. else if (delta == -1)
  508. score -= short_less_penalty;
  509. // 9. Else if delta = -2, decrease score by longLessPenalty.
  510. else if (delta == -2)
  511. score -= long_less_penalty;
  512. }
  513. });
  514. // c. If score > bestScore, then
  515. if (score > best_score) {
  516. // i. Let bestScore be score.
  517. best_score = score;
  518. // ii. Let bestFormat be format.
  519. best_format = format;
  520. }
  521. }
  522. // 11. Return bestFormat.
  523. return best_format;
  524. }
  525. // 11.1.5 BestFitFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-bestfitformatmatcher
  526. Optional<Unicode::CalendarPattern> best_fit_format_matcher(Unicode::CalendarPattern const& options, Vector<Unicode::CalendarPattern> formats)
  527. {
  528. // When the BestFitFormatMatcher abstract operation is called with two arguments options and formats, it performs
  529. // implementation dependent steps, which should return a set of component representations that a typical user of
  530. // the selected locale would perceive as at least as good as the one returned by BasicFormatMatcher.
  531. return basic_format_matcher(options, move(formats));
  532. }
  533. }