LocaleConstructor.cpp 17 KB

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