LocaleConstructor.cpp 16 KB

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