/
PlatformIntlApple.mm
2525 lines (2412 loc) · 106 KB
/
PlatformIntlApple.mm
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 (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/Platform/Intl/BCP47Parser.h"
#include "hermes/Platform/Intl/PlatformIntl.h"
#import <Foundation/Foundation.h>
#include <unordered_set>
static_assert(__has_feature(objc_arc), "arc must be enabled");
namespace hermes {
namespace platform_intl {
namespace {
NSString *u16StringToNSString(const std::u16string &src) {
auto size = src.size();
const auto *cString = (const unichar *)src.c_str();
return [NSString stringWithCharacters:cString length:size];
}
std::u16string nsStringToU16String(NSString *src) {
auto size = src.length;
std::u16string result;
result.resize(size);
[src getCharacters:(unichar *)&result[0] range:NSMakeRange(0, size)];
return result;
}
const std::vector<std::u16string> &getAvailableLocales() {
static const std::vector<std::u16string> *availableLocales = [] {
NSArray<NSString *> *availableLocales =
[NSLocale availableLocaleIdentifiers];
// Intentionally leaked to avoid destruction order problems.
auto *vec = new std::vector<std::u16string>();
for (id str in availableLocales) {
auto u16str = nsStringToU16String(str);
// NSLocale sometimes gives locale identifiers with an underscore instead
// of a dash. We only consider dashes valid, so fix up any identifiers we
// get from NSLocale.
std::replace(u16str.begin(), u16str.end(), u'_', u'-');
// Some locales may still not be properly canonicalized (e.g. en_US_POSIX
// should be en-US-posix).
if (auto parsed = ParsedLocaleIdentifier::parse(u16str))
vec->push_back(parsed->canonicalize());
}
return vec;
}();
return *availableLocales;
}
const std::u16string &getDefaultLocale() {
static const std::u16string *defLocale = new std::u16string([] {
// Environment variable used for testing only
const char *testLocale = std::getenv("_HERMES_TEST_LOCALE");
if (testLocale) {
NSString *nsTestLocale = [NSString stringWithUTF8String:testLocale];
return nsStringToU16String(nsTestLocale);
}
NSString *nsDefLocale = [[NSLocale currentLocale] localeIdentifier];
auto defLocale = nsStringToU16String(nsDefLocale);
// See the comment in getAvailableLocales.
std::replace(defLocale.begin(), defLocale.end(), u'_', u'-');
if (auto parsed = ParsedLocaleIdentifier::parse(defLocale))
return parsed->canonicalize();
return std::u16string(u"und");
}());
return *defLocale;
}
/// https://402.ecma-international.org/8.0/#sec-bestavailablelocale
std::optional<std::u16string> bestAvailableLocale(
const std::vector<std::u16string> &availableLocales,
const std::u16string &locale) {
// 1. Let candidate be locale
std::u16string candidate = locale;
// 2. Repeat
while (true) {
// a. If availableLocales contains an element equal to candidate, return
// candidate.
if (llvh::find(availableLocales, candidate) != availableLocales.end())
return candidate;
// b. Let pos be the character index of the last occurrence of "-" (U+002D)
// within candidate.
size_t pos = candidate.rfind(u'-');
// ...If that character does not occur, return undefined.
if (pos == std::u16string::npos)
return std::nullopt;
// c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate,
// decrease pos by 2.
if (pos >= 2 && candidate[pos - 2] == '-')
pos -= 2;
// d. Let candidate be the substring of candidate from position 0,
// inclusive, to position pos, exclusive.
candidate.resize(pos);
}
}
struct LocaleMatch {
std::u16string locale;
std::map<std::u16string, std::u16string> extensions;
};
/// https://402.ecma-international.org/8.0/#sec-lookupmatcher
LocaleMatch lookupMatcher(
const std::vector<std::u16string> &availableLocales,
const std::vector<std::u16string> &requestedLocales) {
// 1. Let result be a new Record.
LocaleMatch result;
// 2. For each element locale of requestedLocales, do
for (const std::u16string &locale : requestedLocales) {
// a. Let noExtensionsLocale be the String value that is locale with
// any Unicode locale extension sequences removed.
// In practice, we can skip this step because availableLocales never
// contains any extensions, so bestAvailableLocale will trim away any
// unicode extensions.
// b. Let availableLocale be BestAvailableLocale(availableLocales,
// noExtensionsLocale).
std::optional<std::u16string> availableLocale =
bestAvailableLocale(availableLocales, locale);
// c. If availableLocale is not undefined, then
if (availableLocale) {
// i. Set result.[[locale]] to availableLocale.
result.locale = std::move(*availableLocale);
// ii. If locale and noExtensionsLocale are not the same String value,
// then
// 1. Let extension be the String value consisting of the substring of
// the Unicode locale extension sequence within locale.
// 2. Set result.[[extension]] to extension.
auto parsed = ParsedLocaleIdentifier::parse(locale);
result.extensions = std::move(parsed->unicodeExtensionKeywords);
// iii. Return result.
return result;
}
}
// availableLocale was undefined, so set result.[[locale]] to defLocale.
result.locale = getDefaultLocale();
// 5. Return result.
return result;
}
struct ResolvedLocale {
std::u16string locale;
std::u16string dataLocale;
std::unordered_map<std::u16string, std::u16string> extensions;
};
/// https://402.ecma-international.org/8.0/#sec-resolvelocale
ResolvedLocale resolveLocale(
const std::vector<std::u16string> &availableLocales,
const std::vector<std::u16string> &requestedLocales,
const std::unordered_map<std::u16string, std::u16string> &options,
llvh::ArrayRef<std::u16string_view> relevantExtensionKeys) {
// 1. Let matcher be options.[[localeMatcher]].
// 2. If matcher is "lookup", then
// a. Let r be LookupMatcher(availableLocales, requestedLocales).
// 3. Else,
// a. Let r be BestFitMatcher(availableLocales, requestedLocales).
auto r = lookupMatcher(availableLocales, requestedLocales);
// 4. Let foundLocale be r.[[locale]].
auto foundLocale = r.locale;
// 5. Let result be a new Record.
ResolvedLocale result;
// 6. Set result.[[dataLocale]] to foundLocale.
result.dataLocale = foundLocale;
// 7. If r has an [[extension]] field, then
// a. Let components be ! UnicodeExtensionComponents(r.[[extension]]).
// b. Let keywords be components.[[Keywords]].
// 8. Let supportedExtension be "-u".
std::u16string supportedExtension = u"-u";
// 9. For each element key of relevantExtensionKeys, do
for (const auto &keyView : relevantExtensionKeys) {
// TODO(T116352920): Make relevantExtensionKeys an ArrayRef<std::u16string>
// and remove this temporary once we have constexpr std::u16string.
std::u16string key{keyView};
// a. Let foundLocaleData be localeData.[[<foundLocale>]].
// NOTE: We don't actually have access to the underlying locale data, so we
// accept everything and defer to NSLocale.
// b. Assert: Type(foundLocaleData) is Record.
// c. Let keyLocaleData be foundLocaleData.[[<key>]].
// d. Assert: Type(keyLocaleData) is List.
// e. Let value be keyLocaleData[0].
// f. Assert: Type(value) is either String or Null.
// g. Let supportedExtensionAddition be "".
// h. If r has an [[extension]] field, then
auto extIt = r.extensions.find(key);
std::optional<std::u16string> value;
std::u16string supportedExtensionAddition;
// i. If keywords contains an element whose [[Key]] is the same as key, then
if (extIt != r.extensions.end()) {
// 1. Let entry be the element of keywords whose [[Key]] is the same as
// key.
// 2. Let requestedValue be entry.[[Value]].
// 3. If requestedValue is not the empty String, then
// a. If keyLocaleData contains requestedValue, then
// i. Let value be requestedValue.
// ii. Let supportedExtensionAddition be the string-concatenation of "-",
// key, "-", and value.
// 4. Else if keyLocaleData contains "true", then
// a. Let value be "true".
// b. Let supportedExtensionAddition be the string-concatenation of "-"
// and key.
supportedExtensionAddition.append(u"-").append(key);
if (extIt->second.empty())
value = u"true";
else {
value = extIt->second;
supportedExtensionAddition.append(u"-").append(*value);
}
}
// i. If options has a field [[<key>]], then
auto optIt = options.find(key);
if (optIt != options.end()) {
// i. Let optionsValue be options.[[<key>]].
std::u16string optionsValue = optIt->second;
// ii. Assert: Type(optionsValue) is either String, Undefined, or Null.
// iii. If Type(optionsValue) is String, then
// 1. Let optionsValue be the string optionsValue after performing the
// algorithm steps to transform Unicode extension values to canonical
// syntax per Unicode Technical Standard #35 LDML § 3.2.1 Canonical
// Unicode Locale Identifiers, treating key as ukey and optionsValue as
// uvalue productions.
// 2. Let optionsValue be the string optionsValue after performing the
// algorithm steps to replace Unicode extension values with their
// canonical form per Technical Standard #35 LDML § 3.2.1 Canonical
// Unicode Locale Identifiers, treating key as ukey and optionsValue as
// uvalue productions
// 3. If optionsValue is the empty String, then
if (optionsValue.empty()) {
// a. Let optionsValue be "true".
optionsValue = u"true";
}
// iv. If keyLocaleData contains optionsValue, then
// 1. If SameValue(optionsValue, value) is false, then
if (optionsValue != value) {
// a. Let value be optionsValue.
value = optionsValue;
// b. Let supportedExtensionAddition be "".
supportedExtensionAddition = u"";
}
}
// j. Set result.[[<key>]] to value.
if (value)
result.extensions.emplace(key, std::move(*value));
// k. Append supportedExtensionAddition to supportedExtension.
supportedExtension.append(supportedExtensionAddition);
}
// 10. If the number of elements in supportedExtension is greater than 2, then
if (supportedExtension.size() > 2) {
// a. Let foundLocale be InsertUnicodeExtensionAndCanonicalize(foundLocale,
// supportedExtension).
foundLocale.append(supportedExtension);
}
// 11. Set result.[[locale]] to foundLocale.
result.locale = std::move(foundLocale);
// 12. Return result.
return result;
}
/// https://402.ecma-international.org/8.0/#sec-lookupsupportedlocales
std::vector<std::u16string> lookupSupportedLocales(
const std::vector<std::u16string> &availableLocales,
const std::vector<std::u16string> &requestedLocales) {
// 1. Let subset be a new empty List.
std::vector<std::u16string> subset;
// 2. For each element locale of requestedLocales in List order, do
for (const std::u16string &locale : requestedLocales) {
// a. Let noExtensionsLocale be the String value that is locale with all
// Unicode locale extension sequences removed.
// We can skip this step, see the comment in lookupMatcher.
// b. Let availableLocale be BestAvailableLocale(availableLocales,
// noExtensionsLocale).
std::optional<std::u16string> availableLocale =
bestAvailableLocale(availableLocales, locale);
// c. If availableLocale is not undefined, append locale to the end of
// subset.
if (availableLocale) {
subset.push_back(locale);
}
}
// 3. Return subset.
return subset;
}
/// https://402.ecma-international.org/8.0/#sec-supportedlocales
std::vector<std::u16string> supportedLocales(
const std::vector<std::u16string> &availableLocales,
const std::vector<std::u16string> &requestedLocales) {
// 1. Set options to ? CoerceOptionsToObject(options).
// 2. Let matcher be ? GetOption(options, "localeMatcher", "string", «
// "lookup", "best fit" », "best fit").
// 3. If matcher is "best fit", then
// a. Let supportedLocales be BestFitSupportedLocales(availableLocales,
// requestedLocales).
// 4. Else,
// a. Let supportedLocales be LookupSupportedLocales(availableLocales,
// requestedLocales).
// 5. Return CreateArrayFromList(supportedLocales).
// We do not implement a BestFitMatcher, so we can just use LookupMatcher.
return lookupSupportedLocales(availableLocales, requestedLocales);
}
/// https://402.ecma-international.org/8.0/#sec-canonicalizelocalelist
vm::CallResult<std::vector<std::u16string>> canonicalizeLocaleList(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales) {
// 1. If locales is undefined, then
// a. Return a new empty List
// Not needed, this validation occurs closer to VM in 'normalizeLocales'.
// 2. Let seen be a new empty List.
std::vector<std::u16string> seen;
// 3. If Type(locales) is String or Type(locales) is Object and locales has an
// [[InitializedLocale]] internal slot, then
// 4. Else
// We don't yet support Locale object -
// https://402.ecma-international.org/8.0/#locale-objects As of now, 'locales'
// can only be a string list/array. Validation occurs in normalizeLocaleList,
// so this function just takes a vector of strings.
// 5. Let len be ? ToLength(? Get(O, "length")).
// 6. Let k be 0.
// 7. Repeat, while k < len
for (const auto &locale : locales) {
// 7.c.vi. Let canonicalizedTag be CanonicalizeUnicodeLocaleId(tag).
auto parsedOpt = ParsedLocaleIdentifier::parse(locale);
if (!parsedOpt)
return runtime.raiseRangeError(
vm::TwineChar16("Invalid language tag: ") +
vm::TwineChar16(locale.c_str()));
auto canonicalizedTag = parsedOpt->canonicalize();
// 7.c.vii. If canonicalizedTag is not an element of seen, append
// canonicalizedTag as the last element of seen.
if (std::find(seen.begin(), seen.end(), canonicalizedTag) == seen.end()) {
seen.push_back(std::move(canonicalizedTag));
}
}
return seen;
}
vm::CallResult<std::u16string> localeListToLocaleString(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales) {
// 3. Let requestedLocales be ? CanonicalizeLocaleList(locales).
vm::CallResult<std::vector<std::u16string>> requestedLocales =
canonicalizeLocaleList(runtime, locales);
if (LLVM_UNLIKELY(requestedLocales == vm::ExecutionStatus::EXCEPTION)) {
return vm::ExecutionStatus::EXCEPTION;
}
// 4. If requestedLocales is not an empty List, then
// a. Let requestedLocale be requestedLocales[0].
// 5. Else,
// a. Let requestedLocale be DefaultLocale().
std::u16string requestedLocale = requestedLocales->empty()
? getDefaultLocale()
: std::move(requestedLocales->front());
// 6. Let noExtensionsLocale be the String value that is requestedLocale with
// any Unicode locale extension sequences (6.2.1) removed.
// We can skip this step, see the comment in lookupMatcher.
// 7. Let availableLocales be a List with language tags that includes the
// languages for which the Unicode Character Database contains language
// sensitive case mappings. Implementations may add additional language tags
// if they support case mapping for additional locales.
// 8. Let locale be BestAvailableLocale(availableLocales, noExtensionsLocale).
// Convert to C++ array for bestAvailableLocale function
const std::vector<std::u16string> &availableLocales = getAvailableLocales();
std::optional<std::u16string> locale =
bestAvailableLocale(availableLocales, requestedLocale);
// 9. If locale is undefined, let locale be "und".
return locale.value_or(u"und");
}
/// https://402.ecma-international.org/8.0/#sec-getoption
/// Split into getOptionString and getOptionBool to help readability
vm::CallResult<std::optional<std::u16string>> getOptionString(
vm::Runtime &runtime,
const Options &options,
const std::u16string &property,
llvh::ArrayRef<std::u16string_view> values,
std::optional<std::u16string_view> fallback) {
// 1. Assert type(options) is object
// 2. Let value be ? Get(options, property).
auto valueIt = options.find(property);
// 3. If value is undefined, return fallback.
if (valueIt == options.end())
return std::optional<std::u16string>(fallback);
const auto &value = valueIt->second.getString();
// 4. Assert: type is "boolean" or "string".
// 5. If type is "boolean", then
// a. Set value to ! ToBoolean(value).
// 6. If type is "string", then
// a. Set value to ? ToString(value).
// 7. If values is not undefined and values does not contain an element equal
// to value, throw a RangeError exception.
if (!values.empty() && llvh::find(values, value) == values.end())
return runtime.raiseRangeError(
vm::TwineChar16(property.c_str()) +
vm::TwineChar16(" value is invalid."));
// 8. Return value.
return std::optional<std::u16string>(value);
}
std::optional<bool> getOptionBool(
vm::Runtime &runtime,
const Options &options,
const std::u16string &property,
std::optional<bool> fallback) {
// 1. Assert: Type(options) is Object.
// 2. Let value be ? Get(options, property).
auto value = options.find(property);
// 3. If value is undefined, return fallback.
if (value == options.end()) {
return fallback;
}
// 8. Return value.
return value->second.getBool();
}
/// https://402.ecma-international.org/8.0/#sec-defaultnumberoption
vm::CallResult<std::optional<uint8_t>> defaultNumberOption(
vm::Runtime &runtime,
const std::u16string &property,
std::optional<Option> value,
const std::uint8_t minimum,
const std::uint8_t maximum,
std::optional<uint8_t> fallback) {
// 1. If value is undefined, return fallback.
if (!value) {
return fallback;
}
// 2. Set value to ? ToNumber(value).
// 3. If value is NaN or less than minimum or greater than maximum, throw a
// RangeError exception.
if (std::isnan(value->getNumber()) || value->getNumber() < minimum ||
value->getNumber() > maximum) {
return runtime.raiseRangeError(
vm::TwineChar16(property.c_str()) +
vm::TwineChar16(" value is invalid."));
}
// 4. Return floor(value).
return std::optional<uint8_t>(std::floor(value->getNumber()));
}
/// https://402.ecma-international.org/8.0/#sec-getnumberoption
vm::CallResult<std::optional<uint8_t>> getNumberOption(
vm::Runtime &runtime,
const Options &options,
const std::u16string &property,
const std::uint8_t minimum,
const std::uint8_t maximum,
std::optional<uint8_t> fallback) {
// 1. Assert: Type(options) is Object.
// 2. Let value be ? Get(options, property).
std::optional<Option> value;
auto iter = options.find(property);
if (iter != options.end()) {
value = Option(iter->second);
}
// 3. Return ? DefaultNumberOption(value, minimum, maximum, fallback).
auto defaultNumber =
defaultNumberOption(runtime, property, value, minimum, maximum, fallback);
if (LLVM_UNLIKELY(defaultNumber == vm::ExecutionStatus::EXCEPTION)) {
return vm::ExecutionStatus::EXCEPTION;
}
return std::optional<uint8_t>(defaultNumber.getValue());
}
// Implementation of
// https://402.ecma-international.org/8.0/#sec-todatetimeoptions
vm::CallResult<Options> toDateTimeOptions(
vm::Runtime &runtime,
Options options,
std::u16string_view required,
std::u16string_view defaults) {
// 1. If options is undefined, let options be null; otherwise let options be ?
// ToObject(options).
// 2. Let options be OrdinaryObjectCreate(options).
// 3. Let needDefaults be true.
bool needDefaults = true;
// 4. If required is "date" or "any", then
if (required == u"date" || required == u"any") {
// a. For each property name prop of « "weekday", "year", "month", "day" »,
// do
// TODO(T116352920): Make this a std::u16string props[] once we have
// constexpr std::u16string.
static constexpr std::u16string_view props[] = {
u"weekday", u"year", u"month", u"day"};
for (const auto &prop : props) {
// i. Let value be ? Get(options, prop).
if (options.find(std::u16string(prop)) != options.end()) {
// ii. If value is not undefined, let needDefaults be false.
needDefaults = false;
}
}
}
// 5. If required is "time" or "any", then
if (required == u"time" || required == u"any") {
// a. For each property name prop of « "dayPeriod", "hour", "minute",
// "second", "fractionalSecondDigits" », do
static constexpr std::u16string_view props[] = {
u"dayPeriod", u"hour", u"minute", u"second", u"fractionalSecondDigits"};
for (const auto &prop : props) {
// i. Let value be ? Get(options, prop).
if (options.find(std::u16string(prop)) != options.end()) {
// ii. If value is not undefined, let needDefaults be false.
needDefaults = false;
}
}
}
// 6. Let dateStyle be ? Get(options, "dateStyle").
auto dateStyle = options.find(u"dateStyle");
// 7. Let timeStyle be ? Get(options, "timeStyle").
auto timeStyle = options.find(u"timeStyle");
// 8. If dateStyle is not undefined or timeStyle is not undefined, let
// needDefaults be false.
if (dateStyle != options.end() || timeStyle != options.end()) {
needDefaults = false;
}
// 9. If required is "date" and timeStyle is not undefined, then
if (required == u"date" && timeStyle != options.end()) {
// a. Throw a TypeError exception.
return runtime.raiseTypeError(
"Unexpectedly found timeStyle option for \"date\" property");
}
// 10. If required is "time" and dateStyle is not undefined, then
if (required == u"time" && dateStyle != options.end()) {
// a. Throw a TypeError exception.
return runtime.raiseTypeError(
"Unexpectedly found dateStyle option for \"time\" property");
}
// 11. If needDefaults is true and defaults is either "date" or "all", then
if (needDefaults && (defaults == u"date" || defaults == u"all")) {
// a. For each property name prop of « "year", "month", "day" », do
static constexpr std::u16string_view props[] = {u"year", u"month", u"day"};
for (const auto &prop : props) {
// i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
options.emplace(prop, Option(std::u16string(u"numeric")));
}
}
// 12. If needDefaults is true and defaults is either "time" or "all", then
if (needDefaults && (defaults == u"time" || defaults == u"all")) {
// a. For each property name prop of « "hour", "minute", "second" », do
static constexpr std::u16string_view props[] = {
u"hour", u"minute", u"second"};
for (const auto &prop : props) {
// i. Perform ? CreateDataPropertyOrThrow(options, prop, "numeric").
options.emplace(prop, Option(std::u16string(u"numeric")));
}
}
// 13. return options
return options;
}
// https://402.ecma-international.org/8.0/#sec-case-sensitivity-and-case-mapping
std::u16string toASCIIUppercase(std::u16string_view tz) {
std::u16string result;
std::uint8_t offset = 'a' - 'A';
for (char16_t c16 : tz) {
if (c16 >= 'a' && c16 <= 'z') {
result.push_back((char)c16 - offset);
} else {
result.push_back(c16);
}
}
return result;
}
static std::unordered_map<std::u16string, std::u16string> validTimeZoneNames() {
std::unordered_map<std::u16string, std::u16string> result;
static auto nsTimeZoneNames = [NSTimeZone.knownTimeZoneNames
arrayByAddingObjectsFromArray:NSTimeZone.abbreviationDictionary.allKeys];
for (NSString *timeZoneName in nsTimeZoneNames) {
result.emplace(
nsStringToU16String(timeZoneName.uppercaseString),
nsStringToU16String(timeZoneName));
}
return result;
}
// https://402.ecma-international.org/8.0/#sec-canonicalizetimezonename
std::u16string canonicalizeTimeZoneName(std::u16string_view tz) {
// 1. Let ianaTimeZone be the Zone or Link name of the IANA Time Zone Database
// such that timeZone, converted to upper case as described in 6.1, is equal
// to ianaTimeZone, converted to upper case as described in 6.1.
static const auto timeZones = validTimeZoneNames();
auto ianaTimeZoneIt = timeZones.find(toASCIIUppercase(tz));
auto ianaTimeZone = (ianaTimeZoneIt != timeZones.end())
? ianaTimeZoneIt->second
: std::u16string(tz);
// NOTE: We don't use actual IANA database, so we leave (2) unimplemented.
// 2. If ianaTimeZone is a Link name, let ianaTimeZone be the corresponding
// Zone name as specified in the "backward" file of the IANA Time Zone
// Database.
// 3. If ianaTimeZone is "Etc/UTC" or "Etc/GMT", return "UTC".
if (ianaTimeZone == u"Etc/UTC" || ianaTimeZone == u"Etc/GMT")
ianaTimeZone = u"UTC";
// 4. Return ianaTimeZone.
return ianaTimeZone;
}
// https://402.ecma-international.org/8.0/#sec-defaulttimezone
std::u16string getDefaultTimeZone(NSLocale *locale) {
return nsStringToU16String(NSTimeZone.defaultTimeZone.name);
}
// https://402.ecma-international.org/8.0/#sec-isvalidtimezonename
static bool isValidTimeZoneName(std::u16string_view tz) {
static const auto timeZones = validTimeZoneNames();
return timeZones.find(toASCIIUppercase(tz)) != timeZones.end();
}
// https://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Field_Symbol_Table
std::u16string getDefaultHourCycle(NSLocale *locale) {
auto dateFormatPattern =
nsStringToU16String([NSDateFormatter dateFormatFromTemplate:@"j"
options:0
locale:locale]);
for (char16_t c16 : dateFormatPattern) {
if (c16 == u'h') {
return u"h12";
} else if (c16 == u'K') {
return u"h11";
} else if (c16 == u'H') {
return u"h23";
}
}
return u"h24";
}
/// Helper to lookup a \p key in a map represented as a sorted array of pairs.
template <typename K, typename V, size_t N>
std::optional<V> pairMapLookup(const std::pair<K, V> (&arr)[N], const K &key) {
HERMES_SLOW_ASSERT(std::is_sorted(std::begin(arr), std::end(arr)));
auto it = llvh::lower_bound(
arr, key, [](const auto &a, const K &b) { return a.first < b; });
if (it != std::end(arr) && it->first == key)
return it->second;
return std::nullopt;
}
template <size_t N, size_t P = 0>
static constexpr bool isSorted(const std::u16string_view (&v)[N]) {
if constexpr (P < N - 1) {
return v[P] < v[P + 1] && isSorted<N, P + 1>(v);
}
return true;
}
// https://402.ecma-international.org/8.0/#sec-issanctionedsimpleunitidentifier
bool isSanctionedSimpleUnitIdentifier(std::u16string_view unitIdentifier) {
static constexpr std::u16string_view sanctionedIdentifiers[] = {
u"acre", u"bit", u"byte",
u"celsius", u"centimeter", u"day",
u"degree", u"fahrenheit", u"fluid-ounce",
u"foot", u"gallon", u"gigabit",
u"gigabyte", u"gram", u"hectare",
u"hour", u"inch", u"kilobit",
u"kilobyte", u"kilogram", u"kilometer",
u"liter", u"megabit", u"megabyte",
u"meter", u"mile", u"mile-scandinavian",
u"milliliter", u"millimeter", u"millisecond",
u"minute", u"month", u"ounce",
u"percent", u"petabyte", u"pound",
u"second", u"stone", u"terabit",
u"terabyte", u"week", u"yard",
u"year"};
static_assert(
isSorted(sanctionedIdentifiers), "keep sanctionedIdentifiers sorted");
// 1. If unitIdentifier is listed in Table 2 (sanctionedIdentifiers) above,
// return true
// 2. Else, return false.
return std::binary_search(
std::begin(sanctionedIdentifiers),
std::end(sanctionedIdentifiers),
unitIdentifier);
}
// https://402.ecma-international.org/8.0/#sec-iswellformedunitidentifier
bool isWellFormedUnitIdentifier(std::u16string_view unitIdentifier) {
// 1. If the result of IsSanctionedSimpleUnitIdentifier(unitIdentifier) is
// true, then a. Return true.
if (isSanctionedSimpleUnitIdentifier(unitIdentifier))
return true;
// 2. If the substring "-per-" does not occur exactly once in unitIdentifier,
// then a. Return false.
std::u16string_view fractionDelimiter = u"-per-";
auto foundPos = unitIdentifier.find(fractionDelimiter);
if (foundPos == std::u16string_view::npos)
return false;
// 3. Let numerator be the substring of unitIdentifier from the beginning to
// just before "-per-".
// 4. If the result of IsSanctionedSimpleUnitIdentifier(numerator) is false,
// then a. Return false.
auto numerator = unitIdentifier.substr(0, foundPos);
if (!isSanctionedSimpleUnitIdentifier(numerator))
return false;
// 5. Let denominator be the substring of unitIdentifier from just after
// "-per-" to the end.
// 6. If the result of IsSanctionedSimpleUnitIdentifier(denominator) is
// false, then a. Return false.
const size_t denominatorPos = foundPos + fractionDelimiter.size();
auto denominator = unitIdentifier.substr(
denominatorPos, unitIdentifier.length() - denominatorPos);
if (!isSanctionedSimpleUnitIdentifier(denominator))
return false;
// 7. Return true.
return true;
}
/// Helper to convert from a well-formed unit identifier \p id, to one of the
/// supported built-in NSUnit types provided by Foundation.
NSUnit *unitIdentifierToNSUnit(const std::u16string &unitId) {
static const std::pair<std::u16string_view, NSUnit *> units[] = {
{u"acre", NSUnitArea.acres},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"bit", NSUnitInformationStorage.bits},
{u"byte", NSUnitInformationStorage.bytes},
#endif
{u"celsius", NSUnitTemperature.celsius},
{u"centimeter", NSUnitLength.centimeters},
{u"degree", NSUnitAngle.degrees},
{u"fahrenheit", NSUnitTemperature.fahrenheit},
{u"fluid-ounce", NSUnitVolume.fluidOunces},
{u"foot", NSUnitLength.feet},
{u"gallon", NSUnitVolume.gallons},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"gigabit", NSUnitInformationStorage.gigabits},
{u"gigabyte", NSUnitInformationStorage.gigabytes},
#endif
{u"gram", NSUnitMass.grams},
{u"gram-per-liter", NSUnitConcentrationMass.gramsPerLiter},
{u"hectare", NSUnitArea.hectares},
{u"hour", NSUnitDuration.hours},
{u"inch", NSUnitLength.inches},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"kilobit", NSUnitInformationStorage.kilobits},
{u"kilobyte", NSUnitInformationStorage.kilobytes},
#endif
{u"kilogram", NSUnitMass.kilograms},
{u"kilometer", NSUnitLength.kilometers},
{u"kilometer-per-hour", NSUnitSpeed.kilometersPerHour},
{u"liter", NSUnitVolume.liters},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"megabit", NSUnitInformationStorage.megabits},
{u"megabyte", NSUnitInformationStorage.megabytes},
#endif
{u"meter", NSUnitLength.meters},
{u"meter-per-second", NSUnitSpeed.metersPerSecond},
{u"mile", NSUnitLength.miles},
{u"mile-per-gallon", NSUnitFuelEfficiency.milesPerGallon},
{u"mile-per-hour", NSUnitSpeed.milesPerHour},
{u"mile-scandinavian", NSUnitLength.scandinavianMiles},
{u"milliliter", NSUnitVolume.milliliters},
{u"millimeter", NSUnitLength.millimeters},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"millisecond", NSUnitDuration.milliseconds},
#endif
{u"minute", NSUnitDuration.minutes},
{u"ounce", NSUnitMass.ounces},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"petabyte", NSUnitInformationStorage.petabytes},
#endif
{u"pound", NSUnitMass.poundsMass},
{u"second", NSUnitDuration.seconds},
{u"stone", NSUnitMass.stones},
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0
{u"terabit", NSUnitInformationStorage.terabits},
{u"terabyte", NSUnitInformationStorage.terabytes},
#endif
{u"yard", NSUnitLength.yards}
};
if (auto nsUnitOpt = pairMapLookup(units, std::u16string_view(unitId)))
return *nsUnitOpt;
return [[NSUnit alloc] initWithSymbol:u16StringToNSString(unitId)];
}
// https://402.ecma-international.org/8.0/#sec-iswellformedcurrencycode
bool isWellFormedCurrencyCode(std::u16string_view currencyCode) {
// 1. Let normalized be the result of mapping currency to upper case as
// described in 6.1.
auto normalized = toASCIIUppercase(currencyCode);
// 2. If the number of elements in normalized is not 3, return false.
if (normalized.size() != 3)
return false;
// 3. If normalized contains any character that is not in the range "A" to
// "Z" (U+0041 to U+005A), return false.
if (!llvh::all_of(normalized, [](auto c) { return c >= u'A' && c <= u'Z'; }))
return false;
// 4. Return true.
return true;
}
uint8_t getCurrencyDigits(std::u16string_view code) {
// https://en.wikipedia.org/wiki/ISO_4217#Active_codes
static constexpr std::pair<std::u16string_view, uint8_t> currencies[] = {
{u"BHD", 3}, {u"BIF", 0}, {u"CLF", 4}, {u"CLP", 0}, {u"DJF", 0},
{u"GNF", 0}, {u"IQD", 3}, {u"ISK", 0}, {u"JOD", 3}, {u"JPY", 0},
{u"KMF", 0}, {u"KRW", 0}, {u"KWD", 3}, {u"LYD", 3}, {u"OMR", 3},
{u"PYG", 0}, {u"RWF", 0}, {u"TND", 3}, {u"UGX", 0}, {u"UYI", 0},
{u"UYW", 4}, {u"VND", 0}, {u"VUV", 0}, {u"XAF", 0}, {u"XOF", 0},
{u"XPF", 0}};
// 1. If the ISO 4217 currency and funds code list contains currency as an
// alphabetic code, return the minor unit value corresponding to the currency
// from the list; otherwise, return 2.
if (auto digitsOpt = pairMapLookup(currencies, code))
return *digitsOpt;
return 2;
}
}
/// https://402.ecma-international.org/8.0/#sec-intl.getcanonicallocales
vm::CallResult<std::vector<std::u16string>> getCanonicalLocales(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales) {
// 1. Let ll be ? CanonicalizeLocaleList(locales).
// 2. Return CreateArrayFromList(ll).
return canonicalizeLocaleList(runtime, locales);
}
/// https://402.ecma-international.org/8.0/#sup-string.prototype.tolocalelowercase
vm::CallResult<std::u16string> toLocaleLowerCase(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales,
const std::u16string &str) {
NSString *nsStr = u16StringToNSString(str);
// Steps 3-9 in localeListToLocaleString()
vm::CallResult<std::u16string> locale =
localeListToLocaleString(runtime, locales);
// 10. Let cpList be a List containing in order the code points of S as
// defined in es2022, 6.1.4, starting at the first element of S.
// 11. Let cuList be a List where the elements are the result of a lower case
// transformation of the ordered code points in cpList according to the
// Unicode Default Case Conversion algorithm or an implementation-defined
// conversion algorithm. A conforming implementation's lower case
// transformation algorithm must always yield the same cpList given the same
// cuList and locale.
// 12. Let L be a String whose elements are the UTF-16 Encoding (defined in
// es2022, 6.1.4) of the code points of cuList.
NSString *L = u16StringToNSString(locale.getValue());
// 13. Return L.
return nsStringToU16String([nsStr
lowercaseStringWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:L]]);
}
/// https://402.ecma-international.org/8.0/#sup-string.prototype.tolocaleuppercase
vm::CallResult<std::u16string> toLocaleUpperCase(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales,
const std::u16string &str) {
NSString *nsStr = u16StringToNSString(str);
// Steps 3-9 in localeListToLocaleString()
vm::CallResult<std::u16string> locale =
localeListToLocaleString(runtime, locales);
// 10. Let cpList be a List containing in order the code points of S as
// defined in es2022, 6.1.4, starting at the first element of S.
// 11. Let cuList be a List where the elements are the result of a lower case
// transformation of the ordered code points in cpList according to the
// Unicode Default Case Conversion algorithm or an implementation-defined
// conversion algorithm. A conforming implementation's lower case
// transformation algorithm must always yield the same cpList given the same
// cuList and locale.
// 12. Let L be a String whose elements are the UTF-16 Encoding (defined in
// es2022, 6.1.4) of the code points of cuList.
NSString *L = u16StringToNSString(locale.getValue());
// 13. Return L.
return nsStringToU16String([nsStr
uppercaseStringWithLocale:[[NSLocale alloc] initWithLocaleIdentifier:L]]);
}
namespace {
class CollatorApple : public Collator {
public:
CollatorApple() = default;
vm::ExecutionStatus initialize(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales,
const Options &options) noexcept;
Options resolvedOptions() noexcept;
double compare(const std::u16string &x, const std::u16string &y) noexcept;
private:
NSLocale *nsLocale_;
NSStringCompareOptions nsCompareOptions_;
std::u16string locale_;
std::u16string usage_;
std::u16string collation_;
std::u16string caseFirst_;
std::u16string sensitivity_;
bool numeric_;
bool ignorePunctuation_;
};
} // namespace
Collator::Collator() = default;
Collator::~Collator() = default;
/// https://402.ecma-international.org/8.0/#sec-intl.collator.supportedlocalesof
vm::CallResult<std::vector<std::u16string>> Collator::supportedLocalesOf(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales,
const Options &options) noexcept {
// 1. Let availableLocales be %Collator%.[[AvailableLocales]].
const auto &availableLocales = getAvailableLocales();
// 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
auto requestedLocalesRes = canonicalizeLocaleList(runtime, locales);
if (LLVM_UNLIKELY(requestedLocalesRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 3. Return ? SupportedLocales(availableLocales, requestedLocales, options)
return supportedLocales(availableLocales, *requestedLocalesRes);
}
/// https://402.ecma-international.org/8.0/#sec-initializecollator
vm::ExecutionStatus CollatorApple::initialize(
vm::Runtime &runtime,
const std::vector<std::u16string> &locales,
const Options &options) noexcept {
// 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
auto requestedLocalesRes = canonicalizeLocaleList(runtime, locales);
if (LLVM_UNLIKELY(requestedLocalesRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 2. Set options to ? CoerceOptionsToObject(options).
// 3. Let usage be ? GetOption(options, "usage", "string", « "sort", "search"
// », "sort").
static constexpr std::u16string_view usageOpts[] = {u"sort", u"search"};
auto usageRes =
getOptionString(runtime, options, u"usage", usageOpts, {u"sort"});
if (LLVM_UNLIKELY(usageRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 4. Set collator.[[Usage]] to usage.
usage_ = std::move(**usageRes);
// 5. If usage is "sort", then
// a. Let localeData be %Collator%.[[SortLocaleData]].
// 6. Else,
// a. Let localeData be %Collator%.[[SearchLocaleData]].
// 7. Let opt be a new Record.
std::unordered_map<std::u16string, std::u16string> opt;
// 8. Let matcher be ? GetOption(options, "localeMatcher", "string", «
// "lookup", "best fit" », "best fit").
// 9. Set opt.[[localeMatcher]] to matcher.
// We only implement lookup matcher, so we don't need to record this.
static constexpr std::u16string_view localeMatcherOpts[] = {
u"lookup", u"best fit"};
auto localeMatcherRes = getOptionString(
runtime, options, u"localeMatcher", localeMatcherOpts, u"best fit");
if (LLVM_UNLIKELY(localeMatcherRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 10. Let collation be ? GetOption(options, "collation", "string", undefined,
// undefined).
auto collationRes = getOptionString(runtime, options, u"collation", {}, {});
if (LLVM_UNLIKELY(collationRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 11. If collation is not undefined, then
// a. If collation does not match the Unicode Locale Identifier type
// nonterminal, throw a RangeError exception.
// 12. Set opt.[[co]] to collation.
if (auto &collationOpt = *collationRes) {
if (!isUnicodeExtensionType(*collationOpt)) {
return runtime.raiseRangeError(
vm::TwineChar16("Invalid collation: ") +
vm::TwineChar16(collationOpt->c_str()));
}
opt.emplace(u"co", std::move(*collationOpt));
}
// 13. Let numeric be ? GetOption(options, "numeric", "boolean", undefined,
// undefined).
auto numericOpt = getOptionBool(runtime, options, u"numeric", {});
// 14. If numeric is not undefined, then
// a. Let numeric be ! ToString(numeric).
// 15. Set opt.[[kn]] to numeric.
if (numericOpt)
opt.emplace(u"kn", *numericOpt ? u"true" : u"false");
// 16. Let caseFirst be ? GetOption(options, "caseFirst", "string", « "upper",
// "lower", "false" », undefined).
static constexpr std::u16string_view caseFirstOpts[] = {
u"upper", u"lower", u"false"};
auto caseFirstRes =
getOptionString(runtime, options, u"caseFirst", caseFirstOpts, {});
if (LLVM_UNLIKELY(caseFirstRes == vm::ExecutionStatus::EXCEPTION))
return vm::ExecutionStatus::EXCEPTION;
// 17. Set opt.[[kf]] to caseFirst.
if (auto caseFirstOpt = *caseFirstRes)
opt.emplace(u"kf", *caseFirstOpt);
// 18. Let relevantExtensionKeys be %Collator%.[[RelevantExtensionKeys]].
static constexpr std::u16string_view relevantExtensionKeys[] = {
u"co", u"kn", u"kf"};
// 19. Let r be ResolveLocale(%Collator%.[[AvailableLocales]],
// requestedLocales, opt,relevantExtensionKeys, localeData).
auto r = resolveLocale(
getAvailableLocales(), *requestedLocalesRes, opt, relevantExtensionKeys);
// 20. Set collator.[[Locale]] to r.[[locale]].