mirrored from https://chromium.googlesource.com/v8/v8.git
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathi18n.js
More file actions
2261 lines (1871 loc) · 69.8 KB
/
i18n.js
File metadata and controls
2261 lines (1871 loc) · 69.8 KB
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.
// ECMAScript 402 API implementation.
/**
* Intl object is a single object that has some named properties,
* all of which are constructors.
*/
(function(global, utils) {
"use strict";
%CheckIsBootstrapping();
// -------------------------------------------------------------------
// Imports
var ArrayIndexOf;
var ArrayJoin;
var ArrayPush;
var FLAG_intl_extra;
var GlobalDate = global.Date;
var GlobalNumber = global.Number;
var GlobalRegExp = global.RegExp;
var GlobalString = global.String;
var InstallFunctions = utils.InstallFunctions;
var InstallGetter = utils.InstallGetter;
var InternalArray = utils.InternalArray;
var InternalRegExpMatch;
var InternalRegExpReplace
var IsNaN;
var MakeError;
var MakeRangeError;
var MakeTypeError;
var ObjectHasOwnProperty = utils.ImportNow("ObjectHasOwnProperty");
var OverrideFunction = utils.OverrideFunction;
var patternSymbol = utils.ImportNow("intl_pattern_symbol");
var resolvedSymbol = utils.ImportNow("intl_resolved_symbol");
var SetFunctionName = utils.SetFunctionName;
var StringIndexOf;
var StringLastIndexOf;
var StringSubstr;
var StringSubstring;
utils.Import(function(from) {
ArrayIndexOf = from.ArrayIndexOf;
ArrayJoin = from.ArrayJoin;
ArrayPush = from.ArrayPush;
IsNaN = from.IsNaN;
MakeError = from.MakeError;
MakeRangeError = from.MakeRangeError;
MakeTypeError = from.MakeTypeError;
InternalRegExpMatch = from.InternalRegExpMatch;
InternalRegExpReplace = from.InternalRegExpReplace;
StringIndexOf = from.StringIndexOf;
StringLastIndexOf = from.StringLastIndexOf;
StringSubstr = from.StringSubstr;
StringSubstring = from.StringSubstring;
});
utils.ImportFromExperimental(function(from) {
FLAG_intl_extra = from.FLAG_intl_extra;
});
// Utilities for definitions
function InstallFunction(object, name, func) {
InstallFunctions(object, DONT_ENUM, [name, func]);
}
function InstallConstructor(object, name, func) {
%CheckIsBootstrapping();
SetFunctionName(func, name);
%AddNamedProperty(object, name, func, DONT_ENUM);
%SetNativeFlag(func);
%ToFastProperties(object);
}
/**
* Adds bound method to the prototype of the given object.
*/
function AddBoundMethod(obj, methodName, implementation, length, type) {
%CheckIsBootstrapping();
var internalName = %CreatePrivateSymbol(methodName);
// Making getter an anonymous function will cause
// %DefineGetterPropertyUnchecked to properly set the "name"
// property on each JSFunction instance created here, rather
// than (as utils.InstallGetter would) on the SharedFunctionInfo
// associated with all functions returned from AddBoundMethod.
var getter = ANONYMOUS_FUNCTION(function() {
if (!%IsInitializedIntlObjectOfType(this, type)) {
throw MakeTypeError(kMethodCalledOnWrongObject, methodName);
}
if (IS_UNDEFINED(this[internalName])) {
var boundMethod;
if (IS_UNDEFINED(length) || length === 2) {
boundMethod = ANONYMOUS_FUNCTION((x, y) => implementation(this, x, y));
} else if (length === 1) {
boundMethod = ANONYMOUS_FUNCTION(x => implementation(this, x));
} else {
boundMethod = ANONYMOUS_FUNCTION((...args) => {
// DateTimeFormat.format needs to be 0 arg method, but can still
// receive an optional dateValue param. If one was provided, pass it
// along.
if (args.length > 0) {
return implementation(this, args[0]);
} else {
return implementation(this);
}
});
}
%SetNativeFlag(boundMethod);
this[internalName] = boundMethod;
}
return this[internalName];
});
%FunctionRemovePrototype(getter);
%DefineGetterPropertyUnchecked(obj.prototype, methodName, getter, DONT_ENUM);
%SetNativeFlag(getter);
}
// -------------------------------------------------------------------
var Intl = {};
%AddNamedProperty(global, "Intl", Intl, DONT_ENUM);
/**
* Caches available locales for each service.
*/
var AVAILABLE_LOCALES = {
'collator': UNDEFINED,
'numberformat': UNDEFINED,
'dateformat': UNDEFINED,
'breakiterator': UNDEFINED
};
/**
* Caches default ICU locale.
*/
var DEFAULT_ICU_LOCALE = UNDEFINED;
function GetDefaultICULocaleJS() {
if (IS_UNDEFINED(DEFAULT_ICU_LOCALE)) {
DEFAULT_ICU_LOCALE = %GetDefaultICULocale();
}
return DEFAULT_ICU_LOCALE;
}
/**
* Unicode extension regular expression.
*/
var UNICODE_EXTENSION_RE = UNDEFINED;
function GetUnicodeExtensionRE() {
if (IS_UNDEFINED(UNDEFINED)) {
UNICODE_EXTENSION_RE = new GlobalRegExp('-u(-[a-z0-9]{2,8})+', 'g');
}
return UNICODE_EXTENSION_RE;
}
/**
* Matches any Unicode extension.
*/
var ANY_EXTENSION_RE = UNDEFINED;
function GetAnyExtensionRE() {
if (IS_UNDEFINED(ANY_EXTENSION_RE)) {
ANY_EXTENSION_RE = new GlobalRegExp('-[a-z0-9]{1}-.*', 'g');
}
return ANY_EXTENSION_RE;
}
/**
* Replace quoted text (single quote, anything but the quote and quote again).
*/
var QUOTED_STRING_RE = UNDEFINED;
function GetQuotedStringRE() {
if (IS_UNDEFINED(QUOTED_STRING_RE)) {
QUOTED_STRING_RE = new GlobalRegExp("'[^']+'", 'g');
}
return QUOTED_STRING_RE;
}
/**
* Matches valid service name.
*/
var SERVICE_RE = UNDEFINED;
function GetServiceRE() {
if (IS_UNDEFINED(SERVICE_RE)) {
SERVICE_RE =
new GlobalRegExp('^(collator|numberformat|dateformat|breakiterator)$');
}
return SERVICE_RE;
}
/**
* Validates a language tag against bcp47 spec.
* Actual value is assigned on first run.
*/
var LANGUAGE_TAG_RE = UNDEFINED;
function GetLanguageTagRE() {
if (IS_UNDEFINED(LANGUAGE_TAG_RE)) {
BuildLanguageTagREs();
}
return LANGUAGE_TAG_RE;
}
/**
* Helps find duplicate variants in the language tag.
*/
var LANGUAGE_VARIANT_RE = UNDEFINED;
function GetLanguageVariantRE() {
if (IS_UNDEFINED(LANGUAGE_VARIANT_RE)) {
BuildLanguageTagREs();
}
return LANGUAGE_VARIANT_RE;
}
/**
* Helps find duplicate singletons in the language tag.
*/
var LANGUAGE_SINGLETON_RE = UNDEFINED;
function GetLanguageSingletonRE() {
if (IS_UNDEFINED(LANGUAGE_SINGLETON_RE)) {
BuildLanguageTagREs();
}
return LANGUAGE_SINGLETON_RE;
}
/**
* Matches valid IANA time zone names.
*/
var TIMEZONE_NAME_CHECK_RE = UNDEFINED;
function GetTimezoneNameCheckRE() {
if (IS_UNDEFINED(TIMEZONE_NAME_CHECK_RE)) {
TIMEZONE_NAME_CHECK_RE = new GlobalRegExp(
'^([A-Za-z]+)/([A-Za-z_-]+)((?:\/[A-Za-z_-]+)+)*$');
}
return TIMEZONE_NAME_CHECK_RE;
}
/**
* Matches valid location parts of IANA time zone names.
*/
var TIMEZONE_NAME_LOCATION_PART_RE = UNDEFINED;
function GetTimezoneNameLocationPartRE() {
if (IS_UNDEFINED(TIMEZONE_NAME_LOCATION_PART_RE)) {
TIMEZONE_NAME_LOCATION_PART_RE =
new GlobalRegExp('^([A-Za-z]+)((?:[_-][A-Za-z]+)+)*$');
}
return TIMEZONE_NAME_LOCATION_PART_RE;
}
/**
* Returns an intersection of locales and service supported locales.
* Parameter locales is treated as a priority list.
*/
function supportedLocalesOf(service, locales, options) {
if (IS_NULL(InternalRegExpMatch(GetServiceRE(), service))) {
throw MakeError(kWrongServiceType, service);
}
// Provide defaults if matcher was not specified.
if (IS_UNDEFINED(options)) {
options = {};
} else {
options = TO_OBJECT(options);
}
var matcher = options.localeMatcher;
if (!IS_UNDEFINED(matcher)) {
matcher = TO_STRING(matcher);
if (matcher !== 'lookup' && matcher !== 'best fit') {
throw MakeRangeError(kLocaleMatcher, matcher);
}
} else {
matcher = 'best fit';
}
var requestedLocales = initializeLocaleList(locales);
// Cache these, they don't ever change per service.
if (IS_UNDEFINED(AVAILABLE_LOCALES[service])) {
AVAILABLE_LOCALES[service] = getAvailableLocalesOf(service);
}
// Use either best fit or lookup algorithm to match locales.
if (matcher === 'best fit') {
return initializeLocaleList(bestFitSupportedLocalesOf(
requestedLocales, AVAILABLE_LOCALES[service]));
}
return initializeLocaleList(lookupSupportedLocalesOf(
requestedLocales, AVAILABLE_LOCALES[service]));
}
/**
* Returns the subset of the provided BCP 47 language priority list for which
* this service has a matching locale when using the BCP 47 Lookup algorithm.
* Locales appear in the same order in the returned list as in the input list.
*/
function lookupSupportedLocalesOf(requestedLocales, availableLocales) {
var matchedLocales = new InternalArray();
for (var i = 0; i < requestedLocales.length; ++i) {
// Remove -u- extension.
var locale = InternalRegExpReplace(
GetUnicodeExtensionRE(), requestedLocales[i], '');
do {
if (!IS_UNDEFINED(availableLocales[locale])) {
// Push requested locale not the resolved one.
%_Call(ArrayPush, matchedLocales, requestedLocales[i]);
break;
}
// Truncate locale if possible, if not break.
var pos = %_Call(StringLastIndexOf, locale, '-');
if (pos === -1) {
break;
}
locale = %_Call(StringSubstring, locale, 0, pos);
} while (true);
}
return matchedLocales;
}
/**
* Returns the subset of the provided BCP 47 language priority list for which
* this service has a matching locale when using the implementation
* dependent algorithm.
* Locales appear in the same order in the returned list as in the input list.
*/
function bestFitSupportedLocalesOf(requestedLocales, availableLocales) {
// TODO(cira): implement better best fit algorithm.
return lookupSupportedLocalesOf(requestedLocales, availableLocales);
}
/**
* Returns a getOption function that extracts property value for given
* options object. If property is missing it returns defaultValue. If value
* is out of range for that property it throws RangeError.
*/
function getGetOption(options, caller) {
if (IS_UNDEFINED(options)) throw MakeError(kDefaultOptionsMissing, caller);
var getOption = function getOption(property, type, values, defaultValue) {
if (!IS_UNDEFINED(options[property])) {
var value = options[property];
switch (type) {
case 'boolean':
value = TO_BOOLEAN(value);
break;
case 'string':
value = TO_STRING(value);
break;
case 'number':
value = TO_NUMBER(value);
break;
default:
throw MakeError(kWrongValueType);
}
if (!IS_UNDEFINED(values) && %_Call(ArrayIndexOf, values, value) === -1) {
throw MakeRangeError(kValueOutOfRange, value, caller, property);
}
return value;
}
return defaultValue;
}
return getOption;
}
/**
* Compares a BCP 47 language priority list requestedLocales against the locales
* in availableLocales and determines the best available language to meet the
* request. Two algorithms are available to match the locales: the Lookup
* algorithm described in RFC 4647 section 3.4, and an implementation dependent
* best-fit algorithm. Independent of the locale matching algorithm, options
* specified through Unicode locale extension sequences are negotiated
* separately, taking the caller's relevant extension keys and locale data as
* well as client-provided options into consideration. Returns an object with
* a locale property whose value is the language tag of the selected locale,
* and properties for each key in relevantExtensionKeys providing the selected
* value for that key.
*/
function resolveLocale(service, requestedLocales, options) {
requestedLocales = initializeLocaleList(requestedLocales);
var getOption = getGetOption(options, service);
var matcher = getOption('localeMatcher', 'string',
['lookup', 'best fit'], 'best fit');
var resolved;
if (matcher === 'lookup') {
resolved = lookupMatcher(service, requestedLocales);
} else {
resolved = bestFitMatcher(service, requestedLocales);
}
return resolved;
}
/**
* Returns best matched supported locale and extension info using basic
* lookup algorithm.
*/
function lookupMatcher(service, requestedLocales) {
if (IS_NULL(InternalRegExpMatch(GetServiceRE(), service))) {
throw MakeError(kWrongServiceType, service);
}
// Cache these, they don't ever change per service.
if (IS_UNDEFINED(AVAILABLE_LOCALES[service])) {
AVAILABLE_LOCALES[service] = getAvailableLocalesOf(service);
}
for (var i = 0; i < requestedLocales.length; ++i) {
// Remove all extensions.
var locale = InternalRegExpReplace(
GetAnyExtensionRE(), requestedLocales[i], '');
do {
if (!IS_UNDEFINED(AVAILABLE_LOCALES[service][locale])) {
// Return the resolved locale and extension.
var extensionMatch = InternalRegExpMatch(
GetUnicodeExtensionRE(), requestedLocales[i]);
var extension = IS_NULL(extensionMatch) ? '' : extensionMatch[0];
return {'locale': locale, 'extension': extension, 'position': i};
}
// Truncate locale if possible.
var pos = %_Call(StringLastIndexOf, locale, '-');
if (pos === -1) {
break;
}
locale = %_Call(StringSubstring, locale, 0, pos);
} while (true);
}
// Didn't find a match, return default.
return {'locale': GetDefaultICULocaleJS(), 'extension': '', 'position': -1};
}
/**
* Returns best matched supported locale and extension info using
* implementation dependend algorithm.
*/
function bestFitMatcher(service, requestedLocales) {
// TODO(cira): implement better best fit algorithm.
return lookupMatcher(service, requestedLocales);
}
/**
* Parses Unicode extension into key - value map.
* Returns empty object if the extension string is invalid.
* We are not concerned with the validity of the values at this point.
*/
function parseExtension(extension) {
var extensionSplit = %StringSplit(extension, '-', kMaxUint32);
// Assume ['', 'u', ...] input, but don't throw.
if (extensionSplit.length <= 2 ||
(extensionSplit[0] !== '' && extensionSplit[1] !== 'u')) {
return {};
}
// Key is {2}alphanum, value is {3,8}alphanum.
// Some keys may not have explicit values (booleans).
var extensionMap = {};
var previousKey = UNDEFINED;
for (var i = 2; i < extensionSplit.length; ++i) {
var length = extensionSplit[i].length;
var element = extensionSplit[i];
if (length === 2) {
extensionMap[element] = UNDEFINED;
previousKey = element;
} else if (length >= 3 && length <=8 && !IS_UNDEFINED(previousKey)) {
extensionMap[previousKey] = element;
previousKey = UNDEFINED;
} else {
// There is a value that's too long, or that doesn't have a key.
return {};
}
}
return extensionMap;
}
/**
* Populates internalOptions object with boolean key-value pairs
* from extensionMap and options.
* Returns filtered extension (number and date format constructors use
* Unicode extensions for passing parameters to ICU).
* It's used for extension-option pairs only, e.g. kn-normalization, but not
* for 'sensitivity' since it doesn't have extension equivalent.
* Extensions like nu and ca don't have options equivalent, so we place
* undefined in the map.property to denote that.
*/
function setOptions(inOptions, extensionMap, keyValues, getOption, outOptions) {
var extension = '';
var updateExtension = function updateExtension(key, value) {
return '-' + key + '-' + TO_STRING(value);
}
var updateProperty = function updateProperty(property, type, value) {
if (type === 'boolean' && (typeof value === 'string')) {
value = (value === 'true') ? true : false;
}
if (!IS_UNDEFINED(property)) {
defineWEProperty(outOptions, property, value);
}
}
for (var key in keyValues) {
if (HAS_OWN_PROPERTY(keyValues, key)) {
var value = UNDEFINED;
var map = keyValues[key];
if (!IS_UNDEFINED(map.property)) {
// This may return true if user specifies numeric: 'false', since
// Boolean('nonempty') === true.
value = getOption(map.property, map.type, map.values);
}
if (!IS_UNDEFINED(value)) {
updateProperty(map.property, map.type, value);
extension += updateExtension(key, value);
continue;
}
// User options didn't have it, check Unicode extension.
// Here we want to convert strings 'true', 'false' into proper Boolean
// values (not a user error).
if (HAS_OWN_PROPERTY(extensionMap, key)) {
value = extensionMap[key];
if (!IS_UNDEFINED(value)) {
updateProperty(map.property, map.type, value);
extension += updateExtension(key, value);
} else if (map.type === 'boolean') {
// Boolean keys are allowed not to have values in Unicode extension.
// Those default to true.
updateProperty(map.property, map.type, true);
extension += updateExtension(key, true);
}
}
}
}
return extension === ''? '' : '-u' + extension;
}
/**
* Given an array-like, outputs an Array with the numbered
* properties copied over and defined
* configurable: false, writable: false, enumerable: true.
*/
function freezeArray(input) {
var array = [];
var l = input.length;
for (var i = 0; i < l; i++) {
if (i in input) {
%object_define_property(array, i, {value: input[i],
configurable: false,
writable: false,
enumerable: true});
}
}
%object_define_property(array, 'length', {value: l, writable: false});
return array;
}
/**
* It's sometimes desireable to leave user requested locale instead of ICU
* supported one (zh-TW is equivalent to zh-Hant-TW, so we should keep shorter
* one, if that was what user requested).
* This function returns user specified tag if its maximized form matches ICU
* resolved locale. If not we return ICU result.
*/
function getOptimalLanguageTag(original, resolved) {
// Returns Array<Object>, where each object has maximized and base properties.
// Maximized: zh -> zh-Hans-CN
// Base: zh-CN-u-ca-gregory -> zh-CN
// Take care of grandfathered or simple cases.
if (original === resolved) {
return original;
}
var locales = %GetLanguageTagVariants([original, resolved]);
if (locales[0].maximized !== locales[1].maximized) {
return resolved;
}
// Preserve extensions of resolved locale, but swap base tags with original.
var resolvedBase = new GlobalRegExp('^' + locales[1].base, 'g');
return InternalRegExpReplace(resolvedBase, resolved, locales[0].base);
}
/**
* Returns an Object that contains all of supported locales for a given
* service.
* In addition to the supported locales we add xx-ZZ locale for each xx-Yyyy-ZZ
* that is supported. This is required by the spec.
*/
function getAvailableLocalesOf(service) {
var available = %AvailableLocalesOf(service);
for (var i in available) {
if (HAS_OWN_PROPERTY(available, i)) {
var parts = InternalRegExpMatch(
/^([a-z]{2,3})-([A-Z][a-z]{3})-([A-Z]{2})$/, i);
if (!IS_NULL(parts)) {
// Build xx-ZZ. We don't care about the actual value,
// as long it's not undefined.
available[parts[1] + '-' + parts[3]] = null;
}
}
}
return available;
}
/**
* Defines a property and sets writable and enumerable to true.
* Configurable is false by default.
*/
function defineWEProperty(object, property, value) {
%object_define_property(object, property,
{value: value, writable: true, enumerable: true});
}
/**
* Adds property to an object if the value is not undefined.
* Sets configurable descriptor to false.
*/
function addWEPropertyIfDefined(object, property, value) {
if (!IS_UNDEFINED(value)) {
defineWEProperty(object, property, value);
}
}
/**
* Defines a property and sets writable, enumerable and configurable to true.
*/
function defineWECProperty(object, property, value) {
%object_define_property(object, property, {value: value,
writable: true,
enumerable: true,
configurable: true});
}
/**
* Adds property to an object if the value is not undefined.
* Sets all descriptors to true.
*/
function addWECPropertyIfDefined(object, property, value) {
if (!IS_UNDEFINED(value)) {
defineWECProperty(object, property, value);
}
}
/**
* Returns titlecased word, aMeRricA -> America.
*/
function toTitleCaseWord(word) {
return %StringToUpperCase(%_Call(StringSubstr, word, 0, 1)) +
%StringToLowerCase(%_Call(StringSubstr, word, 1));
}
/**
* Returns titlecased location, bueNos_airES -> Buenos_Aires
* or ho_cHi_minH -> Ho_Chi_Minh. It is locale-agnostic and only
* deals with ASCII only characters.
* 'of', 'au' and 'es' are special-cased and lowercased.
*/
function toTitleCaseTimezoneLocation(location) {
var match = InternalRegExpMatch(GetTimezoneNameLocationPartRE(), location)
if (IS_NULL(match)) throw MakeRangeError(kExpectedLocation, location);
var result = toTitleCaseWord(match[1]);
if (!IS_UNDEFINED(match[2]) && 2 < match.length) {
// The first character is a separator, '_' or '-'.
// None of IANA zone names has both '_' and '-'.
var separator = %_Call(StringSubstring, match[2], 0, 1);
var parts = %StringSplit(match[2], separator, kMaxUint32);
for (var i = 1; i < parts.length; i++) {
var part = parts[i]
var lowercasedPart = %StringToLowerCase(part);
result = result + separator +
((lowercasedPart !== 'es' &&
lowercasedPart !== 'of' && lowercasedPart !== 'au') ?
toTitleCaseWord(part) : lowercasedPart);
}
}
return result;
}
/**
* Canonicalizes the language tag, or throws in case the tag is invalid.
*/
function canonicalizeLanguageTag(localeID) {
// null is typeof 'object' so we have to do extra check.
if ((!IS_STRING(localeID) && !IS_RECEIVER(localeID)) ||
IS_NULL(localeID)) {
throw MakeTypeError(kLanguageID);
}
// Optimize for the most common case; a language code alone in
// the canonical form/lowercase (e.g. "en", "fil").
if (IS_STRING(localeID) &&
!IS_NULL(InternalRegExpMatch(/^[a-z]{2,3}$/, localeID))) {
return localeID;
}
var localeString = TO_STRING(localeID);
if (isValidLanguageTag(localeString) === false) {
throw MakeRangeError(kInvalidLanguageTag, localeString);
}
var tag = %CanonicalizeLanguageTag(localeString);
if (tag === 'invalid-tag') {
throw MakeRangeError(kInvalidLanguageTag, localeString);
}
return tag;
}
/**
* Returns an array where all locales are canonicalized and duplicates removed.
* Throws on locales that are not well formed BCP47 tags.
*/
function initializeLocaleList(locales) {
var seen = new InternalArray();
if (!IS_UNDEFINED(locales)) {
// We allow single string localeID.
if (typeof locales === 'string') {
%_Call(ArrayPush, seen, canonicalizeLanguageTag(locales));
return freezeArray(seen);
}
var o = TO_OBJECT(locales);
var len = TO_UINT32(o.length);
for (var k = 0; k < len; k++) {
if (k in o) {
var value = o[k];
var tag = canonicalizeLanguageTag(value);
if (%_Call(ArrayIndexOf, seen, tag) === -1) {
%_Call(ArrayPush, seen, tag);
}
}
}
}
return freezeArray(seen);
}
/**
* Validates the language tag. Section 2.2.9 of the bcp47 spec
* defines a valid tag.
*
* ICU is too permissible and lets invalid tags, like
* hant-cmn-cn, through.
*
* Returns false if the language tag is invalid.
*/
function isValidLanguageTag(locale) {
// Check if it's well-formed, including grandfadered tags.
if (IS_NULL(InternalRegExpMatch(GetLanguageTagRE(), locale))) {
return false;
}
// Just return if it's a x- form. It's all private.
if (%_Call(StringIndexOf, locale, 'x-') === 0) {
return true;
}
// Check if there are any duplicate variants or singletons (extensions).
// Remove private use section.
locale = %StringSplit(locale, '-x-', kMaxUint32)[0];
// Skip language since it can match variant regex, so we start from 1.
// We are matching i-klingon here, but that's ok, since i-klingon-klingon
// is not valid and would fail LANGUAGE_TAG_RE test.
var variants = new InternalArray();
var extensions = new InternalArray();
var parts = %StringSplit(locale, '-', kMaxUint32);
for (var i = 1; i < parts.length; i++) {
var value = parts[i];
if (!IS_NULL(InternalRegExpMatch(GetLanguageVariantRE(), value)) &&
extensions.length === 0) {
if (%_Call(ArrayIndexOf, variants, value) === -1) {
%_Call(ArrayPush, variants, value);
} else {
return false;
}
}
if (!IS_NULL(InternalRegExpMatch(GetLanguageSingletonRE(), value))) {
if (%_Call(ArrayIndexOf, extensions, value) === -1) {
%_Call(ArrayPush, extensions, value);
} else {
return false;
}
}
}
return true;
}
/**
* Builds a regular expresion that validates the language tag
* against bcp47 spec.
* Uses http://tools.ietf.org/html/bcp47, section 2.1, ABNF.
* Runs on load and initializes the global REs.
*/
function BuildLanguageTagREs() {
var alpha = '[a-zA-Z]';
var digit = '[0-9]';
var alphanum = '(' + alpha + '|' + digit + ')';
var regular = '(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|' +
'zh-min|zh-min-nan|zh-xiang)';
var irregular = '(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|' +
'i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|' +
'i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)';
var grandfathered = '(' + irregular + '|' + regular + ')';
var privateUse = '(x(-' + alphanum + '{1,8})+)';
var singleton = '(' + digit + '|[A-WY-Za-wy-z])';
LANGUAGE_SINGLETON_RE = new GlobalRegExp('^' + singleton + '$', 'i');
var extension = '(' + singleton + '(-' + alphanum + '{2,8})+)';
var variant = '(' + alphanum + '{5,8}|(' + digit + alphanum + '{3}))';
LANGUAGE_VARIANT_RE = new GlobalRegExp('^' + variant + '$', 'i');
var region = '(' + alpha + '{2}|' + digit + '{3})';
var script = '(' + alpha + '{4})';
var extLang = '(' + alpha + '{3}(-' + alpha + '{3}){0,2})';
var language = '(' + alpha + '{2,3}(-' + extLang + ')?|' + alpha + '{4}|' +
alpha + '{5,8})';
var langTag = language + '(-' + script + ')?(-' + region + ')?(-' +
variant + ')*(-' + extension + ')*(-' + privateUse + ')?';
var languageTag =
'^(' + langTag + '|' + privateUse + '|' + grandfathered + ')$';
LANGUAGE_TAG_RE = new GlobalRegExp(languageTag, 'i');
}
var resolvedAccessor = {
get() {
%IncrementUseCounter(kIntlResolved);
return this[resolvedSymbol];
},
set(value) {
this[resolvedSymbol] = value;
}
};
/**
* Initializes the given object so it's a valid Collator instance.
* Useful for subclassing.
*/
function initializeCollator(collator, locales, options) {
if (%IsInitializedIntlObject(collator)) {
throw MakeTypeError(kReinitializeIntl, "Collator");
}
if (IS_UNDEFINED(options)) {
options = {};
}
var getOption = getGetOption(options, 'collator');
var internalOptions = {};
defineWEProperty(internalOptions, 'usage', getOption(
'usage', 'string', ['sort', 'search'], 'sort'));
var sensitivity = getOption('sensitivity', 'string',
['base', 'accent', 'case', 'variant']);
if (IS_UNDEFINED(sensitivity) && internalOptions.usage === 'sort') {
sensitivity = 'variant';
}
defineWEProperty(internalOptions, 'sensitivity', sensitivity);
defineWEProperty(internalOptions, 'ignorePunctuation', getOption(
'ignorePunctuation', 'boolean', UNDEFINED, false));
var locale = resolveLocale('collator', locales, options);
// ICU can't take kb, kc... parameters through localeID, so we need to pass
// them as options.
// One exception is -co- which has to be part of the extension, but only for
// usage: sort, and its value can't be 'standard' or 'search'.
var extensionMap = parseExtension(locale.extension);
/**
* Map of Unicode extensions to option properties, and their values and types,
* for a collator.
*/
var COLLATOR_KEY_MAP = {
'kn': {'property': 'numeric', 'type': 'boolean'},
'kf': {'property': 'caseFirst', 'type': 'string',
'values': ['false', 'lower', 'upper']}
};
setOptions(
options, extensionMap, COLLATOR_KEY_MAP, getOption, internalOptions);
var collation = 'default';
var extension = '';
if (HAS_OWN_PROPERTY(extensionMap, 'co') && internalOptions.usage === 'sort') {
/**
* Allowed -u-co- values. List taken from:
* http://unicode.org/repos/cldr/trunk/common/bcp47/collation.xml
*/
var ALLOWED_CO_VALUES = [
'big5han', 'dict', 'direct', 'ducet', 'gb2312', 'phonebk', 'phonetic',
'pinyin', 'reformed', 'searchjl', 'stroke', 'trad', 'unihan', 'zhuyin'
];
if (%_Call(ArrayIndexOf, ALLOWED_CO_VALUES, extensionMap.co) !== -1) {
extension = '-u-co-' + extensionMap.co;
// ICU can't tell us what the collation is, so save user's input.
collation = extensionMap.co;
}
} else if (internalOptions.usage === 'search') {
extension = '-u-co-search';
}
defineWEProperty(internalOptions, 'collation', collation);
var requestedLocale = locale.locale + extension;
// We define all properties C++ code may produce, to prevent security
// problems. If malicious user decides to redefine Object.prototype.locale
// we can't just use plain x.locale = 'us' or in C++ Set("locale", "us").
// %object_define_properties will either succeed defining or throw an error.
var resolved = %object_define_properties({}, {
caseFirst: {writable: true},
collation: {value: internalOptions.collation, writable: true},
ignorePunctuation: {writable: true},
locale: {writable: true},
numeric: {writable: true},
requestedLocale: {value: requestedLocale, writable: true},
sensitivity: {writable: true},
strength: {writable: true},
usage: {value: internalOptions.usage, writable: true}
});
var internalCollator = %CreateCollator(requestedLocale,
internalOptions,
resolved);
// Writable, configurable and enumerable are set to false by default.
%MarkAsInitializedIntlObjectOfType(collator, 'collator', internalCollator);
collator[resolvedSymbol] = resolved;
if (FLAG_intl_extra) {
%object_define_property(collator, 'resolved', resolvedAccessor);
}
return collator;
}