Debian Codegraph @

intl/components/src/Locale.cpp

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #include "mozilla/intl/Locale.h"
6
7 #include "mozilla/Assertions.h"
8 #include "mozilla/DebugOnly.h"
9 #include "mozilla/MathAlgorithms.h"
10 #include "mozilla/Span.h"
11 #include "mozilla/TextUtils.h"
12 #include "mozilla/Variant.h"
13
14 #include "ICU4CGlue.h"
15
16 #include <algorithm>
17 #include <iterator>
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <string>
21 #include <string.h>
22 #include <type_traits>
23 #include <utility>
24
25 #include "unicode/uloc.h"
26 #include "unicode/utypes.h"
27
28 namespace mozilla::intl {
29
30 using namespace intl::LanguageTagLimits;
31
32 template <typename CharT>
33 bool IsStructurallyValidLanguageTag(Span<const CharT> aLanguage) {
34 // unicode_language_subtag = alpha{2,3} | alpha{5,8};
35 size_t length = aLanguage.size();
36 const CharT* str = aLanguage.data();
37 return ((2 <= length && length <= 3) || (5 <= length && length <= 8)) &&
38 std::all_of(str, str + length, IsAsciiAlpha<CharT>);
39 }
40
41 template bool IsStructurallyValidLanguageTag(Span<const char> aLanguage);
42 template bool IsStructurallyValidLanguageTag(Span<const Latin1Char> aLanguage);
43 template bool IsStructurallyValidLanguageTag(Span<const char16_t> aLanguage);
44
45 template <typename CharT>
46 bool IsStructurallyValidScriptTag(Span<const CharT> aScript) {
47 // unicode_script_subtag = alpha{4} ;
48 size_t length = aScript.size();
49 const CharT* str = aScript.data();
50 return length == 4 && std::all_of(str, str + length, IsAsciiAlpha<CharT>);
51 }
52
53 template bool IsStructurallyValidScriptTag(Span<const char> aScript);
54 template bool IsStructurallyValidScriptTag(Span<const Latin1Char> aScript);
55 template bool IsStructurallyValidScriptTag(Span<const char16_t> aScript);
56
57 template <typename CharT>
58 bool IsStructurallyValidRegionTag(Span<const CharT> aRegion) {
59 // unicode_region_subtag = (alpha{2} | digit{3}) ;
60 size_t length = aRegion.size();
61 const CharT* str = aRegion.data();
62 return (length == 2 && std::all_of(str, str + length, IsAsciiAlpha<CharT>)) ||
63 (length == 3 && std::all_of(str, str + length, IsAsciiDigit<CharT>));
64 }
65
66 template bool IsStructurallyValidRegionTag(Span<const char> aRegion);
67 template bool IsStructurallyValidRegionTag(Span<const Latin1Char> aRegion);
68 template bool IsStructurallyValidRegionTag(Span<const char16_t> aRegion);
69
70 #ifdef DEBUG
71 bool IsStructurallyValidVariantTag(Span<const char> aVariant) {
72 // unicode_variant_subtag = (alphanum{5,8} | digit alphanum{3}) ;
73 size_t length = aVariant.size();
74 const char* str = aVariant.data();
75 return ((5 <= length && length <= 8) ||
76 (length == 4 && IsAsciiDigit(str[0]))) &&
77 std::all_of(str, str + length, IsAsciiAlphanumeric<char>);
78 }
79
80 bool IsStructurallyValidUnicodeExtensionTag(Span<const char> aExtension) {
81 return LocaleParser::CanParseUnicodeExtension(aExtension).isOk();
82 }
83
84 static bool IsStructurallyValidExtensionTag(Span<const char> aExtension) {
85 // other_extensions = sep [alphanum-[tTuUxX]] (sep alphanum{2,8})+ ;
86 // NB: Allow any extension, including Unicode and Transform here, because
87 // this function is only used for an assertion.
88
89 size_t length = aExtension.size();
90 const char* str = aExtension.data();
91 const char* const end = aExtension.data() + length;
92 if (length <= 2) {
93 return false;
94 }
95 if (!IsAsciiAlphanumeric(str[0]) || str[0] == 'x' || str[0] == 'X') {
96 return false;
97 }
98 str++;
99 if (*str++ != '-') {
100 return false;
101 }
102 while (true) {
103 const char* sep =
104 reinterpret_cast<const char*>(memchr(str, '-', end - str));
105 size_t len = (sep ? sep : end) - str;
106 if (len < 2 || len > 8 ||
107 !std::all_of(str, str + len, IsAsciiAlphanumeric<char>)) {
108 return false;
109 }
110 if (!sep) {
111 return true;
112 }
113 str = sep + 1;
114 }
115 }
116
117 bool IsStructurallyValidPrivateUseTag(Span<const char> aPrivateUse) {
118 // pu_extensions = sep [xX] (sep alphanum{1,8})+ ;
119
120 size_t length = aPrivateUse.size();
121 const char* str = aPrivateUse.data();
122 const char* const end = aPrivateUse.data() + length;
123 if (length <= 2) {
124 return false;
125 }
126 if (str[0] != 'x' && str[0] != 'X') {
127 return false;
128 }
129 str++;
130 if (*str++ != '-') {
131 return false;
132 }
133 while (true) {
134 const char* sep =
135 reinterpret_cast<const char*>(memchr(str, '-', end - str));
136 size_t len = (sep ? sep : end) - str;
137 if (len == 0 || len > 8 ||
138 !std::all_of(str, str + len, IsAsciiAlphanumeric<char>)) {
139 return false;
140 }
141 if (!sep) {
142 return true;
143 }
144 str = sep + 1;
145 }
146 }
147 #endif
148
149 ptrdiff_t Locale::UnicodeExtensionIndex() const {
150 // The extension subtags aren't necessarily sorted, so we can't use binary
151 // search here.
152 auto p = std::find_if(
153 mExtensions.begin(), mExtensions.end(),
154 [](const auto& ext) { return ext[0] == 'u' || ext[0] == 'U'; });
155 if (p != mExtensions.end()) {
156 return std::distance(mExtensions.begin(), p);
157 }
158 return -1;
159 }
160
161 Maybe<Span<const char>> Locale::GetUnicodeExtension() const {
162 ptrdiff_t index = UnicodeExtensionIndex();
163 if (index >= 0) {
164 return Some(MakeStringSpan(mExtensions[index].get()));
165 }
166 return Nothing();
167 }
168
169 ICUResult Locale::SetUnicodeExtension(Span<const char> aExtension) {
170 MOZ_ASSERT(IsStructurallyValidUnicodeExtensionTag(aExtension));
171
172 auto duplicated = DuplicateStringToUniqueChars(aExtension);
173
174 // Replace the existing Unicode extension subtag or append a new one.
175 ptrdiff_t index = UnicodeExtensionIndex();
176 if (index >= 0) {
177 mExtensions[index] = std::move(duplicated);
178 return Ok();
179 }
180 if (!mExtensions.append(std::move(duplicated))) {
181 return Err(ICUError::OutOfMemory);
182 }
183 return Ok();
184 }
185
186 void Locale::ClearUnicodeExtension() {
187 ptrdiff_t index = UnicodeExtensionIndex();
188 if (index >= 0) {
189 mExtensions.erase(mExtensions.begin() + index);
190 }
191 }
192
193 template <size_t InitialCapacity>
194 static bool SortAlphabetically(Vector<UniqueChars, InitialCapacity>& aSubtags) {
195 size_t length = aSubtags.length();
196
197 // Zero or one element lists are already sorted.
198 if (length < 2) {
199 return true;
200 }
201
202 // Handle two element lists inline.
203 if (length == 2) {
204 if (strcmp(aSubtags[0].get(), aSubtags[1].get()) > 0) {
205 aSubtags[0].swap(aSubtags[1]);
206 }
207 return true;
208 }
209
210 Vector<char*, 8> scratch;
211 if (!scratch.resizeUninitialized(length)) {
212 return false;
213 }
214 for (size_t i = 0; i < length; i++) {
215 scratch[i] = aSubtags[i].release();
216 }
217
218 std::stable_sort(
219 scratch.begin(), scratch.end(),
220 [](const char* a, const char* b) { return strcmp(a, b) < 0; });
221
222 for (size_t i = 0; i < length; i++) {
223 aSubtags[i] = UniqueChars(scratch[i]);
224 }
225 return true;
226 }
227
228 Result<Ok, Locale::CanonicalizationError> Locale::CanonicalizeBaseName() {
229 // Per 6.2.3 CanonicalizeUnicodeLocaleId, the very first step is to
230 // canonicalize the syntax by normalizing the case and ordering all subtags.
231 // The canonical syntax form is specified in UTS 35, 3.2.1.
232
233 // Language codes need to be in lower case. "JA" -> "ja"
234 mLanguage.ToLowerCase();
235 MOZ_ASSERT(IsStructurallyValidLanguageTag(Language().Span()));
236
237 // The first character of a script code needs to be capitalized.
238 // "hans" -> "Hans"
239 mScript.ToTitleCase();
240 MOZ_ASSERT(Script().Missing() ||
241 IsStructurallyValidScriptTag(Script().Span()));
242
243 // Region codes need to be in upper case. "bu" -> "BU"
244 mRegion.ToUpperCase();
245 MOZ_ASSERT(Region().Missing() ||
246 IsStructurallyValidRegionTag(Region().Span()));
247
248 // The canonical case for variant subtags is lowercase.
249 for (UniqueChars& variant : mVariants) {
250 char* variantChars = variant.get();
251 size_t variantLength = strlen(variantChars);
252 AsciiToLowerCase(variantChars, variantLength, variantChars);
253
254 MOZ_ASSERT(IsStructurallyValidVariantTag({variantChars, variantLength}));
255 }
256
257 // Extensions and privateuse subtags are case normalized in the
258 // |canonicalizeExtensions| method.
259
260 // The second step in UTS 35, 3.2.1, is to order all subtags.
261
262 if (mVariants.length() > 1) {
263 // 1. Any variants are in alphabetical order.
264 if (!SortAlphabetically(mVariants)) {
265 return Err(CanonicalizationError::OutOfMemory);
266 }
267
268 // Reject the Locale identifier if a duplicate variant was found, e.g.
269 // "en-variant-Variant".
270 const UniqueChars* duplicate = std::adjacent_find(
271 mVariants.begin(), mVariants.end(), [](const auto& a, const auto& b) {
272 return strcmp(a.get(), b.get()) == 0;
273 });
274 if (duplicate != mVariants.end()) {
275 return Err(CanonicalizationError::DuplicateVariant);
276 }
277 }
278
279 // 2. Any extensions are in alphabetical order by their singleton.
280 // 3. All attributes are sorted in alphabetical order.
281 // 4. All keywords and tfields are sorted by alphabetical order of their keys,
282 // within their respective extensions.
283 // 5. Any type or tfield value "true" is removed.
284 // - A subsequent call to canonicalizeExtensions() will perform these steps.
285
286 // 6.2.3 CanonicalizeUnicodeLocaleId, step 2 transforms the locale identifier
287 // into its canonical form per UTS 3.2.1.
288
289 // 1. Use the bcp47 data to replace keys, types, tfields, and tvalues by their
290 // canonical forms.
291 // - A subsequent call to canonicalizeExtensions() will perform this step.
292
293 // 2. Replace aliases in the unicode_language_id and tlang (if any).
294 // - tlang is handled in canonicalizeExtensions().
295
296 // Replace deprecated language, region, and variant subtags with their
297 // preferred mappings.
298
299 if (!UpdateLegacyMappings()) {
300 return Err(CanonicalizationError::OutOfMemory);
301 }
302
303 // Replace deprecated language subtags with their preferred values.
304 if (!LanguageMapping(mLanguage) && ComplexLanguageMapping(mLanguage)) {
305 PerformComplexLanguageMappings();
306 }
307
308 // Replace deprecated script subtags with their preferred values.
309 if (Script().Present()) {
310 ScriptMapping(mScript);
311 }
312
313 // Replace deprecated region subtags with their preferred values.
314 if (Region().Present()) {
315 if (!RegionMapping(mRegion) && ComplexRegionMapping(mRegion)) {
316 PerformComplexRegionMappings();
317 }
318 }
319
320 // Replace deprecated variant subtags with their preferred values.
321 if (!PerformVariantMappings()) {
322 return Err(CanonicalizationError::OutOfMemory);
323 }
324
325 // No extension replacements are currently present.
326 // Private use sequences are left as is.
327
328 // 3. Replace aliases in special key values.
329 // - A subsequent call to canonicalizeExtensions() will perform this step.
330
331 return Ok();
332 }
333
334 #ifdef DEBUG
335 static bool IsAsciiLowercaseAlphanumericOrDash(Span<const char> aSpan) {
336 const char* ptr = aSpan.data();
337 size_t length = aSpan.size();
338 return std::all_of(ptr, ptr + length, [](auto c) {
339 return IsAsciiLowercaseAlpha(c) || IsAsciiDigit(c) || c == '-';
340 });
341 }
342 #endif
343
344 Result<Ok, Locale::CanonicalizationError> Locale::CanonicalizeExtensions() {
345 // The canonical case for all extension subtags is lowercase.
346 for (UniqueChars& extension : mExtensions) {
347 char* extensionChars = extension.get();
348 size_t extensionLength = strlen(extensionChars);
349 AsciiToLowerCase(extensionChars, extensionLength, extensionChars);
350
351 MOZ_ASSERT(
352 IsStructurallyValidExtensionTag({extensionChars, extensionLength}));
353 }
354
355 // Any extensions are in alphabetical order by their singleton.
356 // "u-ca-chinese-t-zh-latn" -> "t-zh-latn-u-ca-chinese"
357 if (!SortAlphabetically(mExtensions)) {
358 return Err(CanonicalizationError::OutOfMemory);
359 }
360
361 for (UniqueChars& extension : mExtensions) {
362 if (extension[0] == 'u') {
363 MOZ_TRY(CanonicalizeUnicodeExtension(extension));
364 } else if (extension[0] == 't') {
365 MOZ_TRY(CanonicalizeTransformExtension(extension));
366 }
367
368 MOZ_ASSERT(
369 IsAsciiLowercaseAlphanumericOrDash(MakeStringSpan(extension.get())));
370 }
371
372 // The canonical case for privateuse subtags is lowercase.
373 if (char* privateuse = mPrivateUse.get()) {
374 size_t privateuseLength = strlen(privateuse);
375 AsciiToLowerCase(privateuse, privateuseLength, privateuse);
376
377 MOZ_ASSERT(
378 IsStructurallyValidPrivateUseTag({privateuse, privateuseLength}));
379 }
380 return Ok();
381 }
382
383 template <size_t N>
384 static inline bool AppendSpan(Vector<char, N>& vector, Span<const char> aSpan) {
385 return vector.append(aSpan.data(), aSpan.size());
386 }
387
388 /**
389 * CanonicalizeUnicodeExtension( attributes, keywords )
390 *
391 * Canonical syntax per
392 * <https://unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>:
393 *
394 * - All attributes and keywords are in lowercase.
395 * - Note: The parser already converted keywords to lowercase.
396 * - All attributes are sorted in alphabetical order.
397 * - All keywords are sorted by alphabetical order of their keys.
398 * - Any type value "true" is removed.
399 *
400 * Canonical form:
401 * - All keys and types use the canonical form (from the name attribute;
402 * see Section 3.6.4 U Extension Data Files).
403 */
404 Result<Ok, Locale::CanonicalizationError> Locale::CanonicalizeUnicodeExtension(
405 UniqueChars& aUnicodeExtension) {
406 Span<const char> extension = MakeStringSpan(aUnicodeExtension.get());
407 MOZ_ASSERT(extension[0] == 'u');
408 MOZ_ASSERT(extension[1] == '-');
409 MOZ_ASSERT(IsStructurallyValidExtensionTag(extension));
410
411 LocaleParser::AttributesVector attributes;
412 LocaleParser::KeywordsVector keywords;
413
414 using Attribute = LocaleParser::AttributesVector::ElementType;
415 using Keyword = LocaleParser::KeywordsVector::ElementType;
416
417 if (LocaleParser::ParseUnicodeExtension(extension, attributes, keywords)
418 .isErr()) {
419 MOZ_ASSERT_UNREACHABLE("unexpected invalid Unicode extension subtag");
420 return Err(CanonicalizationError::InternalError);
421 }
422
423 auto attributesLess = [extension](const Attribute& a, const Attribute& b) {
424 auto astr = extension.Subspan(a.Begin(), a.Length());
425 auto bstr = extension.Subspan(b.Begin(), b.Length());
426 return astr < bstr;
427 };
428
429 // All attributes are sorted in alphabetical order.
430 if (attributes.length() > 1) {
431 std::stable_sort(attributes.begin(), attributes.end(), attributesLess);
432 }
433
434 auto keywordsLess = [extension](const Keyword& a, const Keyword& b) {
435 auto astr = extension.Subspan(a.Begin(), UnicodeKeyLength);
436 auto bstr = extension.Subspan(b.Begin(), UnicodeKeyLength);
437 return astr < bstr;
438 };
439
440 // All keywords are sorted by alphabetical order of keys.
441 if (keywords.length() > 1) {
442 // Using a stable sort algorithm, guarantees that two keywords using the
443 // same key are never reordered. That means for example
444 // when we have the input "u-nu-thai-kf-false-nu-latn", we are guaranteed to
445 // get the result "u-kf-false-nu-thai-nu-latn", i.e. "nu-thai" still occurs
446 // before "nu-latn".
447 // This is required so that deduplication below preserves the first keyword
448 // for a given key and discards the rest.
449 std::stable_sort(keywords.begin(), keywords.end(), keywordsLess);
450 }
451
452 Vector<char, 32> sb;
453 if (!sb.append('u')) {
454 return Err(CanonicalizationError::OutOfMemory);
455 }
456
457 // Append all Unicode extension attributes.
458 for (size_t i = 0; i < attributes.length(); i++) {
459 const auto& attribute = attributes[i];
460 auto span = extension.Subspan(attribute.Begin(), attribute.Length());
461
462 // Skip duplicate attributes.
463 if (i > 0) {
464 const auto& lastAttribute = attributes[i - 1];
465 if (span ==
466 extension.Subspan(lastAttribute.Begin(), lastAttribute.Length())) {
467 continue;
468 }
469 MOZ_ASSERT(attributesLess(lastAttribute, attribute));
470 }
471
472 if (!sb.append('-')) {
473 return Err(CanonicalizationError::OutOfMemory);
474 }
475 if (!AppendSpan(sb, span)) {
476 return Err(CanonicalizationError::OutOfMemory);
477 }
478 }
479
480 static constexpr size_t UnicodeKeyWithSepLength = UnicodeKeyLength + 1;
481
482 using StringSpan = Span<const char>;
483
484 static constexpr StringSpan True = MakeStringSpan("true");
485
486 // Append all Unicode extension keywords.
487 for (size_t i = 0; i < keywords.length(); i++) {
488 const auto& keyword = keywords[i];
489
490 // Skip duplicate keywords.
491 if (i > 0) {
492 const auto& lastKeyword = keywords[i - 1];
493 if (extension.Subspan(keyword.Begin(), UnicodeKeyLength) ==
494 extension.Subspan(lastKeyword.Begin(), UnicodeKeyLength)) {
495 continue;
496 }
497 MOZ_ASSERT(keywordsLess(lastKeyword, keyword));
498 }
499
500 if (!sb.append('-')) {
501 return Err(CanonicalizationError::OutOfMemory);
502 }
503
504 StringSpan span = extension.Subspan(keyword.Begin(), keyword.Length());
505 if (span.size() == UnicodeKeyLength) {
506 // Keyword without type value.
507 if (!AppendSpan(sb, span)) {
508 return Err(CanonicalizationError::OutOfMemory);
509 }
510 } else {
511 StringSpan key = span.To(UnicodeKeyLength);
512 StringSpan type = span.From(UnicodeKeyWithSepLength);
513
514 // Search if there's a replacement for the current Unicode keyword.
515 if (const char* replacement = ReplaceUnicodeExtensionType(key, type)) {
516 StringSpan repl = MakeStringSpan(replacement);
517 if (repl == True) {
518 // Elide the type "true" if present in the replacement.
519 if (!AppendSpan(sb, key)) {
520 return Err(CanonicalizationError::OutOfMemory);
521 }
522 } else {
523 // Otherwise append the Unicode key (including the separator) and the
524 // replaced type.
525 if (!AppendSpan(sb, span.To(UnicodeKeyWithSepLength))) {
526 return Err(CanonicalizationError::OutOfMemory);
527 }
528 if (!AppendSpan(sb, repl)) {
529 return Err(CanonicalizationError::OutOfMemory);
530 }
531 }
532 } else {
533 if (type == True) {
534 // Elide the Unicode extension type "true".
535 if (!AppendSpan(sb, key)) {
536 return Err(CanonicalizationError::OutOfMemory);
537 }
538 } else {
539 // Otherwise append the complete Unicode extension keyword.
540 if (!AppendSpan(sb, span)) {
541 return Err(CanonicalizationError::OutOfMemory);
542 }
543 }
544 }
545 }
546 }
547
548 // We can keep the previous extension when canonicalization didn't modify it.
549 if (static_cast<Span<const char>>(sb) != extension) {
550 // Otherwise replace the previous extension with the canonical extension.
551 UniqueChars canonical = DuplicateStringToUniqueChars(sb);
552 if (!canonical) {
553 return Err(CanonicalizationError::OutOfMemory);
554 }
555 aUnicodeExtension = std::move(canonical);
556 }
557
558 return Ok();
559 }
560
561 template <class Buffer>
562 static bool LocaleToString(const Locale& aTag, Buffer& aBuffer) {
563 auto appendSubtag = [&aBuffer](const auto& subtag) {
564 auto span = subtag.Span();
565 MOZ_ASSERT(!span.empty());
566 return aBuffer.append(span.data(), span.size());
567 };
568
569 auto appendSubtagSpan = [&aBuffer](Span<const char> subtag) {
570 MOZ_ASSERT(!subtag.empty());
571 return aBuffer.append(subtag.data(), subtag.size());
572 };
573
574 auto appendSubtags = [&aBuffer, &appendSubtagSpan](const auto& subtags) {
575 for (const auto& subtag : subtags) {
576 if (!aBuffer.append('-') || !appendSubtagSpan(subtag)) {
577 return false;
578 }
579 }
580 return true;
581 };
582
583 // Append the language subtag.
584 if (!appendSubtag(aTag.Language())) {
585 return false;
586 }
587
588 // Append the script subtag if present.
589 if (aTag.Script().Present()) {
590 if (!aBuffer.append('-') || !appendSubtag(aTag.Script())) {
591 return false;
592 }
593 }
594
595 // Append the region subtag if present.
596 if (aTag.Region().Present()) {
597 if (!aBuffer.append('-') || !appendSubtag(aTag.Region())) {
598 return false;
599 }
600 }
601
602 // Append the variant subtags if present.
603 if (!appendSubtags(aTag.Variants())) {
604 return false;
605 }
606
607 // Append the extensions subtags if present.
608 if (!appendSubtags(aTag.Extensions())) {
609 return false;
610 }
611
612 // Append the private-use subtag if present.
613 if (auto privateuse = aTag.PrivateUse()) {
614 if (!aBuffer.append('-') || !appendSubtagSpan(privateuse.value())) {
615 return false;
616 }
617 }
618
619 return true;
620 }
621
622 /**
623 * CanonicalizeTransformExtension
624 *
625 * Canonical form per <https://unicode.org/reports/tr35/#BCP47_T_Extension>:
626 *
627 * - These subtags are all in lowercase (that is the canonical casing for these
628 * subtags), [...].
629 *
630 * And per
631 * <https://unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>:
632 *
633 * - All keywords and tfields are sorted by alphabetical order of their keys,
634 * within their respective extensions.
635 */
636 Result<Ok, Locale::CanonicalizationError>
637 Locale::CanonicalizeTransformExtension(UniqueChars& aTransformExtension) {
638 Span<const char> extension = MakeStringSpan(aTransformExtension.get());
639 MOZ_ASSERT(extension[0] == 't');
640 MOZ_ASSERT(extension[1] == '-');
641 MOZ_ASSERT(IsStructurallyValidExtensionTag(extension));
642
643 Locale tag;
644 LocaleParser::TFieldVector fields;
645
646 using TField = LocaleParser::TFieldVector::ElementType;
647
648 if (LocaleParser::ParseTransformExtension(extension, tag, fields).isErr()) {
649 MOZ_ASSERT_UNREACHABLE("unexpected invalid transform extension subtag");
650 return Err(CanonicalizationError::InternalError);
651 }
652
653 auto tfieldLess = [extension](const TField& a, const TField& b) {
654 auto astr = extension.Subspan(a.Begin(), TransformKeyLength);
655 auto bstr = extension.Subspan(b.Begin(), TransformKeyLength);
656 return astr < bstr;
657 };
658
659 // All tfields are sorted by alphabetical order of their keys.
660 if (fields.length() > 1) {
661 std::stable_sort(fields.begin(), fields.end(), tfieldLess);
662 }
663
664 Vector<char, 32> sb;
665 if (!sb.append('t')) {
666 return Err(CanonicalizationError::OutOfMemory);
667 }
668
669 // Append the language subtag if present.
670 //
671 // Replace aliases in tlang per
672 // <https://unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>.
673 if (tag.Language().Present()) {
674 if (!sb.append('-')) {
675 return Err(CanonicalizationError::OutOfMemory);
676 }
677
678 MOZ_TRY(tag.CanonicalizeBaseName());
679
680 // The canonical case for Transform extensions is lowercase per
681 // <https://unicode.org/reports/tr35/#BCP47_T_Extension>. Convert the two
682 // subtags which don't use lowercase for their canonical syntax.
683 tag.mScript.ToLowerCase();
684 tag.mRegion.ToLowerCase();
685
686 if (!LocaleToString(tag, sb)) {
687 return Err(CanonicalizationError::OutOfMemory);
688 }
689 }
690
691 static constexpr size_t TransformKeyWithSepLength = TransformKeyLength + 1;
692
693 using StringSpan = Span<const char>;
694
695 // Append all fields.
696 //
697 // UTS 35, 3.2.1 specifies:
698 // - Any type or tfield value "true" is removed.
699 //
700 // But the `tvalue` subtag is mandatory in `tfield: tkey tvalue`, so ignore
701 // this apparently invalid part of the UTS 35 specification and simply
702 // append all `tfield` subtags.
703 for (const auto& field : fields) {
704 if (!sb.append('-')) {
705 return Err(CanonicalizationError::OutOfMemory);
706 }
707
708 StringSpan span = extension.Subspan(field.Begin(), field.Length());
709 StringSpan key = span.To(TransformKeyLength);
710 StringSpan value = span.From(TransformKeyWithSepLength);
711
712 // Search if there's a replacement for the current transform keyword.
713 if (const char* replacement = ReplaceTransformExtensionType(key, value)) {
714 if (!AppendSpan(sb, span.To(TransformKeyWithSepLength))) {
715 return Err(CanonicalizationError::OutOfMemory);
716 }
717 if (!AppendSpan(sb, MakeStringSpan(replacement))) {
718 return Err(CanonicalizationError::OutOfMemory);
719 }
720 } else {
721 if (!AppendSpan(sb, span)) {
722 return Err(CanonicalizationError::OutOfMemory);
723 }
724 }
725 }
726
727 // We can keep the previous extension when canonicalization didn't modify it.
728 if (static_cast<Span<const char>>(sb) != extension) {
729 // Otherwise replace the previous extension with the canonical extension.
730 UniqueChars canonical = DuplicateStringToUniqueChars(sb);
731 if (!canonical) {
732 return Err(CanonicalizationError::OutOfMemory);
733 }
734 aTransformExtension = std::move(canonical);
735 }
736
737 return Ok();
738 }
739
740 // Zero-terminated ICU Locale ID.
741 using LocaleId =
742 Vector<char, LanguageLength + 1 + ScriptLength + 1 + RegionLength + 1>;
743
744 enum class LikelySubtags : bool { Add, Remove };
745
746 // Return true iff the locale is already maximized resp. minimized.
747 static bool HasLikelySubtags(LikelySubtags aLikelySubtags, const Locale& aTag) {
748 // The locale is already maximized if the language, script, and region
749 // subtags are present and no placeholder subtags ("und", "Zzzz", "ZZ") are
750 // used.
751 if (aLikelySubtags == LikelySubtags::Add) {
752 return !aTag.Language().EqualTo("und") &&
753 (aTag.Script().Present() && !aTag.Script().EqualTo("Zzzz")) &&
754 (aTag.Region().Present() && !aTag.Region().EqualTo("ZZ"));
755 }
756
757 // The locale is already minimized if it only contains a language
758 // subtag whose value is not the placeholder value "und".
759 return !aTag.Language().EqualTo("und") && aTag.Script().Missing() &&
760 aTag.Region().Missing();
761 }
762
763 // Create an ICU locale ID from the given locale.
764 static bool CreateLocaleForLikelySubtags(const Locale& aTag,
765 LocaleId& aLocale) {
766 MOZ_ASSERT(aLocale.length() == 0);
767
768 auto appendSubtag = [&aLocale](const auto& subtag) {
769 auto span = subtag.Span();
770 MOZ_ASSERT(!span.empty());
771 return aLocale.append(span.data(), span.size());
772 };
773
774 // Append the language subtag.
775 if (!appendSubtag(aTag.Language())) {
776 return false;
777 }
778
779 // Append the script subtag if present.
780 if (aTag.Script().Present()) {
781 if (!aLocale.append('_') || !appendSubtag(aTag.Script())) {
782 return false;
783 }
784 }
785
786 // Append the region subtag if present.
787 if (aTag.Region().Present()) {
788 if (!aLocale.append('_') || !appendSubtag(aTag.Region())) {
789 return false;
790 }
791 }
792
793 // Zero-terminated for use with ICU.
794 return aLocale.append('\0');
795 }
796
797 static ICUError ParserErrorToICUError(LocaleParser::ParserError aErr) {
798 using ParserError = LocaleParser::ParserError;
799
800 switch (aErr) {
801 case ParserError::NotParseable:
802 return ICUError::InternalError;
803 case ParserError::OutOfMemory:
804 return ICUError::OutOfMemory;
805 }
806 MOZ_CRASH("Unexpected parser error");
807 }
808
809 static ICUError CanonicalizationErrorToICUError(
810 Locale::CanonicalizationError aErr) {
811 using CanonicalizationError = Locale::CanonicalizationError;
812
813 switch (aErr) {
814 case CanonicalizationError::DuplicateVariant:
815 case CanonicalizationError::InternalError:
816 return ICUError::InternalError;
817 case CanonicalizationError::OutOfMemory:
818 return ICUError::OutOfMemory;
819 }
820 MOZ_CRASH("Unexpected canonicalization error");
821 }
822
823 // Assign the language, script, and region subtags from an ICU locale ID.
824 //
825 // ICU provides |uloc_getLanguage|, |uloc_getScript|, and |uloc_getCountry| to
826 // retrieve these subtags, but unfortunately these functions are rather slow, so
827 // we use our own implementation.
828 static ICUResult AssignFromLocaleId(LocaleId& aLocaleId, Locale& aTag) {
829 // Replace the ICU locale ID separator.
830 std::replace(aLocaleId.begin(), aLocaleId.end(), '_', '-');
831
832 // ICU replaces "und" with the empty string, which means "und" becomes "" and
833 // "und-Latn" becomes "-Latn". Handle this case separately.
834 if (aLocaleId.empty() || aLocaleId[0] == '-') {
835 static constexpr auto und = MakeStringSpan("und");
836 constexpr size_t length = und.size();
837
838 // Insert "und" in front of the locale ID.
839 if (!aLocaleId.growBy(length)) {
840 return Err(ICUError::OutOfMemory);
841 }
842 memmove(aLocaleId.begin() + length, aLocaleId.begin(), aLocaleId.length());
843 memmove(aLocaleId.begin(), und.data(), length);
844 }
845
846 // Retrieve the language, script, and region subtags from the locale ID
847 Locale localeTag;
848 MOZ_TRY(LocaleParser::TryParseBaseName(aLocaleId, localeTag)
849 .mapErr(ParserErrorToICUError));
850
851 aTag.SetLanguage(localeTag.Language());
852 aTag.SetScript(localeTag.Script());
853 aTag.SetRegion(localeTag.Region());
854
855 return Ok();
856 }
857
858 template <decltype(uloc_addLikelySubtags) likelySubtagsFn>
859 static ICUResult CallLikelySubtags(const LocaleId& aLocaleId,
860 LocaleId& aResult) {
861 // Locale ID must be zero-terminated before passing it to ICU.
862 MOZ_ASSERT(aLocaleId.back() == '\0');
863 MOZ_ASSERT(aResult.length() == 0);
864
865 // Ensure there's enough room for the result.
866 MOZ_ALWAYS_TRUE(aResult.resize(LocaleId::InlineLength));
867
868 return FillBufferWithICUCall(
869 aResult, [&aLocaleId](char* chars, int32_t size, UErrorCode* status) {
870 return likelySubtagsFn(aLocaleId.begin(), chars, size, status);
871 });
872 }
873
874 // The canonical way to compute the Unicode BCP 47 locale identifier with likely
875 // subtags is as follows:
876 //
877 // 1. Call uloc_forLanguageTag() to transform the locale identifer into an ICU
878 // locale ID.
879 // 2. Call uloc_addLikelySubtags() to add the likely subtags to the locale ID.
880 // 3. Call uloc_toLanguageTag() to transform the resulting locale ID back into
881 // a Unicode BCP 47 locale identifier.
882 //
883 // Since uloc_forLanguageTag() and uloc_toLanguageTag() are both kind of slow
884 // and we know, by construction, that the input Unicode BCP 47 locale identifier
885 // only contains valid language, script, and region subtags, we can avoid both
886 // calls if we implement them ourselves, see CreateLocaleForLikelySubtags() and
887 // AssignFromLocaleId(). (Where "slow" means about 50% of the execution time of
888 // |Intl.Locale.prototype.maximize|.)
889 static ICUResult LikelySubtags(LikelySubtags aLikelySubtags, Locale& aTag) {
890 // Return early if the input is already maximized/minimized.
891 if (HasLikelySubtags(aLikelySubtags, aTag)) {
892 return Ok();
893 }
894
895 // Create the locale ID for the input argument.
896 LocaleId locale;
897 if (!CreateLocaleForLikelySubtags(aTag, locale)) {
898 return Err(ICUError::OutOfMemory);
899 }
900
901 // Either add or remove likely subtags to/from the locale ID.
902 LocaleId localeLikelySubtags;
903 if (aLikelySubtags == LikelySubtags::Add) {
904 MOZ_TRY(
905 CallLikelySubtags<uloc_addLikelySubtags>(locale, localeLikelySubtags));
906 } else {
907 MOZ_TRY(
908 CallLikelySubtags<uloc_minimizeSubtags>(locale, localeLikelySubtags));
909 }
910
911 // Assign the language, script, and region subtags from the locale ID.
912 MOZ_TRY(AssignFromLocaleId(localeLikelySubtags, aTag));
913
914 // Update mappings in case ICU returned a non-canonical locale.
915 MOZ_TRY(aTag.CanonicalizeBaseName().mapErr(CanonicalizationErrorToICUError));
916
917 return Ok();
918 }
919
920 ICUResult Locale::AddLikelySubtags() {
921 return LikelySubtags(LikelySubtags::Add, *this);
922 }
923
924 ICUResult Locale::RemoveLikelySubtags() {
925 return LikelySubtags(LikelySubtags::Remove, *this);
926 }
927
928 UniqueChars Locale::DuplicateStringToUniqueChars(const char* aStr) {
929 size_t length = strlen(aStr) + 1;
930 auto duplicate = MakeUnique<char[]>(length);
931 memcpy(duplicate.get(), aStr, length);
932 return duplicate;
933 }
934
935 UniqueChars Locale::DuplicateStringToUniqueChars(Span<const char> aStr) {
936 size_t length = aStr.size();
937 auto duplicate = MakeUnique<char[]>(length + 1);
938 memcpy(duplicate.get(), aStr.data(), length);
939 duplicate[length] = '\0';
940 return duplicate;
941 }
942
943 size_t Locale::ToStringCapacity() const {
944 // This is a bit awkward, the buffer class currently does not support
945 // being resized, so we need to calculate the required size up front and
946 // reserve it all at once.
947 auto lengthSubtag = [](const auto& subtag) {
948 auto span = subtag.Span();
949 MOZ_ASSERT(!span.empty());
950 return span.size();
951 };
952
953 auto lengthSubtagZ = [](const char* subtag) {
954 size_t length = strlen(subtag);
955 MOZ_ASSERT(length > 0);
956 return length;
957 };
958
959 auto lengthSubtagsZ = [&lengthSubtagZ](const auto& subtags) {
960 size_t length = 0;
961 for (const auto& subtag : subtags) {
962 length += lengthSubtagZ(subtag.get()) + 1;
963 }
964 return length;
965 };
966
967 // First calculate required capacity
968 size_t capacity = 0;
969
970 capacity += lengthSubtag(mLanguage);
971
972 if (mScript.Present()) {
973 capacity += lengthSubtag(mScript) + 1;
974 }
975
976 if (mRegion.Present()) {
977 capacity += lengthSubtag(mRegion) + 1;
978 }
979
980 capacity += lengthSubtagsZ(mVariants);
981
982 capacity += lengthSubtagsZ(mExtensions);
983
984 if (mPrivateUse.get()) {
985 capacity += lengthSubtagZ(mPrivateUse.get()) + 1;
986 }
987
988 return capacity;
989 }
990
991 size_t Locale::ToStringAppend(char* aBuffer) const {
992 // Current write position inside buffer.
993 size_t offset = 0;
994
995 auto appendHyphen = [&offset, &aBuffer]() {
996 aBuffer[offset] = '-';
997 offset += 1;
998 };
999
1000 auto appendSubtag = [&offset, &aBuffer](const auto& subtag) {
1001 auto span = subtag.Span();
1002 memcpy(aBuffer + offset, span.data(), span.size());
1003 offset += span.size();
1004 };
1005
1006 auto appendSubtagZ = [&offset, &aBuffer](const char* subtag) {
1007 size_t length = strlen(subtag);
1008 memcpy(aBuffer + offset, subtag, length);
1009 offset += length;
1010 };
1011
1012 auto appendSubtagsZ = [&appendHyphen, &appendSubtagZ](const auto& subtags) {
1013 for (const auto& subtag : subtags) {
1014 appendHyphen();
1015 appendSubtagZ(subtag.get());
1016 }
1017 };
1018
1019 // Append the language subtag.
1020 appendSubtag(mLanguage);
1021
1022 // Append the script subtag if present.
1023 if (mScript.Present()) {
1024 appendHyphen();
1025 appendSubtag(mScript);
1026 }
1027
1028 // Append the region subtag if present.
1029 if (mRegion.Present()) {
1030 appendHyphen();
1031 appendSubtag(mRegion);
1032 }
1033
1034 // Append the variant subtags if present.
1035 appendSubtagsZ(mVariants);
1036
1037 // Append the extensions subtags if present.
1038 appendSubtagsZ(mExtensions);
1039
1040 // Append the private-use subtag if present.
1041 if (mPrivateUse.get()) {
1042 appendHyphen();
1043 appendSubtagZ(mPrivateUse.get());
1044 }
1045
1046 return offset;
1047 }
1048
1049 LocaleParser::Token LocaleParser::NextToken() {
1050 MOZ_ASSERT(mIndex <= mLength + 1, "called after 'None' token was read");
1051
1052 TokenKind kind = TokenKind::None;
1053 size_t tokenLength = 0;
1054 for (size_t i = mIndex; i < mLength; i++) {
1055 // UTS 35, section 3.1.
1056 // alpha = [A-Z a-z] ;
1057 // digit = [0-9] ;
1058 char c = CharAt(i);
1059 if (IsAsciiAlpha(c)) {
1060 kind |= TokenKind::Alpha;
1061 } else if (IsAsciiDigit(c)) {
1062 kind |= TokenKind::Digit;
1063 } else if (c == '-' && i > mIndex && i + 1 < mLength) {
1064 break;
1065 } else {
1066 return {TokenKind::Error, 0, 0};
1067 }
1068 tokenLength += 1;
1069 }
1070
1071 Token token{kind, mIndex, tokenLength};
1072 mIndex += tokenLength + 1;
1073 return token;
1074 }
1075
1076 UniqueChars LocaleParser::Chars(size_t aIndex, size_t aLength) const {
1077 // Add +1 to null-terminate the string.
1078 auto chars = MakeUnique<char[]>(aLength + 1);
1079 char* dest = chars.get();
1080 std::copy_n(mLocale + aIndex, aLength, dest);
1081 dest[aLength] = '\0';
1082 return chars;
1083 }
1084
1085 // Parse the `unicode_language_id` production.
1086 //
1087 // unicode_language_id = unicode_language_subtag
1088 // (sep unicode_script_subtag)?
1089 // (sep unicode_region_subtag)?
1090 // (sep unicode_variant_subtag)* ;
1091 //
1092 // sep = "-"
1093 //
1094 // Note: Unicode CLDR locale identifier backward compatibility extensions
1095 // removed from `unicode_language_id`.
1096 //
1097 // |tok| is the current token from |ts|.
1098 //
1099 // All subtags will be added unaltered to |tag|, without canonicalizing their
1100 // case or, in the case of variant subtags, detecting and rejecting duplicate
1101 // variants. Users must subsequently |CanonicalizeBaseName| to perform these
1102 // actions.
1103 //
1104 // Do not use this function directly: use |ParseBaseName| or
1105 // |ParseTlangFromTransformExtension| instead.
1106 Result<Ok, LocaleParser::ParserError> LocaleParser::InternalParseBaseName(
1107 LocaleParser& aLocaleParser, Locale& aTag, Token& aTok) {
1108 if (aLocaleParser.IsLanguage(aTok)) {
1109 aLocaleParser.CopyChars(aTok, aTag.mLanguage);
1110
1111 aTok = aLocaleParser.NextToken();
1112 } else {
1113 // The language subtag is mandatory.
1114 return Err(ParserError::NotParseable);
1115 }
1116
1117 if (aLocaleParser.IsScript(aTok)) {
1118 aLocaleParser.CopyChars(aTok, aTag.mScript);
1119
1120 aTok = aLocaleParser.NextToken();
1121 }
1122
1123 if (aLocaleParser.IsRegion(aTok)) {
1124 aLocaleParser.CopyChars(aTok, aTag.mRegion);
1125
1126 aTok = aLocaleParser.NextToken();
1127 }
1128
1129 auto& variants = aTag.mVariants;
1130 MOZ_ASSERT(variants.length() == 0);
1131 while (aLocaleParser.IsVariant(aTok)) {
1132 auto variant = aLocaleParser.Chars(aTok);
1133 if (!variants.append(std::move(variant))) {
1134 return Err(ParserError::OutOfMemory);
1135 }
1136
1137 aTok = aLocaleParser.NextToken();
1138 }
1139
1140 return Ok();
1141 }
1142
1143 Result<Ok, LocaleParser::ParserError> LocaleParser::TryParse(
1144 mozilla::Span<const char> aLocale, Locale& aTag) {
1145 // |aTag| must be a new, empty Locale.
1146 MOZ_ASSERT(aTag.Language().Missing());
1147 MOZ_ASSERT(aTag.Script().Missing());
1148 MOZ_ASSERT(aTag.Region().Missing());
1149 MOZ_ASSERT(aTag.Variants().empty());
1150 MOZ_ASSERT(aTag.Extensions().empty());
1151 MOZ_ASSERT(aTag.PrivateUse().isNothing());
1152
1153 // unicode_locale_id = unicode_language_id
1154 // extensions*
1155 // pu_extensions? ;
1156
1157 LocaleParser ts(aLocale);
1158 Token tok = ts.NextToken();
1159
1160 MOZ_TRY(ParseBaseName(ts, aTag, tok));
1161
1162 // extensions = unicode_locale_extensions
1163 // | transformed_extensions
1164 // | other_extensions ;
1165
1166 // Bit set of seen singletons.
1167 uint64_t seenSingletons = 0;
1168
1169 auto& extensions = aTag.mExtensions;
1170 while (ts.IsExtensionStart(tok)) {
1171 char singleton = ts.SingletonKey(tok);
1172
1173 // Reject the input if a duplicate singleton was found.
1174 uint64_t hash = 1ULL << (AsciiAlphanumericToNumber(singleton) + 1);
1175 if (seenSingletons & hash) {
1176 return Err(ParserError::NotParseable);
1177 }
1178 seenSingletons |= hash;
1179
1180 Token start = tok;
1181 tok = ts.NextToken();
1182
1183 // We'll check for missing non-singleton subtags after this block by
1184 // comparing |startValue| with the then-current position.
1185 size_t startValue = tok.Index();
1186
1187 if (singleton == 'u') {
1188 while (ts.IsUnicodeExtensionPart(tok)) {
1189 tok = ts.NextToken();
1190 }
1191 } else if (singleton == 't') {
1192 // transformed_extensions = sep [tT]
1193 // ((sep tlang (sep tfield)*)
1194 // | (sep tfield)+) ;
1195
1196 // tlang = unicode_language_subtag
1197 // (sep unicode_script_subtag)?
1198 // (sep unicode_region_subtag)?
1199 // (sep unicode_variant_subtag)* ;
1200 if (ts.IsLanguage(tok)) {
1201 tok = ts.NextToken();
1202
1203 if (ts.IsScript(tok)) {
1204 tok = ts.NextToken();
1205 }
1206
1207 if (ts.IsRegion(tok)) {
1208 tok = ts.NextToken();
1209 }
1210
1211 while (ts.IsVariant(tok)) {
1212 tok = ts.NextToken();
1213 }
1214 }
1215
1216 // tfield = tkey tvalue;
1217 while (ts.IsTransformExtensionKey(tok)) {
1218 tok = ts.NextToken();
1219
1220 size_t startTValue = tok.Index();
1221 while (ts.IsTransformExtensionPart(tok)) {
1222 tok = ts.NextToken();
1223 }
1224
1225 // `tfield` requires at least one `tvalue`.
1226 if (tok.Index() <= startTValue) {
1227 return Err(ParserError::NotParseable);
1228 }
1229 }
1230 } else {
1231 while (ts.IsOtherExtensionPart(tok)) {
1232 tok = ts.NextToken();
1233 }
1234 }
1235
1236 // Singletons must be followed by a non-singleton subtag, "en-a-b" is not
1237 // allowed.
1238 if (tok.Index() <= startValue) {
1239 return Err(ParserError::NotParseable);
1240 }
1241
1242 UniqueChars extension = ts.Extension(start, tok);
1243 if (!extensions.append(std::move(extension))) {
1244 return Err(ParserError::OutOfMemory);
1245 }
1246 }
1247
1248 // Trailing `pu_extension` component of the `unicode_locale_id` production.
1249 if (ts.IsPrivateUseStart(tok)) {
1250 Token start = tok;
1251 tok = ts.NextToken();
1252
1253 size_t startValue = tok.Index();
1254 while (ts.IsPrivateUsePart(tok)) {
1255 tok = ts.NextToken();
1256 }
1257
1258 // There must be at least one subtag after the "-x-".
1259 if (tok.Index() <= startValue) {
1260 return Err(ParserError::NotParseable);
1261 }
1262
1263 UniqueChars privateUse = ts.Extension(start, tok);
1264 aTag.mPrivateUse = std::move(privateUse);
1265 }
1266
1267 if (!tok.IsNone()) {
1268 return Err(ParserError::NotParseable);
1269 }
1270
1271 return Ok();
1272 }
1273
1274 Result<Ok, LocaleParser::ParserError> LocaleParser::TryParseBaseName(
1275 Span<const char> aLocale, Locale& aTag) {
1276 // |aTag| must be a new, empty Locale.
1277 MOZ_ASSERT(aTag.Language().Missing());
1278 MOZ_ASSERT(aTag.Script().Missing());
1279 MOZ_ASSERT(aTag.Region().Missing());
1280 MOZ_ASSERT(aTag.Variants().empty());
1281 MOZ_ASSERT(aTag.Extensions().empty());
1282 MOZ_ASSERT(aTag.PrivateUse().isNothing());
1283
1284 LocaleParser ts(aLocale);
1285 Token tok = ts.NextToken();
1286
1287 MOZ_TRY(ParseBaseName(ts, aTag, tok));
1288 if (!tok.IsNone()) {
1289 return Err(ParserError::NotParseable);
1290 }
1291
1292 return Ok();
1293 }
1294
1295 // Parse |aExtension|, which must be a valid `transformed_extensions` subtag,
1296 // and fill |aTag| and |aFields| from the `tlang` and `tfield` components.
1297 Result<Ok, LocaleParser::ParserError> LocaleParser::ParseTransformExtension(
1298 Span<const char> aExtension, Locale& aTag, TFieldVector& aFields) {
1299 LocaleParser ts(aExtension);
1300 Token tok = ts.NextToken();
1301
1302 if (!ts.IsExtensionStart(tok) || ts.SingletonKey(tok) != 't') {
1303 return Err(ParserError::NotParseable);
1304 }
1305
1306 tok = ts.NextToken();
1307
1308 if (tok.IsNone()) {
1309 return Err(ParserError::NotParseable);
1310 }
1311
1312 if (ts.IsLanguage(tok)) {
1313 // We're parsing a possible `tlang` in a known-valid transform extension, so
1314 // use the special-purpose function that takes advantage of this to compute
1315 // lowercased |tag| contents in an optimal manner.
1316 MOZ_TRY(ParseTlangInTransformExtension(ts, aTag, tok));
1317
1318 // After `tlang` we must have a `tfield` and its `tkey`, or we're at the end
1319 // of the transform extension.
1320 MOZ_ASSERT(ts.IsTransformExtensionKey(tok) || tok.IsNone());
1321 } else {
1322 // If there's no `tlang` subtag, at least one `tfield` must be present.
1323 MOZ_ASSERT(ts.IsTransformExtensionKey(tok));
1324 }
1325
1326 // Trailing `tfield` subtags. (Any other trailing subtags are an error,
1327 // because we're guaranteed to only see a valid tranform extension here.)
1328 while (ts.IsTransformExtensionKey(tok)) {
1329 size_t begin = tok.Index();
1330 tok = ts.NextToken();
1331
1332 size_t startTValue = tok.Index();
1333 while (ts.IsTransformExtensionPart(tok)) {
1334 tok = ts.NextToken();
1335 }
1336
1337 // `tfield` requires at least one `tvalue`.
1338 if (tok.Index() <= startTValue) {
1339 return Err(ParserError::NotParseable);
1340 }
1341
1342 size_t length = tok.Index() - 1 - begin;
1343 if (!aFields.emplaceBack(begin, length)) {
1344 return Err(ParserError::OutOfMemory);
1345 }
1346 }
1347
1348 if (!tok.IsNone()) {
1349 return Err(ParserError::NotParseable);
1350 }
1351
1352 return Ok();
1353 }
1354
1355 // Parse |aExtension|, which must be a valid `unicode_locale_extensions` subtag,
1356 // and fill |aAttributes| and |aKeywords| from the `attribute` and `keyword`
1357 // components.
1358 Result<Ok, LocaleParser::ParserError> LocaleParser::ParseUnicodeExtension(
1359 Span<const char> aExtension, AttributesVector& aAttributes,
1360 KeywordsVector& aKeywords) {
1361 LocaleParser ts(aExtension);
1362 Token tok = ts.NextToken();
1363
1364 // unicode_locale_extensions = sep [uU] ((sep keyword)+ |
1365 // (sep attribute)+ (sep keyword)*) ;
1366
1367 if (!ts.IsExtensionStart(tok) || ts.SingletonKey(tok) != 'u') {
1368 return Err(ParserError::NotParseable);
1369 }
1370
1371 tok = ts.NextToken();
1372
1373 if (tok.IsNone()) {
1374 return Err(ParserError::NotParseable);
1375 }
1376
1377 while (ts.IsUnicodeExtensionAttribute(tok)) {
1378 if (!aAttributes.emplaceBack(tok.Index(), tok.Length())) {
1379 return Err(ParserError::OutOfMemory);
1380 }
1381
1382 tok = ts.NextToken();
1383 }
1384
1385 // keyword = key (sep type)? ;
1386 while (ts.IsUnicodeExtensionKey(tok)) {
1387 size_t begin = tok.Index();
1388 tok = ts.NextToken();
1389
1390 while (ts.IsUnicodeExtensionType(tok)) {
1391 tok = ts.NextToken();
1392 }
1393
1394 if (tok.IsError()) {
1395 return Err(ParserError::NotParseable);
1396 }
1397
1398 size_t length = tok.Index() - 1 - begin;
1399 if (!aKeywords.emplaceBack(begin, length)) {
1400 return Err(ParserError::OutOfMemory);
1401 }
1402 }
1403
1404 if (!tok.IsNone()) {
1405 return Err(ParserError::NotParseable);
1406 }
1407
1408 return Ok();
1409 }
1410
1411 Result<Ok, LocaleParser::ParserError> LocaleParser::CanParseUnicodeExtension(
1412 Span<const char> aExtension) {
1413 LocaleParser ts(aExtension);
1414 Token tok = ts.NextToken();
1415
1416 // unicode_locale_extensions = sep [uU] ((sep keyword)+ |
1417 // (sep attribute)+ (sep keyword)*) ;
1418
1419 if (!ts.IsExtensionStart(tok) || ts.SingletonKey(tok) != 'u') {
1420 return Err(ParserError::NotParseable);
1421 }
1422
1423 tok = ts.NextToken();
1424
1425 if (tok.IsNone()) {
1426 return Err(ParserError::NotParseable);
1427 }
1428
1429 while (ts.IsUnicodeExtensionAttribute(tok)) {
1430 tok = ts.NextToken();
1431 }
1432
1433 // keyword = key (sep type)? ;
1434 while (ts.IsUnicodeExtensionKey(tok)) {
1435 tok = ts.NextToken();
1436
1437 while (ts.IsUnicodeExtensionType(tok)) {
1438 tok = ts.NextToken();
1439 }
1440
1441 if (tok.IsError()) {
1442 return Err(ParserError::NotParseable);
1443 }
1444 }
1445
1446 if (!tok.IsNone()) {
1447 return Err(ParserError::OutOfMemory);
1448 }
1449
1450 return Ok();
1451 }
1452
1453 Result<Ok, LocaleParser::ParserError>
1454 LocaleParser::CanParseUnicodeExtensionType(Span<const char> aUnicodeType) {
1455 MOZ_ASSERT(!aUnicodeType.empty(), "caller must exclude empty strings");
1456
1457 LocaleParser ts(aUnicodeType);
1458 Token tok = ts.NextToken();
1459
1460 while (ts.IsUnicodeExtensionType(tok)) {
1461 tok = ts.NextToken();
1462 }
1463
1464 if (!tok.IsNone()) {
1465 return Err(ParserError::NotParseable);
1466 }
1467
1468 return Ok();
1469 }
1470
1471 } // namespace mozilla::intl