Debian Codegraph @

js/src/builtin/intl/Locale.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* Intl.Locale implementation. */
8
9 #include "builtin/intl/Locale.h"
10
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/Assertions.h"
13 #include "mozilla/intl/Locale.h"
14 #include "mozilla/Maybe.h"
15 #include "mozilla/Span.h"
16 #include "mozilla/TextUtils.h"
17
18 #include <algorithm>
19 #include <string>
20 #include <string.h>
21 #include <utility>
22
23 #include "builtin/Boolean.h"
24 #include "builtin/intl/CommonFunctions.h"
25 #include "builtin/intl/FormatBuffer.h"
26 #include "builtin/intl/LanguageTag.h"
27 #include "builtin/intl/StringAsciiChars.h"
28 #include "builtin/String.h"
29 #include "js/Conversions.h"
30 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
31 #include "js/Printer.h"
32 #include "js/TypeDecls.h"
33 #include "js/Wrapper.h"
34 #include "vm/Compartment.h"
35 #include "vm/GlobalObject.h"
36 #include "vm/JSContext.h"
37 #include "vm/PlainObject.h" // js::PlainObject
38 #include "vm/StringType.h"
39
40 #include "vm/JSObject-inl.h"
41 #include "vm/NativeObject-inl.h"
42
43 using namespace js;
44 using namespace mozilla::intl::LanguageTagLimits;
45
46 const JSClass LocaleObject::class_ = {
47 "Intl.Locale",
48 JSCLASS_HAS_RESERVED_SLOTS(LocaleObject::SLOT_COUNT) |
49 JSCLASS_HAS_CACHED_PROTO(JSProto_Locale),
50 JS_NULL_CLASS_OPS,
51 &LocaleObject::classSpec_,
52 };
53
54 const JSClass& LocaleObject::protoClass_ = PlainObject::class_;
55
56 static inline bool IsLocale(HandleValue v) {
57 return v.isObject() && v.toObject().is<LocaleObject>();
58 }
59
60 // Return the length of the base-name subtags.
61 static size_t BaseNameLength(const mozilla::intl::Locale& tag) {
62 size_t baseNameLength = tag.Language().Length();
63 if (tag.Script().Present()) {
64 baseNameLength += 1 + tag.Script().Length();
65 }
66 if (tag.Region().Present()) {
67 baseNameLength += 1 + tag.Region().Length();
68 }
69 for (const auto& variant : tag.Variants()) {
70 baseNameLength += 1 + variant.size();
71 }
72 return baseNameLength;
73 }
74
75 struct IndexAndLength {
76 size_t index;
77 size_t length;
78
79 IndexAndLength(size_t index, size_t length) : index(index), length(length) {};
80
81 template <typename T>
82 mozilla::Span<const T> spanOf(const T* ptr) const {
83 return {ptr + index, length};
84 }
85 };
86
87 // Compute the Unicode extension's index and length in the extension subtag.
88 static mozilla::Maybe<IndexAndLength> UnicodeExtensionPosition(
89 const mozilla::intl::Locale& tag) {
90 size_t index = 0;
91 for (const auto& extension : tag.Extensions()) {
92 MOZ_ASSERT(!mozilla::IsAsciiUppercaseAlpha(extension[0]),
93 "extensions are case normalized to lowercase");
94
95 size_t extensionLength = extension.size();
96 if (extension[0] == 'u') {
97 return mozilla::Some(IndexAndLength{index, extensionLength});
98 }
99
100 // Add +1 to skip over the preceding separator.
101 index += 1 + extensionLength;
102 }
103 return mozilla::Nothing();
104 }
105
106 static LocaleObject* CreateLocaleObject(JSContext* cx, HandleObject prototype,
107 const mozilla::intl::Locale& tag) {
108 intl::FormatBuffer<char, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
109 if (auto result = tag.ToString(buffer); result.isErr()) {
110 intl::ReportInternalError(cx, result.unwrapErr());
111 return nullptr;
112 }
113
114 RootedString tagStr(cx, buffer.toAsciiString(cx));
115 if (!tagStr) {
116 return nullptr;
117 }
118
119 size_t baseNameLength = BaseNameLength(tag);
120
121 RootedString baseName(cx, NewDependentString(cx, tagStr, 0, baseNameLength));
122 if (!baseName) {
123 return nullptr;
124 }
125
126 RootedValue unicodeExtension(cx, UndefinedValue());
127 if (auto result = UnicodeExtensionPosition(tag)) {
128 JSString* str = NewDependentString(
129 cx, tagStr, baseNameLength + 1 + result->index, result->length);
130 if (!str) {
131 return nullptr;
132 }
133
134 unicodeExtension.setString(str);
135 }
136
137 auto* locale = NewObjectWithClassProto<LocaleObject>(cx, prototype);
138 if (!locale) {
139 return nullptr;
140 }
141
142 locale->setFixedSlot(LocaleObject::LANGUAGE_TAG_SLOT, StringValue(tagStr));
143 locale->setFixedSlot(LocaleObject::BASENAME_SLOT, StringValue(baseName));
144 locale->setFixedSlot(LocaleObject::UNICODE_EXTENSION_SLOT, unicodeExtension);
145
146 return locale;
147 }
148
149 static inline bool IsValidUnicodeExtensionValue(JSContext* cx,
150 const JSLinearString* linear,
151 bool* isValid) {
152 if (linear->length() == 0) {
153 *isValid = false;
154 return true;
155 }
156
157 if (!StringIsAscii(linear)) {
158 *isValid = false;
159 return true;
160 }
161
162 intl::StringAsciiChars chars(linear);
163 if (!chars.init(cx)) {
164 return false;
165 }
166
167 *isValid =
168 mozilla::intl::LocaleParser::CanParseUnicodeExtensionType(chars).isOk();
169 return true;
170 }
171
172 /**
173 * Iterate through (sep keyword) in a valid Unicode extension.
174 *
175 * The Unicode extension value is not required to be in canonical case.
176 */
177 template <typename CharT>
178 class SepKeywordIterator {
179 const CharT* iter_;
180 const CharT* const end_;
181
182 public:
183 SepKeywordIterator(const CharT* unicodeExtensionBegin,
184 const CharT* unicodeExtensionEnd)
185 : iter_(unicodeExtensionBegin), end_(unicodeExtensionEnd) {}
186
187 /**
188 * Return (sep keyword) in the Unicode locale extension from begin to end.
189 * The first call after all (sep keyword) are consumed returns |nullptr|; no
190 * further calls are allowed.
191 */
192 const CharT* next() {
193 MOZ_ASSERT(iter_ != nullptr,
194 "can't call next() once it's returned nullptr");
195
196 constexpr size_t SepKeyLength = 1 + UnicodeKeyLength; // "-co"/"-nu"/etc.
197
198 MOZ_ASSERT(iter_ + SepKeyLength <= end_,
199 "overall Unicode locale extension or non-leading subtags must "
200 "be at least key-sized");
201
202 MOZ_ASSERT(((iter_[0] == 'u' || iter_[0] == 'U') && iter_[1] == '-') ||
203 iter_[0] == '-');
204
205 while (true) {
206 // Skip past '-' so |std::char_traits::find| makes progress. Skipping
207 // 'u' is harmless -- skip or not, |find| returns the first '-'.
208 iter_++;
209
210 // Find the next separator.
211 iter_ = std::char_traits<CharT>::find(
212 iter_, mozilla::PointerRangeSize(iter_, end_), CharT('-'));
213 if (!iter_) {
214 return nullptr;
215 }
216
217 MOZ_ASSERT(iter_ + SepKeyLength <= end_,
218 "non-leading subtags in a Unicode locale extension are all "
219 "at least as long as a key");
220
221 if (iter_ + SepKeyLength == end_ || // key is terminal subtag
222 iter_[SepKeyLength] == '-') { // key is followed by more subtags
223 break;
224 }
225 }
226
227 MOZ_ASSERT(iter_[0] == '-');
228 MOZ_ASSERT(mozilla::IsAsciiAlphanumeric(iter_[1]));
229 MOZ_ASSERT(mozilla::IsAsciiAlpha(iter_[2]));
230 MOZ_ASSERT_IF(iter_ + SepKeyLength < end_, iter_[SepKeyLength] == '-');
231 return iter_;
232 }
233 };
234
235 /**
236 * 9.2.10 GetOption ( options, property, type, values, fallback )
237 *
238 * If the requested property is present and not-undefined, set the result string
239 * to |ToString(value)|. Otherwise set the result string to nullptr.
240 */
241 static bool GetStringOption(JSContext* cx, HandleObject options,
242 Handle<PropertyName*> name,
243 MutableHandle<JSLinearString*> string) {
244 // Step 1.
245 RootedValue option(cx);
246 if (!GetProperty(cx, options, options, name, &option)) {
247 return false;
248 }
249
250 // Step 2.
251 JSLinearString* linear = nullptr;
252 if (!option.isUndefined()) {
253 // Steps 2.a-b, 2.d (not applicable).
254
255 // Steps 2.c, 2.e.
256 JSString* str = ToString(cx, option);
257 if (!str) {
258 return false;
259 }
260 linear = str->ensureLinear(cx);
261 if (!linear) {
262 return false;
263 }
264 }
265
266 // Step 3.
267 string.set(linear);
268 return true;
269 }
270
271 /**
272 * 9.2.10 GetOption ( options, property, type, values, fallback )
273 *
274 * If the requested property is present and not-undefined, set the result string
275 * to |ToString(ToBoolean(value))|. Otherwise set the result string to nullptr.
276 */
277 static bool GetBooleanOption(JSContext* cx, HandleObject options,
278 Handle<PropertyName*> name,
279 MutableHandle<JSLinearString*> string) {
280 // Step 1.
281 RootedValue option(cx);
282 if (!GetProperty(cx, options, options, name, &option)) {
283 return false;
284 }
285
286 // Step 2.
287 JSLinearString* linear = nullptr;
288 if (!option.isUndefined()) {
289 // Steps 2.a, 2.c-d (not applicable).
290
291 // Steps 2.c, 2.e.
292 linear = BooleanToString(cx, ToBoolean(option));
293 }
294
295 // Step 3.
296 string.set(linear);
297 return true;
298 }
299
300 /**
301 * ApplyOptionsToTag ( tag, options )
302 */
303 static bool ApplyOptionsToTag(JSContext* cx, mozilla::intl::Locale& tag,
304 HandleObject options) {
305 // Steps 1-2 (Already performed in caller).
306
307 Rooted<JSLinearString*> option(cx);
308
309 // Step 3.
310 if (!GetStringOption(cx, options, cx->names().language, &option)) {
311 return false;
312 }
313
314 // Step 4.
315 mozilla::intl::LanguageSubtag language;
316 if (option && !intl::ParseStandaloneLanguageTag(option, language)) {
317 if (UniqueChars str = QuoteString(cx, option, '"')) {
318 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
319 JSMSG_INVALID_OPTION_VALUE, "language",
320 str.get());
321 }
322 return false;
323 }
324
325 // Step 5.
326 if (!GetStringOption(cx, options, cx->names().script, &option)) {
327 return false;
328 }
329
330 // Step 6.
331 mozilla::intl::ScriptSubtag script;
332 if (option && !intl::ParseStandaloneScriptTag(option, script)) {
333 if (UniqueChars str = QuoteString(cx, option, '"')) {
334 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
335 JSMSG_INVALID_OPTION_VALUE, "script",
336 str.get());
337 }
338 return false;
339 }
340
341 // Step 7.
342 if (!GetStringOption(cx, options, cx->names().region, &option)) {
343 return false;
344 }
345
346 // Step 8.
347 mozilla::intl::RegionSubtag region;
348 if (option && !intl::ParseStandaloneRegionTag(option, region)) {
349 if (UniqueChars str = QuoteString(cx, option, '"')) {
350 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
351 JSMSG_INVALID_OPTION_VALUE, "region",
352 str.get());
353 }
354 return false;
355 }
356
357 // Step 9 (Already performed in caller).
358
359 // Skip steps 10-13 when no subtags were modified.
360 if (language.Present() || script.Present() || region.Present()) {
361 // Step 10.
362 if (language.Present()) {
363 tag.SetLanguage(language);
364 }
365
366 // Step 11.
367 if (script.Present()) {
368 tag.SetScript(script);
369 }
370
371 // Step 12.
372 if (region.Present()) {
373 tag.SetRegion(region);
374 }
375
376 // Step 13.
377 // Optimized to only canonicalize the base-name subtags. All other
378 // canonicalization steps will happen later.
379 auto result = tag.CanonicalizeBaseName();
380 if (result.isErr()) {
381 if (result.unwrapErr() ==
382 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant) {
383 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
384 JSMSG_DUPLICATE_VARIANT_SUBTAG);
385 } else {
386 intl::ReportInternalError(cx);
387 }
388 return false;
389 }
390 }
391
392 return true;
393 }
394
395 /**
396 * ApplyUnicodeExtensionToTag( tag, options, relevantExtensionKeys )
397 */
398 bool js::intl::ApplyUnicodeExtensionToTag(
399 JSContext* cx, mozilla::intl::Locale& tag,
400 JS::HandleVector<intl::UnicodeExtensionKeyword> keywords) {
401 // If no Unicode extensions were present in the options object, we can skip
402 // everything below and directly return.
403 if (keywords.length() == 0) {
404 return true;
405 }
406
407 Vector<char, 32> newExtension(cx);
408 if (!newExtension.append('u')) {
409 return false;
410 }
411
412 // Check if there's an existing Unicode extension subtag.
413
414 const char* unicodeExtensionEnd = nullptr;
415 const char* unicodeExtensionKeywords = nullptr;
416 if (auto unicodeExtension = tag.GetUnicodeExtension()) {
417 const char* unicodeExtensionBegin = unicodeExtension->data();
418 unicodeExtensionEnd = unicodeExtensionBegin + unicodeExtension->size();
419
420 SepKeywordIterator<char> iter(unicodeExtensionBegin, unicodeExtensionEnd);
421
422 // Find the start of the first keyword.
423 unicodeExtensionKeywords = iter.next();
424
425 // Copy any attributes present before the first keyword.
426 const char* attributesEnd = unicodeExtensionKeywords
427 ? unicodeExtensionKeywords
428 : unicodeExtensionEnd;
429 if (!newExtension.append(unicodeExtensionBegin + 1, attributesEnd)) {
430 return false;
431 }
432 }
433
434 // Append the new keywords before any existing keywords. That way any previous
435 // keyword with the same key is detected as a duplicate when canonicalizing
436 // the Unicode extension subtag and gets discarded.
437
438 for (const auto& keyword : keywords) {
439 UnicodeExtensionKeyword::UnicodeKeySpan key = keyword.key();
440 if (!newExtension.append('-')) {
441 return false;
442 }
443 if (!newExtension.append(key.data(), key.size())) {
444 return false;
445 }
446 if (!newExtension.append('-')) {
447 return false;
448 }
449
450 JS::AutoCheckCannotGC nogc;
451 JSLinearString* type = keyword.type();
452 if (type->hasLatin1Chars()) {
453 if (!newExtension.append(type->latin1Chars(nogc), type->length())) {
454 return false;
455 }
456 } else {
457 if (!newExtension.append(type->twoByteChars(nogc), type->length())) {
458 return false;
459 }
460 }
461 }
462
463 // Append the remaining keywords from the previous Unicode extension subtag.
464 if (unicodeExtensionKeywords) {
465 if (!newExtension.append(unicodeExtensionKeywords, unicodeExtensionEnd)) {
466 return false;
467 }
468 }
469
470 if (auto res = tag.SetUnicodeExtension(newExtension); res.isErr()) {
471 intl::ReportInternalError(cx, res.unwrapErr());
472 return false;
473 }
474
475 return true;
476 }
477
478 static JS::Result<JSString*> LanguageTagFromMaybeWrappedLocale(JSContext* cx,
479 JSObject* obj) {
480 if (obj->is<LocaleObject>()) {
481 return obj->as<LocaleObject>().languageTag();
482 }
483
484 JSObject* unwrapped = CheckedUnwrapStatic(obj);
485 if (!unwrapped) {
486 ReportAccessDenied(cx);
487 return cx->alreadyReportedError();
488 }
489
490 if (!unwrapped->is<LocaleObject>()) {
491 return nullptr;
492 }
493
494 RootedString tagStr(cx, unwrapped->as<LocaleObject>().languageTag());
495 if (!cx->compartment()->wrap(cx, &tagStr)) {
496 return cx->alreadyReportedError();
497 }
498 return tagStr.get();
499 }
500
501 /**
502 * Intl.Locale( tag[, options] )
503 */
504 static bool Locale(JSContext* cx, unsigned argc, Value* vp) {
505 CallArgs args = CallArgsFromVp(argc, vp);
506
507 // Step 1.
508 if (!ThrowIfNotConstructing(cx, args, "Intl.Locale")) {
509 return false;
510 }
511
512 // Steps 2-6 (Inlined 9.1.14, OrdinaryCreateFromConstructor).
513 RootedObject proto(cx);
514 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Locale, &proto)) {
515 return false;
516 }
517
518 // Steps 7-9.
519 HandleValue tagValue = args.get(0);
520 JSString* tagStr;
521 if (tagValue.isObject()) {
522 JS_TRY_VAR_OR_RETURN_FALSE(
523 cx, tagStr,
524 LanguageTagFromMaybeWrappedLocale(cx, &tagValue.toObject()));
525 if (!tagStr) {
526 tagStr = ToString(cx, tagValue);
527 if (!tagStr) {
528 return false;
529 }
530 }
531 } else if (tagValue.isString()) {
532 tagStr = tagValue.toString();
533 } else {
534 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
535 JSMSG_INVALID_LOCALES_ELEMENT);
536 return false;
537 }
538
539 Rooted<JSLinearString*> tagLinearStr(cx, tagStr->ensureLinear(cx));
540 if (!tagLinearStr) {
541 return false;
542 }
543
544 // Steps 10-11.
545 RootedObject options(cx);
546 if (args.hasDefined(1)) {
547 options = ToObject(cx, args[1]);
548 if (!options) {
549 return false;
550 }
551 }
552
553 // ApplyOptionsToTag, steps 2 and 9.
554 mozilla::intl::Locale tag;
555 if (!intl::ParseLocale(cx, tagLinearStr, tag)) {
556 return false;
557 }
558
559 if (tag.Language().Length() > 4) {
560 MOZ_ASSERT(cx->global());
561 cx->runtime()->setUseCounter(cx->global(),
562 JSUseCounter::LEGACY_LANG_SUBTAG);
563 }
564
565 if (auto result = tag.CanonicalizeBaseName(); result.isErr()) {
566 if (result.unwrapErr() ==
567 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant) {
568 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
569 JSMSG_DUPLICATE_VARIANT_SUBTAG);
570 } else {
571 intl::ReportInternalError(cx);
572 }
573 return false;
574 }
575
576 if (options) {
577 // Step 12.
578 if (!ApplyOptionsToTag(cx, tag, options)) {
579 return false;
580 }
581
582 // Step 13.
583 JS::RootedVector<intl::UnicodeExtensionKeyword> keywords(cx);
584
585 // Step 14.
586 Rooted<JSLinearString*> calendar(cx);
587 if (!GetStringOption(cx, options, cx->names().calendar, &calendar)) {
588 return false;
589 }
590
591 // Steps 15-16.
592 if (calendar) {
593 bool isValid;
594 if (!IsValidUnicodeExtensionValue(cx, calendar, &isValid)) {
595 return false;
596 }
597
598 if (!isValid) {
599 if (UniqueChars str = QuoteString(cx, calendar, '"')) {
600 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
601 JSMSG_INVALID_OPTION_VALUE, "calendar",
602 str.get());
603 }
604 return false;
605 }
606
607 if (!keywords.emplaceBack("ca", calendar)) {
608 return false;
609 }
610 }
611
612 // Step 17.
613 Rooted<JSLinearString*> collation(cx);
614 if (!GetStringOption(cx, options, cx->names().collation, &collation)) {
615 return false;
616 }
617
618 // Steps 18-19.
619 if (collation) {
620 bool isValid;
621 if (!IsValidUnicodeExtensionValue(cx, collation, &isValid)) {
622 return false;
623 }
624
625 if (!isValid) {
626 if (UniqueChars str = QuoteString(cx, collation, '"')) {
627 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
628 JSMSG_INVALID_OPTION_VALUE, "collation",
629 str.get());
630 }
631 return false;
632 }
633
634 if (!keywords.emplaceBack("co", collation)) {
635 return false;
636 }
637 }
638
639 // Step 20 (without validation).
640 Rooted<JSLinearString*> hourCycle(cx);
641 if (!GetStringOption(cx, options, cx->names().hourCycle, &hourCycle)) {
642 return false;
643 }
644
645 // Steps 20-21.
646 if (hourCycle) {
647 if (!StringEqualsLiteral(hourCycle, "h11") &&
648 !StringEqualsLiteral(hourCycle, "h12") &&
649 !StringEqualsLiteral(hourCycle, "h23") &&
650 !StringEqualsLiteral(hourCycle, "h24")) {
651 if (UniqueChars str = QuoteString(cx, hourCycle, '"')) {
652 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
653 JSMSG_INVALID_OPTION_VALUE, "hourCycle",
654 str.get());
655 }
656 return false;
657 }
658
659 if (!keywords.emplaceBack("hc", hourCycle)) {
660 return false;
661 }
662 }
663
664 // Step 22 (without validation).
665 Rooted<JSLinearString*> caseFirst(cx);
666 if (!GetStringOption(cx, options, cx->names().caseFirst, &caseFirst)) {
667 return false;
668 }
669
670 // Steps 22-23.
671 if (caseFirst) {
672 if (!StringEqualsLiteral(caseFirst, "upper") &&
673 !StringEqualsLiteral(caseFirst, "lower") &&
674 !StringEqualsLiteral(caseFirst, "false")) {
675 if (UniqueChars str = QuoteString(cx, caseFirst, '"')) {
676 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
677 JSMSG_INVALID_OPTION_VALUE, "caseFirst",
678 str.get());
679 }
680 return false;
681 }
682
683 if (!keywords.emplaceBack("kf", caseFirst)) {
684 return false;
685 }
686 }
687
688 // Steps 24-25.
689 Rooted<JSLinearString*> numeric(cx);
690 if (!GetBooleanOption(cx, options, cx->names().numeric, &numeric)) {
691 return false;
692 }
693
694 // Step 26.
695 if (numeric) {
696 if (!keywords.emplaceBack("kn", numeric)) {
697 return false;
698 }
699 }
700
701 // Step 27.
702 Rooted<JSLinearString*> numberingSystem(cx);
703 if (!GetStringOption(cx, options, cx->names().numberingSystem,
704 &numberingSystem)) {
705 return false;
706 }
707
708 // Steps 28-29.
709 if (numberingSystem) {
710 bool isValid;
711 if (!IsValidUnicodeExtensionValue(cx, numberingSystem, &isValid)) {
712 return false;
713 }
714 if (!isValid) {
715 if (UniqueChars str = QuoteString(cx, numberingSystem, '"')) {
716 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
717 JSMSG_INVALID_OPTION_VALUE,
718 "numberingSystem", str.get());
719 }
720 return false;
721 }
722
723 if (!keywords.emplaceBack("nu", numberingSystem)) {
724 return false;
725 }
726 }
727
728 // Step 30.
729 if (!ApplyUnicodeExtensionToTag(cx, tag, keywords)) {
730 return false;
731 }
732 }
733
734 // ApplyOptionsToTag, steps 9 and 13.
735 // ApplyUnicodeExtensionToTag, step 9.
736 if (auto result = tag.CanonicalizeExtensions(); result.isErr()) {
737 if (result.unwrapErr() ==
738 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant) {
739 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
740 JSMSG_DUPLICATE_VARIANT_SUBTAG);
741 } else {
742 intl::ReportInternalError(cx);
743 }
744 return false;
745 }
746
747 // Steps 6, 31-37.
748 JSObject* obj = CreateLocaleObject(cx, proto, tag);
749 if (!obj) {
750 return false;
751 }
752
753 // Step 38.
754 args.rval().setObject(*obj);
755 return true;
756 }
757
758 using UnicodeKey = const char (&)[UnicodeKeyLength + 1];
759
760 // Returns the tuple [index, length] of the `type` in the `keyword` in Unicode
761 // locale extension |extension| that has |key| as its `key`. If `keyword` lacks
762 // a type, the returned |index| will be where `type` would have been, and
763 // |length| will be set to zero.
764 template <typename CharT>
765 static mozilla::Maybe<IndexAndLength> FindUnicodeExtensionType(
766 const CharT* extension, size_t length, UnicodeKey key) {
767 MOZ_ASSERT(extension[0] == 'u');
768 MOZ_ASSERT(extension[1] == '-');
769
770 const CharT* end = extension + length;
771
772 SepKeywordIterator<CharT> iter(extension, end);
773
774 // Search all keywords until a match was found.
775 const CharT* beginKey;
776 while (true) {
777 beginKey = iter.next();
778 if (!beginKey) {
779 return mozilla::Nothing();
780 }
781
782 // Add +1 to skip over the separator preceding the keyword.
783 MOZ_ASSERT(beginKey[0] == '-');
784 beginKey++;
785
786 // Exit the loop on the first match.
787 if (std::equal(beginKey, beginKey + UnicodeKeyLength, key)) {
788 break;
789 }
790 }
791
792 // Skip over the key.
793 const CharT* beginType = beginKey + UnicodeKeyLength;
794
795 // Find the start of the next keyword.
796 const CharT* endType = iter.next();
797
798 // No further keyword present, the current keyword ends the Unicode extension.
799 if (!endType) {
800 endType = end;
801 }
802
803 // If the keyword has a type, skip over the separator preceding the type.
804 if (beginType != endType) {
805 MOZ_ASSERT(beginType[0] == '-');
806 beginType++;
807 }
808 return mozilla::Some(IndexAndLength{size_t(beginType - extension),
809 size_t(endType - beginType)});
810 }
811
812 static inline auto FindUnicodeExtensionType(
813 const JSLinearString* unicodeExtension, UnicodeKey key) {
814 JS::AutoCheckCannotGC nogc;
815 return unicodeExtension->hasLatin1Chars()
816 ? FindUnicodeExtensionType(
817 reinterpret_cast<const char*>(
818 unicodeExtension->latin1Chars(nogc)),
819 unicodeExtension->length(), key)
820 : FindUnicodeExtensionType(unicodeExtension->twoByteChars(nogc),
821 unicodeExtension->length(), key);
822 }
823
824 // Return the sequence of types for the Unicode extension keyword specified by
825 // key or undefined when the keyword isn't present.
826 static bool GetUnicodeExtension(JSContext* cx, LocaleObject* locale,
827 UnicodeKey key, MutableHandleValue value) {
828 // Return undefined when no Unicode extension subtag is present.
829 const Value& unicodeExtensionValue = locale->unicodeExtension();
830 if (unicodeExtensionValue.isUndefined()) {
831 value.setUndefined();
832 return true;
833 }
834
835 JSLinearString* unicodeExtension =
836 unicodeExtensionValue.toString()->ensureLinear(cx);
837 if (!unicodeExtension) {
838 return false;
839 }
840
841 // Find the type of the requested key in the Unicode extension subtag.
842 auto result = FindUnicodeExtensionType(unicodeExtension, key);
843
844 // Return undefined if the requested key isn't present in the extension.
845 if (!result) {
846 value.setUndefined();
847 return true;
848 }
849
850 size_t index = result->index;
851 size_t length = result->length;
852
853 // Otherwise return the type value of the found keyword.
854 JSString* str = NewDependentString(cx, unicodeExtension, index, length);
855 if (!str) {
856 return false;
857 }
858 value.setString(str);
859 return true;
860 }
861
862 struct BaseNamePartsResult {
863 IndexAndLength language;
864 mozilla::Maybe<IndexAndLength> script;
865 mozilla::Maybe<IndexAndLength> region;
866 };
867
868 // Returns [language-length, script-index, region-index, region-length].
869 template <typename CharT>
870 static BaseNamePartsResult BaseNameParts(const CharT* baseName, size_t length) {
871 size_t languageLength;
872 size_t scriptIndex = 0;
873 size_t regionIndex = 0;
874 size_t regionLength = 0;
875
876 // Search the first separator to find the end of the language subtag.
877 if (const CharT* sep = std::char_traits<CharT>::find(baseName, length, '-')) {
878 languageLength = sep - baseName;
879
880 // Add +1 to skip over the separator character.
881 size_t nextSubtag = languageLength + 1;
882
883 // Script subtags are always four characters long, but take care for a four
884 // character long variant subtag. These start with a digit.
885 if ((nextSubtag + ScriptLength == length ||
886 (nextSubtag + ScriptLength < length &&
887 baseName[nextSubtag + ScriptLength] == '-')) &&
888 mozilla::IsAsciiAlpha(baseName[nextSubtag])) {
889 scriptIndex = nextSubtag;
890 nextSubtag = scriptIndex + ScriptLength + 1;
891 }
892
893 // Region subtags can be either two or three characters long.
894 if (nextSubtag < length) {
895 for (size_t rlen : {AlphaRegionLength, DigitRegionLength}) {
896 MOZ_ASSERT(nextSubtag + rlen <= length);
897 if (nextSubtag + rlen == length || baseName[nextSubtag + rlen] == '-') {
898 regionIndex = nextSubtag;
899 regionLength = rlen;
900 break;
901 }
902 }
903 }
904 } else {
905 // No separator found, the base-name consists of just a language subtag.
906 languageLength = length;
907 }
908
909 // Tell the analysis the |IsStructurallyValid*Tag| functions can't GC.
910 JS::AutoSuppressGCAnalysis nogc;
911
912 IndexAndLength language{0, languageLength};
913 MOZ_ASSERT(
914 mozilla::intl::IsStructurallyValidLanguageTag(language.spanOf(baseName)));
915
916 mozilla::Maybe<IndexAndLength> script{};
917 if (scriptIndex) {
918 script.emplace(scriptIndex, ScriptLength);
919 MOZ_ASSERT(
920 mozilla::intl::IsStructurallyValidScriptTag(script->spanOf(baseName)));
921 }
922
923 mozilla::Maybe<IndexAndLength> region{};
924 if (regionIndex) {
925 region.emplace(regionIndex, regionLength);
926 MOZ_ASSERT(
927 mozilla::intl::IsStructurallyValidRegionTag(region->spanOf(baseName)));
928 }
929
930 return {language, script, region};
931 }
932
933 static inline auto BaseNameParts(const JSLinearString* baseName) {
934 JS::AutoCheckCannotGC nogc;
935 return baseName->hasLatin1Chars()
936 ? BaseNameParts(
937 reinterpret_cast<const char*>(baseName->latin1Chars(nogc)),
938 baseName->length())
939 : BaseNameParts(baseName->twoByteChars(nogc), baseName->length());
940 }
941
942 // Intl.Locale.prototype.maximize ()
943 static bool Locale_maximize(JSContext* cx, const CallArgs& args) {
944 MOZ_ASSERT(IsLocale(args.thisv()));
945
946 // Step 3.
947 auto* locale = &args.thisv().toObject().as<LocaleObject>();
948 Rooted<JSLinearString*> tagStr(cx, locale->languageTag()->ensureLinear(cx));
949 if (!tagStr) {
950 return false;
951 }
952
953 mozilla::intl::Locale tag;
954 if (!intl::ParseLocale(cx, tagStr, tag)) {
955 return false;
956 }
957
958 if (auto result = tag.AddLikelySubtags(); result.isErr()) {
959 intl::ReportInternalError(cx, result.unwrapErr());
960 return false;
961 }
962
963 // Step 4.
964 auto* result = CreateLocaleObject(cx, nullptr, tag);
965 if (!result) {
966 return false;
967 }
968 args.rval().setObject(*result);
969 return true;
970 }
971
972 // Intl.Locale.prototype.maximize ()
973 static bool Locale_maximize(JSContext* cx, unsigned argc, Value* vp) {
974 // Steps 1-2.
975 CallArgs args = CallArgsFromVp(argc, vp);
976 return CallNonGenericMethod<IsLocale, Locale_maximize>(cx, args);
977 }
978
979 // Intl.Locale.prototype.minimize ()
980 static bool Locale_minimize(JSContext* cx, const CallArgs& args) {
981 MOZ_ASSERT(IsLocale(args.thisv()));
982
983 // Step 3.
984 auto* locale = &args.thisv().toObject().as<LocaleObject>();
985 Rooted<JSLinearString*> tagStr(cx, locale->languageTag()->ensureLinear(cx));
986 if (!tagStr) {
987 return false;
988 }
989
990 mozilla::intl::Locale tag;
991 if (!intl::ParseLocale(cx, tagStr, tag)) {
992 return false;
993 }
994
995 if (auto result = tag.RemoveLikelySubtags(); result.isErr()) {
996 intl::ReportInternalError(cx, result.unwrapErr());
997 return false;
998 }
999
1000 // Step 4.
1001 auto* result = CreateLocaleObject(cx, nullptr, tag);
1002 if (!result) {
1003 return false;
1004 }
1005 args.rval().setObject(*result);
1006 return true;
1007 }
1008
1009 // Intl.Locale.prototype.minimize ()
1010 static bool Locale_minimize(JSContext* cx, unsigned argc, Value* vp) {
1011 // Steps 1-2.
1012 CallArgs args = CallArgsFromVp(argc, vp);
1013 return CallNonGenericMethod<IsLocale, Locale_minimize>(cx, args);
1014 }
1015
1016 // Intl.Locale.prototype.toString ()
1017 static bool Locale_toString(JSContext* cx, const CallArgs& args) {
1018 MOZ_ASSERT(IsLocale(args.thisv()));
1019
1020 // Step 3.
1021 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1022 args.rval().setString(locale->languageTag());
1023 return true;
1024 }
1025
1026 // Intl.Locale.prototype.toString ()
1027 static bool Locale_toString(JSContext* cx, unsigned argc, Value* vp) {
1028 // Steps 1-2.
1029 CallArgs args = CallArgsFromVp(argc, vp);
1030 return CallNonGenericMethod<IsLocale, Locale_toString>(cx, args);
1031 }
1032
1033 // get Intl.Locale.prototype.baseName
1034 static bool Locale_baseName(JSContext* cx, const CallArgs& args) {
1035 MOZ_ASSERT(IsLocale(args.thisv()));
1036
1037 // Steps 3-4.
1038 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1039 args.rval().setString(locale->baseName());
1040 return true;
1041 }
1042
1043 // get Intl.Locale.prototype.baseName
1044 static bool Locale_baseName(JSContext* cx, unsigned argc, Value* vp) {
1045 // Steps 1-2.
1046 CallArgs args = CallArgsFromVp(argc, vp);
1047 return CallNonGenericMethod<IsLocale, Locale_baseName>(cx, args);
1048 }
1049
1050 // get Intl.Locale.prototype.calendar
1051 static bool Locale_calendar(JSContext* cx, const CallArgs& args) {
1052 MOZ_ASSERT(IsLocale(args.thisv()));
1053
1054 // Step 3.
1055 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1056 return GetUnicodeExtension(cx, locale, "ca", args.rval());
1057 }
1058
1059 // get Intl.Locale.prototype.calendar
1060 static bool Locale_calendar(JSContext* cx, unsigned argc, Value* vp) {
1061 // Steps 1-2.
1062 CallArgs args = CallArgsFromVp(argc, vp);
1063 return CallNonGenericMethod<IsLocale, Locale_calendar>(cx, args);
1064 }
1065
1066 // get Intl.Locale.prototype.caseFirst
1067 static bool Locale_caseFirst(JSContext* cx, const CallArgs& args) {
1068 MOZ_ASSERT(IsLocale(args.thisv()));
1069
1070 // Step 3.
1071 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1072 return GetUnicodeExtension(cx, locale, "kf", args.rval());
1073 }
1074
1075 // get Intl.Locale.prototype.caseFirst
1076 static bool Locale_caseFirst(JSContext* cx, unsigned argc, Value* vp) {
1077 // Steps 1-2.
1078 CallArgs args = CallArgsFromVp(argc, vp);
1079 return CallNonGenericMethod<IsLocale, Locale_caseFirst>(cx, args);
1080 }
1081
1082 // get Intl.Locale.prototype.collation
1083 static bool Locale_collation(JSContext* cx, const CallArgs& args) {
1084 MOZ_ASSERT(IsLocale(args.thisv()));
1085
1086 // Step 3.
1087 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1088 return GetUnicodeExtension(cx, locale, "co", args.rval());
1089 }
1090
1091 // get Intl.Locale.prototype.collation
1092 static bool Locale_collation(JSContext* cx, unsigned argc, Value* vp) {
1093 // Steps 1-2.
1094 CallArgs args = CallArgsFromVp(argc, vp);
1095 return CallNonGenericMethod<IsLocale, Locale_collation>(cx, args);
1096 }
1097
1098 // get Intl.Locale.prototype.hourCycle
1099 static bool Locale_hourCycle(JSContext* cx, const CallArgs& args) {
1100 MOZ_ASSERT(IsLocale(args.thisv()));
1101
1102 // Step 3.
1103 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1104 return GetUnicodeExtension(cx, locale, "hc", args.rval());
1105 }
1106
1107 // get Intl.Locale.prototype.hourCycle
1108 static bool Locale_hourCycle(JSContext* cx, unsigned argc, Value* vp) {
1109 // Steps 1-2.
1110 CallArgs args = CallArgsFromVp(argc, vp);
1111 return CallNonGenericMethod<IsLocale, Locale_hourCycle>(cx, args);
1112 }
1113
1114 // get Intl.Locale.prototype.numeric
1115 static bool Locale_numeric(JSContext* cx, const CallArgs& args) {
1116 MOZ_ASSERT(IsLocale(args.thisv()));
1117
1118 // Step 3.
1119 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1120 RootedValue value(cx);
1121 if (!GetUnicodeExtension(cx, locale, "kn", &value)) {
1122 return false;
1123 }
1124
1125 // Compare against the empty string per Intl.Locale, step 36.a. The Unicode
1126 // extension is already canonicalized, so we don't need to compare against
1127 // "true" at this point.
1128 MOZ_ASSERT(value.isUndefined() || value.isString());
1129 MOZ_ASSERT_IF(value.isString(),
1130 !StringEqualsLiteral(&value.toString()->asLinear(), "true"));
1131
1132 args.rval().setBoolean(value.isString() && value.toString()->empty());
1133 return true;
1134 }
1135
1136 // get Intl.Locale.prototype.numeric
1137 static bool Locale_numeric(JSContext* cx, unsigned argc, Value* vp) {
1138 // Steps 1-2.
1139 CallArgs args = CallArgsFromVp(argc, vp);
1140 return CallNonGenericMethod<IsLocale, Locale_numeric>(cx, args);
1141 }
1142
1143 // get Intl.Locale.prototype.numberingSystem
1144 static bool Intl_Locale_numberingSystem(JSContext* cx, const CallArgs& args) {
1145 MOZ_ASSERT(IsLocale(args.thisv()));
1146
1147 // Step 3.
1148 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1149 return GetUnicodeExtension(cx, locale, "nu", args.rval());
1150 }
1151
1152 // get Intl.Locale.prototype.numberingSystem
1153 static bool Locale_numberingSystem(JSContext* cx, unsigned argc, Value* vp) {
1154 // Steps 1-2.
1155 CallArgs args = CallArgsFromVp(argc, vp);
1156 return CallNonGenericMethod<IsLocale, Intl_Locale_numberingSystem>(cx, args);
1157 }
1158
1159 // get Intl.Locale.prototype.language
1160 static bool Locale_language(JSContext* cx, const CallArgs& args) {
1161 MOZ_ASSERT(IsLocale(args.thisv()));
1162
1163 // Step 3.
1164 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1165 JSLinearString* baseName = locale->baseName()->ensureLinear(cx);
1166 if (!baseName) {
1167 return false;
1168 }
1169
1170 // Step 4 (Unnecessary assertion).
1171
1172 auto language = BaseNameParts(baseName).language;
1173
1174 size_t index = language.index;
1175 size_t length = language.length;
1176
1177 // Step 5.
1178 JSString* str = NewDependentString(cx, baseName, index, length);
1179 if (!str) {
1180 return false;
1181 }
1182
1183 args.rval().setString(str);
1184 return true;
1185 }
1186
1187 // get Intl.Locale.prototype.language
1188 static bool Locale_language(JSContext* cx, unsigned argc, Value* vp) {
1189 // Steps 1-2.
1190 CallArgs args = CallArgsFromVp(argc, vp);
1191 return CallNonGenericMethod<IsLocale, Locale_language>(cx, args);
1192 }
1193
1194 // get Intl.Locale.prototype.script
1195 static bool Locale_script(JSContext* cx, const CallArgs& args) {
1196 MOZ_ASSERT(IsLocale(args.thisv()));
1197
1198 // Step 3.
1199 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1200 JSLinearString* baseName = locale->baseName()->ensureLinear(cx);
1201 if (!baseName) {
1202 return false;
1203 }
1204
1205 // Step 4 (Unnecessary assertion).
1206
1207 auto script = BaseNameParts(baseName).script;
1208
1209 // Step 5.
1210 if (!script) {
1211 args.rval().setUndefined();
1212 return true;
1213 }
1214
1215 size_t index = script->index;
1216 size_t length = script->length;
1217
1218 // Step 6.
1219 JSString* str = NewDependentString(cx, baseName, index, length);
1220 if (!str) {
1221 return false;
1222 }
1223
1224 args.rval().setString(str);
1225 return true;
1226 }
1227
1228 // get Intl.Locale.prototype.script
1229 static bool Locale_script(JSContext* cx, unsigned argc, Value* vp) {
1230 // Steps 1-2.
1231 CallArgs args = CallArgsFromVp(argc, vp);
1232 return CallNonGenericMethod<IsLocale, Locale_script>(cx, args);
1233 }
1234
1235 // get Intl.Locale.prototype.region
1236 static bool Locale_region(JSContext* cx, const CallArgs& args) {
1237 MOZ_ASSERT(IsLocale(args.thisv()));
1238
1239 // Step 3.
1240 auto* locale = &args.thisv().toObject().as<LocaleObject>();
1241 JSLinearString* baseName = locale->baseName()->ensureLinear(cx);
1242 if (!baseName) {
1243 return false;
1244 }
1245
1246 // Step 4 (Unnecessary assertion).
1247
1248 auto region = BaseNameParts(baseName).region;
1249
1250 // Step 5.
1251 if (!region) {
1252 args.rval().setUndefined();
1253 return true;
1254 }
1255
1256 size_t index = region->index;
1257 size_t length = region->length;
1258
1259 // Step 6.
1260 JSString* str = NewDependentString(cx, baseName, index, length);
1261 if (!str) {
1262 return false;
1263 }
1264
1265 args.rval().setString(str);
1266 return true;
1267 }
1268
1269 // get Intl.Locale.prototype.region
1270 static bool Locale_region(JSContext* cx, unsigned argc, Value* vp) {
1271 // Steps 1-2.
1272 CallArgs args = CallArgsFromVp(argc, vp);
1273 return CallNonGenericMethod<IsLocale, Locale_region>(cx, args);
1274 }
1275
1276 static bool Locale_toSource(JSContext* cx, unsigned argc, Value* vp) {
1277 CallArgs args = CallArgsFromVp(argc, vp);
1278 args.rval().setString(cx->names().Locale);
1279 return true;
1280 }
1281
1282 static const JSFunctionSpec locale_methods[] = {
1283 JS_FN("maximize", Locale_maximize, 0, 0),
1284 JS_FN("minimize", Locale_minimize, 0, 0),
1285 JS_FN("toString", Locale_toString, 0, 0),
1286 JS_FN("toSource", Locale_toSource, 0, 0),
1287 JS_FS_END,
1288 };
1289
1290 static const JSPropertySpec locale_properties[] = {
1291 JS_PSG("baseName", Locale_baseName, 0),
1292 JS_PSG("calendar", Locale_calendar, 0),
1293 JS_PSG("caseFirst", Locale_caseFirst, 0),
1294 JS_PSG("collation", Locale_collation, 0),
1295 JS_PSG("hourCycle", Locale_hourCycle, 0),
1296 JS_PSG("numeric", Locale_numeric, 0),
1297 JS_PSG("numberingSystem", Locale_numberingSystem, 0),
1298 JS_PSG("language", Locale_language, 0),
1299 JS_PSG("script", Locale_script, 0),
1300 JS_PSG("region", Locale_region, 0),
1301 JS_STRING_SYM_PS(toStringTag, "Intl.Locale", JSPROP_READONLY),
1302 JS_PS_END,
1303 };
1304
1305 const ClassSpec LocaleObject::classSpec_ = {
1306 GenericCreateConstructor<Locale, 1, gc::AllocKind::FUNCTION>,
1307 GenericCreatePrototype<LocaleObject>,
1308 nullptr,
1309 nullptr,
1310 locale_methods,
1311 locale_properties,
1312 nullptr,
1313 ClassSpec::DontDefineConstructor,
1314 };
1315
1316 bool js::intl_ValidateAndCanonicalizeLanguageTag(JSContext* cx, unsigned argc,
1317 Value* vp) {
1318 CallArgs args = CallArgsFromVp(argc, vp);
1319 MOZ_ASSERT(args.length() == 2);
1320
1321 HandleValue tagValue = args[0];
1322 bool applyToString = args[1].toBoolean();
1323
1324 if (tagValue.isObject()) {
1325 JSString* tagStr;
1326 JS_TRY_VAR_OR_RETURN_FALSE(
1327 cx, tagStr,
1328 LanguageTagFromMaybeWrappedLocale(cx, &tagValue.toObject()));
1329 if (tagStr) {
1330 args.rval().setString(tagStr);
1331 return true;
1332 }
1333 }
1334
1335 if (!applyToString && !tagValue.isString()) {
1336 args.rval().setNull();
1337 return true;
1338 }
1339
1340 JSString* tagStr = ToString(cx, tagValue);
1341 if (!tagStr) {
1342 return false;
1343 }
1344
1345 Rooted<JSLinearString*> tagLinearStr(cx, tagStr->ensureLinear(cx));
1346 if (!tagLinearStr) {
1347 return false;
1348 }
1349
1350 // Handle the common case (a standalone language) first.
1351 // Only the following Unicode BCP 47 locale identifier subset is accepted:
1352 // unicode_locale_id = unicode_language_id
1353 // unicode_language_id = unicode_language_subtag
1354 // unicode_language_subtag = alpha{2,3}
1355 JSString* language;
1356 JS_TRY_VAR_OR_RETURN_FALSE(
1357 cx, language, intl::ParseStandaloneISO639LanguageTag(cx, tagLinearStr));
1358 if (language) {
1359 args.rval().setString(language);
1360 return true;
1361 }
1362
1363 mozilla::intl::Locale tag;
1364 if (!intl::ParseLocale(cx, tagLinearStr, tag)) {
1365 return false;
1366 }
1367
1368 auto result = tag.Canonicalize();
1369 if (result.isErr()) {
1370 if (result.unwrapErr() ==
1371 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant) {
1372 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1373 JSMSG_DUPLICATE_VARIANT_SUBTAG);
1374 } else {
1375 intl::ReportInternalError(cx);
1376 }
1377 return false;
1378 }
1379
1380 intl::FormatBuffer<char, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
1381 if (auto result = tag.ToString(buffer); result.isErr()) {
1382 intl::ReportInternalError(cx, result.unwrapErr());
1383 return false;
1384 }
1385
1386 JSString* resultStr = buffer.toAsciiString(cx);
1387 if (!resultStr) {
1388 return false;
1389 }
1390
1391 args.rval().setString(resultStr);
1392 return true;
1393 }
1394
1395 bool js::intl_TryValidateAndCanonicalizeLanguageTag(JSContext* cx,
1396 unsigned argc, Value* vp) {
1397 CallArgs args = CallArgsFromVp(argc, vp);
1398 MOZ_ASSERT(args.length() == 1);
1399
1400 Rooted<JSLinearString*> linear(cx, args[0].toString()->ensureLinear(cx));
1401 if (!linear) {
1402 return false;
1403 }
1404
1405 mozilla::intl::Locale tag;
1406 {
1407 if (!StringIsAscii(linear)) {
1408 // The caller handles invalid inputs.
1409 args.rval().setNull();
1410 return true;
1411 }
1412
1413 intl::StringAsciiChars chars(linear);
1414 if (!chars.init(cx)) {
1415 return false;
1416 }
1417
1418 if (mozilla::intl::LocaleParser::TryParse(chars, tag).isErr()) {
1419 // The caller handles invalid inputs.
1420 args.rval().setNull();
1421 return true;
1422 }
1423 }
1424
1425 auto result = tag.Canonicalize();
1426 if (result.isErr()) {
1427 if (result.unwrapErr() ==
1428 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant) {
1429 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1430 JSMSG_DUPLICATE_VARIANT_SUBTAG);
1431 } else {
1432 intl::ReportInternalError(cx);
1433 }
1434 return false;
1435 }
1436
1437 intl::FormatBuffer<char, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
1438 if (auto result = tag.ToString(buffer); result.isErr()) {
1439 intl::ReportInternalError(cx, result.unwrapErr());
1440 return false;
1441 }
1442
1443 JSString* resultStr = buffer.toAsciiString(cx);
1444 if (!resultStr) {
1445 return false;
1446 }
1447 args.rval().setString(resultStr);
1448 return true;
1449 }
1450
1451 bool js::intl_ValidateAndCanonicalizeUnicodeExtensionType(JSContext* cx,
1452 unsigned argc,
1453 Value* vp) {
1454 CallArgs args = CallArgsFromVp(argc, vp);
1455 MOZ_ASSERT(args.length() == 3);
1456
1457 HandleValue typeArg = args[0];
1458 MOZ_ASSERT(typeArg.isString(), "type must be a string");
1459
1460 HandleValue optionArg = args[1];
1461 MOZ_ASSERT(optionArg.isString(), "option name must be a string");
1462
1463 HandleValue keyArg = args[2];
1464 MOZ_ASSERT(keyArg.isString(), "key must be a string");
1465
1466 Rooted<JSLinearString*> unicodeType(cx, typeArg.toString()->ensureLinear(cx));
1467 if (!unicodeType) {
1468 return false;
1469 }
1470
1471 bool isValid;
1472 if (!IsValidUnicodeExtensionValue(cx, unicodeType, &isValid)) {
1473 return false;
1474 }
1475 if (!isValid) {
1476 UniqueChars optionChars = EncodeAscii(cx, optionArg.toString());
1477 if (!optionChars) {
1478 return false;
1479 }
1480
1481 UniqueChars unicodeTypeChars = QuoteString(cx, unicodeType, '"');
1482 if (!unicodeTypeChars) {
1483 return false;
1484 }
1485
1486 JS_ReportErrorNumberASCII(cx, js::GetErrorMessage, nullptr,
1487 JSMSG_INVALID_OPTION_VALUE, optionChars.get(),
1488 unicodeTypeChars.get());
1489 return false;
1490 }
1491
1492 char unicodeKey[UnicodeKeyLength];
1493 {
1494 JSLinearString* str = keyArg.toString()->ensureLinear(cx);
1495 if (!str) {
1496 return false;
1497 }
1498 MOZ_ASSERT(str->length() == UnicodeKeyLength);
1499
1500 for (size_t i = 0; i < UnicodeKeyLength; i++) {
1501 char16_t ch = str->latin1OrTwoByteChar(i);
1502 MOZ_ASSERT(mozilla::IsAscii(ch));
1503 unicodeKey[i] = char(ch);
1504 }
1505 }
1506
1507 UniqueChars unicodeTypeChars = EncodeAscii(cx, unicodeType);
1508 if (!unicodeTypeChars) {
1509 return false;
1510 }
1511
1512 size_t unicodeTypeLength = unicodeType->length();
1513 MOZ_ASSERT(strlen(unicodeTypeChars.get()) == unicodeTypeLength);
1514
1515 // Convert into canonical case before searching for replacements.
1516 mozilla::intl::AsciiToLowerCase(unicodeTypeChars.get(), unicodeTypeLength,
1517 unicodeTypeChars.get());
1518
1519 auto key = mozilla::Span(unicodeKey, UnicodeKeyLength);
1520 auto type = mozilla::Span(unicodeTypeChars.get(), unicodeTypeLength);
1521
1522 // Search if there's a replacement for the current Unicode keyword.
1523 JSString* result;
1524 if (const char* replacement =
1525 mozilla::intl::Locale::ReplaceUnicodeExtensionType(key, type)) {
1526 result = NewStringCopyZ<CanGC>(cx, replacement);
1527 } else {
1528 result = StringToLowerCase(cx, unicodeType);
1529 }
1530 if (!result) {
1531 return false;
1532 }
1533
1534 args.rval().setString(result);
1535 return true;
1536 }