DateTimeFormat.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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. Vector<StringView> const& DateTimeFormat::relevant_extension_keys()
  13. {
  14. // 11.3.3 Internal slots, https://tc39.es/ecma402/#sec-intl.datetimeformat-internal-slots
  15. // The value of the [[RelevantExtensionKeys]] internal slot is « "ca", "hc", "nu" ».
  16. static Vector<StringView> relevant_extension_keys { "ca"sv, "hc"sv, "nu"sv };
  17. return relevant_extension_keys;
  18. }
  19. // 11 DateTimeFormat Objects, https://tc39.es/ecma402/#datetimeformat-objects
  20. DateTimeFormat::DateTimeFormat(Object& prototype)
  21. : Object(prototype)
  22. {
  23. }
  24. DateTimeFormat::Style DateTimeFormat::style_from_string(StringView style)
  25. {
  26. if (style == "full"sv)
  27. return Style::Full;
  28. if (style == "long"sv)
  29. return Style::Long;
  30. if (style == "medium"sv)
  31. return Style::Medium;
  32. if (style == "short"sv)
  33. return Style::Short;
  34. VERIFY_NOT_REACHED();
  35. }
  36. StringView DateTimeFormat::style_to_string(Style style)
  37. {
  38. switch (style) {
  39. case Style::Full:
  40. return "full"sv;
  41. case Style::Long:
  42. return "long"sv;
  43. case Style::Medium:
  44. return "medium"sv;
  45. case Style::Short:
  46. return "short"sv;
  47. default:
  48. VERIFY_NOT_REACHED();
  49. }
  50. }
  51. // 11.1.1 InitializeDateTimeFormat ( dateTimeFormat, locales, options ), https://tc39.es/ecma402/#sec-initializedatetimeformat
  52. ThrowCompletionOr<DateTimeFormat*> initialize_date_time_format(GlobalObject& global_object, DateTimeFormat& date_time_format, Value locales_value, Value options_value)
  53. {
  54. auto& vm = global_object.vm();
  55. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  56. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  57. // 2. Let options be ? ToDateTimeOptions(options, "any", "date").
  58. auto* options = TRY(to_date_time_options(global_object, options_value, OptionRequired::Any, OptionDefaults::Date));
  59. // 3. Let opt be a new Record.
  60. LocaleOptions opt {};
  61. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  62. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv));
  63. // 5. Set opt.[[localeMatcher]] to matcher.
  64. opt.locale_matcher = matcher;
  65. // 6. Let calendar be ? GetOption(options, "calendar", "string", undefined, undefined).
  66. auto calendar = TRY(get_option(global_object, *options, vm.names.calendar, Value::Type::String, {}, Empty {}));
  67. // 7. If calendar is not undefined, then
  68. if (!calendar.is_undefined()) {
  69. // a. If calendar does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  70. if (!Unicode::is_type_identifier(calendar.as_string().string()))
  71. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, calendar, "calendar"sv);
  72. // 8. Set opt.[[ca]] to calendar.
  73. opt.ca = calendar.as_string().string();
  74. }
  75. // 9. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  76. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  77. // 10. If numberingSystem is not undefined, then
  78. if (!numbering_system.is_undefined()) {
  79. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  80. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  81. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  82. // 11. Set opt.[[nu]] to numberingSystem.
  83. opt.nu = numbering_system.as_string().string();
  84. }
  85. // 12. Let hour12 be ? GetOption(options, "hour12", "boolean", undefined, undefined).
  86. auto hour12 = TRY(get_option(global_object, *options, vm.names.hour12, Value::Type::Boolean, {}, Empty {}));
  87. // 13. Let hourCycle be ? GetOption(options, "hourCycle", "string", « "h11", "h12", "h23", "h24" », undefined).
  88. 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 {}));
  89. // 14. If hour12 is not undefined, then
  90. if (!hour12.is_undefined()) {
  91. // a. Let hourCycle be null.
  92. hour_cycle = js_null();
  93. }
  94. // 15. Set opt.[[hc]] to hourCycle.
  95. if (!hour_cycle.is_nullish())
  96. opt.hc = hour_cycle.as_string().string();
  97. // 16. Let localeData be %DateTimeFormat%.[[LocaleData]].
  98. // 17. Let r be ResolveLocale(%DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]], localeData).
  99. auto result = resolve_locale(requested_locales, opt, DateTimeFormat::relevant_extension_keys());
  100. // 18. Set dateTimeFormat.[[Locale]] to r.[[locale]].
  101. date_time_format.set_locale(move(result.locale));
  102. // 19. Let calendar be r.[[ca]].
  103. // 20. Set dateTimeFormat.[[Calendar]] to calendar.
  104. date_time_format.set_calendar(result.ca.release_value());
  105. // 21. Set dateTimeFormat.[[HourCycle]] to r.[[hc]].
  106. date_time_format.set_hour_cycle(result.hc.release_value());
  107. // 22. Set dateTimeFormat.[[NumberingSystem]] to r.[[nu]].
  108. date_time_format.set_numbering_system(result.nu.release_value());
  109. // 23. Let dataLocale be r.[[dataLocale]].
  110. auto data_locale = move(result.data_locale);
  111. // 24. Let timeZone be ? Get(options, "timeZone").
  112. auto time_zone_value = TRY(options->get(vm.names.timeZone));
  113. String time_zone;
  114. // 25. If timeZone is undefined, then
  115. if (time_zone_value.is_undefined()) {
  116. // a. Let timeZone be DefaultTimeZone().
  117. time_zone = Temporal::default_time_zone();
  118. }
  119. // 26. Else,
  120. else {
  121. // a. Let timeZone be ? ToString(timeZone).
  122. time_zone = TRY(time_zone_value.to_string(global_object));
  123. // b. If the result of IsValidTimeZoneName(timeZone) is false, then
  124. if (!Temporal::is_valid_time_zone_name(time_zone)) {
  125. // i. Throw a RangeError exception.
  126. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  127. }
  128. // c. Let timeZone be CanonicalizeTimeZoneName(timeZone).
  129. time_zone = Temporal::canonicalize_time_zone_name(time_zone);
  130. }
  131. // 27. Set dateTimeFormat.[[TimeZone]] to timeZone.
  132. date_time_format.set_time_zone(move(time_zone));
  133. // 28. Let opt be a new Record.
  134. Unicode::CalendarPattern format_options {};
  135. // 29. For each row of Table 4, except the header row, in table order, do
  136. TRY(for_each_calendar_field(global_object, format_options, [&](auto& option, auto const& property, auto const& defaults) -> ThrowCompletionOr<void> {
  137. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  138. // a. Let prop be the name given in the Property column of the row.
  139. // b. If prop is "fractionalSecondDigits", then
  140. if constexpr (IsIntegral<ValueType>) {
  141. // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
  142. auto value = TRY(get_number_option(global_object, *options, property, 1, 3, {}));
  143. // d. Set opt.[[<prop>]] to value.
  144. if (value.has_value())
  145. option = static_cast<ValueType>(value.value());
  146. }
  147. // c. Else,
  148. else {
  149. // i. Let value be ? GetOption(options, prop, "string", « the strings given in the Values column of the row », undefined).
  150. auto value = TRY(get_option(global_object, *options, property, Value::Type::String, defaults, Empty {}));
  151. // d. Set opt.[[<prop>]] to value.
  152. if (!value.is_undefined())
  153. option = Unicode::calendar_pattern_style_from_string(value.as_string().string());
  154. }
  155. return {};
  156. }));
  157. // 30. Let dataLocaleData be localeData.[[<dataLocale>]].
  158. // 31. Let matcher be ? GetOption(options, "formatMatcher", "string", « "basic", "best fit" », "best fit").
  159. matcher = TRY(get_option(global_object, *options, vm.names.formatMatcher, Value::Type::String, AK::Array { "basic"sv, "best fit"sv }, "best fit"sv));
  160. // 32. Let dateStyle be ? GetOption(options, "dateStyle", "string", « "full", "long", "medium", "short" », undefined).
  161. 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 {}));
  162. // 33. Set dateTimeFormat.[[DateStyle]] to dateStyle.
  163. if (!date_style.is_undefined())
  164. date_time_format.set_date_style(date_style.as_string().string());
  165. // 34. Let timeStyle be ? GetOption(options, "timeStyle", "string", « "full", "long", "medium", "short" », undefined).
  166. 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 {}));
  167. // 35. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
  168. if (!time_style.is_undefined())
  169. date_time_format.set_time_style(time_style.as_string().string());
  170. Optional<Unicode::CalendarPattern> best_format {};
  171. // 36. If dateStyle is not undefined or timeStyle is not undefined, then
  172. if (date_time_format.has_date_style() || date_time_format.has_time_style()) {
  173. // a. For each row in Table 4, except the header row, do
  174. TRY(for_each_calendar_field(global_object, format_options, [&](auto const& option, auto const& property, auto const&) -> ThrowCompletionOr<void> {
  175. // i. Let prop be the name given in the Property column of the row.
  176. // ii. Let p be opt.[[<prop>]].
  177. // iii. If p is not undefined, then
  178. if (option.has_value()) {
  179. // 1. Throw a TypeError exception.
  180. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlInvalidDateTimeFormatOption, property, "dateStyle or timeStyle"sv);
  181. }
  182. return {};
  183. }));
  184. // b. Let styles be dataLocaleData.[[styles]].[[<calendar>]].
  185. // c. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles).
  186. best_format = date_time_style_format(data_locale, date_time_format);
  187. }
  188. // 37. Else,
  189. else {
  190. // a. Let formats be dataLocaleData.[[formats]].[[<calendar>]].
  191. auto formats = Unicode::get_calendar_available_formats(data_locale, date_time_format.calendar());
  192. // b. If matcher is "basic", then
  193. if (matcher.as_string().string() == "basic"sv) {
  194. // i. Let bestFormat be BasicFormatMatcher(opt, formats).
  195. best_format = basic_format_matcher(format_options, move(formats));
  196. }
  197. // c. Else,
  198. else {
  199. // i. Let bestFormat be BestFitFormatMatcher(opt, formats).
  200. best_format = best_fit_format_matcher(format_options, move(formats));
  201. }
  202. }
  203. // Non-standard, best_format will be empty if Unicode data generation is disabled.
  204. if (!best_format.has_value())
  205. return &date_time_format;
  206. // 38. For each row in Table 4, except the header row, in table order, do
  207. date_time_format.for_each_calendar_field_zipped_with(*best_format, [&](auto& date_time_format_field, auto const& best_format_field) {
  208. // a. Let prop be the name given in the Property column of the row.
  209. // b. If bestFormat has a field [[<prop>]], then
  210. if (best_format_field.has_value()) {
  211. // i. Let p be bestFormat.[[<prop>]].
  212. // ii. Set dateTimeFormat's internal slot whose name is the Internal Slot column of the row to p.
  213. date_time_format_field = best_format_field;
  214. }
  215. });
  216. String pattern;
  217. // 39. If dateTimeFormat.[[Hour]] is undefined, then
  218. if (!date_time_format.has_hour()) {
  219. // a. Set dateTimeFormat.[[HourCycle]] to undefined.
  220. date_time_format.clear_hour_cycle();
  221. // b. Let pattern be bestFormat.[[pattern]].
  222. pattern = move(best_format->pattern);
  223. // FIXME: Implement step c when range formats are parsed by LibUnicode.
  224. // c. Let rangePatterns be bestFormat.[[rangePatterns]].
  225. }
  226. // 40. Else,
  227. else {
  228. // a. Let hcDefault be dataLocaleData.[[hourCycle]].
  229. auto default_hour_cycle = Unicode::get_default_regional_hour_cycle(data_locale);
  230. VERIFY(default_hour_cycle.has_value());
  231. // b. Let hc be dateTimeFormat.[[HourCycle]].
  232. // c. If hc is null, then
  233. // i. Set hc to hcDefault.
  234. auto hour_cycle = date_time_format.has_hour_cycle() ? date_time_format.hour_cycle() : *default_hour_cycle;
  235. // d. If hour12 is not undefined, then
  236. if (!hour12.is_undefined()) {
  237. // i. If hour12 is true, then
  238. if (hour12.as_bool()) {
  239. // 1. If hcDefault is "h11" or "h23", then
  240. if ((default_hour_cycle == Unicode::HourCycle::H11) || (default_hour_cycle == Unicode::HourCycle::H23)) {
  241. // a. Set hc to "h11".
  242. hour_cycle = Unicode::HourCycle::H11;
  243. }
  244. // 2. Else,
  245. else {
  246. // a. Set hc to "h12".
  247. hour_cycle = Unicode::HourCycle::H12;
  248. }
  249. }
  250. // ii. Else,
  251. else {
  252. // 1. Assert: hour12 is false.
  253. // 2. If hcDefault is "h11" or "h23", then
  254. if ((default_hour_cycle == Unicode::HourCycle::H11) || (default_hour_cycle == Unicode::HourCycle::H23)) {
  255. // a. Set hc to "h23".
  256. hour_cycle = Unicode::HourCycle::H23;
  257. }
  258. // 3. Else,
  259. else {
  260. // a. Set hc to "h24".
  261. hour_cycle = Unicode::HourCycle::H24;
  262. }
  263. }
  264. }
  265. // e. Set dateTimeFormat.[[HourCycle]] to hc.
  266. date_time_format.set_hour_cycle(hour_cycle);
  267. // FIXME: Implement steps f.ii and g.ii when range formats are parsed by LibUnicode.
  268. // f. If dateTimeformat.[[HourCycle]] is "h11" or "h12", then
  269. if ((hour_cycle == Unicode::HourCycle::H11) || (hour_cycle == Unicode::HourCycle::H12)) {
  270. // i. Let pattern be bestFormat.[[pattern12]].
  271. if (best_format->pattern12.has_value())
  272. pattern = best_format->pattern12.release_value();
  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) {
  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) {
  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) {
  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. // 11. Return bestFormat.
  530. return best_format;
  531. }
  532. // 11.1.5 BestFitFormatMatcher ( options, formats ), https://tc39.es/ecma402/#sec-bestfitformatmatcher
  533. Optional<Unicode::CalendarPattern> best_fit_format_matcher(Unicode::CalendarPattern const& options, Vector<Unicode::CalendarPattern> formats)
  534. {
  535. // When the BestFitFormatMatcher abstract operation is called with two arguments options and formats, it performs
  536. // implementation dependent steps, which should return a set of component representations that a typical user of
  537. // the selected locale would perceive as at least as good as the one returned by BasicFormatMatcher.
  538. return basic_format_matcher(options, move(formats));
  539. }
  540. }