| 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 |
#ifndef intl_components_DisplayNames_h_ |
| 5 |
#define intl_components_DisplayNames_h_ |
| 6 |
|
| 7 |
#include <string> |
| 8 |
#include <string_view> |
| 9 |
#include "unicode/udat.h" |
| 10 |
#include "unicode/udatpg.h" |
| 11 |
#include "unicode/uldnames.h" |
| 12 |
#include "unicode/uloc.h" |
| 13 |
#include "unicode/ucurr.h" |
| 14 |
#include "mozilla/intl/Calendar.h" |
| 15 |
#include "mozilla/intl/DateTimePatternGenerator.h" |
| 16 |
#include "mozilla/intl/ICU4CGlue.h" |
| 17 |
#include "mozilla/intl/Locale.h" |
| 18 |
#include "mozilla/Buffer.h" |
| 19 |
#include "mozilla/Casting.h" |
| 20 |
#include "mozilla/PodOperations.h" |
| 21 |
#include "mozilla/Result.h" |
| 22 |
#include "mozilla/Span.h" |
| 23 |
#include "mozilla/TextUtils.h" |
| 24 |
#include "mozilla/UniquePtr.h" |
| 25 |
|
| 26 |
namespace mozilla::intl { |
| 27 |
/** |
| 28 |
* Provide more granular errors for DisplayNames rather than use the generic |
| 29 |
* ICUError type. This helps with providing more actionable feedback for |
| 30 |
* errors with input validation. |
| 31 |
* |
| 32 |
* This type can't be nested in the DisplayNames class because it needs the |
| 33 |
* UnusedZero and HasFreeLSB definitions. |
| 34 |
*/ |
| 35 |
enum class DisplayNamesError { |
| 36 |
// Since we claim UnusedZero<DisplayNamesError>::value and |
| 37 |
// HasFreeLSB<Error>::value == true below, we must only use positive, |
| 38 |
// even enum values. |
| 39 |
InternalError = 2, |
| 40 |
OutOfMemory = 4, |
| 41 |
InvalidOption = 6, |
| 42 |
DuplicateVariantSubtag = 8, |
| 43 |
InvalidLanguageTag = 10, |
| 44 |
}; |
| 45 |
} // namespace mozilla::intl |
| 46 |
|
| 47 |
namespace mozilla::detail { |
| 48 |
// Ensure the efficient packing of the error types into the result. See |
| 49 |
// ICUError.h and the ICUError comments for more information. |
| 50 |
template <> |
| 51 |
struct UnusedZero<intl::DisplayNamesError> |
| 52 |
: UnusedZeroEnum<intl::DisplayNamesError> {}; |
| 53 |
|
| 54 |
template <> |
| 55 |
struct HasFreeLSB<intl::DisplayNamesError> { |
| 56 |
static constexpr bool value = true; |
| 57 |
}; |
| 58 |
} // namespace mozilla::detail |
| 59 |
|
| 60 |
namespace mozilla::intl { |
| 61 |
|
| 62 |
// NOTE: The UTF-35 canonical "code" value for months and quarters are 1-based |
| 63 |
// integers, so some of the following enums are 1-based for consistency with |
| 64 |
// that. For simplicity, we make all of the following enums 1-based, but use |
| 65 |
// `EnumToIndex` (see below) to convert to zero based if indexing into internal |
| 66 |
// (non-ICU) tables. |
| 67 |
|
| 68 |
/** |
| 69 |
* Month choices for display names. |
| 70 |
*/ |
| 71 |
enum class Month : uint8_t { |
| 72 |
January = 1, |
| 73 |
February, |
| 74 |
March, |
| 75 |
April, |
| 76 |
May, |
| 77 |
June, |
| 78 |
July, |
| 79 |
August, |
| 80 |
September, |
| 81 |
October, |
| 82 |
November, |
| 83 |
December, |
| 84 |
// Some calendar systems feature a 13th month. |
| 85 |
// https://en.wikipedia.org/wiki/Undecimber |
| 86 |
Undecimber |
| 87 |
}; |
| 88 |
|
| 89 |
/** |
| 90 |
* Quarter choices for display names. |
| 91 |
*/ |
| 92 |
enum class Quarter : uint8_t { |
| 93 |
Q1 = 1, |
| 94 |
Q2, |
| 95 |
Q3, |
| 96 |
Q4, |
| 97 |
}; |
| 98 |
|
| 99 |
/** |
| 100 |
* Day period choices for display names. |
| 101 |
*/ |
| 102 |
enum class DayPeriod : uint8_t { |
| 103 |
AM = 1, |
| 104 |
PM, |
| 105 |
}; |
| 106 |
|
| 107 |
/** |
| 108 |
* DateTimeField choices for display names. |
| 109 |
*/ |
| 110 |
enum class DateTimeField : uint8_t { |
| 111 |
Era = 1, |
| 112 |
Year, |
| 113 |
Quarter, |
| 114 |
Month, |
| 115 |
WeekOfYear, |
| 116 |
Weekday, |
| 117 |
Day, |
| 118 |
DayPeriod, |
| 119 |
Hour, |
| 120 |
Minute, |
| 121 |
Second, |
| 122 |
TimeZoneName, |
| 123 |
}; |
| 124 |
|
| 125 |
/** |
| 126 |
* DisplayNames provide a way to get the localized names of various types of |
| 127 |
* information such as the names of the day of the week, months, currency etc. |
| 128 |
* |
| 129 |
* This class backs SpiderMonkeys implementation of Intl.DisplayNames |
| 130 |
* https://tc39.es/ecma402/#intl-displaynames-objects |
| 131 |
*/ |
| 132 |
class DisplayNames final { |
| 133 |
public: |
| 134 |
/** |
| 135 |
* The style of the display name, specified by the amount of space available |
| 136 |
* for displaying the text. |
| 137 |
*/ |
| 138 |
enum class Style { |
| 139 |
Narrow, |
| 140 |
Short, |
| 141 |
Long, |
| 142 |
// Note: Abbreviated is not part of ECMA-402, but it is available for |
| 143 |
// internal Mozilla usage. |
| 144 |
Abbreviated, |
| 145 |
}; |
| 146 |
|
| 147 |
/** |
| 148 |
* Use either standard or dialect names for the "Language" type. |
| 149 |
*/ |
| 150 |
enum class LanguageDisplay { |
| 151 |
Standard, |
| 152 |
Dialect, |
| 153 |
}; |
| 154 |
|
| 155 |
/** |
| 156 |
* Determines the fallback behavior if no match is found. |
| 157 |
*/ |
| 158 |
enum class Fallback { |
| 159 |
// The buffer will contain an empty string. |
| 160 |
None, |
| 161 |
// The buffer will contain the code, but typically in a canonicalized form. |
| 162 |
Code |
| 163 |
}; |
| 164 |
|
| 165 |
/** |
| 166 |
* These options correlate to the ECMA-402 DisplayNames options. The defaults |
| 167 |
* values must match the default initialized values of ECMA-402. The type |
| 168 |
* option is omitted as the C++ API relies on directly calling the |
| 169 |
* DisplayNames::Get* methods. |
| 170 |
* |
| 171 |
* https://tc39.es/ecma402/#intl-displaynames-objects |
| 172 |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames |
| 173 |
*/ |
| 174 |
struct Options { |
| 175 |
Style style = Style::Long; |
| 176 |
LanguageDisplay languageDisplay = LanguageDisplay::Standard; |
| 177 |
}; |
| 178 |
|
| 179 |
DisplayNames(ULocaleDisplayNames* aDisplayNames, Span<const char> aLocale, |
| 180 |
Options aOptions) |
| 181 |
: mOptions(aOptions), mULocaleDisplayNames(aDisplayNames) { |
| 182 |
MOZ_ASSERT(aDisplayNames); |
| 183 |
|
| 184 |
// Copy the span and ensure null termination. |
| 185 |
mLocale = Buffer<char>(aLocale.size() + 1); |
| 186 |
PodCopy(mLocale.begin(), aLocale.data(), aLocale.size()); |
| 187 |
mLocale[aLocale.size()] = '\0'; |
| 188 |
} |
| 189 |
|
| 190 |
/** |
| 191 |
* Initialize a new DisplayNames for the provided locale and using the |
| 192 |
* provided options. |
| 193 |
* |
| 194 |
* https://tc39.es/ecma402/#sec-Intl.DisplayNames |
| 195 |
*/ |
| 196 |
static Result<UniquePtr<DisplayNames>, ICUError> TryCreate( |
| 197 |
const char* aLocale, Options aOptions); |
| 198 |
|
| 199 |
// Not copyable or movable |
| 200 |
DisplayNames(const DisplayNames&) = delete; |
| 201 |
DisplayNames& operator=(const DisplayNames&) = delete; |
| 202 |
|
| 203 |
~DisplayNames(); |
| 204 |
|
| 205 |
/** |
| 206 |
* Easily convert to a more specific DisplayNames error. |
| 207 |
*/ |
| 208 |
DisplayNamesError ToError(ICUError aError) const; |
| 209 |
|
| 210 |
/** |
| 211 |
* Easily convert to a more specific DisplayNames error. |
| 212 |
*/ |
| 213 |
DisplayNamesError ToError(Locale::CanonicalizationError aError) const; |
| 214 |
|
| 215 |
private: |
| 216 |
/** |
| 217 |
* A helper function to handle the fallback behavior, where if there is a |
| 218 |
* fallback the buffer is filled with the "code", often in canonicalized form. |
| 219 |
*/ |
| 220 |
template <typename B, typename Fn> |
| 221 |
static Result<Ok, DisplayNamesError> HandleFallback(B& aBuffer, |
| 222 |
Fallback aFallback, |
| 223 |
Fn aGetFallbackSpan) { |
| 224 |
if (aBuffer.length() == 0 && |
| 225 |
aFallback == mozilla::intl::DisplayNames::Fallback::Code) { |
| 226 |
if (!FillBuffer(aGetFallbackSpan(), aBuffer)) { |
| 227 |
return Err(DisplayNamesError::OutOfMemory); |
| 228 |
} |
| 229 |
} |
| 230 |
return Ok(); |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* This is a specialized form of the FillBufferWithICUCall for DisplayNames. |
| 235 |
* Different APIs report that no display name is found with different |
| 236 |
* statuses. This method signals no display name was found by setting the |
| 237 |
* buffer to 0. |
| 238 |
* |
| 239 |
* The display name APIs such as `uldn_scriptDisplayName`, |
| 240 |
* `uloc_getDisplayScript`, and `uldn_regionDisplayName` report |
| 241 |
* U_ILLEGAL_ARGUMENT_ERROR when no display name was found. In order to |
| 242 |
* accomodate fallbacking, return an empty string in this case. |
| 243 |
*/ |
| 244 |
template <typename B, typename F> |
| 245 |
static ICUResult FillBufferWithICUDisplayNames( |
| 246 |
B& aBuffer, UErrorCode aNoDisplayNameStatus, F aCallback) { |
| 247 |
return FillBufferWithICUCall( |
| 248 |
aBuffer, [&](UChar* target, int32_t length, UErrorCode* status) { |
| 249 |
int32_t res = aCallback(target, length, status); |
| 250 |
|
| 251 |
if (*status == aNoDisplayNameStatus) { |
| 252 |
*status = U_ZERO_ERROR; |
| 253 |
res = 0; |
| 254 |
} |
| 255 |
return res; |
| 256 |
}); |
| 257 |
} |
| 258 |
|
| 259 |
/** |
| 260 |
* An internal helper to compute the list of display names for various |
| 261 |
* DateTime options. |
| 262 |
*/ |
| 263 |
Result<Ok, DisplayNamesError> ComputeDateTimeDisplayNames( |
| 264 |
UDateFormatSymbolType symbolType, mozilla::Span<const int32_t> indices, |
| 265 |
Span<const char> aCalendar); |
| 266 |
|
| 267 |
// The following are the stack-allocated sizes for various strings using the |
| 268 |
// mozilla::Vector. The numbers should be large enough to fit the common |
| 269 |
// cases, and when the strings are too large they will fall back to heap |
| 270 |
// allocations. |
| 271 |
|
| 272 |
// Fit BCP 47 locales such as "en-US", "zh-Hant". Locales can get quite long, |
| 273 |
// but 32 should fit most smaller locales without a lot of extensions. |
| 274 |
static constexpr size_t LocaleVecLength = 32; |
| 275 |
// Fit calendar names such as "gregory", "buddhist", "islamic-civil". |
| 276 |
// "islamic-umalqura" is 16 bytes + 1 for null termination, so round up to 32. |
| 277 |
static constexpr size_t CalendarVecLength = 32; |
| 278 |
|
| 279 |
/** |
| 280 |
* Given an ASCII alpha, convert it to upper case. |
| 281 |
*/ |
| 282 |
static inline char16_t AsciiAlphaToUpperCase(char16_t aCh) { |
| 283 |
MOZ_ASSERT(IsAsciiAlpha(aCh)); |
| 284 |
return AsciiToUpperCase(aCh); |
| 285 |
}; |
| 286 |
|
| 287 |
/** |
| 288 |
* Attempt to use enums to safely index into an array. |
| 289 |
* |
| 290 |
* Note: The enums we support here are all defined starting from 1. |
| 291 |
*/ |
| 292 |
template <typename T> |
| 293 |
inline int32_t EnumToIndex(size_t aSize, T aEnum) { |
| 294 |
size_t index = static_cast<size_t>(aEnum) - 1; |
| 295 |
MOZ_RELEASE_ASSERT(index < aSize, |
| 296 |
"Enum indexing mismatch for display names."); |
| 297 |
return index; |
| 298 |
} |
| 299 |
|
| 300 |
/** |
| 301 |
* Convert the month to a numeric code as a string. |
| 302 |
*/ |
| 303 |
static Span<const char> ToCodeString(Month aMonth); |
| 304 |
|
| 305 |
public: |
| 306 |
/** |
| 307 |
* Get the localized name of a language. Part of ECMA-402. |
| 308 |
* |
| 309 |
* Accepts: |
| 310 |
* languageCode ["-" scriptCode] ["-" regionCode ] *("-" variant ) |
| 311 |
* Where the language code is: |
| 312 |
* 1. A two letters ISO 639-1 language code |
| 313 |
* https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes |
| 314 |
* 2. A three letters ISO 639-2 language code |
| 315 |
* https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes |
| 316 |
* |
| 317 |
* Examples: |
| 318 |
* "es-ES" => "European Spanish" (en-US), "español de España" (es-ES) |
| 319 |
* "zh-Hant" => "Traditional Chinese" (en-US), "chino tradicional" (es-ES) |
| 320 |
*/ |
| 321 |
template <typename B> |
| 322 |
Result<Ok, DisplayNamesError> GetLanguage( |
| 323 |
B& aBuffer, Span<const char> aLanguage, |
| 324 |
Fallback aFallback = Fallback::None) const { |
| 325 |
static_assert(std::is_same<typename B::CharType, char16_t>::value); |
| 326 |
mozilla::intl::Locale tag; |
| 327 |
if (LocaleParser::TryParseBaseName(aLanguage, tag).isErr()) { |
| 328 |
return Err(DisplayNamesError::InvalidOption); |
| 329 |
} |
| 330 |
|
| 331 |
{ |
| 332 |
// ICU always canonicalizes the input locale, but since we know that ICU's |
| 333 |
// canonicalization is incomplete, we need to perform our own |
| 334 |
// canonicalization to ensure consistent result. |
| 335 |
auto result = tag.CanonicalizeBaseName(); |
| 336 |
if (result.isErr()) { |
| 337 |
return Err(ToError(result.unwrapErr())); |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
Vector<char, DisplayNames::LocaleVecLength> tagVec; |
| 342 |
{ |
| 343 |
VectorToBufferAdaptor tagBuffer(tagVec); |
| 344 |
auto result = tag.ToString(tagBuffer); |
| 345 |
if (result.isErr()) { |
| 346 |
return Err(ToError(result.unwrapErr())); |
| 347 |
} |
| 348 |
if (!tagVec.append('\0')) { |
| 349 |
// The tag should be null terminated. |
| 350 |
return Err(DisplayNamesError::OutOfMemory); |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
auto result = FillBufferWithICUDisplayNames( |
| 355 |
aBuffer, U_ILLEGAL_ARGUMENT_ERROR, |
| 356 |
[&](UChar* target, int32_t length, UErrorCode* status) { |
| 357 |
return uldn_localeDisplayName(mULocaleDisplayNames.GetConst(), |
| 358 |
tagVec.begin(), target, length, status); |
| 359 |
}); |
| 360 |
if (result.isErr()) { |
| 361 |
return Err(ToError(result.unwrapErr())); |
| 362 |
} |
| 363 |
|
| 364 |
return HandleFallback(aBuffer, aFallback, [&] { |
| 365 |
// Remove the null terminator. |
| 366 |
return Span(tagVec.begin(), tagVec.length() - 1); |
| 367 |
}); |
| 368 |
}; |
| 369 |
|
| 370 |
/** |
| 371 |
* Get the localized name of a region. Part of ECMA-402. |
| 372 |
* |
| 373 |
* Accepts: |
| 374 |
* 1. an ISO-3166 two letters: |
| 375 |
* https://www.iso.org/iso-3166-country-codes.html |
| 376 |
* 2. region code, or a three digits UN M49 Geographic Regions. |
| 377 |
* https://unstats.un.org/unsd/methodology/m49/ |
| 378 |
* |
| 379 |
* Examples |
| 380 |
* "US" => "United States" (en-US), "Estados Unidos", (es-ES) |
| 381 |
* "158" => "Taiwan" (en-US), "Taiwán", (es-ES) |
| 382 |
*/ |
| 383 |
template <typename B> |
| 384 |
Result<Ok, DisplayNamesError> GetRegion( |
| 385 |
B& aBuffer, Span<const char> aCode, |
| 386 |
Fallback aFallback = Fallback::None) const { |
| 387 |
static_assert(std::is_same<typename B::CharType, char16_t>::value); |
| 388 |
|
| 389 |
mozilla::intl::RegionSubtag region; |
| 390 |
if (!IsStructurallyValidRegionTag(aCode)) { |
| 391 |
return Err(DisplayNamesError::InvalidOption); |
| 392 |
} |
| 393 |
region.Set(aCode); |
| 394 |
|
| 395 |
mozilla::intl::Locale tag; |
| 396 |
tag.SetLanguage("und"); |
| 397 |
tag.SetRegion(region); |
| 398 |
|
| 399 |
{ |
| 400 |
// ICU always canonicalizes the input locale, but since we know that ICU's |
| 401 |
// canonicalization is incomplete, we need to perform our own |
| 402 |
// canonicalization to ensure consistent result. |
| 403 |
auto result = tag.CanonicalizeBaseName(); |
| 404 |
if (result.isErr()) { |
| 405 |
return Err(ToError(result.unwrapErr())); |
| 406 |
} |
| 407 |
} |
| 408 |
|
| 409 |
MOZ_ASSERT(tag.Region().Present()); |
| 410 |
|
| 411 |
// Note: ICU requires the region subtag to be in canonical case. |
| 412 |
const mozilla::intl::RegionSubtag& canonicalRegion = tag.Region(); |
| 413 |
|
| 414 |
char regionChars[mozilla::intl::LanguageTagLimits::RegionLength + 1] = {}; |
| 415 |
std::copy_n(canonicalRegion.Span().data(), canonicalRegion.Length(), |
| 416 |
regionChars); |
| 417 |
|
| 418 |
auto result = FillBufferWithICUDisplayNames( |
| 419 |
aBuffer, U_ILLEGAL_ARGUMENT_ERROR, |
| 420 |
[&](UChar* chars, uint32_t size, UErrorCode* status) { |
| 421 |
return uldn_regionDisplayName( |
| 422 |
mULocaleDisplayNames.GetConst(), regionChars, chars, |
| 423 |
AssertedCast<int32_t, uint32_t>(size), status); |
| 424 |
}); |
| 425 |
|
| 426 |
if (result.isErr()) { |
| 427 |
return Err(ToError(result.unwrapErr())); |
| 428 |
} |
| 429 |
|
| 430 |
return HandleFallback(aBuffer, aFallback, [&] { |
| 431 |
region.ToUpperCase(); |
| 432 |
return region.Span(); |
| 433 |
}); |
| 434 |
} |
| 435 |
|
| 436 |
/** |
| 437 |
* Get the localized name of a currency. Part of ECMA-402. |
| 438 |
* |
| 439 |
* Accepts: |
| 440 |
* A 3-letter ISO 4217 currency code. |
| 441 |
* https://en.wikipedia.org/wiki/ISO_4217 |
| 442 |
* |
| 443 |
* Examples: |
| 444 |
* "EUR" => "Euro" (en-US), "euro" (es_ES), "欧元", (zh) |
| 445 |
* "JPY" => "Japanese Yen" (en-US), "yen" (es_ES), "日元", (zh) |
| 446 |
*/ |
| 447 |
template <typename B> |
| 448 |
Result<Ok, DisplayNamesError> GetCurrency( |
| 449 |
B& aBuffer, Span<const char> aCurrency, |
| 450 |
Fallback aFallback = Fallback::None) const { |
| 451 |
static_assert(std::is_same<typename B::CharType, char16_t>::value); |
| 452 |
if (aCurrency.size() != 3) { |
| 453 |
return Err(DisplayNamesError::InvalidOption); |
| 454 |
} |
| 455 |
|
| 456 |
if (!mozilla::IsAsciiAlpha(aCurrency[0]) || |
| 457 |
!mozilla::IsAsciiAlpha(aCurrency[1]) || |
| 458 |
!mozilla::IsAsciiAlpha(aCurrency[2])) { |
| 459 |
return Err(DisplayNamesError::InvalidOption); |
| 460 |
} |
| 461 |
|
| 462 |
// Normally this type of operation wouldn't be safe, but ASCII characters |
| 463 |
// all take 1 byte in UTF-8 encoding, and can be zero padded to be valid |
| 464 |
// UTF-16. Currency codes are all three ASCII letters. |
| 465 |
// Normalize to upper case so we can easily detect the fallback case. |
| 466 |
char16_t currency[] = {AsciiAlphaToUpperCase(aCurrency[0]), |
| 467 |
AsciiAlphaToUpperCase(aCurrency[1]), |
| 468 |
AsciiAlphaToUpperCase(aCurrency[2]), u'\0'}; |
| 469 |
|
| 470 |
UCurrNameStyle style; |
| 471 |
switch (mOptions.style) { |
| 472 |
case Style::Long: |
| 473 |
style = UCURR_LONG_NAME; |
| 474 |
break; |
| 475 |
case Style::Abbreviated: |
| 476 |
case Style::Short: |
| 477 |
style = UCURR_SYMBOL_NAME; |
| 478 |
break; |
| 479 |
case Style::Narrow: |
| 480 |
style = UCURR_NARROW_SYMBOL_NAME; |
| 481 |
break; |
| 482 |
} |
| 483 |
|
| 484 |
int32_t length = 0; |
| 485 |
UErrorCode status = U_ZERO_ERROR; |
| 486 |
const char16_t* name = ucurr_getName(currency, IcuLocale(mLocale), style, |
| 487 |
nullptr, &length, &status); |
| 488 |
if (U_FAILURE(status)) { |
| 489 |
return Err(DisplayNamesError::InternalError); |
| 490 |
} |
| 491 |
|
| 492 |
// No localized currency name was found when the error code is |
| 493 |
// U_USING_DEFAULT_WARNING and the returned string is equal to the (upper |
| 494 |
// case transformed) currency code. When `aFallback` is `Fallback::Code`, |
| 495 |
// we don't have to perform any additional work, because ICU already |
| 496 |
// returned the currency code in its normalized, upper case form. |
| 497 |
if (aFallback == DisplayNames::Fallback::None && |
| 498 |
status == U_USING_DEFAULT_WARNING && length == 3 && |
| 499 |
std::u16string_view{name, 3} == std::u16string_view{currency, 3}) { |
| 500 |
if (aBuffer.length() != 0) { |
| 501 |
// Ensure an empty string is in the buffer when there is no fallback. |
| 502 |
aBuffer.written(0); |
| 503 |
} |
| 504 |
return Ok(); |
| 505 |
} |
| 506 |
|
| 507 |
if (!FillBuffer(Span(name, length), aBuffer)) { |
| 508 |
return Err(DisplayNamesError::OutOfMemory); |
| 509 |
} |
| 510 |
|
| 511 |
return Ok(); |
| 512 |
} |
| 513 |
|
| 514 |
/** |
| 515 |
* Get the localized name of a script. Part of ECMA-402. |
| 516 |
* |
| 517 |
* Accepts: |
| 518 |
* ECMA-402 expects the ISO-15924 four letters script code. |
| 519 |
* https://unicode.org/iso15924/iso15924-codes.html |
| 520 |
* e.g. "Latn" |
| 521 |
* |
| 522 |
* Examples: |
| 523 |
* "Cher" => "Cherokee" (en-US), "cherokee" (es-ES) |
| 524 |
* "Latn" => "Latin" (en-US), "latino" (es-ES) |
| 525 |
*/ |
| 526 |
template <typename B> |
| 527 |
Result<Ok, DisplayNamesError> GetScript( |
| 528 |
B& aBuffer, Span<const char> aScript, |
| 529 |
Fallback aFallback = Fallback::None) const { |
| 530 |
static_assert(std::is_same<typename B::CharType, char16_t>::value); |
| 531 |
mozilla::intl::ScriptSubtag script; |
| 532 |
if (!IsStructurallyValidScriptTag(aScript)) { |
| 533 |
return Err(DisplayNamesError::InvalidOption); |
| 534 |
} |
| 535 |
script.Set(aScript); |
| 536 |
|
| 537 |
mozilla::intl::Locale tag; |
| 538 |
tag.SetLanguage("und"); |
| 539 |
|
| 540 |
tag.SetScript(script); |
| 541 |
|
| 542 |
{ |
| 543 |
// ICU always canonicalizes the input locale, but since we know that ICU's |
| 544 |
// canonicalization is incomplete, we need to perform our own |
| 545 |
// canonicalization to ensure consistent result. |
| 546 |
auto result = tag.CanonicalizeBaseName(); |
| 547 |
if (result.isErr()) { |
| 548 |
return Err(ToError(result.unwrapErr())); |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
MOZ_ASSERT(tag.Script().Present()); |
| 553 |
mozilla::Vector<char, DisplayNames::LocaleVecLength> tagString; |
| 554 |
VectorToBufferAdaptor buffer(tagString); |
| 555 |
|
| 556 |
switch (mOptions.style) { |
| 557 |
case Style::Long: { |
| 558 |
// |uldn_scriptDisplayName| doesn't use the stand-alone form for script |
| 559 |
// subtags, so we're using |uloc_getDisplayScript| instead. (This only |
| 560 |
// applies to the long form.) |
| 561 |
// |
| 562 |
// ICU bug: https://unicode-org.atlassian.net/browse/ICU-9301 |
| 563 |
|
| 564 |
// |uloc_getDisplayScript| expects a full locale identifier as its |
| 565 |
// input. |
| 566 |
if (auto result = tag.ToString(buffer); result.isErr()) { |
| 567 |
return Err(ToError(result.unwrapErr())); |
| 568 |
} |
| 569 |
|
| 570 |
// Null terminate the tag string. |
| 571 |
if (!tagString.append('\0')) { |
| 572 |
return Err(DisplayNamesError::OutOfMemory); |
| 573 |
} |
| 574 |
|
| 575 |
auto result = FillBufferWithICUDisplayNames( |
| 576 |
aBuffer, U_USING_DEFAULT_WARNING, |
| 577 |
[&](UChar* target, int32_t length, UErrorCode* status) { |
| 578 |
return uloc_getDisplayScript(tagString.begin(), |
| 579 |
IcuLocale(mLocale), target, length, |
| 580 |
status); |
| 581 |
}); |
| 582 |
|
| 583 |
if (result.isErr()) { |
| 584 |
return Err(ToError(result.unwrapErr())); |
| 585 |
} |
| 586 |
break; |
| 587 |
} |
| 588 |
case Style::Abbreviated: |
| 589 |
case Style::Short: |
| 590 |
case Style::Narrow: { |
| 591 |
// Note: ICU requires the script subtag to be in canonical case. |
| 592 |
const mozilla::intl::ScriptSubtag& canonicalScript = tag.Script(); |
| 593 |
|
| 594 |
char scriptChars[mozilla::intl::LanguageTagLimits::ScriptLength + 1] = |
| 595 |
{}; |
| 596 |
MOZ_ASSERT(canonicalScript.Length() <= |
| 597 |
mozilla::intl::LanguageTagLimits::ScriptLength + 1); |
| 598 |
std::copy_n(canonicalScript.Span().data(), canonicalScript.Length(), |
| 599 |
scriptChars); |
| 600 |
|
| 601 |
auto result = FillBufferWithICUDisplayNames( |
| 602 |
aBuffer, U_ILLEGAL_ARGUMENT_ERROR, |
| 603 |
[&](UChar* target, int32_t length, UErrorCode* status) { |
| 604 |
return uldn_scriptDisplayName(mULocaleDisplayNames.GetConst(), |
| 605 |
scriptChars, target, length, |
| 606 |
status); |
| 607 |
}); |
| 608 |
|
| 609 |
if (result.isErr()) { |
| 610 |
return Err(ToError(result.unwrapErr())); |
| 611 |
} |
| 612 |
break; |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
return HandleFallback(aBuffer, aFallback, [&] { |
| 617 |
script.ToTitleCase(); |
| 618 |
return script.Span(); |
| 619 |
}); |
| 620 |
}; |
| 621 |
|
| 622 |
/** |
| 623 |
* Get the localized name of a calendar. |
| 624 |
* Part of Intl.DisplayNames V2. https://tc39.es/intl-displaynames-v2/ |
| 625 |
* Accepts: |
| 626 |
* Unicode calendar key: |
| 627 |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#unicode_calendar_keys |
| 628 |
*/ |
| 629 |
template <typename B> |
| 630 |
Result<Ok, DisplayNamesError> GetCalendar( |
| 631 |
B& aBuffer, Span<const char> aCalendar, |
| 632 |
Fallback aFallback = Fallback::None) const { |
| 633 |
if (aCalendar.empty() || !IsAscii(aCalendar)) { |
| 634 |
return Err(DisplayNamesError::InvalidOption); |
| 635 |
} |
| 636 |
|
| 637 |
if (LocaleParser::CanParseUnicodeExtensionType(aCalendar).isErr()) { |
| 638 |
return Err(DisplayNamesError::InvalidOption); |
| 639 |
} |
| 640 |
|
| 641 |
// Convert into canonical case before searching for replacements. |
| 642 |
Vector<char, DisplayNames::CalendarVecLength> lowerCaseCalendar; |
| 643 |
for (size_t i = 0; i < aCalendar.size(); i++) { |
| 644 |
if (!lowerCaseCalendar.append(AsciiToLowerCase(aCalendar[i]))) { |
| 645 |
return Err(DisplayNamesError::OutOfMemory); |
| 646 |
} |
| 647 |
} |
| 648 |
if (!lowerCaseCalendar.append('\0')) { |
| 649 |
return Err(DisplayNamesError::OutOfMemory); |
| 650 |
} |
| 651 |
|
| 652 |
Span<const char> canonicalCalendar = mozilla::Span( |
| 653 |
lowerCaseCalendar.begin(), lowerCaseCalendar.length() - 1); |
| 654 |
|
| 655 |
// Search if there's a replacement for the Unicode calendar keyword. |
| 656 |
{ |
| 657 |
Span<const char> key = mozilla::MakeStringSpan("ca"); |
| 658 |
Span<const char> type = canonicalCalendar; |
| 659 |
if (const char* replacement = |
| 660 |
mozilla::intl::Locale::ReplaceUnicodeExtensionType(key, type)) { |
| 661 |
canonicalCalendar = MakeStringSpan(replacement); |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
// The input calendar name is user-controlled, so be extra cautious before |
| 666 |
// passing arbitrarily large strings to ICU. |
| 667 |
static constexpr size_t maximumCalendarLength = 100; |
| 668 |
|
| 669 |
if (canonicalCalendar.size() <= maximumCalendarLength) { |
| 670 |
// |uldn_keyValueDisplayName| expects old-style keyword values. |
| 671 |
if (const char* legacyCalendar = |
| 672 |
uloc_toLegacyType("calendar", canonicalCalendar.Elements())) { |
| 673 |
auto result = FillBufferWithICUDisplayNames( |
| 674 |
aBuffer, U_ILLEGAL_ARGUMENT_ERROR, |
| 675 |
[&](UChar* chars, uint32_t size, UErrorCode* status) { |
| 676 |
// |uldn_keyValueDisplayName| expects old-style keyword values. |
| 677 |
return uldn_keyValueDisplayName(mULocaleDisplayNames.GetConst(), |
| 678 |
"calendar", legacyCalendar, chars, |
| 679 |
size, status); |
| 680 |
}); |
| 681 |
if (result.isErr()) { |
| 682 |
return Err(ToError(result.unwrapErr())); |
| 683 |
} |
| 684 |
} else { |
| 685 |
aBuffer.written(0); |
| 686 |
} |
| 687 |
} else { |
| 688 |
aBuffer.written(0); |
| 689 |
} |
| 690 |
|
| 691 |
return HandleFallback(aBuffer, aFallback, |
| 692 |
[&] { return canonicalCalendar; }); |
| 693 |
} |
| 694 |
|
| 695 |
/** |
| 696 |
* Get the localized name of a weekday. This is a MozExtension, and not |
| 697 |
* currently part of ECMA-402. |
| 698 |
*/ |
| 699 |
template <typename B> |
| 700 |
Result<Ok, DisplayNamesError> GetWeekday( |
| 701 |
B& aBuffer, Weekday aWeekday, Span<const char> aCalendar, |
| 702 |
Fallback aFallback = Fallback::None) { |
| 703 |
// SpiderMonkey static casts the enum, so ensure it is correctly in range. |
| 704 |
MOZ_ASSERT(aWeekday >= Weekday::Monday && aWeekday <= Weekday::Sunday); |
| 705 |
|
| 706 |
UDateFormatSymbolType symbolType; |
| 707 |
switch (mOptions.style) { |
| 708 |
case DisplayNames::Style::Long: |
| 709 |
symbolType = UDAT_STANDALONE_WEEKDAYS; |
| 710 |
break; |
| 711 |
|
| 712 |
case DisplayNames::Style::Abbreviated: |
| 713 |
// ICU "short" is CLDR "abbreviated" format. |
| 714 |
symbolType = UDAT_STANDALONE_SHORT_WEEKDAYS; |
| 715 |
break; |
| 716 |
|
| 717 |
case DisplayNames::Style::Short: |
| 718 |
// ICU "shorter" is CLDR "short" format. |
| 719 |
symbolType = UDAT_STANDALONE_SHORTER_WEEKDAYS; |
| 720 |
break; |
| 721 |
|
| 722 |
case DisplayNames::Style::Narrow: |
| 723 |
symbolType = UDAT_STANDALONE_NARROW_WEEKDAYS; |
| 724 |
break; |
| 725 |
} |
| 726 |
|
| 727 |
static constexpr int32_t indices[] = { |
| 728 |
UCAL_MONDAY, UCAL_TUESDAY, UCAL_WEDNESDAY, UCAL_THURSDAY, |
| 729 |
UCAL_FRIDAY, UCAL_SATURDAY, UCAL_SUNDAY}; |
| 730 |
|
| 731 |
if (auto result = ComputeDateTimeDisplayNames( |
| 732 |
symbolType, mozilla::Span(indices), aCalendar); |
| 733 |
result.isErr()) { |
| 734 |
return result.propagateErr(); |
| 735 |
} |
| 736 |
MOZ_ASSERT(mDateTimeDisplayNames.length() == std::size(indices)); |
| 737 |
|
| 738 |
auto& name = |
| 739 |
mDateTimeDisplayNames[EnumToIndex(std::size(indices), aWeekday)]; |
| 740 |
if (!FillBuffer(name.AsSpan(), aBuffer)) { |
| 741 |
return Err(DisplayNamesError::OutOfMemory); |
| 742 |
} |
| 743 |
|
| 744 |
// There is no need to fallback, as invalid options are |
| 745 |
// DisplayNamesError::InvalidOption. |
| 746 |
return Ok(); |
| 747 |
} |
| 748 |
|
| 749 |
/** |
| 750 |
* Get the localized name of a month. This is a MozExtension, and not |
| 751 |
* currently part of ECMA-402. |
| 752 |
*/ |
| 753 |
template <typename B> |
| 754 |
Result<Ok, DisplayNamesError> GetMonth(B& aBuffer, Month aMonth, |
| 755 |
Span<const char> aCalendar, |
| 756 |
Fallback aFallback = Fallback::None) { |
| 757 |
// SpiderMonkey static casts the enum, so ensure it is correctly in range. |
| 758 |
MOZ_ASSERT(aMonth >= Month::January && aMonth <= Month::Undecimber); |
| 759 |
|
| 760 |
UDateFormatSymbolType symbolType; |
| 761 |
switch (mOptions.style) { |
| 762 |
case DisplayNames::Style::Long: |
| 763 |
symbolType = UDAT_STANDALONE_MONTHS; |
| 764 |
break; |
| 765 |
|
| 766 |
case DisplayNames::Style::Abbreviated: |
| 767 |
case DisplayNames::Style::Short: |
| 768 |
symbolType = UDAT_STANDALONE_SHORT_MONTHS; |
| 769 |
break; |
| 770 |
|
| 771 |
case DisplayNames::Style::Narrow: |
| 772 |
symbolType = UDAT_STANDALONE_NARROW_MONTHS; |
| 773 |
break; |
| 774 |
} |
| 775 |
|
| 776 |
static constexpr int32_t indices[] = { |
| 777 |
UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, |
| 778 |
UCAL_MAY, UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, |
| 779 |
UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, |
| 780 |
UCAL_UNDECIMBER}; |
| 781 |
|
| 782 |
if (auto result = ComputeDateTimeDisplayNames( |
| 783 |
symbolType, mozilla::Span(indices), aCalendar); |
| 784 |
result.isErr()) { |
| 785 |
return result.propagateErr(); |
| 786 |
} |
| 787 |
MOZ_ASSERT(mDateTimeDisplayNames.length() == std::size(indices)); |
| 788 |
auto& name = mDateTimeDisplayNames[EnumToIndex(std::size(indices), aMonth)]; |
| 789 |
if (!FillBuffer(Span(name.AsSpan()), aBuffer)) { |
| 790 |
return Err(DisplayNamesError::OutOfMemory); |
| 791 |
} |
| 792 |
|
| 793 |
return HandleFallback(aBuffer, aFallback, |
| 794 |
[&] { return ToCodeString(aMonth); }); |
| 795 |
} |
| 796 |
|
| 797 |
/** |
| 798 |
* Get the localized name of a quarter. This is a MozExtension, and not |
| 799 |
* currently part of ECMA-402. |
| 800 |
*/ |
| 801 |
template <typename B> |
| 802 |
Result<Ok, DisplayNamesError> GetQuarter( |
| 803 |
B& aBuffer, Quarter aQuarter, Span<const char> aCalendar, |
| 804 |
Fallback aFallback = Fallback::None) { |
| 805 |
// SpiderMonkey static casts the enum, so ensure it is correctly in range. |
| 806 |
MOZ_ASSERT(aQuarter >= Quarter::Q1 && aQuarter <= Quarter::Q4); |
| 807 |
|
| 808 |
UDateFormatSymbolType symbolType; |
| 809 |
switch (mOptions.style) { |
| 810 |
case DisplayNames::Style::Long: |
| 811 |
symbolType = UDAT_STANDALONE_QUARTERS; |
| 812 |
break; |
| 813 |
|
| 814 |
case DisplayNames::Style::Abbreviated: |
| 815 |
case DisplayNames::Style::Short: |
| 816 |
symbolType = UDAT_STANDALONE_SHORT_QUARTERS; |
| 817 |
break; |
| 818 |
|
| 819 |
case DisplayNames::Style::Narrow: |
| 820 |
symbolType = UDAT_STANDALONE_NARROW_QUARTERS; |
| 821 |
break; |
| 822 |
} |
| 823 |
|
| 824 |
// ICU doesn't provide an enum for quarters. |
| 825 |
static constexpr int32_t indices[] = {0, 1, 2, 3}; |
| 826 |
|
| 827 |
if (auto result = ComputeDateTimeDisplayNames( |
| 828 |
symbolType, mozilla::Span(indices), aCalendar); |
| 829 |
result.isErr()) { |
| 830 |
return result.propagateErr(); |
| 831 |
} |
| 832 |
MOZ_ASSERT(mDateTimeDisplayNames.length() == std::size(indices)); |
| 833 |
|
| 834 |
auto& name = |
| 835 |
mDateTimeDisplayNames[EnumToIndex(std::size(indices), aQuarter)]; |
| 836 |
if (!FillBuffer(Span(name.AsSpan()), aBuffer)) { |
| 837 |
return Err(DisplayNamesError::OutOfMemory); |
| 838 |
} |
| 839 |
|
| 840 |
// There is no need to fallback, as invalid options are |
| 841 |
// DisplayNamesError::InvalidOption. |
| 842 |
return Ok(); |
| 843 |
} |
| 844 |
|
| 845 |
/** |
| 846 |
* Get the localized name of a day period. This is a MozExtension, and not |
| 847 |
* currently part of ECMA-402. |
| 848 |
*/ |
| 849 |
template <typename B> |
| 850 |
Result<Ok, DisplayNamesError> GetDayPeriod( |
| 851 |
B& aBuffer, DayPeriod aDayPeriod, Span<const char> aCalendar, |
| 852 |
Fallback aFallback = Fallback::None) { |
| 853 |
UDateFormatSymbolType symbolType = UDAT_AM_PMS; |
| 854 |
|
| 855 |
static constexpr int32_t indices[] = {UCAL_AM, UCAL_PM}; |
| 856 |
|
| 857 |
if (auto result = ComputeDateTimeDisplayNames( |
| 858 |
symbolType, mozilla::Span(indices), aCalendar); |
| 859 |
result.isErr()) { |
| 860 |
return result.propagateErr(); |
| 861 |
} |
| 862 |
MOZ_ASSERT(mDateTimeDisplayNames.length() == std::size(indices)); |
| 863 |
|
| 864 |
auto& name = |
| 865 |
mDateTimeDisplayNames[EnumToIndex(std::size(indices), aDayPeriod)]; |
| 866 |
if (!FillBuffer(name.AsSpan(), aBuffer)) { |
| 867 |
return Err(DisplayNamesError::OutOfMemory); |
| 868 |
} |
| 869 |
|
| 870 |
// There is no need to fallback, as invalid options are |
| 871 |
// DisplayNamesError::InvalidOption. |
| 872 |
return Ok(); |
| 873 |
} |
| 874 |
|
| 875 |
/** |
| 876 |
* Get the localized name of a date time field. |
| 877 |
* Part of Intl.DisplayNames V2. https://tc39.es/intl-displaynames-v2/ |
| 878 |
* Accepts: |
| 879 |
* "era", "year", "quarter", "month", "weekOfYear", "weekday", "day", |
| 880 |
* "dayPeriod", "hour", "minute", "second", "timeZoneName" |
| 881 |
* Examples: |
| 882 |
* "weekday" => "day of the week" |
| 883 |
* "dayPeriod" => "AM/PM" |
| 884 |
*/ |
| 885 |
template <typename B> |
| 886 |
Result<Ok, DisplayNamesError> GetDateTimeField( |
| 887 |
B& aBuffer, DateTimeField aField, |
| 888 |
DateTimePatternGenerator& aDateTimePatternGen, |
| 889 |
Fallback aFallback = Fallback::None) { |
| 890 |
UDateTimePatternField field; |
| 891 |
switch (aField) { |
| 892 |
case DateTimeField::Era: |
| 893 |
field = UDATPG_ERA_FIELD; |
| 894 |
break; |
| 895 |
case DateTimeField::Year: |
| 896 |
field = UDATPG_YEAR_FIELD; |
| 897 |
break; |
| 898 |
case DateTimeField::Quarter: |
| 899 |
field = UDATPG_QUARTER_FIELD; |
| 900 |
break; |
| 901 |
case DateTimeField::Month: |
| 902 |
field = UDATPG_MONTH_FIELD; |
| 903 |
break; |
| 904 |
case DateTimeField::WeekOfYear: |
| 905 |
field = UDATPG_WEEK_OF_YEAR_FIELD; |
| 906 |
break; |
| 907 |
case DateTimeField::Weekday: |
| 908 |
field = UDATPG_WEEKDAY_FIELD; |
| 909 |
break; |
| 910 |
case DateTimeField::Day: |
| 911 |
field = UDATPG_DAY_FIELD; |
| 912 |
break; |
| 913 |
case DateTimeField::DayPeriod: |
| 914 |
field = UDATPG_DAYPERIOD_FIELD; |
| 915 |
break; |
| 916 |
case DateTimeField::Hour: |
| 917 |
field = UDATPG_HOUR_FIELD; |
| 918 |
break; |
| 919 |
case DateTimeField::Minute: |
| 920 |
field = UDATPG_MINUTE_FIELD; |
| 921 |
break; |
| 922 |
case DateTimeField::Second: |
| 923 |
field = UDATPG_SECOND_FIELD; |
| 924 |
break; |
| 925 |
case DateTimeField::TimeZoneName: |
| 926 |
field = UDATPG_ZONE_FIELD; |
| 927 |
break; |
| 928 |
} |
| 929 |
|
| 930 |
UDateTimePGDisplayWidth width; |
| 931 |
switch (mOptions.style) { |
| 932 |
case DisplayNames::Style::Long: |
| 933 |
width = UDATPG_WIDE; |
| 934 |
break; |
| 935 |
case DisplayNames::Style::Abbreviated: |
| 936 |
case DisplayNames::Style::Short: |
| 937 |
width = UDATPG_ABBREVIATED; |
| 938 |
break; |
| 939 |
case DisplayNames::Style::Narrow: |
| 940 |
width = UDATPG_NARROW; |
| 941 |
break; |
| 942 |
} |
| 943 |
|
| 944 |
auto result = FillBufferWithICUCall( |
| 945 |
aBuffer, [&](UChar* target, int32_t length, UErrorCode* status) { |
| 946 |
return udatpg_getFieldDisplayName( |
| 947 |
aDateTimePatternGen.GetUDateTimePatternGenerator(), field, width, |
| 948 |
target, length, status); |
| 949 |
}); |
| 950 |
|
| 951 |
if (result.isErr()) { |
| 952 |
return Err(ToError(result.unwrapErr())); |
| 953 |
} |
| 954 |
// There is no need to fallback, as invalid options are |
| 955 |
// DisplayNamesError::InvalidOption. |
| 956 |
return Ok(); |
| 957 |
} |
| 958 |
|
| 959 |
Options mOptions; |
| 960 |
Buffer<char> mLocale; |
| 961 |
Vector<Buffer<char16_t>> mDateTimeDisplayNames; |
| 962 |
ICUPointer<ULocaleDisplayNames> mULocaleDisplayNames = |
| 963 |
ICUPointer<ULocaleDisplayNames>(nullptr); |
| 964 |
}; |
| 965 |
|
| 966 |
} // namespace mozilla::intl |
| 967 |
|
| 968 |
#endif |