AbstractOperations.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AllOf.h>
  7. #include <AK/AnyOf.h>
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/Function.h>
  10. #include <AK/QuickSort.h>
  11. #include <AK/TypeCasts.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  15. #include <LibJS/Runtime/Intl/Locale.h>
  16. #include <LibUnicode/Locale.h>
  17. namespace JS::Intl {
  18. // 6.2.2 IsStructurallyValidLanguageTag ( locale ), https://tc39.es/ecma402/#sec-isstructurallyvalidlanguagetag
  19. Optional<Unicode::LocaleID> is_structurally_valid_language_tag(StringView locale)
  20. {
  21. auto contains_duplicate_variant = [](auto& variants) {
  22. if (variants.is_empty())
  23. return false;
  24. quick_sort(variants);
  25. for (size_t i = 0; i < variants.size() - 1; ++i) {
  26. if (variants[i].equals_ignoring_case(variants[i + 1]))
  27. return true;
  28. }
  29. return false;
  30. };
  31. // IsStructurallyValidLanguageTag returns true if all of the following conditions hold, false otherwise:
  32. // locale can be generated from the EBNF grammar for unicode_locale_id in Unicode Technical Standard #35 LDML § 3.2 Unicode Locale Identifier;
  33. auto locale_id = Unicode::parse_unicode_locale_id(locale);
  34. if (!locale_id.has_value())
  35. return {};
  36. // locale does not use any of the backwards compatibility syntax described in Unicode Technical Standard #35 LDML § 3.3 BCP 47 Conformance;
  37. // https://unicode.org/reports/tr35/#BCP_47_Conformance
  38. if (locale.contains('_') || locale_id->language_id.is_root || !locale_id->language_id.language.has_value())
  39. return {};
  40. // the unicode_language_id within locale contains no duplicate unicode_variant_subtag subtags; and
  41. if (contains_duplicate_variant(locale_id->language_id.variants))
  42. return {};
  43. // if locale contains an extensions* component, that component
  44. Vector<char> unique_keys;
  45. for (auto& extension : locale_id->extensions) {
  46. // does not contain any other_extensions components with duplicate [alphanum-[tTuUxX]] subtags,
  47. // contains at most one unicode_locale_extensions component,
  48. // contains at most one transformed_extensions component, and
  49. char key = extension.visit(
  50. [](Unicode::LocaleExtension const&) { return 'u'; },
  51. [](Unicode::TransformedExtension const&) { return 't'; },
  52. [](Unicode::OtherExtension const& ext) { return static_cast<char>(to_ascii_lowercase(ext.key)); });
  53. if (unique_keys.contains_slow(key))
  54. return {};
  55. unique_keys.append(key);
  56. // if a transformed_extensions component that contains a tlang component is present, then
  57. // the tlang component contains no duplicate unicode_variant_subtag subtags.
  58. if (auto* transformed = extension.get_pointer<Unicode::TransformedExtension>()) {
  59. auto& language = transformed->language;
  60. if (language.has_value() && contains_duplicate_variant(language->variants))
  61. return {};
  62. }
  63. }
  64. return locale_id;
  65. }
  66. // 6.2.3 CanonicalizeUnicodeLocaleId ( locale ), https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
  67. String canonicalize_unicode_locale_id(Unicode::LocaleID& locale)
  68. {
  69. // Note: This implementation differs from the spec in how Step 3 is implemented. The spec assumes
  70. // the input to this method is a string, and is written such that operations are performed on parts
  71. // of that string. LibUnicode gives us the parsed locale in a structure, so we can mutate that
  72. // structure directly. From a footnote in the spec:
  73. //
  74. // The third step of this algorithm ensures that a Unicode locale extension sequence in the
  75. // returned language tag contains:
  76. // * only the first instance of any attribute duplicated in the input, and
  77. // * only the first keyword for a given key in the input.
  78. for (auto& extension : locale.extensions) {
  79. if (!extension.has<Unicode::LocaleExtension>())
  80. continue;
  81. auto& locale_extension = extension.get<Unicode::LocaleExtension>();
  82. auto attributes = move(locale_extension.attributes);
  83. for (auto& attribute : attributes) {
  84. if (!locale_extension.attributes.contains_slow(attribute))
  85. locale_extension.attributes.append(move(attribute));
  86. }
  87. auto keywords = move(locale_extension.keywords);
  88. for (auto& keyword : keywords) {
  89. if (!any_of(locale_extension.keywords, [&](auto const& k) { return k.key == keyword.key; }))
  90. locale_extension.keywords.append(move(keyword));
  91. }
  92. break;
  93. }
  94. // 1. Let localeId be the string locale after performing the algorithm to transform it to canonical syntax per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers.
  95. // 2. Let localeId be the string localeId after performing the algorithm to transform it to canonical form.
  96. auto locale_id = Unicode::canonicalize_unicode_locale_id(locale);
  97. VERIFY(locale_id.has_value());
  98. // 4. Return localeId.
  99. return locale_id.release_value();
  100. }
  101. // 6.3.1 IsWellFormedCurrencyCode ( currency ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
  102. static bool is_well_formed_currency_code(StringView currency)
  103. {
  104. // 1. Let normalized be the result of mapping currency to upper case as described in 6.1.
  105. // 2. If the number of elements in normalized is not 3, return false.
  106. if (currency.length() != 3)
  107. return false;
  108. // 3. If normalized contains any character that is not in the range "A" to "Z" (U+0041 to U+005A), return false.
  109. if (!all_of(currency, is_ascii_alpha))
  110. return false;
  111. // 4. Return true.
  112. return true;
  113. }
  114. // 9.2.1 CanonicalizeLocaleList ( locales ), https://tc39.es/ecma402/#sec-canonicalizelocalelist
  115. Vector<String> canonicalize_locale_list(GlobalObject& global_object, Value locales)
  116. {
  117. auto& vm = global_object.vm();
  118. // 1. If locales is undefined, then
  119. if (locales.is_undefined()) {
  120. // a. Return a new empty List.
  121. return {};
  122. }
  123. // 2. Let seen be a new empty List.
  124. Vector<String> seen;
  125. Object* object = nullptr;
  126. // 3. If Type(locales) is String or Type(locales) is Object and locales has an [[InitializedLocale]] internal slot, then
  127. if (locales.is_string() || (locales.is_object() && is<Locale>(locales.as_object()))) {
  128. // a. Let O be CreateArrayFromList(« locales »).
  129. object = Array::create_from(global_object, { locales });
  130. }
  131. // 4. Else,
  132. else {
  133. // a. Let O be ? ToObject(locales).
  134. object = locales.to_object(global_object);
  135. if (vm.exception())
  136. return {};
  137. }
  138. // 5. Let len be ? ToLength(? Get(O, "length")).
  139. auto length_value = object->get(vm.names.length);
  140. if (vm.exception())
  141. return {};
  142. auto length = length_value.to_length(global_object);
  143. if (vm.exception())
  144. return {};
  145. // 6. Let k be 0.
  146. // 7. Repeat, while k < len,
  147. for (size_t k = 0; k < length; ++k) {
  148. // a. Let Pk be ToString(k).
  149. auto property_key = PropertyName { k };
  150. // b. Let kPresent be ? HasProperty(O, Pk).
  151. auto key_present = object->has_property(property_key);
  152. if (vm.exception())
  153. return {};
  154. // c. If kPresent is true, then
  155. if (key_present) {
  156. // i. Let kValue be ? Get(O, Pk).
  157. auto key_value = object->get(property_key);
  158. if (vm.exception())
  159. return {};
  160. // ii. If Type(kValue) is not String or Object, throw a TypeError exception.
  161. if (!key_value.is_string() && !key_value.is_object()) {
  162. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObjectOrString, key_value.to_string_without_side_effects());
  163. return {};
  164. }
  165. String tag;
  166. // iii. If Type(kValue) is Object and kValue has an [[InitializedLocale]] internal slot, then
  167. if (key_value.is_object() && is<Locale>(key_value.as_object())) {
  168. // 1. Let tag be kValue.[[Locale]].
  169. tag = static_cast<Locale const&>(key_value.as_object()).locale();
  170. }
  171. // iv. Else,
  172. else {
  173. // 1. Let tag be ? ToString(kValue).
  174. tag = key_value.to_string(global_object);
  175. if (vm.exception())
  176. return {};
  177. }
  178. // v. If IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
  179. auto locale_id = is_structurally_valid_language_tag(tag);
  180. if (!locale_id.has_value()) {
  181. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, tag);
  182. return {};
  183. }
  184. // vi. Let canonicalizedTag be CanonicalizeUnicodeLocaleId(tag).
  185. auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  186. // vii. If canonicalizedTag is not an element of seen, append canonicalizedTag as the last element of seen.
  187. if (!seen.contains_slow(canonicalized_tag))
  188. seen.append(move(canonicalized_tag));
  189. }
  190. // d. Increase k by 1.
  191. }
  192. return seen;
  193. }
  194. // 9.2.2 BestAvailableLocale ( availableLocales, locale ), https://tc39.es/ecma402/#sec-bestavailablelocale
  195. Optional<String> best_available_locale(StringView const& locale)
  196. {
  197. // 1. Let candidate be locale.
  198. StringView candidate = locale;
  199. // 2. Repeat,
  200. while (true) {
  201. // a. If availableLocales contains an element equal to candidate, return candidate.
  202. if (Unicode::is_locale_available(candidate))
  203. return candidate;
  204. // b. Let pos be the character index of the last occurrence of "-" (U+002D) within candidate. If that character does not occur, return undefined.
  205. auto pos = candidate.find_last('-');
  206. if (!pos.has_value())
  207. return {};
  208. // c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate, decrease pos by 2.
  209. if ((*pos >= 2) && (candidate[*pos - 2] == '-'))
  210. pos = *pos - 2;
  211. // d. Let candidate be the substring of candidate from position 0, inclusive, to position pos, exclusive.
  212. candidate = candidate.substring_view(0, *pos);
  213. }
  214. }
  215. struct MatcherResult {
  216. String locale;
  217. Vector<Unicode::Extension> extensions {};
  218. };
  219. // 9.2.3 LookupMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupmatcher
  220. static MatcherResult lookup_matcher(Vector<String> const& requested_locales)
  221. {
  222. // 1. Let result be a new Record.
  223. MatcherResult result {};
  224. // 2. For each element locale of requestedLocales, do
  225. for (auto const& locale : requested_locales) {
  226. auto locale_id = Unicode::parse_unicode_locale_id(locale);
  227. VERIFY(locale_id.has_value());
  228. // a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
  229. auto extensions = locale_id->remove_extension_type<Unicode::LocaleExtension>();
  230. auto no_extensions_locale = locale_id->to_string();
  231. // b. Let availableLocale be BestAvailableLocale(availableLocales, noExtensionsLocale).
  232. auto available_locale = best_available_locale(no_extensions_locale);
  233. // c. If availableLocale is not undefined, then
  234. if (available_locale.has_value()) {
  235. // i. Set result.[[locale]] to availableLocale.
  236. result.locale = available_locale.release_value();
  237. // ii. If locale and noExtensionsLocale are not the same String value, then
  238. if (locale != no_extensions_locale) {
  239. // 1. Let extension be the String value consisting of the substring of the Unicode locale extension sequence within locale.
  240. // 2. Set result.[[extension]] to extension.
  241. result.extensions.extend(move(extensions));
  242. }
  243. // iii. Return result.
  244. return result;
  245. }
  246. }
  247. // 3. Let defLocale be DefaultLocale().
  248. // 4. Set result.[[locale]] to defLocale.
  249. result.locale = Unicode::default_locale();
  250. // 5. Return result.
  251. return result;
  252. }
  253. // 9.2.4 BestFitMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitmatcher
  254. static MatcherResult best_fit_matcher(Vector<String> const& requested_locales)
  255. {
  256. // The algorithm is implementation dependent, but should produce results that a typical user of the requested locales would
  257. // perceive as at least as good as those produced by the LookupMatcher abstract operation.
  258. return lookup_matcher(requested_locales);
  259. }
  260. // 9.2.6 InsertUnicodeExtensionAndCanonicalize ( locale, extension ), https://tc39.es/ecma402/#sec-insert-unicode-extension-and-canonicalize
  261. String insert_unicode_extension_and_canonicalize(Unicode::LocaleID locale, Unicode::LocaleExtension extension)
  262. {
  263. // Note: This implementation differs from the spec in how the extension is inserted. The spec assumes
  264. // the input to this method is a string, and is written such that operations are performed on parts
  265. // of that string. LibUnicode gives us the parsed locale in a structure, so we can mutate that
  266. // structure directly.
  267. locale.extensions.append(move(extension));
  268. return JS::Intl::canonicalize_unicode_locale_id(locale);
  269. }
  270. template<typename T>
  271. static auto& find_key_in_value(T& value, StringView key)
  272. {
  273. // If you hit this point, you must add any missing keys from [[RelevantExtensionKeys]] to LocaleOptions and LocaleResult.
  274. VERIFY_NOT_REACHED();
  275. }
  276. // 9.2.7 ResolveLocale ( availableLocales, requestedLocales, options, relevantExtensionKeys, localeData ), https://tc39.es/ecma402/#sec-resolvelocale
  277. LocaleResult resolve_locale(Vector<String> const& requested_locales, LocaleOptions const& options, Vector<StringView> const& relevant_extension_keys)
  278. {
  279. // 1. Let matcher be options.[[localeMatcher]].
  280. auto const& matcher = options.locale_matcher;
  281. MatcherResult matcher_result;
  282. // 2. If matcher is "lookup", then
  283. if (matcher.is_string() && (matcher.as_string().string() == "lookup"sv)) {
  284. // a. Let r be LookupMatcher(availableLocales, requestedLocales).
  285. matcher_result = lookup_matcher(requested_locales);
  286. }
  287. // 3. Else,
  288. else {
  289. // a. Let r be BestFitMatcher(availableLocales, requestedLocales).
  290. matcher_result = best_fit_matcher(requested_locales);
  291. }
  292. // 4. Let foundLocale be r.[[locale]].
  293. auto found_locale = move(matcher_result.locale);
  294. // 5. Let result be a new Record.
  295. LocaleResult result {};
  296. // 6. Set result.[[dataLocale]] to foundLocale.
  297. result.data_locale = found_locale;
  298. // 7. If r has an [[extension]] field, then
  299. Vector<Unicode::Keyword> keywords;
  300. for (auto& extension : matcher_result.extensions) {
  301. if (!extension.has<Unicode::LocaleExtension>())
  302. continue;
  303. // a. Let components be ! UnicodeExtensionComponents(r.[[extension]]).
  304. auto& components = extension.get<Unicode::LocaleExtension>();
  305. // b. Let keywords be components.[[Keywords]].
  306. keywords = move(components.keywords);
  307. break;
  308. }
  309. // 8. Let supportedExtension be "-u".
  310. Unicode::LocaleExtension supported_extension {};
  311. // 9. For each element key of relevantExtensionKeys, do
  312. for (auto const& key : relevant_extension_keys) {
  313. // a. Let foundLocaleData be localeData.[[<foundLocale>]].
  314. // b. Assert: Type(foundLocaleData) is Record.
  315. // c. Let keyLocaleData be foundLocaleData.[[<key>]].
  316. // d. Assert: Type(keyLocaleData) is List.
  317. auto key_locale_data = Unicode::get_locale_key_mapping(found_locale, key);
  318. // e. Let value be keyLocaleData[0].
  319. // f. Assert: Type(value) is either String or Null.
  320. Optional<String> value;
  321. if (!key_locale_data.is_empty())
  322. value = key_locale_data[0];
  323. // g. Let supportedExtensionAddition be "".
  324. Optional<Unicode::Keyword> supported_extension_addition {};
  325. // h. If r has an [[extension]] field, then
  326. for (auto& entry : keywords) {
  327. // i. If keywords contains an element whose [[Key]] is the same as key, then
  328. if (entry.key != key)
  329. continue;
  330. // 1. Let entry be the element of keywords whose [[Key]] is the same as key.
  331. // 2. Let requestedValue be entry.[[Value]].
  332. auto requested_value = entry.value;
  333. // 3. If requestedValue is not the empty String, then
  334. if (!requested_value.is_empty()) {
  335. // a. If keyLocaleData contains requestedValue, then
  336. if (key_locale_data.contains_slow(requested_value)) {
  337. // i. Let value be requestedValue.
  338. value = move(requested_value);
  339. // ii. Let supportedExtensionAddition be the string-concatenation of "-", key, "-", and value.
  340. supported_extension_addition = Unicode::Keyword { key, move(entry.value) };
  341. }
  342. }
  343. // 4. Else if keyLocaleData contains "true", then
  344. else if (key_locale_data.contains_slow("true"sv)) {
  345. // a. Let value be "true".
  346. value = "true"sv;
  347. // b. Let supportedExtensionAddition be the string-concatenation of "-" and key.
  348. supported_extension_addition = Unicode::Keyword { key, {} };
  349. }
  350. break;
  351. }
  352. // i. If options has a field [[<key>]], then
  353. // i. Let optionsValue be options.[[<key>]].
  354. // ii. Assert: Type(optionsValue) is either String, Undefined, or Null.
  355. auto options_value = find_key_in_value(options, key);
  356. // iii. If Type(optionsValue) is String, then
  357. if (options_value.has_value()) {
  358. // 1. Let optionsValue be the string optionsValue after performing the algorithm steps to transform Unicode extension values to canonical syntax per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers, treating key as ukey and optionsValue as uvalue productions.
  359. // 2. Let optionsValue be the string optionsValue after performing the algorithm steps to replace Unicode extension values with their canonical form per Unicode Technical Standard #35 LDML § 3.2.1 Canonical Unicode Locale Identifiers, treating key as ukey and optionsValue as uvalue productions.
  360. Unicode::canonicalize_unicode_extension_values(key, *options_value, true);
  361. // 3. If optionsValue is the empty String, then
  362. if (options_value->is_empty()) {
  363. // a. Let optionsValue be "true".
  364. options_value = "true"sv;
  365. }
  366. }
  367. // iv. If keyLocaleData contains optionsValue, then
  368. if (options_value.has_value() && key_locale_data.contains_slow(*options_value)) {
  369. // 1. If SameValue(optionsValue, value) is false, then
  370. if (options_value != value) {
  371. // a. Let value be optionsValue.
  372. value = move(options_value);
  373. // b. Let supportedExtensionAddition be "".
  374. supported_extension_addition.clear();
  375. }
  376. }
  377. // j. Set result.[[<key>]] to value.
  378. find_key_in_value(result, key) = move(value);
  379. // k. Append supportedExtensionAddition to supportedExtension.
  380. if (supported_extension_addition.has_value())
  381. supported_extension.keywords.append(supported_extension_addition.release_value());
  382. }
  383. // 10. If the number of elements in supportedExtension is greater than 2, then
  384. if (!supported_extension.keywords.is_empty()) {
  385. auto locale_id = Unicode::parse_unicode_locale_id(found_locale);
  386. VERIFY(locale_id.has_value());
  387. // a. Let foundLocale be InsertUnicodeExtensionAndCanonicalize(foundLocale, supportedExtension).
  388. found_locale = insert_unicode_extension_and_canonicalize(locale_id.release_value(), move(supported_extension));
  389. }
  390. // 11. Set result.[[locale]] to foundLocale.
  391. result.locale = move(found_locale);
  392. // 12. Return result.
  393. return result;
  394. }
  395. // 9.2.8 LookupSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupsupportedlocales
  396. Vector<String> lookup_supported_locales(Vector<String> const& requested_locales)
  397. {
  398. // 1. Let subset be a new empty List.
  399. Vector<String> subset;
  400. // 2. For each element locale of requestedLocales, do
  401. for (auto const& locale : requested_locales) {
  402. auto locale_id = Unicode::parse_unicode_locale_id(locale);
  403. VERIFY(locale_id.has_value());
  404. // a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
  405. locale_id->remove_extension_type<Unicode::LocaleExtension>();
  406. auto no_extensions_locale = locale_id->to_string();
  407. // b. Let availableLocale be BestAvailableLocale(availableLocales, noExtensionsLocale).
  408. auto available_locale = best_available_locale(no_extensions_locale);
  409. // c. If availableLocale is not undefined, append locale to the end of subset.
  410. if (available_locale.has_value())
  411. subset.append(locale);
  412. }
  413. // 3. Return subset.
  414. return subset;
  415. }
  416. // 9.2.9 BestFitSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitsupportedlocales
  417. Vector<String> best_fit_supported_locales(Vector<String> const& requested_locales)
  418. {
  419. // The BestFitSupportedLocales abstract operation returns the subset of the provided BCP 47
  420. // language priority list requestedLocales for which availableLocales has a matching locale
  421. // when using the Best Fit Matcher algorithm. Locales appear in the same order in the returned
  422. // list as in requestedLocales. The steps taken are implementation dependent.
  423. // :yakbrain:
  424. return lookup_supported_locales(requested_locales);
  425. }
  426. // 9.2.10 SupportedLocales ( availableLocales, requestedLocales, options ), https://tc39.es/ecma402/#sec-supportedlocales
  427. Array* supported_locales(GlobalObject& global_object, Vector<String> const& requested_locales, Value options)
  428. {
  429. auto& vm = global_object.vm();
  430. // 1. Set options to ? CoerceOptionsToObject(options).
  431. auto* options_object = coerce_options_to_object(global_object, options);
  432. if (vm.exception())
  433. return {};
  434. // 2. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  435. auto matcher = get_option(global_object, options_object, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv);
  436. if (vm.exception())
  437. return {};
  438. Vector<String> supported_locales;
  439. // 3. If matcher is "best fit", then
  440. if (matcher.as_string().string() == "best fit"sv) {
  441. // a. Let supportedLocales be BestFitSupportedLocales(availableLocales, requestedLocales).
  442. supported_locales = best_fit_supported_locales(requested_locales);
  443. }
  444. // 4. Else,
  445. else {
  446. // a. Let supportedLocales be LookupSupportedLocales(availableLocales, requestedLocales).
  447. supported_locales = lookup_supported_locales(requested_locales);
  448. }
  449. // 5. Return CreateArrayFromList(supportedLocales).
  450. return Array::create_from<String>(global_object, supported_locales, [&vm](auto& locale) { return js_string(vm, locale); });
  451. }
  452. // 9.2.12 CoerceOptionsToObject ( options ), https://tc39.es/ecma402/#sec-coerceoptionstoobject
  453. Object* coerce_options_to_object(GlobalObject& global_object, Value options)
  454. {
  455. // 1. If options is undefined, then
  456. if (options.is_undefined()) {
  457. // a. Return ! OrdinaryObjectCreate(null).
  458. return Object::create(global_object, nullptr);
  459. }
  460. // 2. Return ? ToObject(options).
  461. return options.to_object(global_object);
  462. }
  463. // 9.2.13 GetOption ( options, property, type, values, fallback ), https://tc39.es/ecma402/#sec-getoption
  464. Value get_option(GlobalObject& global_object, Value options, PropertyName const& property, Value::Type type, Vector<StringView> const& values, Fallback fallback)
  465. {
  466. auto& vm = global_object.vm();
  467. // 1. Assert: Type(options) is Object.
  468. VERIFY(options.is_object());
  469. // 2. Let value be ? Get(options, property).
  470. auto value = options.get(global_object, property);
  471. if (vm.exception())
  472. return {};
  473. // 3. If value is undefined, return fallback.
  474. if (value.is_undefined()) {
  475. return fallback.visit(
  476. [](Empty) { return js_undefined(); },
  477. [](bool f) { return Value(f); },
  478. [&vm](StringView f) { return Value(js_string(vm, f)); });
  479. }
  480. // 4. Assert: type is "boolean" or "string".
  481. VERIFY((type == Value::Type::Boolean) || (type == Value::Type::String));
  482. // 5. If type is "boolean", then
  483. if (type == Value::Type::Boolean) {
  484. // a. Let value be ! ToBoolean(value).
  485. value = Value(value.to_boolean());
  486. }
  487. // 6. If type is "string", then
  488. else {
  489. // a. Let value be ? ToString(value).
  490. value = value.to_primitive_string(global_object);
  491. if (vm.exception())
  492. return {};
  493. }
  494. // 7. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
  495. if (!values.is_empty()) {
  496. // Note: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  497. VERIFY(value.is_string());
  498. if (!values.contains_slow(value.as_string().string())) {
  499. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.to_string_without_side_effects(), property.as_string());
  500. return {};
  501. }
  502. }
  503. // 8. Return value.
  504. return value;
  505. }
  506. // 9.2.16 PartitionPattern ( pattern ), https://tc39.es/ecma402/#sec-partitionpattern
  507. Vector<PatternPartition> partition_pattern(StringView pattern)
  508. {
  509. // 1. Let result be a new empty List.
  510. Vector<PatternPartition> result;
  511. // 2. Let beginIndex be ! StringIndexOf(pattern, "{", 0).
  512. auto begin_index = pattern.find('{', 0);
  513. // 3. Let endIndex be 0.
  514. size_t end_index = 0;
  515. // 4. Let nextIndex be 0.
  516. size_t next_index = 0;
  517. // 5. Let length be the number of code units in pattern.
  518. // 6. Repeat, while beginIndex is an integer index into pattern,
  519. while (begin_index.has_value()) {
  520. // a. Set endIndex to ! StringIndexOf(pattern, "}", beginIndex).
  521. end_index = pattern.find('}', *begin_index).value();
  522. // b. Assert: endIndex is greater than beginIndex.
  523. VERIFY(end_index > *begin_index);
  524. // c. If beginIndex is greater than nextIndex, then
  525. if (*begin_index > next_index) {
  526. // i. Let literal be a substring of pattern from position nextIndex, inclusive, to position beginIndex, exclusive.
  527. auto literal = pattern.substring_view(next_index, *begin_index - next_index);
  528. // ii. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result.
  529. result.append({ "literal"sv, literal });
  530. }
  531. // d. Let p be the substring of pattern from position beginIndex, exclusive, to position endIndex, exclusive.
  532. auto partition = pattern.substring_view(*begin_index + 1, end_index - *begin_index - 1);
  533. // e. Append a new Record { [[Type]]: p, [[Value]]: undefined } as the last element of the list result.
  534. result.append({ partition, {} });
  535. // f. Set nextIndex to endIndex + 1.
  536. next_index = end_index + 1;
  537. // g. Set beginIndex to ! StringIndexOf(pattern, "{", nextIndex).
  538. begin_index = pattern.find('{', next_index);
  539. }
  540. // 7. If nextIndex is less than length, then
  541. if (next_index < pattern.length()) {
  542. // a. Let literal be the substring of pattern from position nextIndex, inclusive, to position length, exclusive.
  543. auto literal = pattern.substring_view(next_index);
  544. // b. Append a new Record { [[Type]]: "literal", [[Value]]: literal } as the last element of the list result.
  545. result.append({ "literal"sv, literal });
  546. }
  547. // 8. Return result.
  548. return result;
  549. }
  550. // 12.1.1 CanonicalCodeForDisplayNames ( type, code ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
  551. Value canonical_code_for_display_names(GlobalObject& global_object, DisplayNames::Type type, StringView code)
  552. {
  553. auto& vm = global_object.vm();
  554. // 1. If type is "language", then
  555. if (type == DisplayNames::Type::Language) {
  556. // a. If code does not match the unicode_language_id production, throw a RangeError exception.
  557. if (!Unicode::parse_unicode_language_id(code).has_value()) {
  558. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "language"sv);
  559. return {};
  560. }
  561. // b. If IsStructurallyValidLanguageTag(code) is false, throw a RangeError exception.
  562. auto locale_id = is_structurally_valid_language_tag(code);
  563. if (!locale_id.has_value()) {
  564. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, code);
  565. return {};
  566. }
  567. // c. Set code to CanonicalizeUnicodeLocaleId(code).
  568. // d. Return code.
  569. auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  570. return js_string(vm, move(canonicalized_tag));
  571. }
  572. // 2. If type is "region", then
  573. if (type == DisplayNames::Type::Region) {
  574. // a. If code does not match the unicode_region_subtag production, throw a RangeError exception.
  575. if (!Unicode::is_unicode_region_subtag(code)) {
  576. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "region"sv);
  577. return {};
  578. }
  579. // b. Let code be the result of mapping code to upper case as described in 6.1.
  580. // c. Return code.
  581. return js_string(vm, code.to_uppercase_string());
  582. }
  583. // 3. If type is "script", then
  584. if (type == DisplayNames::Type::Script) {
  585. // a. If code does not match the unicode_script_subtag production, throw a RangeError exception.
  586. if (!Unicode::is_unicode_script_subtag(code)) {
  587. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "script"sv);
  588. return {};
  589. }
  590. // b. Let code be the result of mapping the first character in code to upper case, and mapping the second, third, and fourth character in code to lower case, as described in 6.1.
  591. // c. Return code.
  592. return js_string(vm, code.to_titlecase_string());
  593. }
  594. // 4. Assert: type is "currency".
  595. VERIFY(type == DisplayNames::Type::Currency);
  596. // 5. If ! IsWellFormedCurrencyCode(code) is false, throw a RangeError exception.
  597. if (!is_well_formed_currency_code(code)) {
  598. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, code, "currency"sv);
  599. return {};
  600. }
  601. // 6. Let code be the result of mapping code to upper case as described in 6.1.
  602. // 7. Return code.
  603. return js_string(vm, code.to_uppercase_string());
  604. }
  605. }