LocaleConstructor.cpp 16 KB

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