Debian Codegraph @

js/src/builtin/intl/SharedIntlData.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* Runtime-wide Intl data shared across compartments. */
8
9 #include "builtin/intl/SharedIntlData.h"
10
11 #include "mozilla/Assertions.h"
12 #include "mozilla/HashFunctions.h"
13 #include "mozilla/intl/Collator.h"
14 #include "mozilla/intl/DateTimeFormat.h"
15 #include "mozilla/intl/DateTimePatternGenerator.h"
16 #include "mozilla/intl/Locale.h"
17 #include "mozilla/intl/NumberFormat.h"
18 #include "mozilla/intl/TimeZone.h"
19 #include "mozilla/Span.h"
20 #include "mozilla/TextUtils.h"
21
22 #include <algorithm>
23 #include <stdint.h>
24 #include <string>
25 #include <string.h>
26 #include <string_view>
27 #include <utility>
28
29 #include "builtin/Array.h"
30 #include "builtin/intl/CommonFunctions.h"
31 #include "builtin/intl/TimeZoneDataGenerated.h"
32 #include "js/Utility.h"
33 #include "js/Vector.h"
34 #include "vm/ArrayObject.h"
35 #include "vm/JSAtomUtils.h" // Atomize
36 #include "vm/JSContext.h"
37 #include "vm/StringType.h"
38
39 using js::HashNumber;
40
41 template <typename Char>
42 static constexpr Char ToUpperASCII(Char c) {
43 return mozilla::IsAsciiLowercaseAlpha(c) ? (c - 0x20) : c;
44 }
45
46 static_assert(ToUpperASCII('a') == 'A', "verifying 'a' uppercases correctly");
47 static_assert(ToUpperASCII('m') == 'M', "verifying 'm' uppercases correctly");
48 static_assert(ToUpperASCII('z') == 'Z', "verifying 'z' uppercases correctly");
49 static_assert(ToUpperASCII(u'a') == u'A',
50 "verifying u'a' uppercases correctly");
51 static_assert(ToUpperASCII(u'k') == u'K',
52 "verifying u'k' uppercases correctly");
53 static_assert(ToUpperASCII(u'z') == u'Z',
54 "verifying u'z' uppercases correctly");
55
56 template <typename Char>
57 static HashNumber HashStringIgnoreCaseASCII(const Char* s, size_t length) {
58 uint32_t hash = 0;
59 for (size_t i = 0; i < length; i++) {
60 hash = mozilla::AddToHash(hash, ToUpperASCII(s[i]));
61 }
62 return hash;
63 }
64
65 js::intl::SharedIntlData::TimeZoneHasher::Lookup::Lookup(
66 const JSLinearString* timeZone)
67 : js::intl::SharedIntlData::LinearStringLookup(timeZone) {
68 if (isLatin1) {
69 hash = HashStringIgnoreCaseASCII(latin1Chars, length);
70 } else {
71 hash = HashStringIgnoreCaseASCII(twoByteChars, length);
72 }
73 }
74
75 template <typename Char1, typename Char2>
76 static bool EqualCharsIgnoreCaseASCII(const Char1* s1, const Char2* s2,
77 size_t len) {
78 for (const Char1* s1end = s1 + len; s1 < s1end; s1++, s2++) {
79 if (ToUpperASCII(*s1) != ToUpperASCII(*s2)) {
80 return false;
81 }
82 }
83 return true;
84 }
85
86 bool js::intl::SharedIntlData::TimeZoneHasher::match(TimeZoneName key,
87 const Lookup& lookup) {
88 if (key->length() != lookup.length) {
89 return false;
90 }
91
92 // Compare time zone names ignoring ASCII case differences.
93 if (key->hasLatin1Chars()) {
94 const Latin1Char* keyChars = key->latin1Chars(lookup.nogc);
95 if (lookup.isLatin1) {
96 return EqualCharsIgnoreCaseASCII(keyChars, lookup.latin1Chars,
97 lookup.length);
98 }
99 return EqualCharsIgnoreCaseASCII(keyChars, lookup.twoByteChars,
100 lookup.length);
101 }
102
103 const char16_t* keyChars = key->twoByteChars(lookup.nogc);
104 if (lookup.isLatin1) {
105 return EqualCharsIgnoreCaseASCII(lookup.latin1Chars, keyChars,
106 lookup.length);
107 }
108 return EqualCharsIgnoreCaseASCII(keyChars, lookup.twoByteChars,
109 lookup.length);
110 }
111
112 static bool IsLegacyICUTimeZone(mozilla::Span<const char> timeZone) {
113 std::string_view timeZoneView(timeZone.data(), timeZone.size());
114 for (const auto& legacyTimeZone : js::timezone::legacyICUTimeZones) {
115 if (timeZoneView == legacyTimeZone) {
116 return true;
117 }
118 }
119 return false;
120 }
121
122 bool js::intl::SharedIntlData::ensureTimeZones(JSContext* cx) {
123 if (timeZoneDataInitialized) {
124 return true;
125 }
126
127 // If ensureTimeZones() was called previously, but didn't complete due to
128 // OOM, clear all sets/maps and start from scratch.
129 availableTimeZones.clearAndCompact();
130
131 auto timeZones = mozilla::intl::TimeZone::GetAvailableTimeZones();
132 if (timeZones.isErr()) {
133 ReportInternalError(cx, timeZones.unwrapErr());
134 return false;
135 }
136
137 Rooted<JSAtom*> timeZone(cx);
138 for (auto timeZoneName : timeZones.unwrap()) {
139 if (timeZoneName.isErr()) {
140 ReportInternalError(cx);
141 return false;
142 }
143 auto timeZoneSpan = timeZoneName.unwrap();
144
145 // Skip legacy ICU time zone names.
146 if (IsLegacyICUTimeZone(timeZoneSpan)) {
147 continue;
148 }
149
150 timeZone = Atomize(cx, timeZoneSpan.data(), timeZoneSpan.size());
151 if (!timeZone) {
152 return false;
153 }
154
155 TimeZoneHasher::Lookup lookup(timeZone);
156 TimeZoneSet::AddPtr p = availableTimeZones.lookupForAdd(lookup);
157
158 // ICU shouldn't report any duplicate time zone names, but if it does,
159 // just ignore the duplicate name.
160 if (!p && !availableTimeZones.add(p, timeZone)) {
161 ReportOutOfMemory(cx);
162 return false;
163 }
164 }
165
166 ianaZonesTreatedAsLinksByICU.clearAndCompact();
167
168 for (const char* rawTimeZone : timezone::ianaZonesTreatedAsLinksByICU) {
169 MOZ_ASSERT(rawTimeZone != nullptr);
170 timeZone = Atomize(cx, rawTimeZone, strlen(rawTimeZone));
171 if (!timeZone) {
172 return false;
173 }
174
175 TimeZoneHasher::Lookup lookup(timeZone);
176 TimeZoneSet::AddPtr p = ianaZonesTreatedAsLinksByICU.lookupForAdd(lookup);
177 MOZ_ASSERT(!p, "Duplicate entry in timezone::ianaZonesTreatedAsLinksByICU");
178
179 if (!ianaZonesTreatedAsLinksByICU.add(p, timeZone)) {
180 ReportOutOfMemory(cx);
181 return false;
182 }
183 }
184
185 ianaLinksCanonicalizedDifferentlyByICU.clearAndCompact();
186
187 Rooted<JSAtom*> linkName(cx);
188 Rooted<JSAtom*>& target = timeZone;
189 for (const auto& linkAndTarget :
190 timezone::ianaLinksCanonicalizedDifferentlyByICU) {
191 const char* rawLinkName = linkAndTarget.link;
192 const char* rawTarget = linkAndTarget.target;
193
194 MOZ_ASSERT(rawLinkName != nullptr);
195 linkName = Atomize(cx, rawLinkName, strlen(rawLinkName));
196 if (!linkName) {
197 return false;
198 }
199
200 MOZ_ASSERT(rawTarget != nullptr);
201 target = Atomize(cx, rawTarget, strlen(rawTarget));
202 if (!target) {
203 return false;
204 }
205
206 TimeZoneHasher::Lookup lookup(linkName);
207 TimeZoneMap::AddPtr p =
208 ianaLinksCanonicalizedDifferentlyByICU.lookupForAdd(lookup);
209 MOZ_ASSERT(
210 !p,
211 "Duplicate entry in timezone::ianaLinksCanonicalizedDifferentlyByICU");
212
213 if (!ianaLinksCanonicalizedDifferentlyByICU.add(p, linkName, target)) {
214 ReportOutOfMemory(cx);
215 return false;
216 }
217 }
218
219 MOZ_ASSERT(!timeZoneDataInitialized,
220 "ensureTimeZones is neither reentrant nor thread-safe");
221 timeZoneDataInitialized = true;
222
223 return true;
224 }
225
226 bool js::intl::SharedIntlData::validateTimeZoneName(
227 JSContext* cx, HandleString timeZone, MutableHandle<JSAtom*> result) {
228 if (!ensureTimeZones(cx)) {
229 return false;
230 }
231
232 Rooted<JSLinearString*> timeZoneLinear(cx, timeZone->ensureLinear(cx));
233 if (!timeZoneLinear) {
234 return false;
235 }
236
237 TimeZoneHasher::Lookup lookup(timeZoneLinear);
238 if (TimeZoneSet::Ptr p = availableTimeZones.lookup(lookup)) {
239 result.set(*p);
240 }
241
242 return true;
243 }
244
245 bool js::intl::SharedIntlData::tryCanonicalizeTimeZoneConsistentWithIANA(
246 JSContext* cx, HandleString timeZone, MutableHandle<JSAtom*> result) {
247 if (!ensureTimeZones(cx)) {
248 return false;
249 }
250
251 Rooted<JSLinearString*> timeZoneLinear(cx, timeZone->ensureLinear(cx));
252 if (!timeZoneLinear) {
253 return false;
254 }
255
256 TimeZoneHasher::Lookup lookup(timeZoneLinear);
257 MOZ_ASSERT(availableTimeZones.has(lookup), "Invalid time zone name");
258
259 if (TimeZoneMap::Ptr p =
260 ianaLinksCanonicalizedDifferentlyByICU.lookup(lookup)) {
261 // The effectively supported time zones aren't known at compile time,
262 // when
263 // 1. SpiderMonkey was compiled with "--with-system-icu".
264 // 2. ICU's dynamic time zone data loading feature was used.
265 // (ICU supports loading time zone files at runtime through the
266 // ICU_TIMEZONE_FILES_DIR environment variable.)
267 // Ensure ICU supports the new target zone before applying the update.
268 TimeZoneName targetTimeZone = p->value();
269 TimeZoneHasher::Lookup targetLookup(targetTimeZone);
270 if (availableTimeZones.has(targetLookup)) {
271 result.set(targetTimeZone);
272 }
273 } else if (TimeZoneSet::Ptr p = ianaZonesTreatedAsLinksByICU.lookup(lookup)) {
274 result.set(*p);
275 }
276
277 return true;
278 }
279
280 JS::Result<js::intl::SharedIntlData::TimeZoneSet::Iterator>
281 js::intl::SharedIntlData::availableTimeZonesIteration(JSContext* cx) {
282 if (!ensureTimeZones(cx)) {
283 return cx->alreadyReportedError();
284 }
285 return availableTimeZones.iter();
286 }
287
288 js::intl::SharedIntlData::LocaleHasher::Lookup::Lookup(
289 const JSLinearString* locale)
290 : js::intl::SharedIntlData::LinearStringLookup(locale) {
291 if (isLatin1) {
292 hash = mozilla::HashString(latin1Chars, length);
293 } else {
294 hash = mozilla::HashString(twoByteChars, length);
295 }
296 }
297
298 js::intl::SharedIntlData::LocaleHasher::Lookup::Lookup(const char* chars,
299 size_t length)
300 : js::intl::SharedIntlData::LinearStringLookup(chars, length) {
301 hash = mozilla::HashString(latin1Chars, length);
302 }
303
304 bool js::intl::SharedIntlData::LocaleHasher::match(Locale key,
305 const Lookup& lookup) {
306 if (key->length() != lookup.length) {
307 return false;
308 }
309
310 if (key->hasLatin1Chars()) {
311 const Latin1Char* keyChars = key->latin1Chars(lookup.nogc);
312 if (lookup.isLatin1) {
313 return EqualChars(keyChars, lookup.latin1Chars, lookup.length);
314 }
315 return EqualChars(keyChars, lookup.twoByteChars, lookup.length);
316 }
317
318 const char16_t* keyChars = key->twoByteChars(lookup.nogc);
319 if (lookup.isLatin1) {
320 return EqualChars(lookup.latin1Chars, keyChars, lookup.length);
321 }
322 return EqualChars(keyChars, lookup.twoByteChars, lookup.length);
323 }
324
325 template <class AvailableLocales>
326 bool js::intl::SharedIntlData::getAvailableLocales(
327 JSContext* cx, LocaleSet& locales,
328 const AvailableLocales& availableLocales) {
329 auto addLocale = [cx, &locales](const char* locale, size_t length) {
330 JSAtom* atom = Atomize(cx, locale, length);
331 if (!atom) {
332 return false;
333 }
334
335 LocaleHasher::Lookup lookup(atom);
336 LocaleSet::AddPtr p = locales.lookupForAdd(lookup);
337
338 // ICU shouldn't report any duplicate locales, but if it does, just
339 // ignore the duplicated locale.
340 if (!p && !locales.add(p, atom)) {
341 ReportOutOfMemory(cx);
342 return false;
343 }
344
345 return true;
346 };
347
348 js::Vector<char, 16> lang(cx);
349
350 for (const char* locale : availableLocales) {
351 size_t length = strlen(locale);
352
353 lang.clear();
354 if (!lang.append(locale, length)) {
355 return false;
356 }
357 MOZ_ASSERT(lang.length() == length);
358
359 std::replace(lang.begin(), lang.end(), '_', '-');
360
361 if (!addLocale(lang.begin(), length)) {
362 return false;
363 }
364
365 // From <https://tc39.es/ecma402/#sec-internal-slots>:
366 //
367 // For locales that include a script subtag in addition to language and
368 // region, the corresponding locale without a script subtag must also be
369 // supported; that is, if an implementation recognizes "zh-Hant-TW", it is
370 // also expected to recognize "zh-TW".
371
372 // 2 * Alpha language subtag
373 // + 1 separator
374 // + 4 * Alphanum script subtag
375 // + 1 separator
376 // + 2 * Alpha region subtag
377 using namespace mozilla::intl::LanguageTagLimits;
378 static constexpr size_t MinLanguageLength = 2;
379 static constexpr size_t MinLengthForScriptAndRegion =
380 MinLanguageLength + 1 + ScriptLength + 1 + AlphaRegionLength;
381
382 // Fast case: Skip locales without script subtags.
383 if (length < MinLengthForScriptAndRegion) {
384 continue;
385 }
386
387 // We don't need the full-fledged language tag parser when we just want to
388 // remove the script subtag.
389
390 // Find the separator between the language and script subtags.
391 const char* sep = std::char_traits<char>::find(lang.begin(), length, '-');
392 if (!sep) {
393 continue;
394 }
395
396 // Possible |script| subtag start position.
397 const char* script = sep + 1;
398
399 // Find the separator between the script and region subtags.
400 sep = std::char_traits<char>::find(script, lang.end() - script, '-');
401 if (!sep) {
402 continue;
403 }
404
405 // Continue with the next locale if we didn't find a script subtag.
406 size_t scriptLength = sep - script;
407 if (!mozilla::intl::IsStructurallyValidScriptTag<char>(
408 {script, scriptLength})) {
409 continue;
410 }
411
412 // Possible |region| subtag start position.
413 const char* region = sep + 1;
414
415 // Search if there's yet another subtag after the region subtag.
416 sep = std::char_traits<char>::find(region, lang.end() - region, '-');
417
418 // Continue with the next locale if we didn't find a region subtag.
419 size_t regionLength = (sep ? sep : lang.end()) - region;
420 if (!mozilla::intl::IsStructurallyValidRegionTag<char>(
421 {region, regionLength})) {
422 continue;
423 }
424
425 // We've found a script and a region subtag.
426
427 static constexpr size_t ScriptWithSeparatorLength = ScriptLength + 1;
428
429 // Remove the script subtag. Note: erase() needs non-const pointers, which
430 // means we can't directly pass |script|.
431 char* p = const_cast<char*>(script);
432 lang.erase(p, p + ScriptWithSeparatorLength);
433
434 MOZ_ASSERT(lang.length() == length - ScriptWithSeparatorLength);
435
436 // Add the locale with the script subtag removed.
437 if (!addLocale(lang.begin(), lang.length())) {
438 return false;
439 }
440 }
441
442 // Forcibly add an entry for the last-ditch locale, in case ICU doesn't
443 // directly support it (but does support it through fallback, e.g. supporting
444 // "en-GB" indirectly using "en" support).
445 {
446 const char* lastDitch = intl::LastDitchLocale();
447 MOZ_ASSERT(strcmp(lastDitch, "en-GB") == 0);
448
449 #ifdef DEBUG
450 static constexpr char lastDitchParent[] = "en";
451
452 LocaleHasher::Lookup lookup(lastDitchParent, strlen(lastDitchParent));
453 MOZ_ASSERT(locales.has(lookup),
454 "shouldn't be a need to add every locale implied by the "
455 "last-ditch locale, merely just the last-ditch locale");
456 #endif
457
458 if (!addLocale(lastDitch, strlen(lastDitch))) {
459 return false;
460 }
461 }
462
463 return true;
464 }
465
466 #ifdef DEBUG
467 template <class AvailableLocales1, class AvailableLocales2>
468 static bool IsSameAvailableLocales(const AvailableLocales1& availableLocales1,
469 const AvailableLocales2& availableLocales2) {
470 return std::equal(std::begin(availableLocales1), std::end(availableLocales1),
471 std::begin(availableLocales2), std::end(availableLocales2),
472 [](const char* a, const char* b) {
473 // Intentionally comparing pointer equivalence.
474 return a == b;
475 });
476 }
477 #endif
478
479 bool js::intl::SharedIntlData::ensureSupportedLocales(JSContext* cx) {
480 if (supportedLocalesInitialized) {
481 return true;
482 }
483
484 // If ensureSupportedLocales() was called previously, but didn't complete due
485 // to OOM, clear all data and start from scratch.
486 supportedLocales.clearAndCompact();
487 collatorSupportedLocales.clearAndCompact();
488
489 if (!getAvailableLocales(cx, supportedLocales,
490 mozilla::intl::Locale::GetAvailableLocales())) {
491 return false;
492 }
493 if (!getAvailableLocales(cx, collatorSupportedLocales,
494 mozilla::intl::Collator::GetAvailableLocales())) {
495 return false;
496 }
497
498 MOZ_ASSERT(IsSameAvailableLocales(
499 mozilla::intl::Locale::GetAvailableLocales(),
500 mozilla::intl::DateTimeFormat::GetAvailableLocales()));
501
502 MOZ_ASSERT(IsSameAvailableLocales(
503 mozilla::intl::Locale::GetAvailableLocales(),
504 mozilla::intl::NumberFormat::GetAvailableLocales()));
505
506 MOZ_ASSERT(!supportedLocalesInitialized,
507 "ensureSupportedLocales is neither reentrant nor thread-safe");
508 supportedLocalesInitialized = true;
509
510 return true;
511 }
512
513 bool js::intl::SharedIntlData::isSupportedLocale(JSContext* cx,
514 SupportedLocaleKind kind,
515 HandleString locale,
516 bool* supported) {
517 if (!ensureSupportedLocales(cx)) {
518 return false;
519 }
520
521 Rooted<JSLinearString*> localeLinear(cx, locale->ensureLinear(cx));
522 if (!localeLinear) {
523 return false;
524 }
525
526 LocaleHasher::Lookup lookup(localeLinear);
527
528 switch (kind) {
529 case SupportedLocaleKind::Collator:
530 *supported = collatorSupportedLocales.has(lookup);
531 return true;
532 case SupportedLocaleKind::DateTimeFormat:
533 case SupportedLocaleKind::DisplayNames:
534 case SupportedLocaleKind::DurationFormat:
535 case SupportedLocaleKind::ListFormat:
536 case SupportedLocaleKind::NumberFormat:
537 case SupportedLocaleKind::PluralRules:
538 case SupportedLocaleKind::RelativeTimeFormat:
539 case SupportedLocaleKind::Segmenter:
540 *supported = supportedLocales.has(lookup);
541 return true;
542 }
543 MOZ_CRASH("Invalid Intl constructor");
544 }
545
546 js::ArrayObject* js::intl::SharedIntlData::availableLocalesOf(
547 JSContext* cx, SupportedLocaleKind kind) {
548 if (!ensureSupportedLocales(cx)) {
549 return nullptr;
550 }
551
552 LocaleSet* localeSet = nullptr;
553 switch (kind) {
554 case SupportedLocaleKind::Collator:
555 localeSet = &collatorSupportedLocales;
556 break;
557 case SupportedLocaleKind::DateTimeFormat:
558 case SupportedLocaleKind::DisplayNames:
559 case SupportedLocaleKind::DurationFormat:
560 case SupportedLocaleKind::ListFormat:
561 case SupportedLocaleKind::NumberFormat:
562 case SupportedLocaleKind::PluralRules:
563 case SupportedLocaleKind::RelativeTimeFormat:
564 case SupportedLocaleKind::Segmenter:
565 localeSet = &supportedLocales;
566 break;
567 default:
568 MOZ_CRASH("Invalid Intl constructor");
569 }
570
571 const uint32_t count = localeSet->count();
572 ArrayObject* result = NewDenseFullyAllocatedArray(cx, count);
573 if (!result) {
574 return nullptr;
575 }
576 result->setDenseInitializedLength(count);
577
578 uint32_t index = 0;
579 for (auto range = localeSet->iter(); !range.done(); range.next()) {
580 JSAtom* locale = range.get();
581 cx->markAtom(locale);
582
583 result->initDenseElement(index++, StringValue(locale));
584 }
585 MOZ_ASSERT(index == count);
586
587 return result;
588 }
589
590 #if DEBUG || MOZ_SYSTEM_ICU
591 bool js::intl::SharedIntlData::ensureUpperCaseFirstLocales(JSContext* cx) {
592 if (upperCaseFirstInitialized) {
593 return true;
594 }
595
596 // If ensureUpperCaseFirstLocales() was called previously, but didn't
597 // complete due to OOM, clear all data and start from scratch.
598 upperCaseFirstLocales.clearAndCompact();
599
600 Rooted<JSAtom*> locale(cx);
601 for (const char* rawLocale : mozilla::intl::Collator::GetAvailableLocales()) {
602 auto collator = mozilla::intl::Collator::TryCreate(rawLocale);
603 if (collator.isErr()) {
604 ReportInternalError(cx, collator.unwrapErr());
605 return false;
606 }
607
608 auto caseFirst = collator.unwrap()->GetCaseFirst();
609 if (caseFirst.isErr()) {
610 ReportInternalError(cx, caseFirst.unwrapErr());
611 return false;
612 }
613
614 if (caseFirst.unwrap() != mozilla::intl::Collator::CaseFirst::Upper) {
615 continue;
616 }
617
618 locale = Atomize(cx, rawLocale, strlen(rawLocale));
619 if (!locale) {
620 return false;
621 }
622
623 LocaleHasher::Lookup lookup(locale);
624 LocaleSet::AddPtr p = upperCaseFirstLocales.lookupForAdd(lookup);
625
626 // ICU shouldn't report any duplicate locales, but if it does, just
627 // ignore the duplicated locale.
628 if (!p && !upperCaseFirstLocales.add(p, locale)) {
629 ReportOutOfMemory(cx);
630 return false;
631 }
632 }
633
634 MOZ_ASSERT(
635 !upperCaseFirstInitialized,
636 "ensureUpperCaseFirstLocales is neither reentrant nor thread-safe");
637 upperCaseFirstInitialized = true;
638
639 return true;
640 }
641 #endif // DEBUG || MOZ_SYSTEM_ICU
642
643 bool js::intl::SharedIntlData::isUpperCaseFirst(JSContext* cx,
644 HandleString locale,
645 bool* isUpperFirst) {
646 #if DEBUG || MOZ_SYSTEM_ICU
647 if (!ensureUpperCaseFirstLocales(cx)) {
648 return false;
649 }
650 #endif
651
652 Rooted<JSLinearString*> localeLinear(cx, locale->ensureLinear(cx));
653 if (!localeLinear) {
654 return false;
655 }
656
657 #if !MOZ_SYSTEM_ICU
658 // "da" (Danish) and "mt" (Maltese) are the only two supported locales using
659 // upper-case first. CLDR also lists "cu" (Church Slavic) as an upper-case
660 // first locale, but since it's not supported in ICU, we don't care about it
661 // here.
662 bool isDefaultUpperCaseFirstLocale =
663 js::StringEqualsLiteral(localeLinear, "da") ||
664 js::StringEqualsLiteral(localeLinear, "mt");
665 #endif
666
667 #if DEBUG || MOZ_SYSTEM_ICU
668 LocaleHasher::Lookup lookup(localeLinear);
669 *isUpperFirst = upperCaseFirstLocales.has(lookup);
670 #else
671 *isUpperFirst = isDefaultUpperCaseFirstLocale;
672 #endif
673
674 #if !MOZ_SYSTEM_ICU
675 MOZ_ASSERT(*isUpperFirst == isDefaultUpperCaseFirstLocale,
676 "upper-case first locales don't match hard-coded list");
677 #endif
678
679 return true;
680 }
681
682 #if DEBUG || MOZ_SYSTEM_ICU
683 bool js::intl::SharedIntlData::ensureIgnorePunctuationLocales(JSContext* cx) {
684 if (ignorePunctuationInitialized) {
685 return true;
686 }
687
688 // If ensureIgnorePunctuationLocales() was called previously, but didn't
689 // complete due to OOM, clear all data and start from scratch.
690 ignorePunctuationLocales.clearAndCompact();
691
692 Rooted<JSAtom*> locale(cx);
693 for (const char* rawLocale : mozilla::intl::Collator::GetAvailableLocales()) {
694 auto collator = mozilla::intl::Collator::TryCreate(rawLocale);
695 if (collator.isErr()) {
696 ReportInternalError(cx, collator.unwrapErr());
697 return false;
698 }
699
700 auto ignorePunctuation = collator.unwrap()->GetIgnorePunctuation();
701 if (ignorePunctuation.isErr()) {
702 ReportInternalError(cx, ignorePunctuation.unwrapErr());
703 return false;
704 }
705
706 if (!ignorePunctuation.unwrap()) {
707 continue;
708 }
709
710 locale = Atomize(cx, rawLocale, strlen(rawLocale));
711 if (!locale) {
712 return false;
713 }
714
715 LocaleHasher::Lookup lookup(locale);
716 LocaleSet::AddPtr p = ignorePunctuationLocales.lookupForAdd(lookup);
717
718 // ICU shouldn't report any duplicate locales, but if it does, just
719 // ignore the duplicated locale.
720 if (!p && !ignorePunctuationLocales.add(p, locale)) {
721 ReportOutOfMemory(cx);
722 return false;
723 }
724 }
725
726 MOZ_ASSERT(
727 !ignorePunctuationInitialized,
728 "ensureIgnorePunctuationLocales is neither reentrant nor thread-safe");
729 ignorePunctuationInitialized = true;
730
731 return true;
732 }
733 #endif // DEBUG || MOZ_SYSTEM_ICU
734
735 bool js::intl::SharedIntlData::isIgnorePunctuation(JSContext* cx,
736 HandleString locale,
737 bool* ignorePunctuation) {
738 #if DEBUG || MOZ_SYSTEM_ICU
739 if (!ensureIgnorePunctuationLocales(cx)) {
740 return false;
741 }
742 #endif
743
744 Rooted<JSLinearString*> localeLinear(cx, locale->ensureLinear(cx));
745 if (!localeLinear) {
746 return false;
747 }
748
749 #if !MOZ_SYSTEM_ICU
750 // "th" (Thai) is the only supported locale which ignores punctuation by
751 // default.
752 bool isDefaultIgnorePunctuationLocale =
753 js::StringEqualsLiteral(localeLinear, "th");
754 #endif
755
756 #if DEBUG || MOZ_SYSTEM_ICU
757 LocaleHasher::Lookup lookup(localeLinear);
758 *ignorePunctuation = ignorePunctuationLocales.has(lookup);
759 #else
760 *ignorePunctuation = isDefaultIgnorePunctuationLocale;
761 #endif
762
763 #if !MOZ_SYSTEM_ICU
764 MOZ_ASSERT(*ignorePunctuation == isDefaultIgnorePunctuationLocale,
765 "ignore punctuation locales don't match hard-coded list");
766 #endif
767
768 return true;
769 }
770
771 void js::intl::DateTimePatternGeneratorDeleter::operator()(
772 mozilla::intl::DateTimePatternGenerator* ptr) {
773 delete ptr;
774 }
775
776 static bool StringsAreEqual(const char* s1, const char* s2) {
777 return !strcmp(s1, s2);
778 }
779
780 mozilla::intl::DateTimePatternGenerator*
781 js::intl::SharedIntlData::getDateTimePatternGenerator(JSContext* cx,
782 const char* locale) {
783 // Return the cached instance if the requested locale matches the locale
784 // of the cached generator.
785 if (dateTimePatternGeneratorLocale &&
786 StringsAreEqual(dateTimePatternGeneratorLocale.get(), locale)) {
787 return dateTimePatternGenerator.get();
788 }
789
790 auto result = mozilla::intl::DateTimePatternGenerator::TryCreate(locale);
791 if (result.isErr()) {
792 intl::ReportInternalError(cx, result.unwrapErr());
793 return nullptr;
794 }
795 // The UniquePtr needs to be recreated as it's using a different Deleter in
796 // order to be able to forward declare DateTimePatternGenerator in
797 // SharedIntlData.h.
798 UniqueDateTimePatternGenerator gen(result.unwrap().release());
799
800 JS::UniqueChars localeCopy = js::DuplicateString(cx, locale);
801 if (!localeCopy) {
802 return nullptr;
803 }
804
805 dateTimePatternGenerator = std::move(gen);
806 dateTimePatternGeneratorLocale = std::move(localeCopy);
807
808 return dateTimePatternGenerator.get();
809 }
810
811 void js::intl::SharedIntlData::destroyInstance() {
812 availableTimeZones.clearAndCompact();
813 ianaZonesTreatedAsLinksByICU.clearAndCompact();
814 ianaLinksCanonicalizedDifferentlyByICU.clearAndCompact();
815 supportedLocales.clearAndCompact();
816 collatorSupportedLocales.clearAndCompact();
817 #if DEBUG || MOZ_SYSTEM_ICU
818 upperCaseFirstLocales.clearAndCompact();
819 ignorePunctuationLocales.clearAndCompact();
820 #endif
821 }
822
823 void js::intl::SharedIntlData::trace(JSTracer* trc) {
824 // Atoms are always tenured.
825 if (!JS::RuntimeHeapIsMinorCollecting()) {
826 availableTimeZones.trace(trc);
827 ianaZonesTreatedAsLinksByICU.trace(trc);
828 ianaLinksCanonicalizedDifferentlyByICU.trace(trc);
829 supportedLocales.trace(trc);
830 collatorSupportedLocales.trace(trc);
831 #if DEBUG || MOZ_SYSTEM_ICU
832 upperCaseFirstLocales.trace(trc);
833 ignorePunctuationLocales.trace(trc);
834 #endif
835 }
836 }
837
838 size_t js::intl::SharedIntlData::sizeOfExcludingThis(
839 mozilla::MallocSizeOf mallocSizeOf) const {
840 return availableTimeZones.shallowSizeOfExcludingThis(mallocSizeOf) +
841 ianaZonesTreatedAsLinksByICU.shallowSizeOfExcludingThis(mallocSizeOf) +
842 ianaLinksCanonicalizedDifferentlyByICU.shallowSizeOfExcludingThis(
843 mallocSizeOf) +
844 supportedLocales.shallowSizeOfExcludingThis(mallocSizeOf) +
845 collatorSupportedLocales.shallowSizeOfExcludingThis(mallocSizeOf) +
846 #if DEBUG || MOZ_SYSTEM_ICU
847 upperCaseFirstLocales.shallowSizeOfExcludingThis(mallocSizeOf) +
848 ignorePunctuationLocales.shallowSizeOfExcludingThis(mallocSizeOf) +
849 #endif
850 mallocSizeOf(dateTimePatternGeneratorLocale.get());
851 }