AbstractOperations.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. /*
  2. * Copyright (c) 2021-2024, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AllOf.h>
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Find.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/TypeCasts.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  14. #include <LibJS/Runtime/Intl/Locale.h>
  15. #include <LibJS/Runtime/Intl/SingleUnitIdentifiers.h>
  16. #include <LibJS/Runtime/VM.h>
  17. #include <LibJS/Runtime/ValueInlines.h>
  18. #include <LibLocale/Locale.h>
  19. #include <LibLocale/UnicodeKeywords.h>
  20. namespace JS::Intl {
  21. Optional<LocaleKey> locale_key_from_value(Value value)
  22. {
  23. if (value.is_undefined())
  24. return OptionalNone {};
  25. if (value.is_null())
  26. return Empty {};
  27. if (value.is_string())
  28. return value.as_string().utf8_string();
  29. VERIFY_NOT_REACHED();
  30. }
  31. // 6.2.2 IsStructurallyValidLanguageTag ( locale ), https://tc39.es/ecma402/#sec-isstructurallyvalidlanguagetag
  32. bool is_structurally_valid_language_tag(StringView locale)
  33. {
  34. auto contains_duplicate_variant = [&](auto& variants) {
  35. if (variants.is_empty())
  36. return false;
  37. quick_sort(variants);
  38. for (size_t i = 0; i < variants.size() - 1; ++i) {
  39. if (variants[i].equals_ignoring_case(variants[i + 1]))
  40. return true;
  41. }
  42. return false;
  43. };
  44. // 1. Let lowerLocale be the ASCII-lowercase of locale.
  45. // NOTE: LibLocale's parsing is case-insensitive.
  46. // 2. If lowerLocale cannot be matched by the unicode_locale_id Unicode locale nonterminal, return false.
  47. auto locale_id = ::Locale::parse_unicode_locale_id(locale);
  48. if (!locale_id.has_value())
  49. return false;
  50. // 3. If lowerLocale uses any of the backwards compatibility syntax described in Unicode Technical Standard #35 Part 1 Core,
  51. // Section 3.3 BCP 47 Conformance, return false.
  52. // https://unicode.org/reports/tr35/#BCP_47_Conformance
  53. if (locale.contains('_') || locale_id->language_id.is_root || !locale_id->language_id.language.has_value())
  54. return false;
  55. // 4. Let languageId be the longest prefix of lowerLocale matched by the unicode_language_id Unicode locale nonterminal.
  56. auto& language_id = locale_id->language_id;
  57. // 5. Let variants be GetLocaleVariants(languageId).
  58. // 6. If variants is not undefined, then
  59. if (auto& variants = language_id.variants; !variants.is_empty()) {
  60. // a. If variants contains any duplicate subtags, return false.
  61. if (contains_duplicate_variant(variants))
  62. return false;
  63. }
  64. HashTable<char> unique_keys;
  65. // 7. Let allExtensions be the suffix of lowerLocale following languageId.
  66. // 8. If allExtensions contains a substring matched by the pu_extensions Unicode locale nonterminal, let extensions be
  67. // the prefix of allExtensions preceding the longest such substring. Otherwise, let extensions be allExtensions.
  68. // 9. If extensions is not the empty String, then
  69. for (auto& extension : locale_id->extensions) {
  70. char key = extension.visit(
  71. [](::Locale::LocaleExtension const&) { return 'u'; },
  72. [](::Locale::TransformedExtension const&) { return 't'; },
  73. [](::Locale::OtherExtension const& ext) { return static_cast<char>(to_ascii_lowercase(ext.key)); });
  74. // a. If extensions contains any duplicate singleton subtags, return false.
  75. if (unique_keys.set(key) != HashSetResult::InsertedNewEntry)
  76. return false;
  77. // b. Let transformExtension be the longest substring of extensions matched by the transformed_extensions Unicode
  78. // locale nonterminal. If there is no such substring, return true.
  79. if (auto* transformed = extension.get_pointer<::Locale::TransformedExtension>()) {
  80. // c. Assert: The substring of transformExtension from 0 to 3 is "-t-".
  81. // d. Let tPrefix be the substring of transformExtension from 3.
  82. // e. Let tlang be the longest prefix of tPrefix matched by the tlang Unicode locale nonterminal. If there is
  83. // no such prefix, return true.
  84. auto& transformed_language = transformed->language;
  85. if (!transformed_language.has_value())
  86. continue;
  87. // f. Let tlangRefinements be the longest suffix of tlang following a non-empty prefix matched by the
  88. // unicode_language_subtag Unicode locale nonterminal.
  89. auto& transformed_refinements = transformed_language->variants;
  90. // g. If tlangRefinements contains any duplicate substrings matched greedily by the unicode_variant_subtag
  91. // Unicode locale nonterminal, return false.
  92. if (contains_duplicate_variant(transformed_refinements))
  93. return false;
  94. }
  95. }
  96. // 10. Return true.
  97. return true;
  98. }
  99. // 6.2.3 CanonicalizeUnicodeLocaleId ( locale ), https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
  100. String canonicalize_unicode_locale_id(StringView locale)
  101. {
  102. return ::Locale::canonicalize_unicode_locale_id(locale);
  103. }
  104. // 6.3.1 IsWellFormedCurrencyCode ( currency ), https://tc39.es/ecma402/#sec-iswellformedcurrencycode
  105. bool is_well_formed_currency_code(StringView currency)
  106. {
  107. // 1. If the length of currency is not 3, return false.
  108. if (currency.length() != 3)
  109. return false;
  110. // 2. Let normalized be the ASCII-uppercase of currency.
  111. // 3. If normalized contains any code unit outside of 0x0041 through 0x005A (corresponding to Unicode characters LATIN CAPITAL LETTER A through LATIN CAPITAL LETTER Z), return false.
  112. if (!all_of(currency, is_ascii_alpha))
  113. return false;
  114. // 4. Return true.
  115. return true;
  116. }
  117. // 6.5.1 IsWellFormedUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-iswellformedunitidentifier
  118. bool is_well_formed_unit_identifier(StringView unit_identifier)
  119. {
  120. // 6.5.2 IsSanctionedSingleUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-issanctionedsingleunitidentifier
  121. constexpr auto is_sanctioned_single_unit_identifier = [](StringView unit_identifier) {
  122. // 1. If unitIdentifier is listed in Table 2 below, return true.
  123. // 2. Else, return false.
  124. static constexpr auto sanctioned_units = sanctioned_single_unit_identifiers();
  125. return find(sanctioned_units.begin(), sanctioned_units.end(), unit_identifier) != sanctioned_units.end();
  126. };
  127. // 1. If ! IsSanctionedSingleUnitIdentifier(unitIdentifier) is true, then
  128. if (is_sanctioned_single_unit_identifier(unit_identifier)) {
  129. // a. Return true.
  130. return true;
  131. }
  132. // 2. Let i be StringIndexOf(unitIdentifier, "-per-", 0).
  133. auto indices = unit_identifier.find_all("-per-"sv);
  134. // 3. If i is -1 or StringIndexOf(unitIdentifier, "-per-", i + 1) is not -1, then
  135. if (indices.size() != 1) {
  136. // a. Return false.
  137. return false;
  138. }
  139. // 4. Assert: The five-character substring "-per-" occurs exactly once in unitIdentifier, at index i.
  140. // NOTE: We skip this because the indices vector being of size 1 already verifies this invariant.
  141. // 5. Let numerator be the substring of unitIdentifier from 0 to i.
  142. auto numerator = unit_identifier.substring_view(0, indices[0]);
  143. // 6. Let denominator be the substring of unitIdentifier from i + 5.
  144. auto denominator = unit_identifier.substring_view(indices[0] + 5);
  145. // 7. If ! IsSanctionedSingleUnitIdentifier(numerator) and ! IsSanctionedSingleUnitIdentifier(denominator) are both true, then
  146. if (is_sanctioned_single_unit_identifier(numerator) && is_sanctioned_single_unit_identifier(denominator)) {
  147. // a. Return true.
  148. return true;
  149. }
  150. // 8. Return false.
  151. return false;
  152. }
  153. // 9.2.1 CanonicalizeLocaleList ( locales ), https://tc39.es/ecma402/#sec-canonicalizelocalelist
  154. ThrowCompletionOr<Vector<String>> canonicalize_locale_list(VM& vm, Value locales)
  155. {
  156. auto& realm = *vm.current_realm();
  157. // 1. If locales is undefined, then
  158. if (locales.is_undefined()) {
  159. // a. Return a new empty List.
  160. return Vector<String> {};
  161. }
  162. // 2. Let seen be a new empty List.
  163. Vector<String> seen;
  164. Object* object = nullptr;
  165. // 3. If Type(locales) is String or Type(locales) is Object and locales has an [[InitializedLocale]] internal slot, then
  166. if (locales.is_string() || (locales.is_object() && is<Locale>(locales.as_object()))) {
  167. // a. Let O be CreateArrayFromList(« locales »).
  168. object = Array::create_from(realm, { locales });
  169. }
  170. // 4. Else,
  171. else {
  172. // a. Let O be ? ToObject(locales).
  173. object = TRY(locales.to_object(vm));
  174. }
  175. // 5. Let len be ? ToLength(? Get(O, "length")).
  176. auto length_value = TRY(object->get(vm.names.length));
  177. auto length = TRY(length_value.to_length(vm));
  178. // 6. Let k be 0.
  179. // 7. Repeat, while k < len,
  180. for (size_t k = 0; k < length; ++k) {
  181. // a. Let Pk be ToString(k).
  182. auto property_key = PropertyKey { k };
  183. // b. Let kPresent be ? HasProperty(O, Pk).
  184. auto key_present = TRY(object->has_property(property_key));
  185. // c. If kPresent is true, then
  186. if (key_present) {
  187. // i. Let kValue be ? Get(O, Pk).
  188. auto key_value = TRY(object->get(property_key));
  189. // ii. If Type(kValue) is not String or Object, throw a TypeError exception.
  190. if (!key_value.is_string() && !key_value.is_object())
  191. return vm.throw_completion<TypeError>(ErrorType::NotAnObjectOrString, key_value);
  192. String tag;
  193. // iii. If Type(kValue) is Object and kValue has an [[InitializedLocale]] internal slot, then
  194. if (key_value.is_object() && is<Locale>(key_value.as_object())) {
  195. // 1. Let tag be kValue.[[Locale]].
  196. tag = static_cast<Locale const&>(key_value.as_object()).locale();
  197. }
  198. // iv. Else,
  199. else {
  200. // 1. Let tag be ? ToString(kValue).
  201. tag = TRY(key_value.to_string(vm));
  202. }
  203. // v. If ! IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
  204. if (!is_structurally_valid_language_tag(tag))
  205. return vm.throw_completion<RangeError>(ErrorType::IntlInvalidLanguageTag, tag);
  206. // vi. Let canonicalizedTag be ! CanonicalizeUnicodeLocaleId(tag).
  207. auto canonicalized_tag = canonicalize_unicode_locale_id(tag);
  208. // vii. If canonicalizedTag is not an element of seen, append canonicalizedTag as the last element of seen.
  209. if (!seen.contains_slow(canonicalized_tag))
  210. seen.append(move(canonicalized_tag));
  211. }
  212. // d. Increase k by 1.
  213. }
  214. return seen;
  215. }
  216. // 9.2.2 BestAvailableLocale ( availableLocales, locale ), https://tc39.es/ecma402/#sec-bestavailablelocale
  217. Optional<StringView> best_available_locale(StringView locale)
  218. {
  219. // 1. Let candidate be locale.
  220. StringView candidate = locale;
  221. // 2. Repeat,
  222. while (true) {
  223. // a. If availableLocales contains candidate, return candidate.
  224. if (::Locale::is_locale_available(candidate))
  225. return candidate;
  226. // b. Let pos be the character index of the last occurrence of "-" (U+002D) within candidate. If that character does not occur, return undefined.
  227. auto pos = candidate.find_last('-');
  228. if (!pos.has_value())
  229. return {};
  230. // c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate, decrease pos by 2.
  231. if ((*pos >= 2) && (candidate[*pos - 2] == '-'))
  232. pos = *pos - 2;
  233. // d. Let candidate be the substring of candidate from position 0, inclusive, to position pos, exclusive.
  234. candidate = candidate.substring_view(0, *pos);
  235. }
  236. }
  237. struct MatcherResult {
  238. String locale;
  239. Vector<::Locale::Extension> extensions {};
  240. };
  241. // 9.2.3 LookupMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupmatcher
  242. static MatcherResult lookup_matcher(Vector<String> const& requested_locales)
  243. {
  244. // 1. Let result be a new Record.
  245. MatcherResult result {};
  246. // 2. For each element locale of requestedLocales, do
  247. for (auto const& locale : requested_locales) {
  248. auto locale_id = ::Locale::parse_unicode_locale_id(locale);
  249. VERIFY(locale_id.has_value());
  250. // a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
  251. auto extensions = locale_id->remove_extension_type<::Locale::LocaleExtension>();
  252. auto no_extensions_locale = locale_id->to_string();
  253. // b. Let availableLocale be ! BestAvailableLocale(availableLocales, noExtensionsLocale).
  254. auto available_locale = best_available_locale(no_extensions_locale);
  255. // c. If availableLocale is not undefined, then
  256. if (available_locale.has_value()) {
  257. // i. Set result.[[locale]] to availableLocale.
  258. result.locale = MUST(String::from_utf8(*available_locale));
  259. // ii. If locale and noExtensionsLocale are not the same String value, then
  260. if (locale != no_extensions_locale) {
  261. // 1. Let extension be the String value consisting of the substring of the Unicode locale extension sequence within locale.
  262. // 2. Set result.[[extension]] to extension.
  263. result.extensions.extend(move(extensions));
  264. }
  265. // iii. Return result.
  266. return result;
  267. }
  268. }
  269. // 3. Let defLocale be ! DefaultLocale().
  270. // 4. Set result.[[locale]] to defLocale.
  271. result.locale = MUST(String::from_utf8(::Locale::default_locale()));
  272. // 5. Return result.
  273. return result;
  274. }
  275. // 9.2.4 BestFitMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitmatcher
  276. static MatcherResult best_fit_matcher(Vector<String> const& requested_locales)
  277. {
  278. // The algorithm is implementation dependent, but should produce results that a typical user of the requested locales would
  279. // perceive as at least as good as those produced by the LookupMatcher abstract operation.
  280. return lookup_matcher(requested_locales);
  281. }
  282. // 9.2.6 InsertUnicodeExtensionAndCanonicalize ( locale, extension ), https://tc39.es/ecma402/#sec-insert-unicode-extension-and-canonicalize
  283. String insert_unicode_extension_and_canonicalize(::Locale::LocaleID locale, ::Locale::LocaleExtension extension)
  284. {
  285. // Note: This implementation differs from the spec in how the extension is inserted. The spec assumes
  286. // the input to this method is a string, and is written such that operations are performed on parts
  287. // of that string. LibUnicode gives us the parsed locale in a structure, so we can mutate that
  288. // structure directly.
  289. locale.extensions.append(move(extension));
  290. return JS::Intl::canonicalize_unicode_locale_id(locale.to_string());
  291. }
  292. template<typename T>
  293. static auto& find_key_in_value(T& value, StringView key)
  294. {
  295. if (key == "ca"sv)
  296. return value.ca;
  297. if (key == "co"sv)
  298. return value.co;
  299. if (key == "hc"sv)
  300. return value.hc;
  301. if (key == "kf"sv)
  302. return value.kf;
  303. if (key == "kn"sv)
  304. return value.kn;
  305. if (key == "nu"sv)
  306. return value.nu;
  307. // If you hit this point, you must add any missing keys from [[RelevantExtensionKeys]] to LocaleOptions and LocaleResult.
  308. VERIFY_NOT_REACHED();
  309. }
  310. static Vector<LocaleKey> available_keyword_values(StringView locale, StringView key)
  311. {
  312. auto key_locale_data = ::Locale::available_keyword_values(locale, key);
  313. Vector<LocaleKey> result;
  314. result.ensure_capacity(key_locale_data.size());
  315. for (auto& keyword : key_locale_data)
  316. result.unchecked_append(move(keyword));
  317. if (key == "hc"sv) {
  318. // https://tc39.es/ecma402/#sec-intl.datetimeformat-internal-slots
  319. // [[LocaleData]].[[<locale>]].[[hc]] must be « null, "h11", "h12", "h23", "h24" ».
  320. result.prepend(Empty {});
  321. }
  322. return result;
  323. }
  324. // 9.2.7 ResolveLocale ( availableLocales, requestedLocales, options, relevantExtensionKeys, localeData ), https://tc39.es/ecma402/#sec-resolvelocale
  325. LocaleResult resolve_locale(Vector<String> const& requested_locales, LocaleOptions const& options, ReadonlySpan<StringView> relevant_extension_keys)
  326. {
  327. static auto true_string = "true"_string;
  328. // 1. Let matcher be options.[[localeMatcher]].
  329. auto const& matcher = options.locale_matcher;
  330. MatcherResult matcher_result;
  331. // 2. If matcher is "lookup", then
  332. if (matcher.is_string() && (matcher.as_string().utf8_string_view()) == "lookup"sv) {
  333. // a. Let r be ! LookupMatcher(availableLocales, requestedLocales).
  334. matcher_result = lookup_matcher(requested_locales);
  335. }
  336. // 3. Else,
  337. else {
  338. // a. Let r be ! BestFitMatcher(availableLocales, requestedLocales).
  339. matcher_result = best_fit_matcher(requested_locales);
  340. }
  341. // 4. Let foundLocale be r.[[locale]].
  342. auto found_locale = move(matcher_result.locale);
  343. // 5. Let result be a new Record.
  344. LocaleResult result {};
  345. // 6. Set result.[[dataLocale]] to foundLocale.
  346. result.data_locale = found_locale;
  347. // 7. If r has an [[extension]] field, then
  348. Vector<::Locale::Keyword> keywords;
  349. for (auto& extension : matcher_result.extensions) {
  350. if (!extension.has<::Locale::LocaleExtension>())
  351. continue;
  352. // a. Let components be ! UnicodeExtensionComponents(r.[[extension]]).
  353. auto& components = extension.get<::Locale::LocaleExtension>();
  354. // b. Let keywords be components.[[Keywords]].
  355. keywords = move(components.keywords);
  356. break;
  357. }
  358. // 8. Let supportedExtension be "-u".
  359. ::Locale::LocaleExtension supported_extension {};
  360. // 9. For each element key of relevantExtensionKeys, do
  361. for (auto const& key : relevant_extension_keys) {
  362. // a. Let foundLocaleData be localeData.[[<foundLocale>]].
  363. // b. Assert: Type(foundLocaleData) is Record.
  364. // c. Let keyLocaleData be foundLocaleData.[[<key>]].
  365. // d. Assert: Type(keyLocaleData) is List.
  366. auto key_locale_data = available_keyword_values(found_locale, key);
  367. // e. Let value be keyLocaleData[0].
  368. // f. Assert: Type(value) is either String or Null.
  369. auto value = key_locale_data[0];
  370. // g. Let supportedExtensionAddition be "".
  371. Optional<::Locale::Keyword> supported_extension_addition {};
  372. // h. If r has an [[extension]] field, then
  373. for (auto& entry : keywords) {
  374. // i. If keywords contains an element whose [[Key]] is the same as key, then
  375. if (entry.key != key)
  376. continue;
  377. // 1. Let entry be the element of keywords whose [[Key]] is the same as key.
  378. // 2. Let requestedValue be entry.[[Value]].
  379. auto requested_value = entry.value;
  380. // 3. If requestedValue is not the empty String, then
  381. if (!requested_value.is_empty()) {
  382. // a. If keyLocaleData contains requestedValue, then
  383. if (key_locale_data.contains_slow(requested_value)) {
  384. // i. Let value be requestedValue.
  385. value = move(requested_value);
  386. // ii. Let supportedExtensionAddition be the string-concatenation of "-", key, "-", and value.
  387. supported_extension_addition = ::Locale::Keyword { MUST(String::from_utf8(key)), move(entry.value) };
  388. }
  389. }
  390. // 4. Else if keyLocaleData contains "true", then
  391. else if (key_locale_data.contains_slow(true_string)) {
  392. // a. Let value be "true".
  393. value = true_string;
  394. // b. Let supportedExtensionAddition be the string-concatenation of "-" and key.
  395. supported_extension_addition = ::Locale::Keyword { MUST(String::from_utf8(key)), {} };
  396. }
  397. break;
  398. }
  399. // i. If options has a field [[<key>]], then
  400. // i. Let optionsValue be options.[[<key>]].
  401. // ii. Assert: Type(optionsValue) is either String, Undefined, or Null.
  402. auto options_value = find_key_in_value(options, key);
  403. // iii. If Type(optionsValue) is String, then
  404. if (auto* options_string = options_value.has_value() ? options_value->get_pointer<String>() : nullptr) {
  405. // 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.
  406. // 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.
  407. *options_string = ::Locale::canonicalize_unicode_extension_values(key, *options_string);
  408. // 3. If optionsValue is the empty String, then
  409. if (options_string->is_empty()) {
  410. // a. Let optionsValue be "true".
  411. *options_string = true_string;
  412. }
  413. }
  414. // iv. If SameValue(optionsValue, value) is false and keyLocaleData contains optionsValue, then
  415. if (options_value.has_value() && (options_value != value) && key_locale_data.contains_slow(*options_value)) {
  416. // 1. Let value be optionsValue.
  417. value = options_value.release_value();
  418. // 2. Let supportedExtensionAddition be "".
  419. supported_extension_addition.clear();
  420. }
  421. // j. Set result.[[<key>]] to value.
  422. find_key_in_value(result, key) = move(value);
  423. // k. Set supportedExtension to the string-concatenation of supportedExtension and supportedExtensionAddition.
  424. if (supported_extension_addition.has_value())
  425. supported_extension.keywords.append(supported_extension_addition.release_value());
  426. }
  427. // 10. If supportedExtension is not "-u", then
  428. if (!supported_extension.keywords.is_empty()) {
  429. auto locale_id = ::Locale::parse_unicode_locale_id(found_locale);
  430. VERIFY(locale_id.has_value());
  431. // a. Set foundLocale to InsertUnicodeExtensionAndCanonicalize(foundLocale, supportedExtension).
  432. found_locale = insert_unicode_extension_and_canonicalize(locale_id.release_value(), move(supported_extension));
  433. }
  434. // 11. Set result.[[locale]] to foundLocale.
  435. result.locale = move(found_locale);
  436. // 12. Return result.
  437. return result;
  438. }
  439. // 9.2.8 LookupSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupsupportedlocales
  440. static Vector<String> lookup_supported_locales(Vector<String> const& requested_locales)
  441. {
  442. // 1. Let subset be a new empty List.
  443. Vector<String> subset;
  444. // 2. For each element locale of requestedLocales, do
  445. for (auto const& locale : requested_locales) {
  446. auto locale_id = ::Locale::parse_unicode_locale_id(locale);
  447. VERIFY(locale_id.has_value());
  448. // a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
  449. locale_id->remove_extension_type<::Locale::LocaleExtension>();
  450. auto no_extensions_locale = locale_id->to_string();
  451. // b. Let availableLocale be ! BestAvailableLocale(availableLocales, noExtensionsLocale).
  452. auto available_locale = best_available_locale(no_extensions_locale);
  453. // c. If availableLocale is not undefined, append locale to the end of subset.
  454. if (available_locale.has_value())
  455. subset.append(locale);
  456. }
  457. // 3. Return subset.
  458. return subset;
  459. }
  460. // 9.2.9 BestFitSupportedLocales ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitsupportedlocales
  461. static Vector<String> best_fit_supported_locales(Vector<String> const& requested_locales)
  462. {
  463. // The BestFitSupportedLocales abstract operation returns the subset of the provided BCP 47
  464. // language priority list requestedLocales for which availableLocales has a matching locale
  465. // when using the Best Fit Matcher algorithm. Locales appear in the same order in the returned
  466. // list as in requestedLocales. The steps taken are implementation dependent.
  467. // :yakbrain:
  468. return lookup_supported_locales(requested_locales);
  469. }
  470. // 9.2.10 SupportedLocales ( availableLocales, requestedLocales, options ), https://tc39.es/ecma402/#sec-supportedlocales
  471. ThrowCompletionOr<Array*> supported_locales(VM& vm, Vector<String> const& requested_locales, Value options)
  472. {
  473. auto& realm = *vm.current_realm();
  474. // 1. Set options to ? CoerceOptionsToObject(options).
  475. auto* options_object = TRY(coerce_options_to_object(vm, options));
  476. // 2. Let matcher be ? GetOption(options, "localeMatcher", string, « "lookup", "best fit" », "best fit").
  477. auto matcher = TRY(get_option(vm, *options_object, vm.names.localeMatcher, OptionType::String, { "lookup"sv, "best fit"sv }, "best fit"sv));
  478. Vector<String> supported_locales;
  479. // 3. If matcher is "best fit", then
  480. if (matcher.as_string().utf8_string_view() == "best fit"sv) {
  481. // a. Let supportedLocales be BestFitSupportedLocales(availableLocales, requestedLocales).
  482. supported_locales = best_fit_supported_locales(requested_locales);
  483. }
  484. // 4. Else,
  485. else {
  486. // a. Let supportedLocales be LookupSupportedLocales(availableLocales, requestedLocales).
  487. supported_locales = lookup_supported_locales(requested_locales);
  488. }
  489. // 5. Return CreateArrayFromList(supportedLocales).
  490. return Array::create_from<String>(realm, supported_locales, [&vm](auto& locale) { return PrimitiveString::create(vm, move(locale)); }).ptr();
  491. }
  492. // 9.2.12 CoerceOptionsToObject ( options ), https://tc39.es/ecma402/#sec-coerceoptionstoobject
  493. ThrowCompletionOr<Object*> coerce_options_to_object(VM& vm, Value options)
  494. {
  495. auto& realm = *vm.current_realm();
  496. // 1. If options is undefined, then
  497. if (options.is_undefined()) {
  498. // a. Return OrdinaryObjectCreate(null).
  499. return Object::create(realm, nullptr).ptr();
  500. }
  501. // 2. Return ? ToObject(options).
  502. return TRY(options.to_object(vm)).ptr();
  503. }
  504. // NOTE: 9.2.13 GetOption has been removed and is being pulled in from ECMA-262 in the Temporal proposal.
  505. // 9.2.14 GetBooleanOrStringNumberFormatOption ( options, property, stringValues, fallback ), https://tc39.es/ecma402/#sec-getbooleanorstringnumberformatoption
  506. ThrowCompletionOr<StringOrBoolean> get_boolean_or_string_number_format_option(VM& vm, Object const& options, PropertyKey const& property, ReadonlySpan<StringView> string_values, StringOrBoolean fallback)
  507. {
  508. // 1. Let value be ? Get(options, property).
  509. auto value = TRY(options.get(property));
  510. // 2. If value is undefined, return fallback.
  511. if (value.is_undefined())
  512. return fallback;
  513. // 3. If value is true, return true.
  514. if (value.is_boolean() && value.as_bool())
  515. return StringOrBoolean { true };
  516. // 4. If ToBoolean(value) is false, return false.
  517. if (!value.to_boolean())
  518. return StringOrBoolean { false };
  519. // 5. Let value be ? ToString(value).
  520. auto value_string = TRY(value.to_string(vm));
  521. // 6. If stringValues does not contain value, throw a RangeError exception.
  522. auto it = find(string_values.begin(), string_values.end(), value_string.bytes_as_string_view());
  523. if (it == string_values.end())
  524. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, value_string, property.as_string());
  525. // 7. Return value.
  526. return StringOrBoolean { *it };
  527. }
  528. // 9.2.15 DefaultNumberOption ( value, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-defaultnumberoption
  529. ThrowCompletionOr<Optional<int>> default_number_option(VM& vm, Value value, int minimum, int maximum, Optional<int> fallback)
  530. {
  531. // 1. If value is undefined, return fallback.
  532. if (value.is_undefined())
  533. return fallback;
  534. // 2. Set value to ? ToNumber(value).
  535. value = TRY(value.to_number(vm));
  536. // 3. If value is NaN or less than minimum or greater than maximum, throw a RangeError exception.
  537. if (value.is_nan() || (value.as_double() < minimum) || (value.as_double() > maximum))
  538. return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaNOrOutOfRange, value, minimum, maximum);
  539. // 4. Return floor(value).
  540. return floor(value.as_double());
  541. }
  542. // 9.2.16 GetNumberOption ( options, property, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-getnumberoption
  543. ThrowCompletionOr<Optional<int>> get_number_option(VM& vm, Object const& options, PropertyKey const& property, int minimum, int maximum, Optional<int> fallback)
  544. {
  545. // 1. Assert: Type(options) is Object.
  546. // 2. Let value be ? Get(options, property).
  547. auto value = TRY(options.get(property));
  548. // 3. Return ? DefaultNumberOption(value, minimum, maximum, fallback).
  549. return default_number_option(vm, value, minimum, maximum, move(fallback));
  550. }
  551. }