LocaleConstructor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Optional.h>
  7. #include <AK/String.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  12. #include <LibJS/Runtime/Intl/Locale.h>
  13. #include <LibJS/Runtime/Intl/LocaleConstructor.h>
  14. #include <LibUnicode/Locale.h>
  15. namespace JS::Intl {
  16. struct LocaleAndKeys {
  17. String locale;
  18. Optional<String> ca;
  19. Optional<String> co;
  20. Optional<String> hc;
  21. Optional<String> kf;
  22. Optional<String> kn;
  23. Optional<String> nu;
  24. };
  25. static Vector<StringView> const& locale_relevant_extension_keys()
  26. {
  27. // 14.2.2 Internal slots, https://tc39.es/ecma402/#sec-intl.locale-internal-slots
  28. // The value of the [[RelevantExtensionKeys]] internal slot is « "ca", "co", "hc", "kf", "kn", "nu" ».
  29. // If %Collator%.[[RelevantExtensionKeys]] does not contain "kf", then remove "kf" from %Locale%.[[RelevantExtensionKeys]].
  30. // If %Collator%.[[RelevantExtensionKeys]] does not contain "kn", then remove "kn" from %Locale%.[[RelevantExtensionKeys]].
  31. // FIXME: We do not yet have an Intl.Collator object. For now, we behave as if "kf" and "kn" exist, as test262 depends on it.
  32. static Vector<StringView> relevant_extension_keys { "ca"sv, "co"sv, "hc"sv, "kf"sv, "kn"sv, "nu"sv };
  33. return relevant_extension_keys;
  34. }
  35. // Note: This is not an AO in the spec. This just serves to abstract very similar steps in ApplyOptionsToTag and the Intl.Locale constructor.
  36. static Optional<String> get_string_option(GlobalObject& global_object, Object const& options, PropertyName const& property, Function<bool(StringView)> validator, Vector<StringView> const& values = {})
  37. {
  38. auto& vm = global_object.vm();
  39. auto option = get_option(global_object, &options, property, Value::Type::String, values, Empty {});
  40. if (vm.exception())
  41. return {};
  42. if (option.is_undefined())
  43. return {};
  44. if (validator && !validator(option.as_string().string())) {
  45. vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, option, property);
  46. return {};
  47. }
  48. return option.as_string().string();
  49. }
  50. // 14.1.1 ApplyOptionsToTag ( tag, options ), https://tc39.es/ecma402/#sec-apply-options-to-tag
  51. static Optional<String> apply_options_to_tag(GlobalObject& global_object, StringView tag, Object const& options)
  52. {
  53. auto& vm = global_object.vm();
  54. // 1. Assert: Type(tag) is String.
  55. // 2. Assert: Type(options) is Object.
  56. // 3. If IsStructurallyValidLanguageTag(tag) is false, throw a RangeError exception.
  57. auto locale_id = is_structurally_valid_language_tag(tag);
  58. if (!locale_id.has_value()) {
  59. vm.throw_exception<RangeError>(global_object, ErrorType::IntlInvalidLanguageTag, tag);
  60. return {};
  61. }
  62. // 4. Let language be ? GetOption(options, "language", "string", undefined, undefined).
  63. // 5. If language is not undefined, then
  64. // a. If language does not match the unicode_language_subtag production, throw a RangeError exception.
  65. auto language = get_string_option(global_object, options, vm.names.language, Unicode::is_unicode_language_subtag);
  66. if (vm.exception())
  67. return {};
  68. // 6. Let script be ? GetOption(options, "script", "string", undefined, undefined).
  69. // 7. If script is not undefined, then
  70. // a. If script does not match the unicode_script_subtag production, throw a RangeError exception.
  71. auto script = get_string_option(global_object, options, vm.names.script, Unicode::is_unicode_script_subtag);
  72. if (vm.exception())
  73. return {};
  74. // 8. Let region be ? GetOption(options, "region", "string", undefined, undefined).
  75. // 9. If region is not undefined, then
  76. // a. If region does not match the unicode_region_subtag production, throw a RangeError exception.
  77. auto region = get_string_option(global_object, options, vm.names.region, Unicode::is_unicode_region_subtag);
  78. if (vm.exception())
  79. return {};
  80. // 10. Set tag to CanonicalizeUnicodeLocaleId(tag).
  81. auto canonicalized_tag = JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  82. // 11. Assert: tag matches the unicode_locale_id production.
  83. locale_id = Unicode::parse_unicode_locale_id(canonicalized_tag);
  84. VERIFY(locale_id.has_value());
  85. // 12. Let languageId be the substring of tag corresponding to the unicode_language_id production.
  86. auto& language_id = locale_id->language_id;
  87. // 13. If language is not undefined, then
  88. if (language.has_value()) {
  89. // a. Set languageId to languageId with the substring corresponding to the unicode_language_subtag production replaced by the string language.
  90. language_id.language = language.release_value();
  91. }
  92. // 14. If script is not undefined, then
  93. if (script.has_value()) {
  94. // a. If languageId does not contain a unicode_script_subtag production, then
  95. // i. Set languageId to the string-concatenation of the unicode_language_subtag production of languageId, "-", script, and the rest of languageId.
  96. // b. Else,
  97. // i. Set languageId to languageId with the substring corresponding to the unicode_script_subtag production replaced by the string script.
  98. language_id.script = script.release_value();
  99. }
  100. // 15. If region is not undefined, then
  101. if (region.has_value()) {
  102. // a. If languageId does not contain a unicode_region_subtag production, then
  103. // i. Set languageId to the string-concatenation of the unicode_language_subtag production of languageId, the substring corresponding to "-"` and the `unicode_script_subtag` production if present, `"-", region, and the rest of languageId.
  104. // b. Else,
  105. // i. Set languageId to languageId with the substring corresponding to the unicode_region_subtag production replaced by the string region.
  106. language_id.region = region.release_value();
  107. }
  108. // 16. Set tag to tag with the substring corresponding to the unicode_language_id production replaced by the string languageId.
  109. // 17. Return CanonicalizeUnicodeLocaleId(tag).
  110. return JS::Intl::canonicalize_unicode_locale_id(*locale_id);
  111. }
  112. // 14.1.2 ApplyUnicodeExtensionToTag ( tag, options, relevantExtensionKeys ), https://tc39.es/ecma402/#sec-apply-unicode-extension-to-tag
  113. static LocaleAndKeys apply_unicode_extension_to_tag(StringView tag, LocaleAndKeys options, Vector<StringView> const& relevant_extension_keys)
  114. {
  115. // 1. Assert: Type(tag) is String.
  116. // 2. Assert: tag matches the unicode_locale_id production.
  117. auto locale_id = Unicode::parse_unicode_locale_id(tag);
  118. VERIFY(locale_id.has_value());
  119. Vector<String> attributes;
  120. Vector<Unicode::Keyword> keywords;
  121. // 3. If tag contains a substring that is a Unicode locale extension sequence, then
  122. for (auto& extension : locale_id->extensions) {
  123. if (!extension.has<Unicode::LocaleExtension>())
  124. continue;
  125. // a. Let extension be the String value consisting of the substring of the Unicode locale extension sequence within tag.
  126. // b. Let components be ! UnicodeExtensionComponents(extension).
  127. auto& components = extension.get<Unicode::LocaleExtension>();
  128. // c. Let attributes be components.[[Attributes]].
  129. attributes = move(components.attributes);
  130. // d. Let keywords be components.[[Keywords]].
  131. keywords = move(components.keywords);
  132. break;
  133. }
  134. // 4. Else,
  135. // a. Let attributes be a new empty List.
  136. // b. Let keywords be a new empty List.
  137. auto field_from_key = [](LocaleAndKeys& value, StringView key) -> Optional<String>& {
  138. if (key == "ca"sv)
  139. return value.ca;
  140. if (key == "co"sv)
  141. return value.co;
  142. if (key == "hc"sv)
  143. return value.hc;
  144. if (key == "kf"sv)
  145. return value.kf;
  146. if (key == "kn"sv)
  147. return value.kn;
  148. if (key == "nu"sv)
  149. return value.nu;
  150. VERIFY_NOT_REACHED();
  151. };
  152. // 5. Let result be a new Record.
  153. LocaleAndKeys result {};
  154. // 6. For each element key of relevantExtensionKeys, do
  155. for (auto const& key : relevant_extension_keys) {
  156. // a. Let value be undefined.
  157. Optional<String> value {};
  158. Unicode::Keyword* entry = nullptr;
  159. // b. If keywords contains an element whose [[Key]] is the same as key, then
  160. if (auto it = keywords.find_if([&](auto const& k) { return key == k.key; }); it != keywords.end()) {
  161. // i. Let entry be the element of keywords whose [[Key]] is the same as key.
  162. entry = &(*it);
  163. // ii. Let value be entry.[[Value]].
  164. StringBuilder builder;
  165. builder.join('-', entry->types);
  166. value = builder.build();
  167. }
  168. // c. Else,
  169. // i. Let entry be empty.
  170. // d. Assert: options has a field [[<key>]].
  171. // e. Let optionsValue be options.[[<key>]].
  172. auto options_value = field_from_key(options, key);
  173. // f. If optionsValue is not undefined, then
  174. if (options_value.has_value()) {
  175. // i. Assert: Type(optionsValue) is String.
  176. // ii. Let value be optionsValue.
  177. value = options_value.release_value();
  178. // iii. If entry is not empty, then
  179. if (entry != nullptr) {
  180. // 1. Set entry.[[Value]] to value.
  181. entry->types = value->split('-');
  182. }
  183. // iv. Else,
  184. else {
  185. // 1. Append the Record { [[Key]]: key, [[Value]]: value } to keywords.
  186. keywords.append({ key, value->split('-') });
  187. }
  188. }
  189. // g. Set result.[[<key>]] to value.
  190. field_from_key(result, key) = move(value);
  191. }
  192. // 7. Let locale be the String value that is tag with any Unicode locale extension sequences removed.
  193. locale_id->remove_extension_type<Unicode::LocaleExtension>();
  194. auto locale = locale_id->to_string();
  195. // 8. Let newExtension be a Unicode BCP 47 U Extension based on attributes and keywords.
  196. Unicode::LocaleExtension new_extension { move(attributes), move(keywords) };
  197. // 9. If newExtension is not the empty String, then
  198. if (!new_extension.attributes.is_empty() || !new_extension.keywords.is_empty()) {
  199. // a. Let locale be ! InsertUnicodeExtensionAndCanonicalize(locale, newExtension).
  200. locale = insert_unicode_extension_and_canonicalize(locale_id.release_value(), move(new_extension));
  201. }
  202. // 10. Set result.[[locale]] to locale.
  203. result.locale = move(locale);
  204. // 11. Return result.
  205. return result;
  206. }
  207. // 14.1 The Intl.Locale Constructor, https://tc39.es/ecma402/#sec-intl-locale-constructor
  208. LocaleConstructor::LocaleConstructor(GlobalObject& global_object)
  209. : NativeFunction(vm().names.Locale.as_string(), *global_object.function_prototype())
  210. {
  211. }
  212. void LocaleConstructor::initialize(GlobalObject& global_object)
  213. {
  214. NativeFunction::initialize(global_object);
  215. auto& vm = this->vm();
  216. // 14.2.1 Intl.Locale.prototype, https://tc39.es/ecma402/#sec-Intl.Locale.prototype
  217. define_direct_property(vm.names.prototype, global_object.intl_locale_prototype(), 0);
  218. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  219. }
  220. // 14.1.3 Intl.Locale ( tag [ , options ] ), https://tc39.es/ecma402/#sec-Intl.Locale
  221. Value LocaleConstructor::call()
  222. {
  223. // 1. If NewTarget is undefined, throw a TypeError exception.
  224. vm().throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, "Intl.Locale");
  225. return {};
  226. }
  227. // 14.1.3 Intl.Locale ( tag [ , options ] ), https://tc39.es/ecma402/#sec-Intl.Locale
  228. Value LocaleConstructor::construct(FunctionObject& new_target)
  229. {
  230. auto& vm = this->vm();
  231. auto& global_object = this->global_object();
  232. auto tag = vm.argument(0);
  233. auto options = vm.argument(1);
  234. // 2. Let relevantExtensionKeys be %Locale%.[[RelevantExtensionKeys]].
  235. auto const& relevant_extension_keys = locale_relevant_extension_keys();
  236. // 3. Let internalSlotsList be « [[InitializedLocale]], [[Locale]], [[Calendar]], [[Collation]], [[HourCycle]], [[NumberingSystem]] ».
  237. // 4. If relevantExtensionKeys contains "kf", then
  238. // a. Append [[CaseFirst]] as the last element of internalSlotsList.
  239. // 5. If relevantExtensionKeys contains "kn", then
  240. // a. Append [[Numeric]] as the last element of internalSlotsList.
  241. // 6. Let locale be ? OrdinaryCreateFromConstructor(NewTarget, "%Locale.prototype%", internalSlotsList).
  242. auto* locale = ordinary_create_from_constructor<Locale>(global_object, new_target, &GlobalObject::intl_locale_prototype);
  243. if (vm.exception())
  244. return {};
  245. // 7. If Type(tag) is not String or Object, throw a TypeError exception.
  246. if (!tag.is_string() && !tag.is_object()) {
  247. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObjectOrString, "tag"sv);
  248. return {};
  249. }
  250. // 8. If Type(tag) is Object and tag has an [[InitializedLocale]] internal slot, then
  251. if (tag.is_object() && is<Locale>(tag.as_object())) {
  252. // a. Let tag be tag.[[Locale]].
  253. auto const& tag_object = static_cast<Locale const&>(tag.as_object());
  254. tag = js_string(vm, tag_object.locale());
  255. }
  256. // 9. Else,
  257. else {
  258. // a. Let tag be ? ToString(tag).
  259. tag = tag.to_primitive_string(global_object);
  260. if (vm.exception())
  261. return {};
  262. }
  263. // 10. Set options to ? CoerceOptionsToObject(options).
  264. options = coerce_options_to_object(global_object, options);
  265. if (vm.exception())
  266. return {};
  267. // 11. Set tag to ? ApplyOptionsToTag(tag, options).
  268. auto canonicalized_tag = apply_options_to_tag(global_object, tag.as_string().string(), options.as_object());
  269. if (vm.exception())
  270. return {};
  271. // 12. Let opt be a new Record.
  272. LocaleAndKeys opt {};
  273. // 13. Let calendar be ? GetOption(options, "calendar", "string", undefined, undefined).
  274. // 14. If calendar is not undefined, then
  275. // a. If calendar does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  276. // 15. Set opt.[[ca]] to calendar.
  277. opt.ca = get_string_option(global_object, options.as_object(), vm.names.calendar, Unicode::is_type_identifier);
  278. if (vm.exception())
  279. return {};
  280. // 16. Let collation be ? GetOption(options, "collation", "string", undefined, undefined).
  281. // 17. If collation is not undefined, then
  282. // a. If collation does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  283. // 18. Set opt.[[co]] to collation.
  284. opt.co = get_string_option(global_object, options.as_object(), vm.names.collation, Unicode::is_type_identifier);
  285. if (vm.exception())
  286. return {};
  287. // 19. Let hc be ? GetOption(options, "hourCycle", "string", « "h11", "h12", "h23", "h24" », undefined).
  288. // 20. Set opt.[[hc]] to hc.
  289. opt.hc = get_string_option(global_object, options.as_object(), vm.names.hourCycle, nullptr, { "h11"sv, "h12"sv, "h23"sv, "h24"sv });
  290. if (vm.exception())
  291. return {};
  292. // 21. Let kf be ? GetOption(options, "caseFirst", "string", « "upper", "lower", "false" », undefined).
  293. // 22. Set opt.[[kf]] to kf.
  294. opt.kf = get_string_option(global_object, options.as_object(), vm.names.caseFirst, nullptr, { "upper"sv, "lower"sv, "false"sv });
  295. if (vm.exception())
  296. return {};
  297. // 23. Let kn be ? GetOption(options, "numeric", "boolean", undefined, undefined).
  298. auto kn = get_option(global_object, options, vm.names.numeric, Value::Type::Boolean, {}, Empty {});
  299. if (vm.exception())
  300. return {};
  301. // 24. If kn is not undefined, set kn to ! ToString(kn).
  302. // 25. Set opt.[[kn]] to kn.
  303. if (!kn.is_undefined())
  304. opt.kn = kn.to_string(global_object);
  305. // 26. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  306. // 27. If numberingSystem is not undefined, then
  307. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  308. // 28. Set opt.[[nu]] to numberingSystem.
  309. opt.nu = get_string_option(global_object, options.as_object(), vm.names.numberingSystem, Unicode::is_type_identifier);
  310. if (vm.exception())
  311. return {};
  312. // 29. Let r be ! ApplyUnicodeExtensionToTag(tag, opt, relevantExtensionKeys).
  313. auto result = apply_unicode_extension_to_tag(*canonicalized_tag, move(opt), relevant_extension_keys);
  314. // 30. Set locale.[[Locale]] to r.[[locale]].
  315. locale->set_locale(move(result.locale));
  316. // 31. Set locale.[[Calendar]] to r.[[ca]].
  317. if (result.ca.has_value())
  318. locale->set_calendar(result.ca.release_value());
  319. // 32. Set locale.[[Collation]] to r.[[co]].
  320. if (result.co.has_value())
  321. locale->set_collation(result.co.release_value());
  322. // 33. Set locale.[[HourCycle]] to r.[[hc]].
  323. if (result.hc.has_value())
  324. locale->set_hour_cycle(result.hc.release_value());
  325. // 34. If relevantExtensionKeys contains "kf", then
  326. if (relevant_extension_keys.contains_slow("kf"sv)) {
  327. // a. Set locale.[[CaseFirst]] to r.[[kf]].
  328. if (result.kf.has_value())
  329. locale->set_case_first(result.kf.release_value());
  330. }
  331. // 35. If relevantExtensionKeys contains "kn", then
  332. if (relevant_extension_keys.contains_slow("kn"sv)) {
  333. // a. If ! SameValue(r.[[kn]], "true") is true or r.[[kn]] is the empty String, then
  334. if (result.kn.has_value() && (same_value(js_string(vm, *result.kn), js_string(vm, "true")) || result.kn->is_empty())) {
  335. // i. Set locale.[[Numeric]] to true.
  336. locale->set_numeric(true);
  337. }
  338. // b. Else,
  339. else {
  340. // i. Set locale.[[Numeric]] to false.
  341. locale->set_numeric(false);
  342. }
  343. }
  344. // 36. Set locale.[[NumberingSystem]] to r.[[nu]].
  345. if (result.nu.has_value())
  346. locale->set_numbering_system(result.nu.release_value());
  347. // 37. Return locale.
  348. return locale;
  349. }
  350. }