LocaleConstructor.cpp 18 KB

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