forked from unicode-org/icu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollationtest.cpp
1928 lines (1813 loc) · 75.3 KB
/
collationtest.cpp
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
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2012-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* collationtest.cpp
*
* created on: 2012apr27
* created by: Markus W. Scherer
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/coll.h"
#include "unicode/errorcode.h"
#include "unicode/localpointer.h"
#include "unicode/normalizer2.h"
#include "unicode/sortkey.h"
#include "unicode/std_string.h"
#include "unicode/strenum.h"
#include "unicode/stringpiece.h"
#include "unicode/tblcoll.h"
#include "unicode/uiter.h"
#include "unicode/uniset.h"
#include "unicode/unistr.h"
#include "unicode/usetiter.h"
#include "unicode/ustring.h"
#include "charstr.h"
#include "cmemory.h"
#include "collation.h"
#include "collationdata.h"
#include "collationfcd.h"
#include "collationiterator.h"
#include "collationroot.h"
#include "collationrootelements.h"
#include "collationruleparser.h"
#include "collationweights.h"
#include "cstring.h"
#include "intltest.h"
#include "normalizer2impl.h"
#include "ucbuf.h"
#include "uhash.h"
#include "uitercollationiterator.h"
#include "utf16collationiterator.h"
#include "utf8collationiterator.h"
#include "uvectr32.h"
#include "uvectr64.h"
#include "writesrc.h"
class CodePointIterator;
// TODO: try to share code with IntlTestCollator; for example, prettify(CollationKey)
class CollationTest : public IntlTest {
public:
CollationTest()
: fcd(nullptr), nfd(nullptr),
fileLineNumber(0),
coll(nullptr) {}
~CollationTest() {
delete coll;
}
void runIndexedTest(int32_t index, UBool exec, const char *&name, char *par=nullptr) override;
void TestMinMax();
void TestImplicits();
void TestNulTerminated();
void TestIllegalUTF8();
void TestShortFCDData();
void TestFCD();
void TestCollationWeights();
void TestRootElements();
void TestTailoredElements();
void TestDataDriven();
void TestLongLocale();
void TestBuilderContextsOverflow();
void TestHang22414();
private:
void checkFCD(const char *name, CollationIterator &ci, CodePointIterator &cpi);
void checkAllocWeights(CollationWeights &cw,
uint32_t lowerLimit, uint32_t upperLimit, int32_t n,
int32_t someLength, int32_t minCount);
static UnicodeString printSortKey(const uint8_t *p, int32_t length);
static UnicodeString printCollationKey(const CollationKey &key);
// Helpers & fields for data-driven test.
static UBool isCROrLF(char16_t c) { return c == 0xa || c == 0xd; }
static UBool isSpace(char16_t c) { return c == 9 || c == 0x20 || c == 0x3000; }
static UBool isSectionStarter(char16_t c) { return c == 0x25 || c == 0x2a || c == 0x40; } // %*@
int32_t skipSpaces(int32_t i) {
while(isSpace(fileLine[i])) { ++i; }
return i;
}
UBool readNonEmptyLine(UCHARBUF *f, IcuTestErrorCode &errorCode);
void parseString(int32_t &start, UnicodeString &prefix, UnicodeString &s, UErrorCode &errorCode);
Collation::Level parseRelationAndString(UnicodeString &s, IcuTestErrorCode &errorCode);
void parseAndSetAttribute(IcuTestErrorCode &errorCode);
void parseAndSetReorderCodes(int32_t start, IcuTestErrorCode &errorCode);
void buildTailoring(UCHARBUF *f, IcuTestErrorCode &errorCode);
void setRootCollator(IcuTestErrorCode &errorCode);
void setLocaleCollator(IcuTestErrorCode &errorCode);
UBool needsNormalization(const UnicodeString &s, UErrorCode &errorCode) const;
UBool getSortKeyParts(const char16_t *s, int32_t length,
CharString &dest, int32_t partSize,
IcuTestErrorCode &errorCode);
UBool getCollationKey(const char *norm, const UnicodeString &line,
const char16_t *s, int32_t length,
CollationKey &key, IcuTestErrorCode &errorCode);
UBool getMergedCollationKey(const char16_t *s, int32_t length,
CollationKey &key, IcuTestErrorCode &errorCode);
UBool checkCompareTwo(const char *norm, const UnicodeString &prevFileLine,
const UnicodeString &prevString, const UnicodeString &s,
UCollationResult expectedOrder, Collation::Level expectedLevel,
IcuTestErrorCode &errorCode);
void checkCompareStrings(UCHARBUF *f, IcuTestErrorCode &errorCode);
const Normalizer2 *fcd, *nfd;
UnicodeString fileLine;
int32_t fileLineNumber;
UnicodeString fileTestName;
Collator *coll;
};
extern IntlTest *createCollationTest() {
return new CollationTest();
}
void CollationTest::runIndexedTest(int32_t index, UBool exec, const char *&name, char * /*par*/) {
if(exec) {
logln("TestSuite CollationTest: ");
}
TESTCASE_AUTO_BEGIN;
TESTCASE_AUTO(TestMinMax);
TESTCASE_AUTO(TestImplicits);
TESTCASE_AUTO(TestNulTerminated);
TESTCASE_AUTO(TestIllegalUTF8);
TESTCASE_AUTO(TestShortFCDData);
TESTCASE_AUTO(TestFCD);
TESTCASE_AUTO(TestCollationWeights);
TESTCASE_AUTO(TestRootElements);
TESTCASE_AUTO(TestTailoredElements);
TESTCASE_AUTO(TestDataDriven);
TESTCASE_AUTO(TestLongLocale);
TESTCASE_AUTO(TestBuilderContextsOverflow);
TESTCASE_AUTO(TestHang22414);
TESTCASE_AUTO_END;
}
void CollationTest::TestMinMax() {
IcuTestErrorCode errorCode(*this, "TestMinMax");
setRootCollator(errorCode);
if(errorCode.isFailure()) {
errorCode.reset();
return;
}
RuleBasedCollator *rbc = dynamic_cast<RuleBasedCollator *>(coll);
if(rbc == nullptr) {
errln("the root collator is not a RuleBasedCollator");
return;
}
static const char16_t s[2] = { 0xfffe, 0xffff };
UVector64 ces(errorCode);
rbc->internalGetCEs(UnicodeString(false, s, 2), ces, errorCode);
errorCode.assertSuccess();
if(ces.size() != 2) {
errln("expected 2 CEs for <FFFE, FFFF>, got %d", (int)ces.size());
return;
}
int64_t ce = ces.elementAti(0);
int64_t expected = Collation::makeCE(Collation::MERGE_SEPARATOR_PRIMARY);
if(ce != expected) {
errln("CE(U+fffe)=%04lx != 02..", (long)ce);
}
ce = ces.elementAti(1);
expected = Collation::makeCE(Collation::MAX_PRIMARY);
if(ce != expected) {
errln("CE(U+ffff)=%04lx != max..", (long)ce);
}
}
void CollationTest::TestImplicits() {
IcuTestErrorCode errorCode(*this, "TestImplicits");
const CollationData *cd = CollationRoot::getData(errorCode);
if(errorCode.errDataIfFailureAndReset("CollationRoot::getData()")) {
return;
}
// Implicit primary weights should be assigned for the following sets,
// and sort in ascending order by set and then code point.
// See https://www.unicode.org/reports/tr10/#Implicit_Weights
// core Han Unified Ideographs
UnicodeSet coreHan("[\\p{unified_ideograph}&"
"[\\p{Block=CJK_Unified_Ideographs}"
"\\p{Block=CJK_Compatibility_Ideographs}]]",
errorCode);
// all other Unified Han ideographs
UnicodeSet otherHan("[\\p{unified ideograph}-"
"[\\p{Block=CJK_Unified_Ideographs}"
"\\p{Block=CJK_Compatibility_Ideographs}]]",
errorCode);
UnicodeSet unassigned("[[:Cn:][:Cs:][:Co:]]", errorCode);
unassigned.remove(0xfffe, 0xffff); // These have special CLDR root mappings.
// Starting with CLDR 26/ICU 54, the root Han order may instead be
// the Unihan radical-stroke order.
// The tests should pass either way, so we only test the order of a small set of Han characters
// whose radical-stroke order is the same as their code point order.
//
// When the radical-stroke data (kRSUnicode) for one of these characters changes
// such that it no longer sorts in code point order,
// then we need to remove it from this set.
// (These changes are easiest to see in the change history of the Unicode Tools file
// unicodetools/data/ucd/dev/Unihan/kRSUnicode.txt.)
// For example, in Unicode 15.1, U+503B has a kRSUnicode value of 9.9
// while the neighboring characters still have 9.8. We remove the out-of-order U+503B.
//
// FYI: The Unicode Tools program GenerateUnihanCollators prints something like
// hanInCPOrder = [一-世丘-丫中-丼举-么乊-习乣-亏...鼢-齡齣-龏龑-龥]
// number of original-Unihan characters out of order: 318
UnicodeSet someHanInCPOrder(
u"[\u4E00-\u4E16\u4E18-\u4E2B\u4E2D-\u4E3C\u4E3E-\u4E48"
u"\u4E4A-\u4E60\u4E63-\u4E8F\u4E91-\u4F63\u4F65-\u503A\u503C-\u50F1\u50F3-\u50F6]",
errorCode);
UnicodeSet inOrder(someHanInCPOrder);
inOrder.addAll(unassigned).freeze();
if(errorCode.errIfFailureAndReset("UnicodeSet")) {
return;
}
const UnicodeSet *sets[] = { &coreHan, &otherHan, &unassigned };
const char *const setNames[] = { "core Han", "Han extensions", "unassigned" };
UChar32 prev = 0;
uint32_t prevPrimary = 0;
UTF16CollationIterator ci(cd, false, nullptr, nullptr, nullptr);
for(int32_t i = 0; i < UPRV_LENGTHOF(sets); ++i) {
const char *setName = setNames[i];
LocalPointer<UnicodeSetIterator> iter(new UnicodeSetIterator(*sets[i]));
while(iter->next()) {
UChar32 c = iter->getCodepoint();
UnicodeString s(c);
ci.setText(s.getBuffer(), s.getBuffer() + s.length());
int64_t ce = ci.nextCE(errorCode);
int64_t ce2 = ci.nextCE(errorCode);
if(errorCode.errIfFailureAndReset("CollationIterator.nextCE()")) {
return;
}
if(ce == Collation::NO_CE || ce2 != Collation::NO_CE) {
errln("%s: CollationIterator.nextCE(U+%04lx) did not yield exactly one CE",
setName, (long)c);
continue;
}
if((ce & 0xffffffff) != Collation::COMMON_SEC_AND_TER_CE) {
errln("%s: CollationIterator.nextCE(U+%04lx) has non-common sec/ter weights: %08lx",
setName, (long)c, (long)(ce & 0xffffffff));
continue;
}
uint32_t primary = (uint32_t)(ce >> 32);
if(!(primary > prevPrimary) && inOrder.contains(c) && inOrder.contains(prev)) {
errln("%s: CE(U+%04lx)=%04lx.. not greater than CE(U+%04lx)=%04lx..",
setName, (long)c, (long)primary, (long)prev, (long)prevPrimary);
}
prev = c;
prevPrimary = primary;
}
}
}
void CollationTest::TestNulTerminated() {
IcuTestErrorCode errorCode(*this, "TestNulTerminated");
const CollationData *data = CollationRoot::getData(errorCode);
if(errorCode.errDataIfFailureAndReset("CollationRoot::getData()")) {
return;
}
static const char16_t s[] = { 0x61, 0x62, 0x61, 0x62, 0 };
UTF16CollationIterator ci1(data, false, s, s, s + 2);
UTF16CollationIterator ci2(data, false, s + 2, s + 2, nullptr);
for(int32_t i = 0;; ++i) {
int64_t ce1 = ci1.nextCE(errorCode);
int64_t ce2 = ci2.nextCE(errorCode);
if(errorCode.errIfFailureAndReset("CollationIterator.nextCE()")) {
return;
}
if(ce1 != ce2) {
errln("CollationIterator.nextCE(with length) != nextCE(NUL-terminated) at CE %d", (int)i);
break;
}
if(ce1 == Collation::NO_CE) { break; }
}
}
void CollationTest::TestIllegalUTF8() {
IcuTestErrorCode errorCode(*this, "TestIllegalUTF8");
setRootCollator(errorCode);
if(errorCode.isFailure()) {
errorCode.reset();
return;
}
coll->setAttribute(UCOL_STRENGTH, UCOL_IDENTICAL, errorCode);
static const StringPiece strings[] = {
// string with U+FFFD == illegal byte sequence
u8"a\uFFFDz", "a\x80z", // trail byte
u8"a\uFFFD\uFFFDz", "a\xc1\x81z", // non-shortest form
u8"a\uFFFD\uFFFD\uFFFDz", "a\xe0\x82\x83z", // non-shortest form
u8"a\uFFFD\uFFFD\uFFFDz", "a\xed\xa0\x80z", // lead surrogate: would be U+D800
u8"a\uFFFD\uFFFD\uFFFDz", "a\xed\xbf\xbfz", // trail surrogate: would be U+DFFF
u8"a\uFFFD\uFFFD\uFFFD\uFFFDz", "a\xf0\x8f\xbf\xbfz", // non-shortest form
u8"a\uFFFD\uFFFD\uFFFD\uFFFDz", "a\xf4\x90\x80\x80z" // out of range: would be U+110000
};
for(int32_t i = 0; i < UPRV_LENGTHOF(strings); i += 2) {
StringPiece fffd(strings[i]);
StringPiece illegal(strings[i + 1]);
UCollationResult order = coll->compareUTF8(fffd, illegal, errorCode);
if(order != UCOL_EQUAL) {
errln("compareUTF8(pair %d: U+FFFD, illegal UTF-8)=%d != UCOL_EQUAL",
(int)i, order);
}
}
}
namespace {
void addLeadSurrogatesForSupplementary(const UnicodeSet &src, UnicodeSet &dest) {
for(UChar32 c = 0x10000; c < 0x110000;) {
UChar32 next = c + 0x400;
if(src.containsSome(c, next - 1)) {
dest.add(U16_LEAD(c));
}
c = next;
}
}
} // namespace
void CollationTest::TestShortFCDData() {
// See CollationFCD class comments.
IcuTestErrorCode errorCode(*this, "TestShortFCDData");
UnicodeSet expectedLccc("[:^lccc=0:]", errorCode);
errorCode.assertSuccess();
expectedLccc.add(0xdc00, 0xdfff); // add all trail surrogates
addLeadSurrogatesForSupplementary(expectedLccc, expectedLccc);
UnicodeSet lccc; // actual
for(UChar32 c = 0; c <= 0xffff; ++c) {
if(CollationFCD::hasLccc(c)) { lccc.add(c); }
}
UnicodeSet diff(expectedLccc);
diff.removeAll(lccc);
diff.remove(0x10000, 0x10ffff); // hasLccc() only works for the BMP
UnicodeString empty("[]");
UnicodeString diffString;
diff.toPattern(diffString, true);
assertEquals("CollationFCD::hasLccc() expected-actual", empty, diffString);
diff = lccc;
diff.removeAll(expectedLccc);
diff.toPattern(diffString, true);
assertEquals("CollationFCD::hasLccc() actual-expected", empty, diffString, true);
UnicodeSet expectedTccc("[:^tccc=0:]", errorCode);
if (errorCode.isSuccess()) {
addLeadSurrogatesForSupplementary(expectedLccc, expectedTccc);
addLeadSurrogatesForSupplementary(expectedTccc, expectedTccc);
UnicodeSet tccc; // actual
for(UChar32 c = 0; c <= 0xffff; ++c) {
if(CollationFCD::hasTccc(c)) { tccc.add(c); }
}
diff = expectedTccc;
diff.removeAll(tccc);
diff.remove(0x10000, 0x10ffff); // hasTccc() only works for the BMP
assertEquals("CollationFCD::hasTccc() expected-actual", empty, diffString);
diff = tccc;
diff.removeAll(expectedTccc);
diff.toPattern(diffString, true);
assertEquals("CollationFCD::hasTccc() actual-expected", empty, diffString);
}
}
class CodePointIterator {
public:
CodePointIterator(const UChar32 *cp, int32_t length) : cp(cp), length(length), pos(0) {}
void resetToStart() { pos = 0; }
UChar32 next() { return (pos < length) ? cp[pos++] : U_SENTINEL; }
UChar32 previous() { return (pos > 0) ? cp[--pos] : U_SENTINEL; }
int32_t getLength() const { return length; }
int getIndex() const { return (int)pos; }
private:
const UChar32 *cp;
int32_t length;
int32_t pos;
};
void CollationTest::checkFCD(const char *name,
CollationIterator &ci, CodePointIterator &cpi) {
IcuTestErrorCode errorCode(*this, "checkFCD");
// Iterate forward to the limit.
for(;;) {
UChar32 c1 = ci.nextCodePoint(errorCode);
UChar32 c2 = cpi.next();
if(c1 != c2) {
errln("%s.nextCodePoint(to limit, 1st pass) = U+%04lx != U+%04lx at %d",
name, (long)c1, (long)c2, cpi.getIndex());
return;
}
if(c1 < 0) { break; }
}
// Iterate backward most of the way.
for(int32_t n = (cpi.getLength() * 2) / 3; n > 0; --n) {
UChar32 c1 = ci.previousCodePoint(errorCode);
UChar32 c2 = cpi.previous();
if(c1 != c2) {
errln("%s.previousCodePoint() = U+%04lx != U+%04lx at %d",
name, (long)c1, (long)c2, cpi.getIndex());
return;
}
}
// Forward again.
for(;;) {
UChar32 c1 = ci.nextCodePoint(errorCode);
UChar32 c2 = cpi.next();
if(c1 != c2) {
errln("%s.nextCodePoint(to limit again) = U+%04lx != U+%04lx at %d",
name, (long)c1, (long)c2, cpi.getIndex());
return;
}
if(c1 < 0) { break; }
}
// Iterate backward to the start.
for(;;) {
UChar32 c1 = ci.previousCodePoint(errorCode);
UChar32 c2 = cpi.previous();
if(c1 != c2) {
errln("%s.previousCodePoint(to start) = U+%04lx != U+%04lx at %d",
name, (long)c1, (long)c2, cpi.getIndex());
return;
}
if(c1 < 0) { break; }
}
}
void CollationTest::TestFCD() {
IcuTestErrorCode errorCode(*this, "TestFCD");
const CollationData *data = CollationRoot::getData(errorCode);
if(errorCode.errDataIfFailureAndReset("CollationRoot::getData()")) {
return;
}
// Input string, not FCD, NUL-terminated.
static const char16_t s[] = {
0x308, 0xe1, 0x62, 0x301, 0x327, 0x430, 0x62,
U16_LEAD(0x1D15F), U16_TRAIL(0x1D15F), // MUSICAL SYMBOL QUARTER NOTE=1D158 1D165, ccc=0, 216
0x327, 0x308, // ccc=202, 230
U16_LEAD(0x1D16D), U16_TRAIL(0x1D16D), // MUSICAL SYMBOL COMBINING AUGMENTATION DOT, ccc=226
U16_LEAD(0x1D15F), U16_TRAIL(0x1D15F),
U16_LEAD(0x1D16D), U16_TRAIL(0x1D16D),
0xac01,
0xe7, // Character with tccc!=0 decomposed together with mis-ordered sequence.
U16_LEAD(0x1D16D), U16_TRAIL(0x1D16D), U16_LEAD(0x1D165), U16_TRAIL(0x1D165),
0xe1, // Character with tccc!=0 decomposed together with decomposed sequence.
0xf73, 0xf75, // Tibetan composite vowels must be decomposed.
0x4e00, 0xf81,
0
};
// Expected code points.
static const UChar32 cp[] = {
0x308, 0xe1, 0x62, 0x327, 0x301, 0x430, 0x62,
0x1D158, 0x327, 0x1D165, 0x1D16D, 0x308,
0x1D15F, 0x1D16D,
0xac01,
0x63, 0x327, 0x1D165, 0x1D16D,
0x61,
0xf71, 0xf71, 0xf72, 0xf74, 0x301,
0x4e00, 0xf71, 0xf80
};
FCDUTF16CollationIterator u16ci(data, false, s, s, nullptr);
if(errorCode.errIfFailureAndReset("FCDUTF16CollationIterator constructor")) {
return;
}
CodePointIterator cpi(cp, UPRV_LENGTHOF(cp));
checkFCD("FCDUTF16CollationIterator", u16ci, cpi);
cpi.resetToStart();
std::string utf8;
UnicodeString(s).toUTF8String(utf8);
FCDUTF8CollationIterator u8ci(data, false,
reinterpret_cast<const uint8_t *>(utf8.c_str()), 0, -1);
if(errorCode.errIfFailureAndReset("FCDUTF8CollationIterator constructor")) {
return;
}
checkFCD("FCDUTF8CollationIterator", u8ci, cpi);
cpi.resetToStart();
UCharIterator iter;
uiter_setString(&iter, s, UPRV_LENGTHOF(s) - 1); // -1: without the terminating NUL
FCDUIterCollationIterator uici(data, false, iter, 0);
if(errorCode.errIfFailureAndReset("FCDUIterCollationIterator constructor")) {
return;
}
checkFCD("FCDUIterCollationIterator", uici, cpi);
}
void CollationTest::checkAllocWeights(CollationWeights &cw,
uint32_t lowerLimit, uint32_t upperLimit, int32_t n,
int32_t someLength, int32_t minCount) {
if(!cw.allocWeights(lowerLimit, upperLimit, n)) {
errln("CollationWeights::allocWeights(%lx, %lx, %ld) = false",
(long)lowerLimit, (long)upperLimit, (long)n);
return;
}
uint32_t previous = lowerLimit;
int32_t count = 0; // number of weights that have someLength
for(int32_t i = 0; i < n; ++i) {
uint32_t w = cw.nextWeight();
if(w == 0xffffffff) {
errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() "
"returns only %ld weights",
(long)lowerLimit, (long)upperLimit, (long)n, (long)i);
return;
}
if(!(previous < w && w < upperLimit)) {
errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() "
"number %ld -> %lx not between %lx and %lx",
(long)lowerLimit, (long)upperLimit, (long)n,
(long)(i + 1), (long)w, (long)previous, (long)upperLimit);
return;
}
if(CollationWeights::lengthOfWeight(w) == someLength) { ++count; }
}
if(count < minCount) {
errln("CollationWeights::allocWeights(%lx, %lx, %ld).nextWeight() "
"returns only %ld < %ld weights of length %d",
(long)lowerLimit, (long)upperLimit, (long)n,
(long)count, (long)minCount, (int)someLength);
}
}
void CollationTest::TestCollationWeights() {
CollationWeights cw;
// Non-compressible primaries use 254 second bytes 02..FF.
logln("CollationWeights.initForPrimary(non-compressible)");
cw.initForPrimary(false);
// Expect 1 weight 11 and 254 weights 12xx.
checkAllocWeights(cw, 0x10000000, 0x13000000, 255, 1, 1);
checkAllocWeights(cw, 0x10000000, 0x13000000, 255, 2, 254);
// Expect 255 two-byte weights from the ranges 10ff, 11xx, 1202.
checkAllocWeights(cw, 0x10fefe40, 0x12030300, 260, 2, 255);
// Expect 254 two-byte weights from the ranges 10ff and 11xx.
checkAllocWeights(cw, 0x10fefe40, 0x12030300, 600, 2, 254);
// Expect 254^2=64516 three-byte weights.
// During computation, there should be 3 three-byte ranges
// 10ffff, 11xxxx, 120202.
// The middle one should be split 64515:1,
// and the newly-split-off range and the last ranged lengthened.
checkAllocWeights(cw, 0x10fffe00, 0x12020300, 1 + 64516 + 254 + 1, 3, 64516);
// Expect weights 1102 & 1103.
checkAllocWeights(cw, 0x10ff0000, 0x11040000, 2, 2, 2);
// Expect weights 102102 & 102103.
checkAllocWeights(cw, 0x1020ff00, 0x10210400, 2, 3, 2);
// Compressible primaries use 251 second bytes 04..FE.
logln("CollationWeights.initForPrimary(compressible)");
cw.initForPrimary(true);
// Expect 1 weight 11 and 251 weights 12xx.
checkAllocWeights(cw, 0x10000000, 0x13000000, 252, 1, 1);
checkAllocWeights(cw, 0x10000000, 0x13000000, 252, 2, 251);
// Expect 252 two-byte weights from the ranges 10fe, 11xx, 1204.
checkAllocWeights(cw, 0x10fdfe40, 0x12050300, 260, 2, 252);
// Expect weights 1104 & 1105.
checkAllocWeights(cw, 0x10fe0000, 0x11060000, 2, 2, 2);
// Expect weights 102102 & 102103.
checkAllocWeights(cw, 0x1020ff00, 0x10210400, 2, 3, 2);
// Secondary and tertiary weights use only bytes 3 & 4.
logln("CollationWeights.initForSecondary()");
cw.initForSecondary();
// Expect weights fbxx and all four fc..ff.
checkAllocWeights(cw, 0xfb20, 0x10000, 20, 3, 4);
logln("CollationWeights.initForTertiary()");
cw.initForTertiary();
// Expect weights 3dxx and both 3e & 3f.
checkAllocWeights(cw, 0x3d02, 0x4000, 10, 3, 2);
}
namespace {
UBool isValidCE(const CollationRootElements &re, const CollationData &data,
uint32_t p, uint32_t s, uint32_t ctq) {
uint32_t p1 = p >> 24;
uint32_t p2 = (p >> 16) & 0xff;
uint32_t p3 = (p >> 8) & 0xff;
uint32_t p4 = p & 0xff;
uint32_t s1 = s >> 8;
uint32_t s2 = s & 0xff;
// ctq = Case, Tertiary, Quaternary
uint32_t c = (ctq & Collation::CASE_MASK) >> 14;
uint32_t t = ctq & Collation::ONLY_TERTIARY_MASK;
uint32_t t1 = t >> 8;
uint32_t t2 = t & 0xff;
uint32_t q = ctq & Collation::QUATERNARY_MASK;
// No leading zero bytes.
if((p != 0 && p1 == 0) || (s != 0 && s1 == 0) || (t != 0 && t1 == 0)) {
return false;
}
// No intermediate zero bytes.
if(p1 != 0 && p2 == 0 && (p & 0xffff) != 0) {
return false;
}
if(p2 != 0 && p3 == 0 && p4 != 0) {
return false;
}
// Minimum & maximum lead bytes.
if((p1 != 0 && p1 <= Collation::MERGE_SEPARATOR_BYTE) ||
s1 == Collation::LEVEL_SEPARATOR_BYTE ||
t1 == Collation::LEVEL_SEPARATOR_BYTE || t1 > 0x3f) {
return false;
}
if(c > 2) {
return false;
}
// The valid byte range for the second primary byte depends on compressibility.
if(p2 != 0) {
if(data.isCompressibleLeadByte(p1)) {
if(p2 <= Collation::PRIMARY_COMPRESSION_LOW_BYTE ||
Collation::PRIMARY_COMPRESSION_HIGH_BYTE <= p2) {
return false;
}
} else {
if(p2 <= Collation::LEVEL_SEPARATOR_BYTE) {
return false;
}
}
}
// Other bytes just need to avoid the level separator.
// Trailing zeros are ok.
U_ASSERT(Collation::LEVEL_SEPARATOR_BYTE == 1);
if(p3 == Collation::LEVEL_SEPARATOR_BYTE || p4 == Collation::LEVEL_SEPARATOR_BYTE ||
s2 == Collation::LEVEL_SEPARATOR_BYTE || t2 == Collation::LEVEL_SEPARATOR_BYTE) {
return false;
}
// Well-formed CEs.
if(p == 0) {
if(s == 0) {
if(t == 0) {
// Completely ignorable CE.
// Quaternary CEs are not supported.
if(c != 0 || q != 0) {
return false;
}
} else {
// Tertiary CE.
if(t < re.getTertiaryBoundary() || c != 2) {
return false;
}
}
} else {
// Secondary CE.
if(s < re.getSecondaryBoundary() || t == 0 || t >= re.getTertiaryBoundary()) {
return false;
}
}
} else {
// Primary CE.
if(s == 0 || (Collation::COMMON_WEIGHT16 < s && s <= re.getLastCommonSecondary()) ||
s >= re.getSecondaryBoundary()) {
return false;
}
if(t == 0 || t >= re.getTertiaryBoundary()) {
return false;
}
}
return true;
}
UBool isValidCE(const CollationRootElements &re, const CollationData &data, int64_t ce) {
uint32_t p = (uint32_t)(ce >> 32);
uint32_t secTer = (uint32_t)ce;
return isValidCE(re, data, p, secTer >> 16, secTer & 0xffff);
}
class RootElementsIterator {
public:
RootElementsIterator(const CollationData &root)
: data(root),
elements(root.rootElements), length(root.rootElementsLength),
pri(0), secTer(0),
index((int32_t)elements[CollationRootElements::IX_FIRST_TERTIARY_INDEX]) {}
UBool next() {
if(index >= length) { return false; }
uint32_t p = elements[index];
if(p == CollationRootElements::PRIMARY_SENTINEL) { return false; }
if((p & CollationRootElements::SEC_TER_DELTA_FLAG) != 0) {
++index;
secTer = p & ~CollationRootElements::SEC_TER_DELTA_FLAG;
return true;
}
if((p & CollationRootElements::PRIMARY_STEP_MASK) != 0) {
// End of a range, enumerate the primaries in the range.
int32_t step = (int32_t)p & CollationRootElements::PRIMARY_STEP_MASK;
p &= 0xffffff00;
if(pri == p) {
// Finished the range, return the next CE after it.
++index;
return next();
}
U_ASSERT(pri < p);
// Return the next primary in this range.
UBool isCompressible = data.isCompressiblePrimary(pri);
if((pri & 0xffff) == 0) {
pri = Collation::incTwoBytePrimaryByOffset(pri, isCompressible, step);
} else {
pri = Collation::incThreeBytePrimaryByOffset(pri, isCompressible, step);
}
return true;
}
// Simple primary CE.
++index;
pri = p;
// Does this have an explicit below-common sec/ter unit,
// or does it imply a common one?
if(index == length) {
secTer = Collation::COMMON_SEC_AND_TER_CE;
} else {
secTer = elements[index];
if((secTer & CollationRootElements::SEC_TER_DELTA_FLAG) == 0) {
// No sec/ter delta.
secTer = Collation::COMMON_SEC_AND_TER_CE;
} else {
secTer &= ~CollationRootElements::SEC_TER_DELTA_FLAG;
if(secTer > Collation::COMMON_SEC_AND_TER_CE) {
// Implied sec/ter.
secTer = Collation::COMMON_SEC_AND_TER_CE;
} else {
// Explicit sec/ter below common/common.
++index;
}
}
}
return true;
}
uint32_t getPrimary() const { return pri; }
uint32_t getSecTer() const { return secTer; }
private:
const CollationData &data;
const uint32_t *elements;
int32_t length;
uint32_t pri;
uint32_t secTer;
int32_t index;
};
} // namespace
void CollationTest::TestRootElements() {
IcuTestErrorCode errorCode(*this, "TestRootElements");
const CollationData *root = CollationRoot::getData(errorCode);
if(errorCode.errDataIfFailureAndReset("CollationRoot::getData()")) {
return;
}
CollationRootElements rootElements(root->rootElements, root->rootElementsLength);
RootElementsIterator iter(*root);
// We check each root CE for validity,
// and we also verify that there is a tailoring gap between each two CEs.
CollationWeights cw1c; // compressible primary weights
CollationWeights cw1u; // uncompressible primary weights
CollationWeights cw2;
CollationWeights cw3;
cw1c.initForPrimary(true);
cw1u.initForPrimary(false);
cw2.initForSecondary();
cw3.initForTertiary();
// Note: The root elements do not include Han-implicit or unassigned-implicit CEs,
// nor the special merge-separator CE for U+FFFE.
uint32_t prevPri = 0;
uint32_t prevSec = 0;
uint32_t prevTer = 0;
while(iter.next()) {
uint32_t pri = iter.getPrimary();
uint32_t secTer = iter.getSecTer();
// CollationRootElements CEs must have 0 case and quaternary bits.
if((secTer & Collation::CASE_AND_QUATERNARY_MASK) != 0) {
errln("CollationRootElements CE has non-zero case and/or quaternary bits: %08lx %08lx",
(long)pri, (long)secTer);
}
uint32_t sec = secTer >> 16;
uint32_t ter = secTer & Collation::ONLY_TERTIARY_MASK;
uint32_t ctq = ter;
if(pri == 0 && sec == 0 && ter != 0) {
// Tertiary CEs must have uppercase bits,
// but they are not stored in the CollationRootElements.
ctq |= 0x8000;
}
if(!isValidCE(rootElements, *root, pri, sec, ctq)) {
errln("invalid root CE %08lx %08lx", (long)pri, (long)secTer);
} else {
if(pri != prevPri) {
uint32_t newWeight = 0;
if(prevPri == 0 || prevPri >= Collation::FFFD_PRIMARY) {
// There is currently no tailoring gap after primary ignorables,
// and we forbid tailoring after U+FFFD and U+FFFF.
} else if(root->isCompressiblePrimary(prevPri)) {
if(!cw1c.allocWeights(prevPri, pri, 1)) {
errln("no primary/compressible tailoring gap between %08lx and %08lx",
(long)prevPri, (long)pri);
} else {
newWeight = cw1c.nextWeight();
}
} else {
if(!cw1u.allocWeights(prevPri, pri, 1)) {
errln("no primary/uncompressible tailoring gap between %08lx and %08lx",
(long)prevPri, (long)pri);
} else {
newWeight = cw1u.nextWeight();
}
}
if(newWeight != 0 && !(prevPri < newWeight && newWeight < pri)) {
errln("mis-allocated primary weight, should get %08lx < %08lx < %08lx",
(long)prevPri, (long)newWeight, (long)pri);
}
} else if(sec != prevSec) {
uint32_t lowerLimit =
prevSec == 0 ? rootElements.getSecondaryBoundary() - 0x100 : prevSec;
if(!cw2.allocWeights(lowerLimit, sec, 1)) {
errln("no secondary tailoring gap between %04x and %04x", lowerLimit, sec);
} else {
uint32_t newWeight = cw2.nextWeight();
if(!(prevSec < newWeight && newWeight < sec)) {
errln("mis-allocated secondary weight, should get %04x < %04x < %04x",
(long)lowerLimit, (long)newWeight, (long)sec);
}
}
} else if(ter != prevTer) {
uint32_t lowerLimit =
prevTer == 0 ? rootElements.getTertiaryBoundary() - 0x100 : prevTer;
if(!cw3.allocWeights(lowerLimit, ter, 1)) {
errln("no teriary tailoring gap between %04x and %04x", lowerLimit, ter);
} else {
uint32_t newWeight = cw3.nextWeight();
if(!(prevTer < newWeight && newWeight < ter)) {
errln("mis-allocated secondary weight, should get %04x < %04x < %04x",
(long)lowerLimit, (long)newWeight, (long)ter);
}
}
} else {
errln("duplicate root CE %08lx %08lx", (long)pri, (long)secTer);
}
}
prevPri = pri;
prevSec = sec;
prevTer = ter;
}
}
void CollationTest::TestTailoredElements() {
IcuTestErrorCode errorCode(*this, "TestTailoredElements");
const CollationData *root = CollationRoot::getData(errorCode);
if(errorCode.errDataIfFailureAndReset("CollationRoot::getData()")) {
return;
}
CollationRootElements rootElements(root->rootElements, root->rootElementsLength);
UHashtable *prevLocales = uhash_open(uhash_hashChars, uhash_compareChars, nullptr, errorCode);
if(errorCode.errIfFailureAndReset("failed to create a hash table")) {
return;
}
uhash_setKeyDeleter(prevLocales, uprv_free);
// TestRootElements() tests the root collator which does not have tailorings.
uhash_puti(prevLocales, uprv_strdup(""), 1, errorCode);
uhash_puti(prevLocales, uprv_strdup("root"), 1, errorCode);
uhash_puti(prevLocales, uprv_strdup("root@collation=standard"), 1, errorCode);
UVector64 ces(errorCode);
LocalPointer<StringEnumeration> locales(Collator::getAvailableLocales());
U_ASSERT(locales.isValid());
const char *localeID = "root";
do {
Locale locale(localeID);
LocalPointer<StringEnumeration> types(
Collator::getKeywordValuesForLocale("collation", locale, false, errorCode));
errorCode.assertSuccess();
const char *type; // first: default type
while((type = types->next(nullptr, errorCode)) != nullptr) {
if(strncmp(type, "private-", 8) == 0) {
errln("Collator::getKeywordValuesForLocale(%s) returns private collation keyword: %s",
localeID, type);
}
Locale localeWithType(locale);
localeWithType.setKeywordValue("collation", type, errorCode);
errorCode.assertSuccess();
LocalPointer<Collator> coll(Collator::createInstance(localeWithType, errorCode));
if(errorCode.errIfFailureAndReset("Collator::createInstance(%s)",
localeWithType.getName())) {
continue;
}
Locale actual = coll->getLocale(ULOC_ACTUAL_LOCALE, errorCode);
if(uhash_geti(prevLocales, actual.getName()) != 0) {
continue;
}
uhash_puti(prevLocales, uprv_strdup(actual.getName()), 1, errorCode);
errorCode.assertSuccess();
logln("TestTailoredElements(): requested %s -> actual %s",
localeWithType.getName(), actual.getName());
RuleBasedCollator *rbc = dynamic_cast<RuleBasedCollator *>(coll.getAlias());
if(rbc == nullptr) {
continue;
}
// Note: It would be better to get tailored strings such that we can
// identify the prefix, and only get the CEs for the prefix+string,
// not also for the prefix.
// There is currently no API for that.
// It would help in an unusual case where a contraction starting in the prefix
// extends past its end, and we do not see the intended mapping.
// For example, for a mapping p|st, if there is also a contraction ps,
// then we get CEs(ps)+CEs(t), rather than CEs(p|st).
LocalPointer<UnicodeSet> tailored(coll->getTailoredSet(errorCode));
errorCode.assertSuccess();
UnicodeSetIterator iter(*tailored);
while(iter.next()) {
const UnicodeString &s = iter.getString();
ces.removeAllElements();
rbc->internalGetCEs(s, ces, errorCode);
errorCode.assertSuccess();
for(int32_t i = 0; i < ces.size(); ++i) {
int64_t ce = ces.elementAti(i);
if(!isValidCE(rootElements, *root, ce)) {
errln("invalid tailored CE %016llx at CE index %d from string:",
(long long)ce, (int)i);
infoln(prettify(s));
}
}
}
}
} while((localeID = locales->next(nullptr, errorCode)) != nullptr);
uhash_close(prevLocales);
}
UnicodeString CollationTest::printSortKey(const uint8_t *p, int32_t length) {
UnicodeString s;
for(int32_t i = 0; i < length; ++i) {
if(i > 0) { s.append((char16_t)0x20); }
uint8_t b = p[i];
if(b == 0) {
s.append((char16_t)0x2e); // period
} else if(b == 1) {
s.append((char16_t)0x7c); // vertical bar
} else {
appendHex(b, 2, s);
}
}
return s;
}
UnicodeString CollationTest::printCollationKey(const CollationKey &key) {
int32_t length;
const uint8_t *p = key.getByteArray(length);
return printSortKey(p, length);
}
UBool CollationTest::readNonEmptyLine(UCHARBUF *f, IcuTestErrorCode &errorCode) {
for(;;) {
int32_t lineLength;
const char16_t *line = ucbuf_readline(f, &lineLength, errorCode);
if(line == nullptr || errorCode.isFailure()) {
fileLine.remove();
return false;
}
++fileLineNumber;
// Strip trailing CR/LF, comments, and spaces.
const char16_t *comment = u_memchr(line, 0x23, lineLength); // '#'
if(comment != nullptr) {