LocaleConstructor.cpp 17 KB

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