| 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 |
/* Structured representation of Unicode locale IDs used with Intl functions. */ |
| 6 |
|
| 7 |
#ifndef intl_components_Locale_h |
| 8 |
#define intl_components_Locale_h |
| 9 |
|
| 10 |
#include "mozilla/Assertions.h" |
| 11 |
#include "mozilla/intl/ICUError.h" |
| 12 |
#include "mozilla/intl/ICU4CGlue.h" |
| 13 |
#include "mozilla/Maybe.h" |
| 14 |
#include "mozilla/Span.h" |
| 15 |
#include "mozilla/TextUtils.h" |
| 16 |
#include "mozilla/Try.h" |
| 17 |
#include "mozilla/TypedEnumBits.h" |
| 18 |
#include "mozilla/Variant.h" |
| 19 |
#include "mozilla/Vector.h" |
| 20 |
|
| 21 |
#include <algorithm> |
| 22 |
#include <stddef.h> |
| 23 |
#include <stdint.h> |
| 24 |
#include <string.h> |
| 25 |
#include <utility> |
| 26 |
|
| 27 |
#include "unicode/uloc.h" |
| 28 |
|
| 29 |
namespace mozilla::intl { |
| 30 |
|
| 31 |
/** |
| 32 |
* Return true if |language| is a valid language subtag. |
| 33 |
*/ |
| 34 |
template <typename CharT> |
| 35 |
bool IsStructurallyValidLanguageTag(mozilla::Span<const CharT> aLanguage); |
| 36 |
|
| 37 |
/** |
| 38 |
* Return true if |script| is a valid script subtag. |
| 39 |
*/ |
| 40 |
template <typename CharT> |
| 41 |
bool IsStructurallyValidScriptTag(mozilla::Span<const CharT> aScript); |
| 42 |
|
| 43 |
/** |
| 44 |
* Return true if |region| is a valid region subtag. |
| 45 |
*/ |
| 46 |
template <typename CharT> |
| 47 |
bool IsStructurallyValidRegionTag(mozilla::Span<const CharT> aRegion); |
| 48 |
|
| 49 |
#ifdef DEBUG |
| 50 |
/** |
| 51 |
* Return true if |variant| is a valid variant subtag. |
| 52 |
*/ |
| 53 |
bool IsStructurallyValidVariantTag(mozilla::Span<const char> aVariant); |
| 54 |
|
| 55 |
/** |
| 56 |
* Return true if |extension| is a valid Unicode extension subtag. |
| 57 |
*/ |
| 58 |
bool IsStructurallyValidUnicodeExtensionTag( |
| 59 |
mozilla::Span<const char> aExtension); |
| 60 |
|
| 61 |
/** |
| 62 |
* Return true if |privateUse| is a valid private-use subtag. |
| 63 |
*/ |
| 64 |
bool IsStructurallyValidPrivateUseTag(mozilla::Span<const char> aPrivateUse); |
| 65 |
|
| 66 |
#endif |
| 67 |
|
| 68 |
template <typename CharT> |
| 69 |
char AsciiToLowerCase(CharT aChar) { |
| 70 |
MOZ_ASSERT(mozilla::IsAscii(aChar)); |
| 71 |
return mozilla::IsAsciiUppercaseAlpha(aChar) ? (aChar + 0x20) : aChar; |
| 72 |
} |
| 73 |
|
| 74 |
template <typename CharT> |
| 75 |
char AsciiToUpperCase(CharT aChar) { |
| 76 |
MOZ_ASSERT(mozilla::IsAscii(aChar)); |
| 77 |
return mozilla::IsAsciiLowercaseAlpha(aChar) ? (aChar - 0x20) : aChar; |
| 78 |
} |
| 79 |
|
| 80 |
template <typename CharT> |
| 81 |
void AsciiToLowerCase(CharT* aChars, size_t aLength, char* aDest) { |
| 82 |
char (&fn)(CharT) = AsciiToLowerCase; |
| 83 |
std::transform(aChars, aChars + aLength, aDest, fn); |
| 84 |
} |
| 85 |
|
| 86 |
template <typename CharT> |
| 87 |
void AsciiToUpperCase(CharT* aChars, size_t aLength, char* aDest) { |
| 88 |
char (&fn)(CharT) = AsciiToUpperCase; |
| 89 |
std::transform(aChars, aChars + aLength, aDest, fn); |
| 90 |
} |
| 91 |
|
| 92 |
template <typename CharT> |
| 93 |
void AsciiToTitleCase(CharT* aChars, size_t aLength, char* aDest) { |
| 94 |
if (aLength > 0) { |
| 95 |
AsciiToUpperCase(aChars, 1, aDest); |
| 96 |
AsciiToLowerCase(aChars + 1, aLength - 1, aDest + 1); |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
// Constants for language subtag lengths. |
| 101 |
namespace LanguageTagLimits { |
| 102 |
|
| 103 |
// unicode_language_subtag = alpha{2,3} | alpha{5,8} ; |
| 104 |
static constexpr size_t LanguageLength = 8; |
| 105 |
|
| 106 |
// unicode_script_subtag = alpha{4} ; |
| 107 |
static constexpr size_t ScriptLength = 4; |
| 108 |
|
| 109 |
// unicode_region_subtag = (alpha{2} | digit{3}) ; |
| 110 |
static constexpr size_t RegionLength = 3; |
| 111 |
static constexpr size_t AlphaRegionLength = 2; |
| 112 |
static constexpr size_t DigitRegionLength = 3; |
| 113 |
|
| 114 |
// key = alphanum alpha ; |
| 115 |
static constexpr size_t UnicodeKeyLength = 2; |
| 116 |
|
| 117 |
// tkey = alpha digit ; |
| 118 |
static constexpr size_t TransformKeyLength = 2; |
| 119 |
|
| 120 |
} // namespace LanguageTagLimits |
| 121 |
|
| 122 |
// Fixed size language subtag which is stored inline in Locale. |
| 123 |
template <size_t SubtagLength> |
| 124 |
class LanguageTagSubtag final { |
| 125 |
uint8_t mLength = 0; |
| 126 |
char mChars[SubtagLength] = {}; // zero initialize |
| 127 |
|
| 128 |
public: |
| 129 |
LanguageTagSubtag() = default; |
| 130 |
|
| 131 |
LanguageTagSubtag(const LanguageTagSubtag& aOther) { |
| 132 |
std::copy_n(aOther.mChars, SubtagLength, mChars); |
| 133 |
mLength = aOther.mLength; |
| 134 |
} |
| 135 |
|
| 136 |
LanguageTagSubtag& operator=(const LanguageTagSubtag& aOther) { |
| 137 |
std::copy_n(aOther.mChars, SubtagLength, mChars); |
| 138 |
mLength = aOther.mLength; |
| 139 |
return *this; |
| 140 |
} |
| 141 |
|
| 142 |
size_t Length() const { return mLength; } |
| 143 |
bool Missing() const { return mLength == 0; } |
| 144 |
bool Present() const { return mLength > 0; } |
| 145 |
|
| 146 |
mozilla::Span<const char> Span() const { return {mChars, mLength}; } |
| 147 |
|
| 148 |
template <typename CharT> |
| 149 |
void Set(mozilla::Span<const CharT> str) { |
| 150 |
MOZ_ASSERT(str.size() <= SubtagLength); |
| 151 |
std::copy_n(str.data(), str.size(), mChars); |
| 152 |
mLength = str.size(); |
| 153 |
} |
| 154 |
|
| 155 |
// The toXYZCase() methods are using |SubtagLength| instead of |length()|, |
| 156 |
// because current compilers (tested GCC and Clang) can't infer the maximum |
| 157 |
// string length - even when using hints like |std::min| - and instead are |
| 158 |
// emitting SIMD optimized code. Using a fixed sized length avoids emitting |
| 159 |
// the SIMD code. (Emitting SIMD code doesn't make sense here, because the |
| 160 |
// SIMD code only kicks in for long strings.) A fixed length will |
| 161 |
// additionally ensure the compiler unrolls the loop in the case conversion |
| 162 |
// code. |
| 163 |
|
| 164 |
void ToLowerCase() { AsciiToLowerCase(mChars, SubtagLength, mChars); } |
| 165 |
|
| 166 |
void ToUpperCase() { AsciiToUpperCase(mChars, SubtagLength, mChars); } |
| 167 |
|
| 168 |
void ToTitleCase() { AsciiToTitleCase(mChars, SubtagLength, mChars); } |
| 169 |
|
| 170 |
template <size_t N> |
| 171 |
bool EqualTo(const char (&str)[N]) const { |
| 172 |
static_assert(N - 1 <= SubtagLength, |
| 173 |
"subtag literals must not exceed the maximum subtag length"); |
| 174 |
|
| 175 |
return mLength == N - 1 && memcmp(mChars, str, N - 1) == 0; |
| 176 |
} |
| 177 |
}; |
| 178 |
|
| 179 |
using LanguageSubtag = LanguageTagSubtag<LanguageTagLimits::LanguageLength>; |
| 180 |
using ScriptSubtag = LanguageTagSubtag<LanguageTagLimits::ScriptLength>; |
| 181 |
using RegionSubtag = LanguageTagSubtag<LanguageTagLimits::RegionLength>; |
| 182 |
|
| 183 |
using Latin1Char = unsigned char; |
| 184 |
using UniqueChars = UniquePtr<char[]>; |
| 185 |
|
| 186 |
/** |
| 187 |
* Object representing a Unicode BCP 47 locale identifier. |
| 188 |
* |
| 189 |
* All subtags are already in canonicalized case. |
| 190 |
*/ |
| 191 |
class MOZ_STACK_CLASS Locale final { |
| 192 |
LanguageSubtag mLanguage = {}; |
| 193 |
ScriptSubtag mScript = {}; |
| 194 |
RegionSubtag mRegion = {}; |
| 195 |
|
| 196 |
using VariantsVector = Vector<UniqueChars, 2>; |
| 197 |
using ExtensionsVector = Vector<UniqueChars, 2>; |
| 198 |
|
| 199 |
VariantsVector mVariants; |
| 200 |
ExtensionsVector mExtensions; |
| 201 |
UniqueChars mPrivateUse = nullptr; |
| 202 |
|
| 203 |
friend class LocaleParser; |
| 204 |
|
| 205 |
public: |
| 206 |
enum class CanonicalizationError : uint8_t { |
| 207 |
DuplicateVariant, |
| 208 |
InternalError, |
| 209 |
OutOfMemory, |
| 210 |
}; |
| 211 |
|
| 212 |
private: |
| 213 |
Result<Ok, CanonicalizationError> CanonicalizeUnicodeExtension( |
| 214 |
UniqueChars& unicodeExtension); |
| 215 |
|
| 216 |
Result<Ok, CanonicalizationError> CanonicalizeTransformExtension( |
| 217 |
UniqueChars& transformExtension); |
| 218 |
|
| 219 |
public: |
| 220 |
static bool LanguageMapping(LanguageSubtag& aLanguage); |
| 221 |
static bool ComplexLanguageMapping(const LanguageSubtag& aLanguage); |
| 222 |
|
| 223 |
private: |
| 224 |
static bool ScriptMapping(ScriptSubtag& aScript); |
| 225 |
static bool RegionMapping(RegionSubtag& aRegion); |
| 226 |
static bool ComplexRegionMapping(const RegionSubtag& aRegion); |
| 227 |
|
| 228 |
void PerformComplexLanguageMappings(); |
| 229 |
void PerformComplexRegionMappings(); |
| 230 |
[[nodiscard]] bool PerformVariantMappings(); |
| 231 |
|
| 232 |
[[nodiscard]] bool UpdateLegacyMappings(); |
| 233 |
|
| 234 |
static bool SignLanguageMapping(LanguageSubtag& aLanguage, |
| 235 |
const RegionSubtag& aRegion); |
| 236 |
|
| 237 |
static const char* ReplaceTransformExtensionType( |
| 238 |
mozilla::Span<const char> aKey, mozilla::Span<const char> aType); |
| 239 |
|
| 240 |
public: |
| 241 |
/** |
| 242 |
* Given a Unicode key and type, return the null-terminated preferred |
| 243 |
* replacement for that type if there is one, or null if there is none, e.g. |
| 244 |
* in effect |
| 245 |
* |ReplaceUnicodeExtensionType("ca", "islamicc") == "islamic-civil"| |
| 246 |
* and |
| 247 |
* |ReplaceUnicodeExtensionType("ca", "islamic-civil") == nullptr|. |
| 248 |
*/ |
| 249 |
static const char* ReplaceUnicodeExtensionType( |
| 250 |
mozilla::Span<const char> aKey, mozilla::Span<const char> aType); |
| 251 |
|
| 252 |
public: |
| 253 |
Locale() = default; |
| 254 |
Locale(const Locale&) = delete; |
| 255 |
Locale& operator=(const Locale&) = delete; |
| 256 |
Locale(Locale&&) = default; |
| 257 |
Locale& operator=(Locale&&) = default; |
| 258 |
|
| 259 |
template <class Vec> |
| 260 |
class SubtagIterator { |
| 261 |
using Iter = decltype(std::declval<const Vec>().begin()); |
| 262 |
|
| 263 |
Iter mIter; |
| 264 |
|
| 265 |
public: |
| 266 |
explicit SubtagIterator(Iter iter) : mIter(iter) {} |
| 267 |
|
| 268 |
// std::iterator traits. |
| 269 |
using iterator_category = std::input_iterator_tag; |
| 270 |
using value_type = Span<const char>; |
| 271 |
using difference_type = ptrdiff_t; |
| 272 |
using pointer = value_type*; |
| 273 |
using reference = value_type&; |
| 274 |
|
| 275 |
SubtagIterator& operator++() { |
| 276 |
mIter++; |
| 277 |
return *this; |
| 278 |
} |
| 279 |
|
| 280 |
SubtagIterator operator++(int) { |
| 281 |
SubtagIterator result = *this; |
| 282 |
++(*this); |
| 283 |
return result; |
| 284 |
} |
| 285 |
|
| 286 |
bool operator==(const SubtagIterator& aOther) const { |
| 287 |
return mIter == aOther.mIter; |
| 288 |
} |
| 289 |
|
| 290 |
bool operator!=(const SubtagIterator& aOther) const { |
| 291 |
return !(*this == aOther); |
| 292 |
} |
| 293 |
|
| 294 |
value_type operator*() const { return MakeStringSpan(mIter->get()); } |
| 295 |
}; |
| 296 |
|
| 297 |
template <size_t N> |
| 298 |
class SubtagEnumeration { |
| 299 |
using Vec = Vector<UniqueChars, N>; |
| 300 |
|
| 301 |
const Vec& mVector; |
| 302 |
|
| 303 |
public: |
| 304 |
explicit SubtagEnumeration(const Vec& aVector) : mVector(aVector) {} |
| 305 |
|
| 306 |
size_t length() const { return mVector.length(); } |
| 307 |
bool empty() const { return mVector.empty(); } |
| 308 |
|
| 309 |
auto begin() const { return SubtagIterator<Vec>(mVector.begin()); } |
| 310 |
auto end() const { return SubtagIterator<Vec>(mVector.end()); } |
| 311 |
|
| 312 |
Span<const char> operator[](size_t aIndex) const { |
| 313 |
return MakeStringSpan(mVector[aIndex].get()); |
| 314 |
} |
| 315 |
}; |
| 316 |
|
| 317 |
const LanguageSubtag& Language() const { return mLanguage; } |
| 318 |
const ScriptSubtag& Script() const { return mScript; } |
| 319 |
const RegionSubtag& Region() const { return mRegion; } |
| 320 |
auto Variants() const { return SubtagEnumeration(mVariants); } |
| 321 |
auto Extensions() const { return SubtagEnumeration(mExtensions); } |
| 322 |
Maybe<Span<const char>> PrivateUse() const { |
| 323 |
if (const char* p = mPrivateUse.get()) { |
| 324 |
return Some(MakeStringSpan(p)); |
| 325 |
} |
| 326 |
return Nothing(); |
| 327 |
} |
| 328 |
|
| 329 |
/** |
| 330 |
* Return the Unicode extension subtag or Nothing if not present. |
| 331 |
*/ |
| 332 |
Maybe<Span<const char>> GetUnicodeExtension() const; |
| 333 |
|
| 334 |
private: |
| 335 |
ptrdiff_t UnicodeExtensionIndex() const; |
| 336 |
|
| 337 |
public: |
| 338 |
/** |
| 339 |
* Set the language subtag. The input must be a valid language subtag. |
| 340 |
*/ |
| 341 |
template <size_t N> |
| 342 |
void SetLanguage(const char (&aLanguage)[N]) { |
| 343 |
mozilla::Span<const char> span(aLanguage, N - 1); |
| 344 |
MOZ_ASSERT(IsStructurallyValidLanguageTag(span)); |
| 345 |
mLanguage.Set(span); |
| 346 |
} |
| 347 |
|
| 348 |
/** |
| 349 |
* Set the language subtag. The input must be a valid language subtag. |
| 350 |
*/ |
| 351 |
void SetLanguage(const LanguageSubtag& aLanguage) { |
| 352 |
MOZ_ASSERT(IsStructurallyValidLanguageTag(aLanguage.Span())); |
| 353 |
mLanguage.Set(aLanguage.Span()); |
| 354 |
} |
| 355 |
|
| 356 |
/** |
| 357 |
* Set the script subtag. The input must be a valid script subtag. |
| 358 |
*/ |
| 359 |
template <size_t N> |
| 360 |
void SetScript(const char (&aScript)[N]) { |
| 361 |
mozilla::Span<const char> span(aScript, N - 1); |
| 362 |
MOZ_ASSERT(IsStructurallyValidScriptTag(span)); |
| 363 |
mScript.Set(span); |
| 364 |
} |
| 365 |
|
| 366 |
/** |
| 367 |
* Set the script subtag. The input must be a valid script subtag or the empty |
| 368 |
* string. |
| 369 |
*/ |
| 370 |
void SetScript(const ScriptSubtag& aScript) { |
| 371 |
MOZ_ASSERT(aScript.Missing() || |
| 372 |
IsStructurallyValidScriptTag(aScript.Span())); |
| 373 |
mScript.Set(aScript.Span()); |
| 374 |
} |
| 375 |
|
| 376 |
/** |
| 377 |
* Set the region subtag. The input must be a valid region subtag. |
| 378 |
*/ |
| 379 |
template <size_t N> |
| 380 |
void SetRegion(const char (&aRegion)[N]) { |
| 381 |
mozilla::Span<const char> span(aRegion, N - 1); |
| 382 |
MOZ_ASSERT(IsStructurallyValidRegionTag(span)); |
| 383 |
mRegion.Set(span); |
| 384 |
} |
| 385 |
|
| 386 |
/** |
| 387 |
* Set the region subtag. The input must be a valid region subtag or the empty |
| 388 |
* empty string. |
| 389 |
*/ |
| 390 |
void SetRegion(const RegionSubtag& aRegion) { |
| 391 |
MOZ_ASSERT(aRegion.Missing() || |
| 392 |
IsStructurallyValidRegionTag(aRegion.Span())); |
| 393 |
mRegion.Set(aRegion.Span()); |
| 394 |
} |
| 395 |
|
| 396 |
/** |
| 397 |
* Removes all variant subtags. |
| 398 |
*/ |
| 399 |
void ClearVariants() { mVariants.clearAndFree(); } |
| 400 |
|
| 401 |
/** |
| 402 |
* Set the Unicode extension subtag. The input must be a valid Unicode |
| 403 |
* extension subtag. |
| 404 |
*/ |
| 405 |
ICUResult SetUnicodeExtension(Span<const char> aExtension); |
| 406 |
|
| 407 |
/** |
| 408 |
* Remove any Unicode extension subtag if present. |
| 409 |
*/ |
| 410 |
void ClearUnicodeExtension(); |
| 411 |
|
| 412 |
/** Canonicalize the base-name (language, script, region, variant) subtags. */ |
| 413 |
Result<Ok, CanonicalizationError> CanonicalizeBaseName(); |
| 414 |
|
| 415 |
/** |
| 416 |
* Canonicalize all extension subtags. |
| 417 |
*/ |
| 418 |
Result<Ok, CanonicalizationError> CanonicalizeExtensions(); |
| 419 |
|
| 420 |
/** |
| 421 |
* Canonicalizes the given structurally valid Unicode BCP 47 locale |
| 422 |
* identifier, including regularized case of subtags. For example, the |
| 423 |
* locale Zh-haNS-bu-variant2-Variant1-u-ca-chinese-t-Zh-laTN-x-PRIVATE, |
| 424 |
* where |
| 425 |
* |
| 426 |
* Zh ; 2*3ALPHA |
| 427 |
* -haNS ; ["-" script] |
| 428 |
* -bu ; ["-" region] |
| 429 |
* -variant2 ; *("-" variant) |
| 430 |
* -Variant1 |
| 431 |
* -u-ca-chinese ; *("-" extension) |
| 432 |
* -t-Zh-laTN |
| 433 |
* -x-PRIVATE ; ["-" privateuse] |
| 434 |
* |
| 435 |
* becomes zh-Hans-MM-variant1-variant2-t-zh-latn-u-ca-chinese-x-private |
| 436 |
* |
| 437 |
* Spec: ECMAScript Internationalization API Specification, 6.2.3. |
| 438 |
*/ |
| 439 |
Result<Ok, CanonicalizationError> Canonicalize() { |
| 440 |
MOZ_TRY(CanonicalizeBaseName()); |
| 441 |
return CanonicalizeExtensions(); |
| 442 |
} |
| 443 |
|
| 444 |
/** |
| 445 |
* Fill the buffer with a string representation of the locale. |
| 446 |
*/ |
| 447 |
template <typename B> |
| 448 |
ICUResult ToString(B& aBuffer) const { |
| 449 |
static_assert(std::is_same_v<typename B::CharType, char>); |
| 450 |
|
| 451 |
size_t capacity = ToStringCapacity(); |
| 452 |
|
| 453 |
// Attempt to reserve needed capacity |
| 454 |
if (!aBuffer.reserve(capacity)) { |
| 455 |
return Err(ICUError::OutOfMemory); |
| 456 |
} |
| 457 |
|
| 458 |
size_t offset = ToStringAppend(aBuffer.data()); |
| 459 |
|
| 460 |
MOZ_ASSERT(capacity == offset); |
| 461 |
aBuffer.written(offset); |
| 462 |
|
| 463 |
return Ok(); |
| 464 |
} |
| 465 |
|
| 466 |
/** |
| 467 |
* Add likely-subtags to the locale. |
| 468 |
* |
| 469 |
* Spec: <https://www.unicode.org/reports/tr35/#Likely_Subtags> |
| 470 |
*/ |
| 471 |
ICUResult AddLikelySubtags(); |
| 472 |
|
| 473 |
/** |
| 474 |
* Remove likely-subtags from the locale. |
| 475 |
* |
| 476 |
* Spec: <https://www.unicode.org/reports/tr35/#Likely_Subtags> |
| 477 |
*/ |
| 478 |
ICUResult RemoveLikelySubtags(); |
| 479 |
|
| 480 |
/** |
| 481 |
* Returns the default locale as an ICU locale identifier. The returned string |
| 482 |
* is NOT a valid BCP 47 locale! |
| 483 |
* |
| 484 |
* Also see <https://unicode-org.github.io/icu/userguide/locale>. |
| 485 |
*/ |
| 486 |
static const char* GetDefaultLocale() { return uloc_getDefault(); } |
| 487 |
|
| 488 |
/** |
| 489 |
* Returns an iterator over all supported locales. |
| 490 |
* |
| 491 |
* The returned strings are ICU locale identifiers and NOT BCP 47 language |
| 492 |
* tags. |
| 493 |
* |
| 494 |
* Also see <https://unicode-org.github.io/icu/userguide/locale>. |
| 495 |
*/ |
| 496 |
static auto GetAvailableLocales() { |
| 497 |
return AvailableLocalesEnumeration<uloc_countAvailable, |
| 498 |
uloc_getAvailable>(); |
| 499 |
} |
| 500 |
|
| 501 |
private: |
| 502 |
static UniqueChars DuplicateStringToUniqueChars(const char* aStr); |
| 503 |
static UniqueChars DuplicateStringToUniqueChars(Span<const char> aStr); |
| 504 |
size_t ToStringCapacity() const; |
| 505 |
size_t ToStringAppend(char* aBuffer) const; |
| 506 |
}; |
| 507 |
|
| 508 |
/** |
| 509 |
* Parser for Unicode BCP 47 locale identifiers. |
| 510 |
* |
| 511 |
* <https://unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers> |
| 512 |
*/ |
| 513 |
class MOZ_STACK_CLASS LocaleParser final { |
| 514 |
public: |
| 515 |
enum class ParserError : uint8_t { |
| 516 |
// Input was not parseable as a locale, subtag or extension. |
| 517 |
NotParseable, |
| 518 |
// Unable to allocate memory for the parser to operate. |
| 519 |
OutOfMemory, |
| 520 |
}; |
| 521 |
|
| 522 |
// Exposed as |public| for |MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS|. |
| 523 |
enum class TokenKind : uint8_t { |
| 524 |
None = 0b000, |
| 525 |
Alpha = 0b001, |
| 526 |
Digit = 0b010, |
| 527 |
AlphaDigit = 0b011, |
| 528 |
Error = 0b100 |
| 529 |
}; |
| 530 |
|
| 531 |
private: |
| 532 |
class Token final { |
| 533 |
size_t mIndex; |
| 534 |
size_t mLength; |
| 535 |
TokenKind mKind; |
| 536 |
|
| 537 |
public: |
| 538 |
Token(TokenKind aKind, size_t aIndex, size_t aLength) |
| 539 |
: mIndex(aIndex), mLength(aLength), mKind(aKind) {} |
| 540 |
|
| 541 |
TokenKind Kind() const { return mKind; } |
| 542 |
size_t Index() const { return mIndex; } |
| 543 |
size_t Length() const { return mLength; } |
| 544 |
|
| 545 |
bool IsError() const { return mKind == TokenKind::Error; } |
| 546 |
bool IsNone() const { return mKind == TokenKind::None; } |
| 547 |
bool IsAlpha() const { return mKind == TokenKind::Alpha; } |
| 548 |
bool IsDigit() const { return mKind == TokenKind::Digit; } |
| 549 |
bool IsAlphaDigit() const { return mKind == TokenKind::AlphaDigit; } |
| 550 |
}; |
| 551 |
|
| 552 |
const char* mLocale; |
| 553 |
size_t mLength; |
| 554 |
size_t mIndex = 0; |
| 555 |
|
| 556 |
explicit LocaleParser(Span<const char> aLocale) |
| 557 |
: mLocale(aLocale.data()), mLength(aLocale.size()) {} |
| 558 |
|
| 559 |
char CharAt(size_t aIndex) const { return mLocale[aIndex]; } |
| 560 |
|
| 561 |
// Copy the token characters into |subtag|. |
| 562 |
template <size_t N> |
| 563 |
void CopyChars(const Token& aTok, LanguageTagSubtag<N>& aSubtag) const { |
| 564 |
aSubtag.Set(mozilla::Span(mLocale + aTok.Index(), aTok.Length())); |
| 565 |
} |
| 566 |
|
| 567 |
// Create a string copy of |length| characters starting at |index|. |
| 568 |
UniqueChars Chars(size_t aIndex, size_t aLength) const; |
| 569 |
|
| 570 |
// Create a string copy of the token characters. |
| 571 |
UniqueChars Chars(const Token& aTok) const { |
| 572 |
return Chars(aTok.Index(), aTok.Length()); |
| 573 |
} |
| 574 |
|
| 575 |
UniqueChars Extension(const Token& aStart, const Token& aEnd) const { |
| 576 |
MOZ_ASSERT(aStart.Index() < aEnd.Index()); |
| 577 |
|
| 578 |
size_t length = aEnd.Index() - 1 - aStart.Index(); |
| 579 |
return Chars(aStart.Index(), length); |
| 580 |
} |
| 581 |
|
| 582 |
Token NextToken(); |
| 583 |
|
| 584 |
// unicode_language_subtag = alpha{2,3} | alpha{5,8} ; |
| 585 |
// |
| 586 |
// Four character language subtags are not allowed in Unicode BCP 47 locale |
| 587 |
// identifiers. Also see the comparison to Unicode CLDR locale identifiers in |
| 588 |
// <https://unicode.org/reports/tr35/#BCP_47_Conformance>. |
| 589 |
bool IsLanguage(const Token& aTok) const { |
| 590 |
return aTok.IsAlpha() && ((2 <= aTok.Length() && aTok.Length() <= 3) || |
| 591 |
(5 <= aTok.Length() && aTok.Length() <= 8)); |
| 592 |
} |
| 593 |
|
| 594 |
// unicode_script_subtag = alpha{4} ; |
| 595 |
bool IsScript(const Token& aTok) const { |
| 596 |
return aTok.IsAlpha() && aTok.Length() == 4; |
| 597 |
} |
| 598 |
|
| 599 |
// unicode_region_subtag = (alpha{2} | digit{3}) ; |
| 600 |
bool IsRegion(const Token& aTok) const { |
| 601 |
return (aTok.IsAlpha() && aTok.Length() == 2) || |
| 602 |
(aTok.IsDigit() && aTok.Length() == 3); |
| 603 |
} |
| 604 |
|
| 605 |
// unicode_variant_subtag = (alphanum{5,8} | digit alphanum{3}) ; |
| 606 |
bool IsVariant(const Token& aTok) const { |
| 607 |
return (5 <= aTok.Length() && aTok.Length() <= 8) || |
| 608 |
(aTok.Length() == 4 && mozilla::IsAsciiDigit(CharAt(aTok.Index()))); |
| 609 |
} |
| 610 |
|
| 611 |
// Returns the code unit of the first character at the given singleton token. |
| 612 |
// Always returns the lower case form of an alphabetical character. |
| 613 |
char SingletonKey(const Token& aTok) const { |
| 614 |
MOZ_ASSERT(aTok.Length() == 1); |
| 615 |
return AsciiToLowerCase(CharAt(aTok.Index())); |
| 616 |
} |
| 617 |
|
| 618 |
// extensions = unicode_locale_extensions | |
| 619 |
// transformed_extensions | |
| 620 |
// other_extensions ; |
| 621 |
// |
| 622 |
// unicode_locale_extensions = sep [uU] ((sep keyword)+ | |
| 623 |
// (sep attribute)+ (sep keyword)*) ; |
| 624 |
// |
| 625 |
// transformed_extensions = sep [tT] ((sep tlang (sep tfield)*) | |
| 626 |
// (sep tfield)+) ; |
| 627 |
// |
| 628 |
// other_extensions = sep [alphanum-[tTuUxX]] (sep alphanum{2,8})+ ; |
| 629 |
bool IsExtensionStart(const Token& aTok) const { |
| 630 |
return aTok.Length() == 1 && SingletonKey(aTok) != 'x'; |
| 631 |
} |
| 632 |
|
| 633 |
// other_extensions = sep [alphanum-[tTuUxX]] (sep alphanum{2,8})+ ; |
| 634 |
bool IsOtherExtensionPart(const Token& aTok) const { |
| 635 |
return 2 <= aTok.Length() && aTok.Length() <= 8; |
| 636 |
} |
| 637 |
|
| 638 |
// unicode_locale_extensions = sep [uU] ((sep keyword)+ | |
| 639 |
// (sep attribute)+ (sep keyword)*) ; |
| 640 |
// keyword = key (sep type)? ; |
| 641 |
bool IsUnicodeExtensionPart(const Token& aTok) const { |
| 642 |
return IsUnicodeExtensionKey(aTok) || IsUnicodeExtensionType(aTok) || |
| 643 |
IsUnicodeExtensionAttribute(aTok); |
| 644 |
} |
| 645 |
|
| 646 |
// attribute = alphanum{3,8} ; |
| 647 |
bool IsUnicodeExtensionAttribute(const Token& aTok) const { |
| 648 |
return 3 <= aTok.Length() && aTok.Length() <= 8; |
| 649 |
} |
| 650 |
|
| 651 |
// key = alphanum alpha ; |
| 652 |
bool IsUnicodeExtensionKey(const Token& aTok) const { |
| 653 |
return aTok.Length() == 2 && |
| 654 |
mozilla::IsAsciiAlpha(CharAt(aTok.Index() + 1)); |
| 655 |
} |
| 656 |
|
| 657 |
// type = alphanum{3,8} (sep alphanum{3,8})* ; |
| 658 |
bool IsUnicodeExtensionType(const Token& aTok) const { |
| 659 |
return 3 <= aTok.Length() && aTok.Length() <= 8; |
| 660 |
} |
| 661 |
|
| 662 |
// tkey = alpha digit ; |
| 663 |
bool IsTransformExtensionKey(const Token& aTok) const { |
| 664 |
return aTok.Length() == 2 && mozilla::IsAsciiAlpha(CharAt(aTok.Index())) && |
| 665 |
mozilla::IsAsciiDigit(CharAt(aTok.Index() + 1)); |
| 666 |
} |
| 667 |
|
| 668 |
// tvalue = (sep alphanum{3,8})+ ; |
| 669 |
bool IsTransformExtensionPart(const Token& aTok) const { |
| 670 |
return 3 <= aTok.Length() && aTok.Length() <= 8; |
| 671 |
} |
| 672 |
|
| 673 |
// pu_extensions = sep [xX] (sep alphanum{1,8})+ ; |
| 674 |
bool IsPrivateUseStart(const Token& aTok) const { |
| 675 |
return aTok.Length() == 1 && SingletonKey(aTok) == 'x'; |
| 676 |
} |
| 677 |
|
| 678 |
// pu_extensions = sep [xX] (sep alphanum{1,8})+ ; |
| 679 |
bool IsPrivateUsePart(const Token& aTok) const { |
| 680 |
return 1 <= aTok.Length() && aTok.Length() <= 8; |
| 681 |
} |
| 682 |
|
| 683 |
// Helper function for use in |ParseBaseName| and |
| 684 |
// |ParseTlangInTransformExtension|. Do not use this directly! |
| 685 |
static Result<Ok, ParserError> InternalParseBaseName( |
| 686 |
LocaleParser& aLocaleParser, Locale& aTag, Token& aTok); |
| 687 |
|
| 688 |
// Parse the `unicode_language_id` production, i.e. the |
| 689 |
// language/script/region/variants portion of a locale, into |aTag|. |
| 690 |
// |aTok| must be the current token. |
| 691 |
static Result<Ok, ParserError> ParseBaseName(LocaleParser& aLocaleParser, |
| 692 |
Locale& aTag, Token& aTok) { |
| 693 |
return InternalParseBaseName(aLocaleParser, aTag, aTok); |
| 694 |
} |
| 695 |
|
| 696 |
// Parse the `tlang` production within a parsed 't' transform extension. |
| 697 |
// The precise requirements for "previously parsed" are: |
| 698 |
// |
| 699 |
// * the input begins from current token |tok| with a valid `tlang` |
| 700 |
// * the `tlang` is wholly lowercase (*not* canonical case) |
| 701 |
// * variant subtags in the `tlang` may contain duplicates and be |
| 702 |
// unordered |
| 703 |
// |
| 704 |
// Return an error on internal failure. Otherwise, return a success value. If |
| 705 |
// there was no `tlang`, then |tag.language().missing()|. But if there was a |
| 706 |
// `tlang`, then |tag| is filled with subtags exactly as they appeared in the |
| 707 |
// parse input. |
| 708 |
static Result<Ok, ParserError> ParseTlangInTransformExtension( |
| 709 |
LocaleParser& aLocaleParser, Locale& aTag, Token& aTok) { |
| 710 |
MOZ_ASSERT(aLocaleParser.IsLanguage(aTok)); |
| 711 |
return InternalParseBaseName(aLocaleParser, aTag, aTok); |
| 712 |
} |
| 713 |
|
| 714 |
friend class Locale; |
| 715 |
|
| 716 |
class Range final { |
| 717 |
size_t mBegin; |
| 718 |
size_t mLength; |
| 719 |
|
| 720 |
public: |
| 721 |
Range(size_t aBegin, size_t aLength) : mBegin(aBegin), mLength(aLength) {} |
| 722 |
|
| 723 |
size_t Begin() const { return mBegin; } |
| 724 |
size_t Length() const { return mLength; } |
| 725 |
}; |
| 726 |
|
| 727 |
using TFieldVector = Vector<Range, 8>; |
| 728 |
using AttributesVector = Vector<Range, 8>; |
| 729 |
using KeywordsVector = Vector<Range, 8>; |
| 730 |
|
| 731 |
// Parse |extension|, which must be a validated, fully lowercase |
| 732 |
// `transformed_extensions` subtag, and fill |tag| and |fields| from the |
| 733 |
// `tlang` and `tfield` components. Data in |tag| is lowercase, consistent |
| 734 |
// with |extension|. |
| 735 |
static Result<Ok, ParserError> ParseTransformExtension( |
| 736 |
mozilla::Span<const char> aExtension, Locale& aTag, |
| 737 |
TFieldVector& aFields); |
| 738 |
|
| 739 |
// Parse |extension|, which must be a validated, fully lowercase |
| 740 |
// `unicode_locale_extensions` subtag, and fill |attributes| and |keywords| |
| 741 |
// from the `attribute` and `keyword` components. |
| 742 |
static Result<Ok, ParserError> ParseUnicodeExtension( |
| 743 |
mozilla::Span<const char> aExtension, AttributesVector& aAttributes, |
| 744 |
KeywordsVector& aKeywords); |
| 745 |
|
| 746 |
public: |
| 747 |
// Parse the input string as a locale. |
| 748 |
// |
| 749 |
// NOTE: |aTag| must be a new, empty Locale. |
| 750 |
static Result<Ok, ParserError> TryParse(Span<const char> aLocale, |
| 751 |
Locale& aTag); |
| 752 |
|
| 753 |
// Parse the input string as the base-name parts (language, script, region, |
| 754 |
// variants) of a locale. |
| 755 |
// |
| 756 |
// NOTE: |aTag| must be a new, empty Locale. |
| 757 |
static Result<Ok, ParserError> TryParseBaseName(Span<const char> aLocale, |
| 758 |
Locale& aTag); |
| 759 |
|
| 760 |
// Return Ok() iff |extension| can be parsed as a Unicode extension subtag. |
| 761 |
static Result<Ok, ParserError> CanParseUnicodeExtension( |
| 762 |
Span<const char> aExtension); |
| 763 |
|
| 764 |
// Return Ok() iff |unicodeType| can be parsed as a Unicode extension type. |
| 765 |
static Result<Ok, ParserError> CanParseUnicodeExtensionType( |
| 766 |
Span<const char> aUnicodeType); |
| 767 |
}; |
| 768 |
|
| 769 |
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(LocaleParser::TokenKind) |
| 770 |
|
| 771 |
} // namespace mozilla::intl |
| 772 |
|
| 773 |
#endif /* intl_components_Locale_h */ |