AbstractOperations.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/CharacterTypes.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/TypeCasts.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  13. #include <LibUnicode/Locale.h>
  14. namespace JS::Intl {
  15. // 6.2.2 IsStructurallyValidLanguageTag ( locale ), https://tc39.es/ecma402/#sec-isstructurallyvalidlanguagetag
  16. static Optional<Unicode::LocaleID> is_structurally_valid_language_tag(StringView locale)
  17. {
  18. auto contains_duplicate_variant = [](Vector<StringView>& variants) {
  19. if (variants.is_empty())
  20. return false;
  21. quick_sort(variants);
  22. for (size_t i = 0; i < variants.size() - 1; ++i) {
  23. if (variants[i] == variants[i + 1])
  24. return true;
  25. }
  26. return false;
  27. };
  28. // IsStructurallyValidLanguageTag returns true if all of the following conditions hold, false otherwise:
  29. // locale can be generated from the EBNF grammar for unicode_locale_id in Unicode Technical Standard #35 LDML § 3.2 Unicode Locale Identifier;
  30. auto locale_id = Unicode::parse_unicode_locale_id(locale);
  31. if (!locale_id.has_value())
  32. return {};
  33. // locale does not use any of the backwards compatibility syntax described in Unicode Technical Standard #35 LDML § 3.3 BCP 47 Conformance;
  34. // https://unicode.org/reports/tr35/#BCP_47_Conformance
  35. if (locale.contains('_') || locale_id->language_id.is_root || !locale_id->language_id.language.has_value())
  36. return {};
  37. // the unicode_language_id within locale contains no duplicate unicode_variant_subtag subtags; and
  38. if (contains_duplicate_variant(locale_id->language_id.variants))
  39. return {};
  40. // if locale contains an extensions* component, that component
  41. Vector<char> unique_keys;
  42. for (auto& extension : locale_id->extensions) {
  43. // does not contain any other_extensions components with duplicate [alphanum-[tTuUxX]] subtags,
  44. // contains at most one unicode_locale_extensions component,
  45. // contains at most one transformed_extensions component, and
  46. char key = extension.visit(
  47. [](Unicode::LocaleExtension const&) { return 'u'; },
  48. [](Unicode::TransformedExtension const&) { return 't'; },
  49. [](Unicode::OtherExtension const& ext) { return static_cast<char>(to_ascii_lowercase(ext.key)); });
  50. if (unique_keys.contains_slow(key))
  51. return {};
  52. unique_keys.append(key);
  53. // if a transformed_extensions component that contains a tlang component is present, then
  54. // the tlang component contains no duplicate unicode_variant_subtag subtags.
  55. if (auto* transformed = extension.get_pointer<Unicode::TransformedExtension>()) {
  56. auto& language = transformed->language;
  57. if (language.has_value() && contains_duplicate_variant(language->variants))
  58. return {};
  59. }
  60. }
  61. return locale_id;
  62. }
  63. // 6.2.3 CanonicalizeUnicodeLocaleId ( locale ), https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
  64. static String canonicalize_unicode_locale_id(Unicode::LocaleID& locale)
  65. {
  66. // 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.
  67. // 2. Let localeId be the string localeId after performing the algorithm to transform it to canonical form.
  68. auto locale_id = Unicode::canonicalize_unicode_locale_id(locale);
  69. VERIFY(locale_id.has_value());
  70. // FIXME: Handle extensions.
  71. // 3. If localeId contains a substring extension that is a Unicode locale extension sequence, then
  72. // a. Let components be ! UnicodeExtensionComponents(extension).
  73. // b. Let attributes be components.[[Attributes]].
  74. // c. Let keywords be components.[[Keywords]].
  75. // d. Let newExtension be "u".
  76. // e. For each element attr of attributes, do
  77. // i. Append "-" to newExtension.
  78. // ii. Append attr to newExtension.
  79. // f. For each Record { [[Key]], [[Value]] } keyword in keywords, do
  80. // i. Append "-" to newExtension.
  81. // ii. Append keyword.[[Key]] to newExtension.
  82. // iii. If keyword.[[Value]] is not the empty String, then
  83. // 1. Append "-" to newExtension.
  84. // 2. Append keyword.[[Value]] to newExtension.
  85. // g. Assert: newExtension is not equal to "u".
  86. // h. Let localeId be localeId with the substring corresponding to extension replaced by the string newExtension.
  87. // 4. Return localeId.
  88. return locale_id.release_value();
  89. }
  90. // 6.3.1 IsWellFormedCurrencyCode ( currency ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
  91. static bool is_well_formed_currency_code(StringView currency)
  92. {
  93. // 1. Let normalized be the result of mapping currency to upper case as described in 6.1.
  94. // 2. If the number of elements in normalized is not 3, return false.
  95. if (currency.length() != 3)
  96. return false;
  97. // 3. If normalized contains any character that is not in the range "A" to "Z" (U+0041 to U+005A), return false.
  98. if (!all_of(currency, is_ascii_alpha))
  99. return false;
  100. // 4. Return true.
  101. return true;
  102. }
  103. // 9.2.1 CanonicalizeLocaleList ( locales ), https://tc39.es/ecma402/#sec-canonicalizelocalelist
  104. Vector<String> canonicalize_locale_list(GlobalObject& global_object, Value locales)
  105. {
  106. auto& vm = global_object.vm();
  107. // 1. If locales is undefined, then
  108. if (locales.is_undefined()) {
  109. // a. Return a new empty List.
  110. return {};
  111. }
  112. // 2. Let seen be a new empty List.
  113. Vector<String> seen;
  114. Object* object = nullptr;
  115. // 3. If Type(locales) is String or Type(locales) is Object and locales has an [[InitializedLocale]] internal slot, then
  116. // FIXME: When we have an Intl.Locale object, handle it it here.
  117. if (locales.is_string()) {
  118. // a. Let O be CreateArrayFromList(« locales »).
  119. object = Array::create_from(global_object, { locales });
  120. }
  121. // 4. Else,
  122. else {
  123. // a. Let O be ? ToObject(locales).
  124. object = locales.to_object(global_object);
  125. if (vm.exception())
  126. return {};
  127. }
  128. // 5. Let len be ? ToLength(? Get(O, "length")).
  129. auto length_value = object->get(vm.names.length);
  130. if (vm.exception())
  131. return {};
  132. auto length = length_value.to_length(global_object);
  133. if (vm.exception())
  134. return {};
  135. // 6. Let k be 0.
  136. // 7. Repeat, while k < len,
  137. for (size_t k = 0; k < length; ++k) {
  138. // a. Let Pk be ToString(k).
  139. auto property_key = PropertyName { k };
  140. // b. Let kPresent be ? HasProperty(O, Pk).
  141. auto key_present = object->has_property(property_key);
  142. if (vm.exception())
  143. return {};
  144. // c. If kPresent is true, then
  145. if (key_present) {
  146. // i. Let kValue be ? Get(O, Pk).
  147. auto key_value = object->get(property_key);
  148. if (vm.exception())
  149. return {};
  150. // ii. If Type(kValue) is not String or Object, throw a TypeError exception.
  151. if (!key_value.is_string() && !key_value.is_object()) {
  152. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObjectOrString, key_value.to_string_without_side_effects());
  153. return {};
  154. }
  155. // iii. If Type(kValue) is Object and kValue has an [[InitializedLocale]] internal slot, then
  156. // 1. Let tag be kValue.[[Locale]].
  157. // iv. Else,
  158. // 1. Let tag be ? ToString(kValue).
  159. // FIXME: When we have an Intl.Locale object, handle it it here.
  160. auto tag = key_value.to_string(global_object);
  161. if (vm.exception())
  162. return {};
  163. // v. If IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
  164. auto locale_id = is_structurally_valid_language_tag(tag);
  165. if (!locale_id.has_value()) {
  166. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, tag);
  167. return {};
  168. }
  169. // vi. Let canonicalizedTag be CanonicalizeUnicodeLocaleId(tag).
  170. auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  171. // vii. If canonicalizedTag is not an element of seen, append canonicalizedTag as the last element of seen.
  172. if (!seen.contains_slow(canonicalized_tag))
  173. seen.append(move(canonicalized_tag));
  174. }
  175. // d. Increase k by 1.
  176. }
  177. return seen;
  178. }
  179. // 9.2.2 BestAvailableLocale ( availableLocales, locale ), https://tc39.es/ecma402/#sec-bestavailablelocale
  180. static Optional<String> best_available_locale(StringView const& locale)
  181. {
  182. // 1. Let candidate be locale.
  183. StringView candidate = locale;
  184. // 2. Repeat,
  185. while (true) {
  186. // a. If availableLocales contains an element equal to candidate, return candidate.
  187. if (Unicode::is_locale_available(candidate))
  188. return candidate;
  189. // b. Let pos be the character index of the last occurrence of "-" (U+002D) within candidate. If that character does not occur, return undefined.
  190. auto pos = candidate.find_last('-');
  191. if (!pos.has_value())
  192. return {};
  193. // c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate, decrease pos by 2.
  194. if ((*pos >= 2) && (candidate[*pos - 2] == '-'))
  195. pos = *pos - 2;
  196. // d. Let candidate be the substring of candidate from position 0, inclusive, to position pos, exclusive.
  197. candidate = candidate.substring_view(0, *pos);
  198. }
  199. }
  200. // 9.2.3 LookupMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-lookupmatcher
  201. static LocaleResult lookup_matcher(Vector<String> const& requested_locales)
  202. {
  203. // 1. Let result be a new Record.
  204. LocaleResult result {};
  205. // 2. For each element locale of requestedLocales, do
  206. for (auto const& locale : requested_locales) {
  207. // a. Let noExtensionsLocale be the String value that is locale with any Unicode locale extension sequences removed.
  208. auto const& no_extensions_locale = locale; // FIXME: Handle extensions.
  209. // b. Let availableLocale be BestAvailableLocale(availableLocales, noExtensionsLocale).
  210. auto available_locale = best_available_locale(no_extensions_locale);
  211. // c. If availableLocale is not undefined, then
  212. if (available_locale.has_value()) {
  213. // i. Set result.[[locale]] to availableLocale.
  214. result.locale = available_locale.release_value();
  215. // FIXME: Handle extensions.
  216. // ii. If locale and noExtensionsLocale are not the same String value, then
  217. // 1. Let extension be the String value consisting of the substring of the Unicode locale extension sequence within locale.
  218. // 2. Set result.[[extension]] to extension.
  219. // iii. Return result.
  220. return result;
  221. }
  222. }
  223. // 3. Let defLocale be DefaultLocale().
  224. // 4. Set result.[[locale]] to defLocale.
  225. result.locale = Unicode::default_locale();
  226. // 5. Return result.
  227. return result;
  228. }
  229. // 9.2.4 BestFitMatcher ( availableLocales, requestedLocales ), https://tc39.es/ecma402/#sec-bestfitmatcher
  230. static LocaleResult best_fit_matcher(Vector<String> const& requested_locales)
  231. {
  232. // The algorithm is implementation dependent, but should produce results that a typical user of the requested locales would
  233. // perceive as at least as good as those produced by the LookupMatcher abstract operation.
  234. return lookup_matcher(requested_locales);
  235. }
  236. // 9.2.7 ResolveLocale ( availableLocales, requestedLocales, options, relevantExtensionKeys, localeData ), https://tc39.es/ecma402/#sec-resolvelocale
  237. LocaleResult resolve_locale(Vector<String> const& requested_locales, LocaleOptions const& options, [[maybe_unused]] Vector<StringView> relevant_extension_keys)
  238. {
  239. // 1. Let matcher be options.[[localeMatcher]].
  240. auto const& matcher = options.locale_matcher;
  241. LocaleResult result;
  242. // 2. If matcher is "lookup", then
  243. if (matcher.is_string() && (matcher.as_string().string() == "lookup"sv)) {
  244. // a. Let r be LookupMatcher(availableLocales, requestedLocales).
  245. result = lookup_matcher(requested_locales);
  246. }
  247. // 3. Else,
  248. else {
  249. // a. Let r be BestFitMatcher(availableLocales, requestedLocales).
  250. result = best_fit_matcher(requested_locales);
  251. }
  252. // 4. Let foundLocale be r.[[locale]].
  253. // 5. Let result be a new Record.
  254. // 6. Set result.[[dataLocale]] to foundLocale.
  255. // FIXME: Handle extensions.
  256. // 7. If r has an [[extension]] field, then
  257. // a. Let components be ! UnicodeExtensionComponents(r.[[extension]]).
  258. // b. Let keywords be components.[[Keywords]].
  259. // 8. Let supportedExtension be "-u".
  260. // 9. For each element key of relevantExtensionKeys, do
  261. // a. Let foundLocaleData be localeData.[[<foundLocale>]].
  262. // b. Assert: Type(foundLocaleData) is Record.
  263. // c. Let keyLocaleData be foundLocaleData.[[<key>]].
  264. // d. Assert: Type(keyLocaleData) is List.
  265. // e. Let value be keyLocaleData[0].
  266. // f. Assert: Type(value) is either String or Null.
  267. // g. Let supportedExtensionAddition be "".
  268. // h. If r has an [[extension]] field, then
  269. // i. If keywords contains an element whose [[Key]] is the same as key, then
  270. // 1. Let entry be the element of keywords whose [[Key]] is the same as key.
  271. // 2. Let requestedValue be entry.[[Value]].
  272. // 3. If requestedValue is not the empty String, then
  273. // a. If keyLocaleData contains requestedValue, then
  274. // i. Let value be requestedValue.
  275. // ii. Let supportedExtensionAddition be the string-concatenation of "-", key, "-", and value.
  276. // 4. Else if keyLocaleData contains "true", then
  277. // a. Let value be "true".
  278. // b. Let supportedExtensionAddition be the string-concatenation of "-" and key.
  279. // i. If options has a field [[<key>]], then
  280. // i. Let optionsValue be options.[[<key>]].
  281. // ii. Assert: Type(optionsValue) is either String, Undefined, or Null.
  282. // iii. If Type(optionsValue) is String, then
  283. // 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.
  284. // 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.
  285. // 3. If optionsValue is the empty String, then
  286. // a. Let optionsValue be "true".
  287. // iv. If keyLocaleData contains optionsValue, then
  288. // 1. If SameValue(optionsValue, value) is false, then
  289. // a. Let value be optionsValue.
  290. // b. Let supportedExtensionAddition be "".
  291. // j. Set result.[[<key>]] to value.
  292. // k. Append supportedExtensionAddition to supportedExtension.
  293. // 10. If the number of elements in supportedExtension is greater than 2, then
  294. // a. Let foundLocale be InsertUnicodeExtensionAndCanonicalize(foundLocale, supportedExtension).
  295. // 11. Set result.[[locale]] to foundLocale.
  296. // 12. Return result.
  297. return result;
  298. }
  299. // 9.2.13 GetOption ( options, property, type, values, fallback ), https://tc39.es/ecma402/#sec-getoption
  300. Value get_option(GlobalObject& global_object, Value options, PropertyName const& property, Value::Type type, Vector<StringView> const& values, Fallback fallback)
  301. {
  302. auto& vm = global_object.vm();
  303. // 1. Assert: Type(options) is Object.
  304. VERIFY(options.is_object());
  305. // 2. Let value be ? Get(options, property).
  306. auto value = options.get(global_object, property);
  307. if (vm.exception())
  308. return {};
  309. // 3. If value is undefined, return fallback.
  310. if (value.is_undefined()) {
  311. return fallback.visit(
  312. [](Empty) { return js_undefined(); },
  313. [](bool f) { return Value(f); },
  314. [&vm](StringView f) { return Value(js_string(vm, f)); });
  315. }
  316. // 4. Assert: type is "boolean" or "string".
  317. VERIFY((type == Value::Type::Boolean) || (type == Value::Type::String));
  318. // 5. If type is "boolean", then
  319. if (type == Value::Type::Boolean) {
  320. // a. Let value be ! ToBoolean(value).
  321. value = Value(value.to_boolean());
  322. }
  323. // 6. If type is "string", then
  324. else {
  325. // a. Let value be ? ToString(value).
  326. value = value.to_primitive_string(global_object);
  327. if (vm.exception())
  328. return {};
  329. }
  330. // 7. If values is not undefined and values does not contain an element equal to value, throw a RangeError exception.
  331. if (!values.is_empty()) {
  332. // Note: Every location in the spec that invokes GetOption with type=boolean also has values=undefined.
  333. VERIFY(value.is_string());
  334. if (!values.contains_slow(value.as_string().string())) {
  335. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, value.to_string_without_side_effects(), property.as_string());
  336. return {};
  337. }
  338. }
  339. // 8. Return value.
  340. return value;
  341. }
  342. // 12.1.1 CanonicalCodeForDisplayNames ( type, code ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
  343. Value canonical_code_for_display_names(GlobalObject& global_object, DisplayNames::Type type, StringView code)
  344. {
  345. auto& vm = global_object.vm();
  346. // 1. If type is "language", then
  347. if (type == DisplayNames::Type::Language) {
  348. // a. If code does not match the unicode_language_id production, throw a RangeError exception.
  349. if (!Unicode::parse_unicode_language_id(code).has_value()) {
  350. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidCode, code, "language"sv);
  351. return {};
  352. }
  353. // b. If IsStructurallyValidLanguageTag(code) is false, throw a RangeError exception.
  354. auto locale_id = is_structurally_valid_language_tag(code);
  355. if (!locale_id.has_value()) {
  356. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, code);
  357. return {};
  358. }
  359. // c. Set code to CanonicalizeUnicodeLocaleId(code).
  360. // d. Return code.
  361. auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  362. return js_string(vm, move(canonicalized_tag));
  363. }
  364. // 2. If type is "region", then
  365. if (type == DisplayNames::Type::Region) {
  366. // a. If code does not match the unicode_region_subtag production, throw a RangeError exception.
  367. if (!Unicode::is_unicode_region_subtag(code)) {
  368. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidCode, code, "region"sv);
  369. return {};
  370. }
  371. // b. Let code be the result of mapping code to upper case as described in 6.1.
  372. // c. Return code.
  373. return js_string(vm, code.to_uppercase_string());
  374. }
  375. // 3. If type is "script", then
  376. if (type == DisplayNames::Type::Script) {
  377. // a. If code does not match the unicode_script_subtag production, throw a RangeError exception.
  378. if (!Unicode::is_unicode_script_subtag(code)) {
  379. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidCode, code, "script"sv);
  380. return {};
  381. }
  382. // 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.
  383. // c. Return code.
  384. return js_string(vm, code.to_titlecase_string());
  385. }
  386. // 4. Assert: type is "currency".
  387. VERIFY(type == DisplayNames::Type::Currency);
  388. // 5. If ! IsWellFormedCurrencyCode(code) is false, throw a RangeError exception.
  389. if (!is_well_formed_currency_code(code)) {
  390. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidCode, code, "currency"sv);
  391. return {};
  392. }
  393. // 6. Let code be the result of mapping code to upper case as described in 6.1.
  394. // 7. Return code.
  395. return js_string(vm, code.to_uppercase_string());
  396. }
  397. }