Debian Codegraph @

js/src/builtin/intl/IntlObject.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 /* Implementation of the Intl object and its non-constructor properties. */
8
9 #include "builtin/intl/IntlObject.h"
10
11 #include "mozilla/Assertions.h"
12 #include "mozilla/intl/Calendar.h"
13 #include "mozilla/intl/Collator.h"
14 #include "mozilla/intl/Currency.h"
15 #include "mozilla/intl/Locale.h"
16 #include "mozilla/intl/MeasureUnitGenerated.h"
17 #include "mozilla/intl/TimeZone.h"
18
19 #include <algorithm>
20 #include <array>
21 #include <cstring>
22 #include <iterator>
23 #include <string_view>
24
25 #include "builtin/Array.h"
26 #include "builtin/intl/CommonFunctions.h"
27 #include "builtin/intl/FormatBuffer.h"
28 #include "builtin/intl/NumberingSystemsGenerated.h"
29 #include "builtin/intl/SharedIntlData.h"
30 #include "builtin/intl/StringAsciiChars.h"
31 #include "ds/Sort.h"
32 #include "js/Class.h"
33 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
34 #include "js/GCAPI.h"
35 #include "js/GCVector.h"
36 #include "js/PropertySpec.h"
37 #include "js/Result.h"
38 #include "js/StableStringChars.h"
39 #include "vm/GlobalObject.h"
40 #include "vm/JSAtomUtils.h" // ClassName
41 #include "vm/JSContext.h"
42 #include "vm/PlainObject.h" // js::PlainObject
43 #include "vm/StringType.h"
44
45 #include "vm/JSObject-inl.h"
46 #include "vm/NativeObject-inl.h"
47
48 using namespace js;
49
50 /******************** Intl ********************/
51
52 bool js::intl_GetCalendarInfo(JSContext* cx, unsigned argc, Value* vp) {
53 CallArgs args = CallArgsFromVp(argc, vp);
54 MOZ_ASSERT(args.length() == 1);
55
56 UniqueChars locale = intl::EncodeLocale(cx, args[0].toString());
57 if (!locale) {
58 return false;
59 }
60
61 auto result = mozilla::intl::Calendar::TryCreate(locale.get());
62 if (result.isErr()) {
63 intl::ReportInternalError(cx, result.unwrapErr());
64 return false;
65 }
66 auto calendar = result.unwrap();
67
68 RootedObject info(cx, NewPlainObject(cx));
69 if (!info) {
70 return false;
71 }
72
73 RootedValue v(cx);
74
75 v.setInt32(static_cast<int32_t>(calendar->GetFirstDayOfWeek()));
76 if (!DefineDataProperty(cx, info, cx->names().firstDayOfWeek, v)) {
77 return false;
78 }
79
80 v.setInt32(calendar->GetMinimalDaysInFirstWeek());
81 if (!DefineDataProperty(cx, info, cx->names().minDays, v)) {
82 return false;
83 }
84
85 Rooted<ArrayObject*> weekendArray(cx, NewDenseEmptyArray(cx));
86 if (!weekendArray) {
87 return false;
88 }
89
90 auto weekend = calendar->GetWeekend();
91 if (weekend.isErr()) {
92 intl::ReportInternalError(cx, weekend.unwrapErr());
93 return false;
94 }
95
96 for (auto day : weekend.unwrap()) {
97 if (!NewbornArrayPush(cx, weekendArray,
98 Int32Value(static_cast<int32_t>(day)))) {
99 return false;
100 }
101 }
102
103 v.setObject(*weekendArray);
104 if (!DefineDataProperty(cx, info, cx->names().weekend, v)) {
105 return false;
106 }
107
108 args.rval().setObject(*info);
109 return true;
110 }
111
112 static void ReportBadKey(JSContext* cx, JSString* key) {
113 if (UniqueChars chars = QuoteString(cx, key, '"')) {
114 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_KEY,
115 chars.get());
116 }
117 }
118
119 static bool SameOrParentLocale(const JSLinearString* locale,
120 const JSLinearString* otherLocale) {
121 // Return true if |locale| is the same locale as |otherLocale|.
122 if (locale->length() == otherLocale->length()) {
123 return EqualStrings(locale, otherLocale);
124 }
125
126 // Also return true if |locale| is the parent locale of |otherLocale|.
127 if (locale->length() < otherLocale->length()) {
128 return HasSubstringAt(otherLocale, locale, 0) &&
129 otherLocale->latin1OrTwoByteChar(locale->length()) == '-';
130 }
131
132 return false;
133 }
134
135 using SupportedLocaleKind = js::intl::SharedIntlData::SupportedLocaleKind;
136
137 // 9.2.2 BestAvailableLocale ( availableLocales, locale )
138 static JS::Result<JSLinearString*> BestAvailableLocale(
139 JSContext* cx, SupportedLocaleKind kind, Handle<JSLinearString*> locale,
140 Handle<JSLinearString*> defaultLocale) {
141 // In the spec, [[availableLocales]] is formally a list of all available
142 // locales. But in our implementation, it's an *incomplete* list, not
143 // necessarily including the default locale (and all locales implied by it,
144 // e.g. "de" implied by "de-CH"), if that locale isn't in every
145 // [[availableLocales]] list (because that locale is supported through
146 // fallback, e.g. "de-CH" supported through "de").
147 //
148 // If we're considering the default locale, augment the spec loop with
149 // additional checks to also test whether the current prefix is a prefix of
150 // the default locale.
151
152 intl::SharedIntlData& sharedIntlData = cx->runtime()->sharedIntlData.ref();
153
154 auto findLast = [](const auto* chars, size_t length) {
155 auto rbegin = std::make_reverse_iterator(chars + length);
156 auto rend = std::make_reverse_iterator(chars);
157 auto p = std::find(rbegin, rend, '-');
158
159 // |dist(chars, p.base())| is equal to |dist(p, rend)|, pick whichever you
160 // find easier to reason about when using reserve iterators.
161 ptrdiff_t r = std::distance(chars, p.base());
162 MOZ_ASSERT(r == std::distance(p, rend));
163
164 // But always subtract one to convert from the reverse iterator result to
165 // the correspoding forward iterator value, because reserve iterators point
166 // to one element past the forward iterator value.
167 return r - 1;
168 };
169
170 // Step 1.
171 Rooted<JSLinearString*> candidate(cx, locale);
172
173 // Step 2.
174 while (true) {
175 // Step 2.a.
176 bool supported = false;
177 if (!sharedIntlData.isSupportedLocale(cx, kind, candidate, &supported)) {
178 return cx->alreadyReportedError();
179 }
180 if (supported) {
181 return candidate.get();
182 }
183
184 if (defaultLocale && SameOrParentLocale(candidate, defaultLocale)) {
185 return candidate.get();
186 }
187
188 // Step 2.b.
189 ptrdiff_t pos;
190 if (candidate->hasLatin1Chars()) {
191 JS::AutoCheckCannotGC nogc;
192 pos = findLast(candidate->latin1Chars(nogc), candidate->length());
193 } else {
194 JS::AutoCheckCannotGC nogc;
195 pos = findLast(candidate->twoByteChars(nogc), candidate->length());
196 }
197
198 if (pos < 0) {
199 return nullptr;
200 }
201
202 // Step 2.c.
203 size_t length = size_t(pos);
204 if (length >= 2 && candidate->latin1OrTwoByteChar(length - 2) == '-') {
205 length -= 2;
206 }
207
208 // Step 2.d.
209 candidate = NewDependentString(cx, candidate, 0, length);
210 if (!candidate) {
211 return cx->alreadyReportedError();
212 }
213 }
214 }
215
216 // 9.2.2 BestAvailableLocale ( availableLocales, locale )
217 //
218 // Carries an additional third argument in our implementation to provide the
219 // default locale. See the doc-comment in the header file.
220 bool js::intl_BestAvailableLocale(JSContext* cx, unsigned argc, Value* vp) {
221 CallArgs args = CallArgsFromVp(argc, vp);
222 MOZ_ASSERT(args.length() == 3);
223
224 SupportedLocaleKind kind;
225 {
226 JSLinearString* typeStr = args[0].toString()->ensureLinear(cx);
227 if (!typeStr) {
228 return false;
229 }
230
231 if (StringEqualsLiteral(typeStr, "Collator")) {
232 kind = SupportedLocaleKind::Collator;
233 } else if (StringEqualsLiteral(typeStr, "DateTimeFormat")) {
234 kind = SupportedLocaleKind::DateTimeFormat;
235 } else if (StringEqualsLiteral(typeStr, "DisplayNames")) {
236 kind = SupportedLocaleKind::DisplayNames;
237 } else if (StringEqualsLiteral(typeStr, "DurationFormat")) {
238 kind = SupportedLocaleKind::DurationFormat;
239 } else if (StringEqualsLiteral(typeStr, "ListFormat")) {
240 kind = SupportedLocaleKind::ListFormat;
241 } else if (StringEqualsLiteral(typeStr, "NumberFormat")) {
242 kind = SupportedLocaleKind::NumberFormat;
243 } else if (StringEqualsLiteral(typeStr, "PluralRules")) {
244 kind = SupportedLocaleKind::PluralRules;
245 } else if (StringEqualsLiteral(typeStr, "RelativeTimeFormat")) {
246 kind = SupportedLocaleKind::RelativeTimeFormat;
247 } else {
248 MOZ_ASSERT(StringEqualsLiteral(typeStr, "Segmenter"));
249 kind = SupportedLocaleKind::Segmenter;
250 }
251 }
252
253 Rooted<JSLinearString*> locale(cx, args[1].toString()->ensureLinear(cx));
254 if (!locale) {
255 return false;
256 }
257
258 #ifdef DEBUG
259 {
260 MOZ_ASSERT(StringIsAscii(locale), "language tags are ASCII-only");
261
262 // |locale| is a structurally valid language tag.
263 mozilla::intl::Locale tag;
264
265 using ParserError = mozilla::intl::LocaleParser::ParserError;
266 mozilla::Result<mozilla::Ok, ParserError> parse_result = Ok();
267 {
268 intl::StringAsciiChars chars(locale);
269 if (!chars.init(cx)) {
270 return false;
271 }
272
273 parse_result = mozilla::intl::LocaleParser::TryParse(chars, tag);
274 }
275
276 if (parse_result.isErr()) {
277 MOZ_ASSERT(parse_result.unwrapErr() == ParserError::OutOfMemory,
278 "locale is a structurally valid language tag");
279
280 intl::ReportInternalError(cx);
281 return false;
282 }
283
284 MOZ_ASSERT(!tag.GetUnicodeExtension(),
285 "locale must contain no Unicode extensions");
286
287 if (auto result = tag.Canonicalize(); result.isErr()) {
288 MOZ_ASSERT(
289 result.unwrapErr() !=
290 mozilla::intl::Locale::CanonicalizationError::DuplicateVariant);
291 intl::ReportInternalError(cx);
292 return false;
293 }
294
295 intl::FormatBuffer<char, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
296 if (auto result = tag.ToString(buffer); result.isErr()) {
297 intl::ReportInternalError(cx, result.unwrapErr());
298 return false;
299 }
300
301 MOZ_ASSERT(StringEqualsAscii(locale, buffer.data(), buffer.length()),
302 "locale is a canonicalized language tag");
303 }
304 #endif
305
306 MOZ_ASSERT(args[2].isNull() || args[2].isString());
307
308 Rooted<JSLinearString*> defaultLocale(cx);
309 if (args[2].isString()) {
310 defaultLocale = args[2].toString()->ensureLinear(cx);
311 if (!defaultLocale) {
312 return false;
313 }
314 }
315
316 JSString* result;
317 JS_TRY_VAR_OR_RETURN_FALSE(
318 cx, result, BestAvailableLocale(cx, kind, locale, defaultLocale));
319
320 if (result) {
321 args.rval().setString(result);
322 } else {
323 args.rval().setUndefined();
324 }
325 return true;
326 }
327
328 bool js::intl_supportedLocaleOrFallback(JSContext* cx, unsigned argc,
329 Value* vp) {
330 CallArgs args = CallArgsFromVp(argc, vp);
331 MOZ_ASSERT(args.length() == 1);
332
333 Rooted<JSLinearString*> locale(cx, args[0].toString()->ensureLinear(cx));
334 if (!locale) {
335 return false;
336 }
337
338 mozilla::intl::Locale tag;
339 bool canParseLocale = false;
340 if (StringIsAscii(locale)) {
341 intl::StringAsciiChars chars(locale);
342 if (!chars.init(cx)) {
343 return false;
344 }
345
346 // Tell the analysis the |tag.canonicalize()| method can't GC.
347 JS::AutoSuppressGCAnalysis nogc;
348
349 canParseLocale = mozilla::intl::LocaleParser::TryParse(chars, tag).isOk() &&
350 tag.Canonicalize().isOk();
351 }
352
353 Rooted<JSLinearString*> candidate(cx);
354 if (!canParseLocale) {
355 candidate = NewStringCopyZ<CanGC>(cx, intl::LastDitchLocale());
356 if (!candidate) {
357 return false;
358 }
359 } else {
360 // The default locale must be in [[AvailableLocales]], and that list must
361 // not contain any locales with Unicode extension sequences, so remove any
362 // present in the candidate.
363 tag.ClearUnicodeExtension();
364
365 intl::FormatBuffer<char, intl::INITIAL_CHAR_BUFFER_SIZE> buffer(cx);
366 if (auto result = tag.ToString(buffer); result.isErr()) {
367 intl::ReportInternalError(cx, result.unwrapErr());
368 return false;
369 }
370
371 candidate = buffer.toAsciiString(cx);
372 if (!candidate) {
373 return false;
374 }
375
376 // Certain old-style language tags lack a script code, but in current
377 // usage they *would* include a script code. Map these over to modern
378 // forms.
379 for (const auto& mapping : js::intl::oldStyleLanguageTagMappings) {
380 const char* oldStyle = mapping.oldStyle;
381 const char* modernStyle = mapping.modernStyle;
382
383 if (StringEqualsAscii(candidate, oldStyle)) {
384 candidate = NewStringCopyZ<CanGC>(cx, modernStyle);
385 if (!candidate) {
386 return false;
387 }
388 break;
389 }
390 }
391 }
392
393 // 9.1 Internal slots of Service Constructors
394 //
395 // - [[AvailableLocales]] is a List [...]. The list must include the value
396 // returned by the DefaultLocale abstract operation (6.2.4), [...].
397 //
398 // That implies we must ignore any candidate which isn't supported by all
399 // Intl service constructors.
400
401 Rooted<JSLinearString*> supportedCollator(cx);
402 JS_TRY_VAR_OR_RETURN_FALSE(
403 cx, supportedCollator,
404 BestAvailableLocale(cx, SupportedLocaleKind::Collator, candidate,
405 nullptr));
406
407 Rooted<JSLinearString*> supportedDateTimeFormat(cx);
408 JS_TRY_VAR_OR_RETURN_FALSE(
409 cx, supportedDateTimeFormat,
410 BestAvailableLocale(cx, SupportedLocaleKind::DateTimeFormat, candidate,
411 nullptr));
412
413 #ifdef DEBUG
414 // Note: We don't test the supported locales of the remaining Intl service
415 // constructors, because the set of supported locales is exactly equal to
416 // the set of supported locales of Intl.DateTimeFormat.
417 for (auto kind : {
418 SupportedLocaleKind::DisplayNames,
419 SupportedLocaleKind::DurationFormat,
420 SupportedLocaleKind::ListFormat,
421 SupportedLocaleKind::NumberFormat,
422 SupportedLocaleKind::PluralRules,
423 SupportedLocaleKind::RelativeTimeFormat,
424 SupportedLocaleKind::Segmenter,
425 }) {
426 JSLinearString* supported;
427 JS_TRY_VAR_OR_RETURN_FALSE(
428 cx, supported, BestAvailableLocale(cx, kind, candidate, nullptr));
429
430 MOZ_ASSERT(!!supported == !!supportedDateTimeFormat);
431 MOZ_ASSERT_IF(supported, EqualStrings(supported, supportedDateTimeFormat));
432 }
433 #endif
434
435 // Accept the candidate locale if it is supported by all Intl service
436 // constructors.
437 if (supportedCollator && supportedDateTimeFormat) {
438 // Use the actually supported locale instead of the candidate locale. For
439 // example when the candidate locale "en-US-posix" is supported through
440 // "en-US", use "en-US" as the default locale.
441 //
442 // Also prefer the supported locale with more subtags. For example when
443 // requesting "de-CH" and Intl.DateTimeFormat supports "de-CH", but
444 // Intl.Collator only "de", still return "de-CH" as the result.
445 if (SameOrParentLocale(supportedCollator, supportedDateTimeFormat)) {
446 candidate = supportedDateTimeFormat;
447 } else {
448 candidate = supportedCollator;
449 }
450 } else {
451 candidate = NewStringCopyZ<CanGC>(cx, intl::LastDitchLocale());
452 if (!candidate) {
453 return false;
454 }
455 }
456
457 args.rval().setString(candidate);
458 return true;
459 }
460
461 using StringList = GCVector<JSLinearString*>;
462
463 /**
464 * Create a sorted array from a list of strings.
465 */
466 static ArrayObject* CreateArrayFromList(JSContext* cx,
467 MutableHandle<StringList> list) {
468 // Reserve scratch space for MergeSort().
469 size_t initialLength = list.length();
470 if (!list.growBy(initialLength)) {
471 return nullptr;
472 }
473
474 // Sort all strings in alphabetical order.
475 MOZ_ALWAYS_TRUE(
476 MergeSort(list.begin(), initialLength, list.begin() + initialLength,
477 [](const auto* a, const auto* b, bool* lessOrEqual) {
478 *lessOrEqual = CompareStrings(a, b) <= 0;
479 return true;
480 }));
481
482 // Ensure we don't add duplicate entries to the array.
483 auto* end = std::unique(
484 list.begin(), list.begin() + initialLength,
485 [](const auto* a, const auto* b) { return EqualStrings(a, b); });
486
487 // std::unique leaves the elements after |end| with an unspecified value, so
488 // remove them first. And also delete the elements in the scratch space.
489 list.shrinkBy(std::distance(end, list.end()));
490
491 // And finally copy the strings into the result array.
492 auto* array = NewDenseFullyAllocatedArray(cx, list.length());
493 if (!array) {
494 return nullptr;
495 }
496 array->setDenseInitializedLength(list.length());
497
498 for (size_t i = 0; i < list.length(); ++i) {
499 array->initDenseElement(i, StringValue(list[i]));
500 }
501
502 return array;
503 }
504
505 /**
506 * Create an array from a sorted list of strings.
507 */
508 template <size_t N>
509 static ArrayObject* CreateArrayFromSortedList(
510 JSContext* cx, const std::array<const char*, N>& list) {
511 // Ensure the list is sorted and doesn't contain duplicates.
512 #ifdef DEBUG
513 // See bug 1583449 for why the lambda can't be in the MOZ_ASSERT.
514 auto isLargerThanOrEqual = [](const auto& a, const auto& b) {
515 return std::strcmp(a, b) >= 0;
516 };
517 #endif
518 MOZ_ASSERT(std::adjacent_find(std::begin(list), std::end(list),
519 isLargerThanOrEqual) == std::end(list));
520
521 size_t length = std::size(list);
522
523 Rooted<ArrayObject*> array(cx, NewDenseFullyAllocatedArray(cx, length));
524 if (!array) {
525 return nullptr;
526 }
527 array->ensureDenseInitializedLength(0, length);
528
529 for (size_t i = 0; i < length; ++i) {
530 auto* str = NewStringCopyZ<CanGC>(cx, list[i]);
531 if (!str) {
532 return nullptr;
533 }
534 array->initDenseElement(i, StringValue(str));
535 }
536 return array;
537 }
538
539 /**
540 * Create an array from an intl::Enumeration.
541 */
542 template <const auto& unsupported, class Enumeration>
543 static bool EnumerationIntoList(JSContext* cx, Enumeration values,
544 MutableHandle<StringList> list) {
545 for (auto value : values) {
546 if (value.isErr()) {
547 intl::ReportInternalError(cx);
548 return false;
549 }
550 auto span = value.unwrap();
551
552 // Skip over known, unsupported values.
553 std::string_view sv(span.data(), span.size());
554 if (std::any_of(std::begin(unsupported), std::end(unsupported),
555 [sv](const auto& e) { return sv == e; })) {
556 continue;
557 }
558
559 auto* string = NewStringCopy<CanGC>(cx, span);
560 if (!string) {
561 return false;
562 }
563 if (!list.append(string)) {
564 return false;
565 }
566 }
567
568 return true;
569 }
570
571 /**
572 * Returns the list of calendar types which mustn't be returned by
573 * |Intl.supportedValuesOf()|.
574 */
575 static constexpr auto UnsupportedCalendars() {
576 // No calendar values are currently unsupported.
577 return std::array<const char*, 0>{};
578 }
579
580 // Defined outside of the function to workaround bugs in GCC<9.
581 // Also see <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85589>.
582 static constexpr auto UnsupportedCalendarsArray = UnsupportedCalendars();
583
584 /**
585 * AvailableCalendars ( )
586 */
587 static ArrayObject* AvailableCalendars(JSContext* cx) {
588 Rooted<StringList> list(cx, StringList(cx));
589
590 {
591 // Hazard analysis complains that the mozilla::Result destructor calls a
592 // GC function, which is unsound when returning an unrooted value. Work
593 // around this issue by restricting the lifetime of |keywords| to a
594 // separate block.
595 auto keywords = mozilla::intl::Calendar::GetBcp47KeywordValuesForLocale("");
596 if (keywords.isErr()) {
597 intl::ReportInternalError(cx, keywords.unwrapErr());
598 return nullptr;
599 }
600
601 static constexpr auto& unsupported = UnsupportedCalendarsArray;
602
603 if (!EnumerationIntoList<unsupported>(cx, keywords.unwrap(), &list)) {
604 return nullptr;
605 }
606 }
607
608 return CreateArrayFromList(cx, &list);
609 }
610
611 /**
612 * Returns the list of collation types which mustn't be returned by
613 * |Intl.supportedValuesOf()|.
614 */
615 static constexpr auto UnsupportedCollations() {
616 return std::array{
617 "search",
618 "standard",
619 };
620 }
621
622 // Defined outside of the function to workaround bugs in GCC<9.
623 // Also see <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85589>.
624 static constexpr auto UnsupportedCollationsArray = UnsupportedCollations();
625
626 /**
627 * AvailableCollations ( )
628 */
629 static ArrayObject* AvailableCollations(JSContext* cx) {
630 Rooted<StringList> list(cx, StringList(cx));
631
632 {
633 // Hazard analysis complains that the mozilla::Result destructor calls a
634 // GC function, which is unsound when returning an unrooted value. Work
635 // around this issue by restricting the lifetime of |keywords| to a
636 // separate block.
637 auto keywords = mozilla::intl::Collator::GetBcp47KeywordValues();
638 if (keywords.isErr()) {
639 intl::ReportInternalError(cx, keywords.unwrapErr());
640 return nullptr;
641 }
642
643 static constexpr auto& unsupported = UnsupportedCollationsArray;
644
645 if (!EnumerationIntoList<unsupported>(cx, keywords.unwrap(), &list)) {
646 return nullptr;
647 }
648 }
649
650 return CreateArrayFromList(cx, &list);
651 }
652
653 /**
654 * Returns a list of known, unsupported currencies which are returned by
655 * |Currency::GetISOCurrencies()|.
656 */
657 static constexpr auto UnsupportedCurrencies() {
658 // "MVP" is also marked with "questionable, remove?" in ucurr.cpp, but only
659 // this single currency code isn't supported by |Intl.DisplayNames| and
660 // therefore must be excluded by |Intl.supportedValuesOf|.
661 return std::array{
662 "LSM", // https://unicode-org.atlassian.net/browse/ICU-21687
663 };
664 }
665
666 /**
667 * Return a list of known, missing currencies which aren't returned by
668 * |Currency::GetISOCurrencies()|.
669 */
670 static constexpr auto MissingCurrencies() {
671 return std::array{
672 "SLE", // https://unicode-org.atlassian.net/browse/ICU-21989
673 "VED", // https://unicode-org.atlassian.net/browse/ICU-21989
674 };
675 }
676
677 // Defined outside of the function to workaround bugs in GCC<9.
678 // Also see <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85589>.
679 static constexpr auto UnsupportedCurrenciesArray = UnsupportedCurrencies();
680 static constexpr auto MissingCurrenciesArray = MissingCurrencies();
681
682 /**
683 * AvailableCurrencies ( )
684 */
685 static ArrayObject* AvailableCurrencies(JSContext* cx) {
686 Rooted<StringList> list(cx, StringList(cx));
687
688 {
689 // Hazard analysis complains that the mozilla::Result destructor calls a
690 // GC function, which is unsound when returning an unrooted value. Work
691 // around this issue by restricting the lifetime of |currencies| to a
692 // separate block.
693 auto currencies = mozilla::intl::Currency::GetISOCurrencies();
694 if (currencies.isErr()) {
695 intl::ReportInternalError(cx, currencies.unwrapErr());
696 return nullptr;
697 }
698
699 static constexpr auto& unsupported = UnsupportedCurrenciesArray;
700
701 if (!EnumerationIntoList<unsupported>(cx, currencies.unwrap(), &list)) {
702 return nullptr;
703 }
704 }
705
706 // Add known missing values.
707 for (const char* value : MissingCurrenciesArray) {
708 auto* string = NewStringCopyZ<CanGC>(cx, value);
709 if (!string) {
710 return nullptr;
711 }
712 if (!list.append(string)) {
713 return nullptr;
714 }
715 }
716
717 return CreateArrayFromList(cx, &list);
718 }
719
720 /**
721 * AvailableNumberingSystems ( )
722 */
723 static ArrayObject* AvailableNumberingSystems(JSContext* cx) {
724 static constexpr std::array numberingSystems = {
725 NUMBERING_SYSTEMS_WITH_SIMPLE_DIGIT_MAPPINGS};
726
727 return CreateArrayFromSortedList(cx, numberingSystems);
728 }
729
730 /**
731 * AvailableTimeZones ( )
732 */
733 static ArrayObject* AvailableTimeZones(JSContext* cx) {
734 // Unsorted list of canonical time zone names, possibly containing duplicates.
735 Rooted<StringList> timeZones(cx, StringList(cx));
736
737 intl::SharedIntlData& sharedIntlData = cx->runtime()->sharedIntlData.ref();
738 auto iterResult = sharedIntlData.availableTimeZonesIteration(cx);
739 if (iterResult.isErr()) {
740 return nullptr;
741 }
742 auto iter = iterResult.unwrap();
743
744 Rooted<JSAtom*> validatedTimeZone(cx);
745 for (; !iter.done(); iter.next()) {
746 validatedTimeZone = iter.get();
747
748 // Canonicalize the time zone before adding it to the result array.
749 auto* timeZone = intl::CanonicalizeTimeZone(cx, validatedTimeZone);
750 if (!timeZone) {
751 return nullptr;
752 }
753
754 if (!timeZones.append(timeZone)) {
755 return nullptr;
756 }
757 }
758
759 return CreateArrayFromList(cx, &timeZones);
760 }
761
762 template <size_t N>
763 constexpr auto MeasurementUnitNames(
764 const mozilla::intl::SimpleMeasureUnit (&units)[N]) {
765 std::array<const char*, N> array = {};
766 for (size_t i = 0; i < N; ++i) {
767 array[i] = units[i].name;
768 }
769 return array;
770 }
771
772 /**
773 * AvailableUnits ( )
774 */
775 static ArrayObject* AvailableUnits(JSContext* cx) {
776 static constexpr auto simpleMeasureUnitNames =
777 MeasurementUnitNames(mozilla::intl::simpleMeasureUnits);
778
779 return CreateArrayFromSortedList(cx, simpleMeasureUnitNames);
780 }
781
782 bool js::intl_SupportedValuesOf(JSContext* cx, unsigned argc, JS::Value* vp) {
783 CallArgs args = CallArgsFromVp(argc, vp);
784 MOZ_ASSERT(args.length() == 1);
785 MOZ_ASSERT(args[0].isString());
786
787 JSLinearString* key = args[0].toString()->ensureLinear(cx);
788 if (!key) {
789 return false;
790 }
791
792 ArrayObject* list;
793 if (StringEqualsLiteral(key, "calendar")) {
794 list = AvailableCalendars(cx);
795 } else if (StringEqualsLiteral(key, "collation")) {
796 list = AvailableCollations(cx);
797 } else if (StringEqualsLiteral(key, "currency")) {
798 list = AvailableCurrencies(cx);
799 } else if (StringEqualsLiteral(key, "numberingSystem")) {
800 list = AvailableNumberingSystems(cx);
801 } else if (StringEqualsLiteral(key, "timeZone")) {
802 list = AvailableTimeZones(cx);
803 } else if (StringEqualsLiteral(key, "unit")) {
804 list = AvailableUnits(cx);
805 } else {
806 ReportBadKey(cx, key);
807 return false;
808 }
809 if (!list) {
810 return false;
811 }
812
813 args.rval().setObject(*list);
814 return true;
815 }
816
817 static bool intl_toSource(JSContext* cx, unsigned argc, Value* vp) {
818 CallArgs args = CallArgsFromVp(argc, vp);
819 args.rval().setString(cx->names().Intl);
820 return true;
821 }
822
823 static const JSFunctionSpec intl_static_methods[] = {
824 JS_FN("toSource", intl_toSource, 0, 0),
825 JS_SELF_HOSTED_FN("getCanonicalLocales", "Intl_getCanonicalLocales", 1, 0),
826 JS_SELF_HOSTED_FN("supportedValuesOf", "Intl_supportedValuesOf", 1, 0),
827 JS_FS_END,
828 };
829
830 static const JSPropertySpec intl_static_properties[] = {
831 JS_STRING_SYM_PS(toStringTag, "Intl", JSPROP_READONLY),
832 JS_PS_END,
833 };
834
835 static JSObject* CreateIntlObject(JSContext* cx, JSProtoKey key) {
836 RootedObject proto(cx, &cx->global()->getObjectPrototype());
837
838 // The |Intl| object is just a plain object with some "static" function
839 // properties and some constructor properties.
840 return NewTenuredObjectWithGivenProto(cx, &IntlClass, proto);
841 }
842
843 /**
844 * Initializes the Intl Object and its standard built-in properties.
845 * Spec: ECMAScript Internationalization API Specification, 8.0, 8.1
846 */
847 static bool IntlClassFinish(JSContext* cx, HandleObject intl,
848 HandleObject proto) {
849 // Add the constructor properties.
850 RootedId ctorId(cx);
851 RootedValue ctorValue(cx);
852 for (const auto& protoKey : {
853 JSProto_Collator,
854 JSProto_DateTimeFormat,
855 JSProto_DisplayNames,
856 JSProto_DurationFormat,
857 JSProto_ListFormat,
858 JSProto_Locale,
859 JSProto_NumberFormat,
860 JSProto_PluralRules,
861 JSProto_RelativeTimeFormat,
862 JSProto_Segmenter,
863 }) {
864 if (GlobalObject::skipDeselectedConstructor(cx, protoKey)) {
865 continue;
866 }
867
868 JSObject* ctor = GlobalObject::getOrCreateConstructor(cx, protoKey);
869 if (!ctor) {
870 return false;
871 }
872
873 ctorId = NameToId(ClassName(protoKey, cx));
874 ctorValue.setObject(*ctor);
875 if (!DefineDataProperty(cx, intl, ctorId, ctorValue, 0)) {
876 return false;
877 }
878 }
879
880 return true;
881 }
882
883 static const ClassSpec IntlClassSpec = {
884 CreateIntlObject, nullptr, intl_static_methods, intl_static_properties,
885 nullptr, nullptr, IntlClassFinish,
886 };
887
888 const JSClass js::IntlClass = {
889 "Intl",
890 JSCLASS_HAS_CACHED_PROTO(JSProto_Intl),
891 JS_NULL_CLASS_OPS,
892 &IntlClassSpec,
893 };