-
Notifications
You must be signed in to change notification settings - Fork 30.9k
/
Copy pathintl-objects.cc
2115 lines (1849 loc) Β· 79.6 KB
/
intl-objects.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_INTL_SUPPORT
#error Internationalization is expected to be enabled.
#endif // V8_INTL_SUPPORT
#include "src/objects/intl-objects.h"
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include "src/api/api-inl.h"
#include "src/execution/isolate.h"
#include "src/handles/global-handles.h"
#include "src/heap/factory.h"
#include "src/objects/js-collator-inl.h"
#include "src/objects/js-date-time-format-inl.h"
#include "src/objects/js-locale-inl.h"
#include "src/objects/js-locale.h"
#include "src/objects/js-number-format-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/property-descriptor.h"
#include "src/objects/string.h"
#include "src/strings/string-case.h"
#include "unicode/basictz.h"
#include "unicode/brkiter.h"
#include "unicode/calendar.h"
#include "unicode/coll.h"
#include "unicode/datefmt.h"
#include "unicode/decimfmt.h"
#include "unicode/formattedvalue.h"
#include "unicode/localebuilder.h"
#include "unicode/locid.h"
#include "unicode/normalizer2.h"
#include "unicode/numberformatter.h"
#include "unicode/numfmt.h"
#include "unicode/numsys.h"
#include "unicode/timezone.h"
#include "unicode/ures.h"
#include "unicode/ustring.h"
#include "unicode/uvernum.h" // U_ICU_VERSION_MAJOR_NUM
#define XSTR(s) STR(s)
#define STR(s) #s
static_assert(
V8_MINIMUM_ICU_VERSION <= U_ICU_VERSION_MAJOR_NUM,
"v8 is required to build with ICU " XSTR(V8_MINIMUM_ICU_VERSION) " and up");
#undef STR
#undef XSTR
namespace v8 {
namespace internal {
namespace {
constexpr uint8_t kToLower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23,
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73,
0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,
0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B,
0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3,
0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB,
0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xD7,
0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3,
0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB,
0xFC, 0xFD, 0xFE, 0xFF,
};
inline constexpr uint16_t ToLatin1Lower(uint16_t ch) {
return static_cast<uint16_t>(kToLower[ch]);
}
// Does not work for U+00DF (sharp-s), U+00B5 (micron), U+00FF.
inline constexpr uint16_t ToLatin1Upper(uint16_t ch) {
#if V8_CAN_HAVE_DCHECK_IN_CONSTEXPR
DCHECK(ch != 0xDF && ch != 0xB5 && ch != 0xFF);
#endif
return ch &
~((IsAsciiLower(ch) || (((ch & 0xE0) == 0xE0) && ch != 0xF7)) << 5);
}
template <typename Char>
bool ToUpperFastASCII(const Vector<const Char>& src,
Handle<SeqOneByteString> result) {
// Do a faster loop for the case where all the characters are ASCII.
uint16_t ored = 0;
int32_t index = 0;
for (auto it = src.begin(); it != src.end(); ++it) {
uint16_t ch = static_cast<uint16_t>(*it);
ored |= ch;
result->SeqOneByteStringSet(index++, ToAsciiUpper(ch));
}
return !(ored & ~0x7F);
}
const uint16_t sharp_s = 0xDF;
template <typename Char>
bool ToUpperOneByte(const Vector<const Char>& src, uint8_t* dest,
int* sharp_s_count) {
// Still pretty-fast path for the input with non-ASCII Latin-1 characters.
// There are two special cases.
// 1. U+00B5 and U+00FF are mapped to a character beyond U+00FF.
// 2. Lower case sharp-S converts to "SS" (two characters)
*sharp_s_count = 0;
for (auto it = src.begin(); it != src.end(); ++it) {
uint16_t ch = static_cast<uint16_t>(*it);
if (V8_UNLIKELY(ch == sharp_s)) {
++(*sharp_s_count);
continue;
}
if (V8_UNLIKELY(ch == 0xB5 || ch == 0xFF)) {
// Since this upper-cased character does not fit in an 8-bit string, we
// need to take the 16-bit path.
return false;
}
*dest++ = ToLatin1Upper(ch);
}
return true;
}
template <typename Char>
void ToUpperWithSharpS(const Vector<const Char>& src,
Handle<SeqOneByteString> result) {
int32_t dest_index = 0;
for (auto it = src.begin(); it != src.end(); ++it) {
uint16_t ch = static_cast<uint16_t>(*it);
if (ch == sharp_s) {
result->SeqOneByteStringSet(dest_index++, 'S');
result->SeqOneByteStringSet(dest_index++, 'S');
} else {
result->SeqOneByteStringSet(dest_index++, ToLatin1Upper(ch));
}
}
}
inline int FindFirstUpperOrNonAscii(String s, int length) {
for (int index = 0; index < length; ++index) {
uint16_t ch = s.Get(index);
if (V8_UNLIKELY(IsAsciiUpper(ch) || ch & ~0x7F)) {
return index;
}
}
return length;
}
const UChar* GetUCharBufferFromFlat(const String::FlatContent& flat,
std::unique_ptr<uc16[]>* dest,
int32_t length) {
DCHECK(flat.IsFlat());
if (flat.IsOneByte()) {
if (!*dest) {
dest->reset(NewArray<uc16>(length));
CopyChars(dest->get(), flat.ToOneByteVector().begin(), length);
}
return reinterpret_cast<const UChar*>(dest->get());
} else {
return reinterpret_cast<const UChar*>(flat.ToUC16Vector().begin());
}
}
template <typename T>
MaybeHandle<T> New(Isolate* isolate, Handle<JSFunction> constructor,
Handle<Object> locales, Handle<Object> options,
const char* method) {
Handle<Map> map;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, map,
JSFunction::GetDerivedMap(isolate, constructor, constructor), T);
return T::New(isolate, map, locales, options, method);
}
} // namespace
const uint8_t* Intl::ToLatin1LowerTable() { return &kToLower[0]; }
icu::UnicodeString Intl::ToICUUnicodeString(Isolate* isolate,
Handle<String> string) {
DCHECK(string->IsFlat());
DisallowHeapAllocation no_gc;
std::unique_ptr<uc16[]> sap;
// Short one-byte strings can be expanded on the stack to avoid allocating a
// temporary buffer.
constexpr int kShortStringSize = 80;
UChar short_string_buffer[kShortStringSize];
const UChar* uchar_buffer = nullptr;
const String::FlatContent& flat = string->GetFlatContent(no_gc);
int32_t length = string->length();
if (flat.IsOneByte() && length <= kShortStringSize) {
CopyChars(short_string_buffer, flat.ToOneByteVector().begin(), length);
uchar_buffer = short_string_buffer;
} else {
uchar_buffer = GetUCharBufferFromFlat(flat, &sap, length);
}
return icu::UnicodeString(uchar_buffer, length);
}
icu::StringPiece Intl::ToICUStringPiece(Isolate* isolate,
Handle<String> string) {
DCHECK(string->IsFlat());
DisallowHeapAllocation no_gc;
const String::FlatContent& flat = string->GetFlatContent(no_gc);
if (!flat.IsOneByte()) return icu::StringPiece(nullptr, 0);
int32_t length = string->length();
const char* char_buffer =
reinterpret_cast<const char*>(flat.ToOneByteVector().begin());
if (!String::IsAscii(char_buffer, length)) {
return icu::StringPiece(nullptr, 0);
}
return icu::StringPiece(char_buffer, length);
}
namespace {
MaybeHandle<String> LocaleConvertCase(Isolate* isolate, Handle<String> s,
bool is_to_upper, const char* lang) {
auto case_converter = is_to_upper ? u_strToUpper : u_strToLower;
int32_t src_length = s->length();
int32_t dest_length = src_length;
UErrorCode status;
Handle<SeqTwoByteString> result;
std::unique_ptr<uc16[]> sap;
if (dest_length == 0) return ReadOnlyRoots(isolate).empty_string_handle();
// This is not a real loop. It'll be executed only once (no overflow) or
// twice (overflow).
for (int i = 0; i < 2; ++i) {
// Case conversion can increase the string length (e.g. sharp-S => SS) so
// that we have to handle RangeError exceptions here.
ASSIGN_RETURN_ON_EXCEPTION(
isolate, result, isolate->factory()->NewRawTwoByteString(dest_length),
String);
DisallowHeapAllocation no_gc;
DCHECK(s->IsFlat());
String::FlatContent flat = s->GetFlatContent(no_gc);
const UChar* src = GetUCharBufferFromFlat(flat, &sap, src_length);
status = U_ZERO_ERROR;
dest_length =
case_converter(reinterpret_cast<UChar*>(result->GetChars(no_gc)),
dest_length, src, src_length, lang, &status);
if (status != U_BUFFER_OVERFLOW_ERROR) break;
}
// In most cases, the output will fill the destination buffer completely
// leading to an unterminated string (U_STRING_NOT_TERMINATED_WARNING).
// Only in rare cases, it'll be shorter than the destination buffer and
// |result| has to be truncated.
DCHECK(U_SUCCESS(status));
if (V8_LIKELY(status == U_STRING_NOT_TERMINATED_WARNING)) {
DCHECK(dest_length == result->length());
return result;
}
DCHECK(dest_length < result->length());
return SeqString::Truncate(result, dest_length);
}
} // namespace
// A stripped-down version of ConvertToLower that can only handle flat one-byte
// strings and does not allocate. Note that {src} could still be, e.g., a
// one-byte sliced string with a two-byte parent string.
// Called from TF builtins.
String Intl::ConvertOneByteToLower(String src, String dst) {
DCHECK_EQ(src.length(), dst.length());
DCHECK(src.IsOneByteRepresentation());
DCHECK(src.IsFlat());
DCHECK(dst.IsSeqOneByteString());
DisallowHeapAllocation no_gc;
const int length = src.length();
String::FlatContent src_flat = src.GetFlatContent(no_gc);
uint8_t* dst_data = SeqOneByteString::cast(dst).GetChars(no_gc);
if (src_flat.IsOneByte()) {
const uint8_t* src_data = src_flat.ToOneByteVector().begin();
bool has_changed_character = false;
int index_to_first_unprocessed =
FastAsciiConvert<true>(reinterpret_cast<char*>(dst_data),
reinterpret_cast<const char*>(src_data), length,
&has_changed_character);
if (index_to_first_unprocessed == length) {
return has_changed_character ? dst : src;
}
// If not ASCII, we keep the result up to index_to_first_unprocessed and
// process the rest.
for (int index = index_to_first_unprocessed; index < length; ++index) {
dst_data[index] = ToLatin1Lower(static_cast<uint16_t>(src_data[index]));
}
} else {
DCHECK(src_flat.IsTwoByte());
int index_to_first_unprocessed = FindFirstUpperOrNonAscii(src, length);
if (index_to_first_unprocessed == length) return src;
const uint16_t* src_data = src_flat.ToUC16Vector().begin();
CopyChars(dst_data, src_data, index_to_first_unprocessed);
for (int index = index_to_first_unprocessed; index < length; ++index) {
dst_data[index] = ToLatin1Lower(static_cast<uint16_t>(src_data[index]));
}
}
return dst;
}
MaybeHandle<String> Intl::ConvertToLower(Isolate* isolate, Handle<String> s) {
if (!s->IsOneByteRepresentation()) {
// Use a slower implementation for strings with characters beyond U+00FF.
return LocaleConvertCase(isolate, s, false, "");
}
int length = s->length();
// We depend here on the invariant that the length of a Latin1
// string is invariant under ToLowerCase, and the result always
// fits in the Latin1 range in the *root locale*. It does not hold
// for ToUpperCase even in the root locale.
// Scan the string for uppercase and non-ASCII characters for strings
// shorter than a machine-word without any memory allocation overhead.
// TODO(jshin): Apply this to a longer input by breaking FastAsciiConvert()
// to two parts, one for scanning the prefix with no change and the other for
// handling ASCII-only characters.
bool is_short = length < static_cast<int>(sizeof(uintptr_t));
if (is_short) {
bool is_lower_ascii = FindFirstUpperOrNonAscii(*s, length) == length;
if (is_lower_ascii) return s;
}
Handle<SeqOneByteString> result =
isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
return Handle<String>(Intl::ConvertOneByteToLower(*s, *result), isolate);
}
MaybeHandle<String> Intl::ConvertToUpper(Isolate* isolate, Handle<String> s) {
int32_t length = s->length();
if (s->IsOneByteRepresentation() && length > 0) {
Handle<SeqOneByteString> result =
isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
DCHECK(s->IsFlat());
int sharp_s_count;
bool is_result_single_byte;
{
DisallowHeapAllocation no_gc;
String::FlatContent flat = s->GetFlatContent(no_gc);
uint8_t* dest = result->GetChars(no_gc);
if (flat.IsOneByte()) {
Vector<const uint8_t> src = flat.ToOneByteVector();
bool has_changed_character = false;
int index_to_first_unprocessed = FastAsciiConvert<false>(
reinterpret_cast<char*>(result->GetChars(no_gc)),
reinterpret_cast<const char*>(src.begin()), length,
&has_changed_character);
if (index_to_first_unprocessed == length) {
return has_changed_character ? result : s;
}
// If not ASCII, we keep the result up to index_to_first_unprocessed and
// process the rest.
is_result_single_byte =
ToUpperOneByte(src.SubVector(index_to_first_unprocessed, length),
dest + index_to_first_unprocessed, &sharp_s_count);
} else {
DCHECK(flat.IsTwoByte());
Vector<const uint16_t> src = flat.ToUC16Vector();
if (ToUpperFastASCII(src, result)) return result;
is_result_single_byte = ToUpperOneByte(src, dest, &sharp_s_count);
}
}
// Go to the full Unicode path if there are characters whose uppercase
// is beyond the Latin-1 range (cannot be represented in OneByteString).
if (V8_UNLIKELY(!is_result_single_byte)) {
return LocaleConvertCase(isolate, s, true, "");
}
if (sharp_s_count == 0) return result;
// We have sharp_s_count sharp-s characters, but the result is still
// in the Latin-1 range.
ASSIGN_RETURN_ON_EXCEPTION(
isolate, result,
isolate->factory()->NewRawOneByteString(length + sharp_s_count),
String);
DisallowHeapAllocation no_gc;
String::FlatContent flat = s->GetFlatContent(no_gc);
if (flat.IsOneByte()) {
ToUpperWithSharpS(flat.ToOneByteVector(), result);
} else {
ToUpperWithSharpS(flat.ToUC16Vector(), result);
}
return result;
}
return LocaleConvertCase(isolate, s, true, "");
}
std::string Intl::GetNumberingSystem(const icu::Locale& icu_locale) {
// Ugly hack. ICU doesn't expose numbering system in any way, so we have
// to assume that for given locale NumberingSystem constructor produces the
// same digits as NumberFormat/Calendar would.
UErrorCode status = U_ZERO_ERROR;
std::unique_ptr<icu::NumberingSystem> numbering_system(
icu::NumberingSystem::createInstance(icu_locale, status));
if (U_SUCCESS(status)) return numbering_system->getName();
return "latn";
}
icu::Locale Intl::CreateICULocale(const std::string& bcp47_locale) {
DisallowHeapAllocation no_gc;
// Convert BCP47 into ICU locale format.
UErrorCode status = U_ZERO_ERROR;
icu::Locale icu_locale = icu::Locale::forLanguageTag(bcp47_locale, status);
CHECK(U_SUCCESS(status));
if (icu_locale.isBogus()) {
FATAL("Failed to create ICU locale, are ICU data files missing?");
}
return icu_locale;
}
// static
MaybeHandle<String> Intl::ToString(Isolate* isolate,
const icu::UnicodeString& string) {
return isolate->factory()->NewStringFromTwoByte(Vector<const uint16_t>(
reinterpret_cast<const uint16_t*>(string.getBuffer()), string.length()));
}
MaybeHandle<String> Intl::ToString(Isolate* isolate,
const icu::UnicodeString& string,
int32_t begin, int32_t end) {
return Intl::ToString(isolate, string.tempSubStringBetween(begin, end));
}
namespace {
Handle<JSObject> InnerAddElement(Isolate* isolate, Handle<JSArray> array,
int index, Handle<String> field_type_string,
Handle<String> value) {
// let element = $array[$index] = {
// type: $field_type_string,
// value: $value
// }
// return element;
Factory* factory = isolate->factory();
Handle<JSObject> element = factory->NewJSObject(isolate->object_function());
JSObject::AddProperty(isolate, element, factory->type_string(),
field_type_string, NONE);
JSObject::AddProperty(isolate, element, factory->value_string(), value, NONE);
JSObject::AddDataElement(array, index, element, NONE);
return element;
}
} // namespace
void Intl::AddElement(Isolate* isolate, Handle<JSArray> array, int index,
Handle<String> field_type_string, Handle<String> value) {
// Same as $array[$index] = {type: $field_type_string, value: $value};
InnerAddElement(isolate, array, index, field_type_string, value);
}
void Intl::AddElement(Isolate* isolate, Handle<JSArray> array, int index,
Handle<String> field_type_string, Handle<String> value,
Handle<String> additional_property_name,
Handle<String> additional_property_value) {
// Same as $array[$index] = {
// type: $field_type_string, value: $value,
// $additional_property_name: $additional_property_value
// }
Handle<JSObject> element =
InnerAddElement(isolate, array, index, field_type_string, value);
JSObject::AddProperty(isolate, element, additional_property_name,
additional_property_value, NONE);
}
namespace {
// Build the shortened locale; eg, convert xx_Yyyy_ZZ to xx_ZZ.
//
// If locale has a script tag then return true and the locale without the
// script else return false and an empty string.
bool RemoveLocaleScriptTag(const std::string& icu_locale,
std::string* locale_less_script) {
icu::Locale new_locale = icu::Locale::createCanonical(icu_locale.c_str());
const char* icu_script = new_locale.getScript();
if (icu_script == nullptr || strlen(icu_script) == 0) {
*locale_less_script = std::string();
return false;
}
const char* icu_language = new_locale.getLanguage();
const char* icu_country = new_locale.getCountry();
icu::Locale short_locale = icu::Locale(icu_language, icu_country);
*locale_less_script = short_locale.getName();
return true;
}
bool ValidateResource(const icu::Locale locale, const char* path,
const char* key) {
bool result = false;
UErrorCode status = U_ZERO_ERROR;
UResourceBundle* bundle = ures_open(path, locale.getName(), &status);
if (bundle != nullptr && status == U_ZERO_ERROR) {
if (key == nullptr) {
result = true;
} else {
UResourceBundle* key_bundle =
ures_getByKey(bundle, key, nullptr, &status);
result = key_bundle != nullptr && (status == U_ZERO_ERROR);
ures_close(key_bundle);
}
}
ures_close(bundle);
if (!result) {
if ((locale.getCountry()[0] != '\0') && (locale.getScript()[0] != '\0')) {
// Fallback to try without country.
std::string without_country(locale.getLanguage());
without_country = without_country.append("-").append(locale.getScript());
return ValidateResource(without_country.c_str(), path, key);
} else if ((locale.getCountry()[0] != '\0') ||
(locale.getScript()[0] != '\0')) {
// Fallback to try with only language.
std::string language(locale.getLanguage());
return ValidateResource(language.c_str(), path, key);
}
}
return result;
}
} // namespace
std::set<std::string> Intl::BuildLocaleSet(
const icu::Locale* icu_available_locales, int32_t count, const char* path,
const char* validate_key) {
std::set<std::string> locales;
for (int32_t i = 0; i < count; ++i) {
std::string locale =
Intl::ToLanguageTag(icu_available_locales[i]).FromJust();
if (path != nullptr || validate_key != nullptr) {
if (!ValidateResource(icu_available_locales[i], path, validate_key)) {
continue;
}
}
locales.insert(locale);
std::string shortened_locale;
if (RemoveLocaleScriptTag(locale, &shortened_locale)) {
std::replace(shortened_locale.begin(), shortened_locale.end(), '_', '-');
locales.insert(shortened_locale);
}
}
return locales;
}
Maybe<std::string> Intl::ToLanguageTag(const icu::Locale& locale) {
UErrorCode status = U_ZERO_ERROR;
std::string res = locale.toLanguageTag<std::string>(status);
if (U_FAILURE(status)) {
return Nothing<std::string>();
}
CHECK(U_SUCCESS(status));
// Hack to remove -true and -yes from unicode extensions
// Address https://crbug.com/v8/8565
// TODO(ftang): Move the following "remove true" logic into ICU toLanguageTag
// by fixing ICU-20310.
size_t u_ext_start = res.find("-u-");
if (u_ext_start != std::string::npos) {
// remove "-true" and "-yes" after -u-
const std::vector<std::string> remove_items({"-true", "-yes"});
for (auto item = remove_items.begin(); item != remove_items.end(); item++) {
for (size_t sep_remove =
res.find(*item, u_ext_start + 5 /* strlen("-u-xx") == 5 */);
sep_remove != std::string::npos; sep_remove = res.find(*item)) {
size_t end_of_sep_remove = sep_remove + item->length();
if (res.length() == end_of_sep_remove ||
res.at(end_of_sep_remove) == '-') {
res.erase(sep_remove, item->length());
}
}
}
}
return Just(res);
}
namespace {
std::string DefaultLocale(Isolate* isolate) {
if (isolate->default_locale().empty()) {
icu::Locale default_locale;
// Translate ICU's fallback locale to a well-known locale.
if (strcmp(default_locale.getName(), "en_US_POSIX") == 0 ||
strcmp(default_locale.getName(), "c") == 0) {
isolate->set_default_locale("en-US");
} else {
// Set the locale
isolate->set_default_locale(
default_locale.isBogus()
? "und"
: Intl::ToLanguageTag(default_locale).FromJust());
}
DCHECK(!isolate->default_locale().empty());
}
return isolate->default_locale();
}
} // namespace
// See ecma402/#legacy-constructor.
MaybeHandle<Object> Intl::LegacyUnwrapReceiver(Isolate* isolate,
Handle<JSReceiver> receiver,
Handle<JSFunction> constructor,
bool has_initialized_slot) {
Handle<Object> obj_is_instance_of;
ASSIGN_RETURN_ON_EXCEPTION(isolate, obj_is_instance_of,
Object::InstanceOf(isolate, receiver, constructor),
Object);
bool is_instance_of = obj_is_instance_of->BooleanValue(isolate);
// 2. If receiver does not have an [[Initialized...]] internal slot
// and ? InstanceofOperator(receiver, constructor) is true, then
if (!has_initialized_slot && is_instance_of) {
// 2. a. Let new_receiver be ? Get(receiver, %Intl%.[[FallbackSymbol]]).
Handle<Object> new_receiver;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, new_receiver,
JSReceiver::GetProperty(isolate, receiver,
isolate->factory()->intl_fallback_symbol()),
Object);
return new_receiver;
}
return receiver;
}
Maybe<bool> Intl::GetStringOption(Isolate* isolate, Handle<JSReceiver> options,
const char* property,
std::vector<const char*> values,
const char* service,
std::unique_ptr<char[]>* result) {
Handle<String> property_str =
isolate->factory()->NewStringFromAsciiChecked(property);
// 1. Let value be ? Get(options, property).
Handle<Object> value;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, value,
Object::GetPropertyOrElement(isolate, options, property_str),
Nothing<bool>());
if (value->IsUndefined(isolate)) {
return Just(false);
}
// 2. c. Let value be ? ToString(value).
Handle<String> value_str;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, value_str, Object::ToString(isolate, value), Nothing<bool>());
std::unique_ptr<char[]> value_cstr = value_str->ToCString();
// 2. d. if values is not undefined, then
if (values.size() > 0) {
// 2. d. i. If values does not contain an element equal to value,
// throw a RangeError exception.
for (size_t i = 0; i < values.size(); i++) {
if (strcmp(values.at(i), value_cstr.get()) == 0) {
// 2. e. return value
*result = std::move(value_cstr);
return Just(true);
}
}
Handle<String> service_str =
isolate->factory()->NewStringFromAsciiChecked(service);
THROW_NEW_ERROR_RETURN_VALUE(
isolate,
NewRangeError(MessageTemplate::kValueOutOfRange, value, service_str,
property_str),
Nothing<bool>());
}
// 2. e. return value
*result = std::move(value_cstr);
return Just(true);
}
V8_WARN_UNUSED_RESULT Maybe<bool> Intl::GetBoolOption(
Isolate* isolate, Handle<JSReceiver> options, const char* property,
const char* service, bool* result) {
Handle<String> property_str =
isolate->factory()->NewStringFromAsciiChecked(property);
// 1. Let value be ? Get(options, property).
Handle<Object> value;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, value,
Object::GetPropertyOrElement(isolate, options, property_str),
Nothing<bool>());
// 2. If value is not undefined, then
if (!value->IsUndefined(isolate)) {
// 2. b. i. Let value be ToBoolean(value).
*result = value->BooleanValue(isolate);
// 2. e. return value
return Just(true);
}
return Just(false);
}
namespace {
bool IsTwoLetterLanguage(const std::string& locale) {
// Two letters, both in range 'a'-'z'...
return locale.length() == 2 && IsAsciiLower(locale[0]) &&
IsAsciiLower(locale[1]);
}
bool IsDeprecatedLanguage(const std::string& locale) {
// Check if locale is one of the deprecated language tags:
return locale == "in" || locale == "iw" || locale == "ji" || locale == "jw" ||
locale == "mo";
}
// Reference:
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
bool IsGrandfatheredTagWithoutPreferredVaule(const std::string& locale) {
if (V8_UNLIKELY(locale == "zh-min" || locale == "cel-gaulish")) return true;
if (locale.length() > 6 /* i-mingo is 7 chars long */ &&
V8_UNLIKELY(locale[0] == 'i' && locale[1] == '-')) {
return locale.substr(2) == "default" || locale.substr(2) == "enochian" ||
locale.substr(2) == "mingo";
}
return false;
}
} // anonymous namespace
Maybe<std::string> Intl::CanonicalizeLanguageTag(Isolate* isolate,
Handle<Object> locale_in) {
Handle<String> locale_str;
// This does part of the validity checking spec'ed in CanonicalizeLocaleList:
// 7c ii. If Type(kValue) is not String or Object, throw a TypeError
// exception.
// 7c iii. Let tag be ? ToString(kValue).
// 7c iv. If IsStructurallyValidLanguageTag(tag) is false, throw a
// RangeError exception.
if (locale_in->IsString()) {
locale_str = Handle<String>::cast(locale_in);
} else if (locale_in->IsJSReceiver()) {
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, locale_str,
Object::ToString(isolate, locale_in),
Nothing<std::string>());
} else {
THROW_NEW_ERROR_RETURN_VALUE(isolate,
NewTypeError(MessageTemplate::kLanguageID),
Nothing<std::string>());
}
std::string locale(locale_str->ToCString().get());
if (!IsStructurallyValidLanguageTag(locale)) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate, NewRangeError(MessageTemplate::kLocaleBadParameters),
Nothing<std::string>());
}
return Intl::CanonicalizeLanguageTag(isolate, locale);
}
Maybe<std::string> Intl::CanonicalizeLanguageTag(Isolate* isolate,
const std::string& locale_in) {
std::string locale = locale_in;
if (locale.length() == 0 ||
!String::IsAscii(locale.data(), static_cast<int>(locale.length()))) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate,
NewRangeError(
MessageTemplate::kInvalidLanguageTag,
isolate->factory()->NewStringFromAsciiChecked(locale.c_str())),
Nothing<std::string>());
}
// Optimize for the most common case: a 2-letter language code in the
// canonical form/lowercase that is not one of the deprecated codes
// (in, iw, ji, jw). Don't check for ~70 of 3-letter deprecated language
// codes. Instead, let them be handled by ICU in the slow path. However,
// fast-track 'fil' (3-letter canonical code).
if ((IsTwoLetterLanguage(locale) && !IsDeprecatedLanguage(locale)) ||
locale == "fil") {
return Just(locale);
}
// Because per BCP 47 2.1.1 language tags are case-insensitive, lowercase
// the input before any more check.
std::transform(locale.begin(), locale.end(), locale.begin(), ToAsciiLower);
// ICU maps a few grandfathered tags to what looks like a regular language
// tag even though IANA language tag registry does not have a preferred
// entry map for them. Return them as they're with lowercasing.
if (IsGrandfatheredTagWithoutPreferredVaule(locale)) {
return Just(locale);
}
// // ECMA 402 6.2.3
// TODO(jshin): uloc_{for,to}TanguageTag can fail even for a structually valid
// language tag if it's too long (much longer than 100 chars). Even if we
// allocate a longer buffer, ICU will still fail if it's too long. Either
// propose to Ecma 402 to put a limit on the locale length or change ICU to
// handle long locale names better. See
// https://unicode-org.atlassian.net/browse/ICU-13417
UErrorCode error = U_ZERO_ERROR;
// uloc_forLanguageTag checks the structrual validity. If the input BCP47
// language tag is parsed all the way to the end, it indicates that the input
// is structurally valid. Due to a couple of bugs, we can't use it
// without Chromium patches or ICU 62 or earlier.
icu::Locale icu_locale = icu::Locale::forLanguageTag(locale.c_str(), error);
if (U_FAILURE(error) || icu_locale.isBogus()) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate,
NewRangeError(
MessageTemplate::kInvalidLanguageTag,
isolate->factory()->NewStringFromAsciiChecked(locale.c_str())),
Nothing<std::string>());
}
Maybe<std::string> maybe_to_language_tag = Intl::ToLanguageTag(icu_locale);
if (maybe_to_language_tag.IsNothing()) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate,
NewRangeError(
MessageTemplate::kInvalidLanguageTag,
isolate->factory()->NewStringFromAsciiChecked(locale.c_str())),
Nothing<std::string>());
}
return maybe_to_language_tag;
}
Maybe<std::vector<std::string>> Intl::CanonicalizeLocaleList(
Isolate* isolate, Handle<Object> locales, bool only_return_one_result) {
// 1. If locales is undefined, then
if (locales->IsUndefined(isolate)) {
// 1a. Return a new empty List.
return Just(std::vector<std::string>());
}
// 2. Let seen be a new empty List.
std::vector<std::string> seen;
// 3. If Type(locales) is String or locales has an [[InitializedLocale]]
// internal slot, then
if (locales->IsJSLocale()) {
// Since this value came from JSLocale, which is already went though the
// CanonializeLanguageTag process once, therefore there are no need to
// call CanonializeLanguageTag again.
seen.push_back(JSLocale::ToString(Handle<JSLocale>::cast(locales)));
return Just(seen);
}
if (locales->IsString()) {
// 3a. Let O be CreateArrayFromList(Β« locales Β»).
// Instead of creating a one-element array and then iterating over it,
// we inline the body of the iteration:
std::string canonicalized_tag;
if (!CanonicalizeLanguageTag(isolate, locales).To(&canonicalized_tag)) {
return Nothing<std::vector<std::string>>();
}
seen.push_back(canonicalized_tag);
return Just(seen);
}
// 4. Else,
// 4a. Let O be ? ToObject(locales).
Handle<JSReceiver> o;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, o,
Object::ToObject(isolate, locales),
Nothing<std::vector<std::string>>());
// 5. Let len be ? ToLength(? Get(O, "length")).
Handle<Object> length_obj;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, length_obj,
Object::GetLengthFromArrayLike(isolate, o),
Nothing<std::vector<std::string>>());
// TODO(jkummerow): Spec violation: strictly speaking, we have to iterate
// up to 2^53-1 if {length_obj} says so. Since cases above 2^32 probably
// don't happen in practice (and would be very slow if they do), we'll keep
// the code simple for now by using a saturating to-uint32 conversion.
double raw_length = length_obj->Number();
uint32_t len =
raw_length >= kMaxUInt32 ? kMaxUInt32 : static_cast<uint32_t>(raw_length);
// 6. Let k be 0.
// 7. Repeat, while k < len
for (uint32_t k = 0; k < len; k++) {
// 7a. Let Pk be ToString(k).
// 7b. Let kPresent be ? HasProperty(O, Pk).
LookupIterator it(isolate, o, k);
Maybe<bool> maybe_found = JSReceiver::HasProperty(&it);
MAYBE_RETURN(maybe_found, Nothing<std::vector<std::string>>());
// 7c. If kPresent is true, then
if (!maybe_found.FromJust()) continue;
// 7c i. Let kValue be ? Get(O, Pk).
Handle<Object> k_value;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, k_value, Object::GetProperty(&it),
Nothing<std::vector<std::string>>());
// 7c ii. If Type(kValue) is not String or Object, throw a TypeError
// exception.
// 7c iii. If Type(kValue) is Object and kValue has an [[InitializedLocale]]
// internal slot, then
std::string canonicalized_tag;
if (k_value->IsJSLocale()) {
// 7c iii. 1. Let tag be kValue.[[Locale]].
canonicalized_tag = JSLocale::ToString(Handle<JSLocale>::cast(k_value));
// 7c iv. Else,
} else {
// 7c iv 1. Let tag be ? ToString(kValue).
// 7c v. If IsStructurallyValidLanguageTag(tag) is false, throw a
// RangeError exception.
// 7c vi. Let canonicalizedTag be CanonicalizeLanguageTag(tag).
if (!CanonicalizeLanguageTag(isolate, k_value).To(&canonicalized_tag)) {
return Nothing<std::vector<std::string>>();
}
}
// 7c vi. If canonicalizedTag is not an element of seen, append
// canonicalizedTag as the last element of seen.
if (std::find(seen.begin(), seen.end(), canonicalized_tag) == seen.end()) {
seen.push_back(canonicalized_tag);
}
// 7d. Increase k by 1. (See loop header.)
// Optimization: some callers only need one result.
if (only_return_one_result) return Just(seen);
}
// 8. Return seen.
return Just(seen);
}
// ecma402 #sup-string.prototype.tolocalelowercase
// ecma402 #sup-string.prototype.tolocaleuppercase
MaybeHandle<String> Intl::StringLocaleConvertCase(Isolate* isolate,
Handle<String> s,
bool to_upper,
Handle<Object> locales) {
std::vector<std::string> requested_locales;
if (!CanonicalizeLocaleList(isolate, locales, true).To(&requested_locales)) {
return MaybeHandle<String>();
}
std::string requested_locale = requested_locales.size() == 0
? DefaultLocale(isolate)
: requested_locales[0];
size_t dash = requested_locale.find('-');
if (dash != std::string::npos) {
requested_locale = requested_locale.substr(0, dash);
}
// Primary language tag can be up to 8 characters long in theory.
// https://tools.ietf.org/html/bcp47#section-2.2.1
DCHECK_LE(requested_locale.length(), 8);
s = String::Flatten(isolate, s);
// All the languages requiring special-handling have two-letter codes.
// Note that we have to check for '!= 2' here because private-use language
// tags (x-foo) or grandfathered irregular tags (e.g. i-enochian) would have
// only 'x' or 'i' when they get here.
if (V8_UNLIKELY(requested_locale.length() != 2)) {
if (to_upper) {
return ConvertToUpper(isolate, s);
}
return ConvertToLower(isolate, s);
}
// TODO(jshin): Consider adding a fast path for ASCII or Latin-1. The fastpath
// in the root locale needs to be adjusted for az, lt and tr because even case
// mapping of ASCII range characters are different in those locales.
// Greek (el) does not require any adjustment.
if (V8_UNLIKELY((requested_locale == "tr") || (requested_locale == "el") ||
(requested_locale == "lt") || (requested_locale == "az"))) {
return LocaleConvertCase(isolate, s, to_upper, requested_locale.c_str());
} else {
if (to_upper) {
return ConvertToUpper(isolate, s);