• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /********************************************************************
4  * COPYRIGHT:
5  * Copyright (c) 1997-2016, International Business Machines Corporation and
6  * others. All Rights Reserved.
7  ********************************************************************/
8 
9 #include "unicode/utypes.h"
10 
11 #if !UCONFIG_NO_NORMALIZATION
12 
13 #include "unicode/uchar.h"
14 #include "unicode/errorcode.h"
15 #include "unicode/normlzr.h"
16 #include "unicode/stringoptions.h"
17 #include "unicode/stringpiece.h"
18 #include "unicode/uniset.h"
19 #include "unicode/usetiter.h"
20 #include "unicode/schriter.h"
21 #include "unicode/utf16.h"
22 #include "cmemory.h"
23 #include "cstring.h"
24 #include "normalizer2impl.h"
25 #include "testutil.h"
26 #include "tstnorm.h"
27 
28 #define ARRAY_LENGTH(array) UPRV_LENGTHOF(array)
29 
runIndexedTest(int32_t index,UBool exec,const char * & name,char *)30 void BasicNormalizerTest::runIndexedTest(int32_t index, UBool exec,
31                                          const char* &name, char* /*par*/) {
32     if(exec) {
33         logln("TestSuite BasicNormalizerTest: ");
34     }
35     TESTCASE_AUTO_BEGIN;
36     TESTCASE_AUTO(TestDecomp);
37     TESTCASE_AUTO(TestCompatDecomp);
38     TESTCASE_AUTO(TestCanonCompose);
39     TESTCASE_AUTO(TestCompatCompose);
40     TESTCASE_AUTO(TestPrevious);
41     TESTCASE_AUTO(TestHangulDecomp);
42     TESTCASE_AUTO(TestHangulCompose);
43     TESTCASE_AUTO(TestTibetan);
44     TESTCASE_AUTO(TestCompositionExclusion);
45     TESTCASE_AUTO(TestZeroIndex);
46     TESTCASE_AUTO(TestVerisign);
47     TESTCASE_AUTO(TestPreviousNext);
48     TESTCASE_AUTO(TestNormalizerAPI);
49     TESTCASE_AUTO(TestConcatenate);
50     TESTCASE_AUTO(FindFoldFCDExceptions);
51     TESTCASE_AUTO(TestCompare);
52     TESTCASE_AUTO(TestSkippable);
53 #if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION
54     TESTCASE_AUTO(TestCustomComp);
55     TESTCASE_AUTO(TestCustomFCC);
56 #endif
57     TESTCASE_AUTO(TestFilteredNormalizer2Coverage);
58     TESTCASE_AUTO(TestNormalizeUTF8WithEdits);
59     TESTCASE_AUTO(TestLowMappingToEmpty_D);
60     TESTCASE_AUTO(TestLowMappingToEmpty_FCD);
61     TESTCASE_AUTO(TestNormalizeIllFormedText);
62     TESTCASE_AUTO(TestComposeJamoTBase);
63     TESTCASE_AUTO(TestComposeBoundaryAfter);
64     TESTCASE_AUTO_END;
65 }
66 
67 /**
68  * Convert Java-style strings with \u Unicode escapes into UnicodeString objects
69  */
str(const char * input)70 static UnicodeString str(const char *input)
71 {
72     UnicodeString str(input, ""); // Invariant conversion
73     return str.unescape();
74 }
75 
76 
BasicNormalizerTest()77 BasicNormalizerTest::BasicNormalizerTest()
78 {
79   // canonTest
80   // Input                    Decomposed                    Composed
81 
82     canonTests[0][0] = str("cat");  canonTests[0][1] = str("cat"); canonTests[0][2] =  str("cat");
83 
84     canonTests[1][0] = str("\\u00e0ardvark");    canonTests[1][1] = str("a\\u0300ardvark");  canonTests[1][2] = str("\\u00e0ardvark");
85 
86     canonTests[2][0] = str("\\u1e0a"); canonTests[2][1] = str("D\\u0307"); canonTests[2][2] = str("\\u1e0a");                 // D-dot_above
87 
88     canonTests[3][0] = str("D\\u0307");  canonTests[3][1] = str("D\\u0307"); canonTests[3][2] = str("\\u1e0a");            // D dot_above
89 
90     canonTests[4][0] = str("\\u1e0c\\u0307"); canonTests[4][1] = str("D\\u0323\\u0307");  canonTests[4][2] = str("\\u1e0c\\u0307");         // D-dot_below dot_above
91 
92     canonTests[5][0] = str("\\u1e0a\\u0323"); canonTests[5][1] = str("D\\u0323\\u0307");  canonTests[5][2] = str("\\u1e0c\\u0307");        // D-dot_above dot_below
93 
94     canonTests[6][0] = str("D\\u0307\\u0323"); canonTests[6][1] = str("D\\u0323\\u0307");  canonTests[6][2] = str("\\u1e0c\\u0307");         // D dot_below dot_above
95 
96     canonTests[7][0] = str("\\u1e10\\u0307\\u0323");  canonTests[7][1] = str("D\\u0327\\u0323\\u0307"); canonTests[7][2] = str("\\u1e10\\u0323\\u0307");     // D dot_below cedilla dot_above
97 
98     canonTests[8][0] = str("D\\u0307\\u0328\\u0323"); canonTests[8][1] = str("D\\u0328\\u0323\\u0307"); canonTests[8][2] = str("\\u1e0c\\u0328\\u0307");     // D dot_above ogonek dot_below
99 
100     canonTests[9][0] = str("\\u1E14"); canonTests[9][1] = str("E\\u0304\\u0300"); canonTests[9][2] = str("\\u1E14");         // E-macron-grave
101 
102     canonTests[10][0] = str("\\u0112\\u0300"); canonTests[10][1] = str("E\\u0304\\u0300");  canonTests[10][2] = str("\\u1E14");            // E-macron + grave
103 
104     canonTests[11][0] = str("\\u00c8\\u0304"); canonTests[11][1] = str("E\\u0300\\u0304");  canonTests[11][2] = str("\\u00c8\\u0304");         // E-grave + macron
105 
106     canonTests[12][0] = str("\\u212b"); canonTests[12][1] = str("A\\u030a"); canonTests[12][2] = str("\\u00c5");             // angstrom_sign
107 
108     canonTests[13][0] = str("\\u00c5");      canonTests[13][1] = str("A\\u030a");  canonTests[13][2] = str("\\u00c5");            // A-ring
109 
110     canonTests[14][0] = str("\\u00C4ffin");  canonTests[14][1] = str("A\\u0308ffin");  canonTests[14][2] = str("\\u00C4ffin");
111 
112     canonTests[15][0] = str("\\u00C4\\uFB03n"); canonTests[15][1] = str("A\\u0308\\uFB03n"); canonTests[15][2] = str("\\u00C4\\uFB03n");
113 
114     canonTests[16][0] = str("Henry IV"); canonTests[16][1] = str("Henry IV"); canonTests[16][2] = str("Henry IV");
115 
116     canonTests[17][0] = str("Henry \\u2163");  canonTests[17][1] = str("Henry \\u2163");  canonTests[17][2] = str("Henry \\u2163");
117 
118     canonTests[18][0] = str("\\u30AC");  canonTests[18][1] = str("\\u30AB\\u3099");  canonTests[18][2] = str("\\u30AC");              // ga (Katakana)
119 
120     canonTests[19][0] = str("\\u30AB\\u3099"); canonTests[19][1] = str("\\u30AB\\u3099");  canonTests[19][2] = str("\\u30AC");            // ka + ten
121 
122     canonTests[20][0] = str("\\uFF76\\uFF9E"); canonTests[20][1] = str("\\uFF76\\uFF9E");  canonTests[20][2] = str("\\uFF76\\uFF9E");       // hw_ka + hw_ten
123 
124     canonTests[21][0] = str("\\u30AB\\uFF9E"); canonTests[21][1] = str("\\u30AB\\uFF9E");  canonTests[21][2] = str("\\u30AB\\uFF9E");         // ka + hw_ten
125 
126     canonTests[22][0] = str("\\uFF76\\u3099"); canonTests[22][1] = str("\\uFF76\\u3099");  canonTests[22][2] = str("\\uFF76\\u3099");         // hw_ka + ten
127 
128     canonTests[23][0] = str("A\\u0300\\u0316"); canonTests[23][1] = str("A\\u0316\\u0300");  canonTests[23][2] = str("\\u00C0\\u0316");
129 
130     /* compatTest */
131   // Input                        Decomposed                        Composed
132   compatTests[0][0] = str("cat"); compatTests[0][1] = str("cat"); compatTests[0][2] = str("cat") ;
133 
134   compatTests[1][0] = str("\\uFB4f");  compatTests[1][1] = str("\\u05D0\\u05DC"); compatTests[1][2] = str("\\u05D0\\u05DC");  // Alef-Lamed vs. Alef, Lamed
135 
136   compatTests[2][0] = str("\\u00C4ffin"); compatTests[2][1] = str("A\\u0308ffin"); compatTests[2][2] = str("\\u00C4ffin") ;
137 
138   compatTests[3][0] = str("\\u00C4\\uFB03n"); compatTests[3][1] = str("A\\u0308ffin"); compatTests[3][2] = str("\\u00C4ffin") ; // ffi ligature -> f + f + i
139 
140   compatTests[4][0] = str("Henry IV"); compatTests[4][1] = str("Henry IV"); compatTests[4][2] = str("Henry IV") ;
141 
142   compatTests[5][0] = str("Henry \\u2163"); compatTests[5][1] = str("Henry IV");  compatTests[5][2] = str("Henry IV") ;
143 
144   compatTests[6][0] = str("\\u30AC"); compatTests[6][1] = str("\\u30AB\\u3099"); compatTests[6][2] = str("\\u30AC") ; // ga (Katakana)
145 
146   compatTests[7][0] = str("\\u30AB\\u3099"); compatTests[7][1] = str("\\u30AB\\u3099"); compatTests[7][2] = str("\\u30AC") ; // ka + ten
147 
148   compatTests[8][0] = str("\\uFF76\\u3099"); compatTests[8][1] = str("\\u30AB\\u3099"); compatTests[8][2] = str("\\u30AC") ; // hw_ka + ten
149 
150   /* These two are broken in Unicode 2.1.2 but fixed in 2.1.5 and later */
151   compatTests[9][0] = str("\\uFF76\\uFF9E"); compatTests[9][1] = str("\\u30AB\\u3099"); compatTests[9][2] = str("\\u30AC") ; // hw_ka + hw_ten
152 
153   compatTests[10][0] = str("\\u30AB\\uFF9E"); compatTests[10][1] = str("\\u30AB\\u3099"); compatTests[10][2] = str("\\u30AC") ; // ka + hw_ten
154 
155   /* Hangul Canonical */
156   // Input                        Decomposed                        Composed
157   hangulCanon[0][0] = str("\\ud4db"); hangulCanon[0][1] = str("\\u1111\\u1171\\u11b6"); hangulCanon[0][2] = str("\\ud4db") ;
158 
159   hangulCanon[1][0] = str("\\u1111\\u1171\\u11b6"), hangulCanon[1][1] = str("\\u1111\\u1171\\u11b6"),   hangulCanon[1][2] = str("\\ud4db");
160 }
161 
~BasicNormalizerTest()162 BasicNormalizerTest::~BasicNormalizerTest()
163 {
164 }
165 
TestPrevious()166 void BasicNormalizerTest::TestPrevious()
167 {
168   Normalizer* norm = new Normalizer("", UNORM_NFD);
169 
170   logln("testing decomp...");
171   uint32_t i;
172   for (i = 0; i < ARRAY_LENGTH(canonTests); i++) {
173     backAndForth(norm, canonTests[i][0]);
174   }
175 
176   logln("testing compose...");
177   norm->setMode(UNORM_NFC);
178   for (i = 0; i < ARRAY_LENGTH(canonTests); i++) {
179     backAndForth(norm, canonTests[i][0]);
180   }
181 
182   delete norm;
183 }
184 
TestDecomp()185 void BasicNormalizerTest::TestDecomp()
186 {
187   Normalizer* norm = new Normalizer("", UNORM_NFD);
188   iterateTest(norm, canonTests, ARRAY_LENGTH(canonTests), 1);
189   staticTest(UNORM_NFD, 0, canonTests, ARRAY_LENGTH(canonTests), 1);
190   delete norm;
191 }
192 
TestCompatDecomp()193 void BasicNormalizerTest::TestCompatDecomp()
194 {
195   Normalizer* norm = new Normalizer("", UNORM_NFKD);
196   iterateTest(norm, compatTests, ARRAY_LENGTH(compatTests), 1);
197 
198   staticTest(UNORM_NFKD, 0,
199          compatTests, ARRAY_LENGTH(compatTests), 1);
200   delete norm;
201 }
202 
TestCanonCompose()203 void BasicNormalizerTest::TestCanonCompose()
204 {
205   Normalizer* norm = new Normalizer("", UNORM_NFC);
206   iterateTest(norm, canonTests, ARRAY_LENGTH(canonTests), 2);
207 
208   staticTest(UNORM_NFC, 0, canonTests,
209          ARRAY_LENGTH(canonTests), 2);
210   delete norm;
211 }
212 
TestCompatCompose()213 void BasicNormalizerTest::TestCompatCompose()
214 {
215   Normalizer* norm = new Normalizer("", UNORM_NFKC);
216   iterateTest(norm, compatTests, ARRAY_LENGTH(compatTests), 2);
217 
218   staticTest(UNORM_NFKC, 0,
219          compatTests, ARRAY_LENGTH(compatTests), 2);
220   delete norm;
221 }
222 
223 
224 //-------------------------------------------------------------------------------
225 
TestHangulCompose()226 void BasicNormalizerTest::TestHangulCompose()
227 {
228   // Make sure that the static composition methods work
229   logln("Canonical composition...");
230   staticTest(UNORM_NFC, 0,                    hangulCanon,  ARRAY_LENGTH(hangulCanon),  2);
231   logln("Compatibility composition...");
232 
233   // Now try iterative composition....
234   logln("Static composition...");
235   Normalizer* norm = new Normalizer("", UNORM_NFC);
236   iterateTest(norm, hangulCanon, ARRAY_LENGTH(hangulCanon), 2);
237   norm->setMode(UNORM_NFKC);
238 
239   // And finally, make sure you can do it in reverse too
240   logln("Reverse iteration...");
241   norm->setMode(UNORM_NFC);
242   for (uint32_t i = 0; i < ARRAY_LENGTH(hangulCanon); i++) {
243     backAndForth(norm, hangulCanon[i][0]);
244   }
245   delete norm;
246 }
247 
TestHangulDecomp()248 void BasicNormalizerTest::TestHangulDecomp()
249 {
250   // Make sure that the static decomposition methods work
251   logln("Canonical decomposition...");
252   staticTest(UNORM_NFD, 0,                     hangulCanon,  ARRAY_LENGTH(hangulCanon),  1);
253   logln("Compatibility decomposition...");
254 
255   // Now the iterative decomposition methods...
256   logln("Iterative decomposition...");
257   Normalizer* norm = new Normalizer("", UNORM_NFD);
258   iterateTest(norm, hangulCanon, ARRAY_LENGTH(hangulCanon), 1);
259   norm->setMode(UNORM_NFKD);
260 
261   // And finally, make sure you can do it in reverse too
262   logln("Reverse iteration...");
263   norm->setMode(UNORM_NFD);
264   for (uint32_t i = 0; i < ARRAY_LENGTH(hangulCanon); i++) {
265     backAndForth(norm, hangulCanon[i][0]);
266   }
267   delete norm;
268 }
269 
270 /**
271  * The Tibetan vowel sign AA, 0f71, was messed up prior to Unicode version 2.1.9.
272  */
TestTibetan(void)273 void BasicNormalizerTest::TestTibetan(void) {
274     UnicodeString decomp[1][3];
275     decomp[0][0] = str("\\u0f77");
276     decomp[0][1] = str("\\u0f77");
277     decomp[0][2] = str("\\u0fb2\\u0f71\\u0f80");
278 
279     UnicodeString compose[1][3];
280     compose[0][0] = str("\\u0fb2\\u0f71\\u0f80");
281     compose[0][1] = str("\\u0fb2\\u0f71\\u0f80");
282     compose[0][2] = str("\\u0fb2\\u0f71\\u0f80");
283 
284     staticTest(UNORM_NFD,         0, decomp, ARRAY_LENGTH(decomp), 1);
285     staticTest(UNORM_NFKD,  0, decomp, ARRAY_LENGTH(decomp), 2);
286     staticTest(UNORM_NFC,        0, compose, ARRAY_LENGTH(compose), 1);
287     staticTest(UNORM_NFKC, 0, compose, ARRAY_LENGTH(compose), 2);
288 }
289 
290 /**
291  * Make sure characters in the CompositionExclusion.txt list do not get
292  * composed to.
293  */
TestCompositionExclusion(void)294 void BasicNormalizerTest::TestCompositionExclusion(void) {
295     // This list is generated from CompositionExclusion.txt.
296     // Update whenever the normalizer tables are updated.  Note
297     // that we test all characters listed, even those that can be
298     // derived from the Unicode DB and are therefore commented
299     // out.
300     // ### TODO read composition exclusion from source/data/unidata file
301     // and test against that
302     UnicodeString EXCLUDED = str(
303         "\\u0340\\u0341\\u0343\\u0344\\u0374\\u037E\\u0387\\u0958"
304         "\\u0959\\u095A\\u095B\\u095C\\u095D\\u095E\\u095F\\u09DC"
305         "\\u09DD\\u09DF\\u0A33\\u0A36\\u0A59\\u0A5A\\u0A5B\\u0A5E"
306         "\\u0B5C\\u0B5D\\u0F43\\u0F4D\\u0F52\\u0F57\\u0F5C\\u0F69"
307         "\\u0F73\\u0F75\\u0F76\\u0F78\\u0F81\\u0F93\\u0F9D\\u0FA2"
308         "\\u0FA7\\u0FAC\\u0FB9\\u1F71\\u1F73\\u1F75\\u1F77\\u1F79"
309         "\\u1F7B\\u1F7D\\u1FBB\\u1FBE\\u1FC9\\u1FCB\\u1FD3\\u1FDB"
310         "\\u1FE3\\u1FEB\\u1FEE\\u1FEF\\u1FF9\\u1FFB\\u1FFD\\u2000"
311         "\\u2001\\u2126\\u212A\\u212B\\u2329\\u232A\\uF900\\uFA10"
312         "\\uFA12\\uFA15\\uFA20\\uFA22\\uFA25\\uFA26\\uFA2A\\uFB1F"
313         "\\uFB2A\\uFB2B\\uFB2C\\uFB2D\\uFB2E\\uFB2F\\uFB30\\uFB31"
314         "\\uFB32\\uFB33\\uFB34\\uFB35\\uFB36\\uFB38\\uFB39\\uFB3A"
315         "\\uFB3B\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46"
316         "\\uFB47\\uFB48\\uFB49\\uFB4A\\uFB4B\\uFB4C\\uFB4D\\uFB4E"
317         );
318     UErrorCode status = U_ZERO_ERROR;
319     for (int32_t i=0; i<EXCLUDED.length(); ++i) {
320         UnicodeString a(EXCLUDED.charAt(i));
321         UnicodeString b;
322         UnicodeString c;
323         Normalizer::normalize(a, UNORM_NFKD, 0, b, status);
324         Normalizer::normalize(b, UNORM_NFC, 0, c, status);
325         if (c == a) {
326             errln("FAIL: " + hex(a) + " x DECOMP_COMPAT => " +
327                   hex(b) + " x COMPOSE => " +
328                   hex(c));
329         } else if (verbose) {
330             logln("Ok: " + hex(a) + " x DECOMP_COMPAT => " +
331                   hex(b) + " x COMPOSE => " +
332                   hex(c));
333         }
334     }
335 }
336 
337 /**
338  * Test for a problem that showed up just before ICU 1.6 release
339  * having to do with combining characters with an index of zero.
340  * Such characters do not participate in any canonical
341  * decompositions.  However, having an index of zero means that
342  * they all share one typeMask[] entry, that is, they all have to
343  * map to the same canonical class, which is not the case, in
344  * reality.
345  */
TestZeroIndex(void)346 void BasicNormalizerTest::TestZeroIndex(void) {
347     const char* DATA[] = {
348         // Expect col1 x COMPOSE_COMPAT => col2
349         // Expect col2 x DECOMP => col3
350         "A\\u0316\\u0300", "\\u00C0\\u0316", "A\\u0316\\u0300",
351         "A\\u0300\\u0316", "\\u00C0\\u0316", "A\\u0316\\u0300",
352         "A\\u0327\\u0300", "\\u00C0\\u0327", "A\\u0327\\u0300",
353         "c\\u0321\\u0327", "c\\u0321\\u0327", "c\\u0321\\u0327",
354         "c\\u0327\\u0321", "\\u00E7\\u0321", "c\\u0327\\u0321",
355     };
356     int32_t DATA_length = UPRV_LENGTHOF(DATA);
357 
358     for (int32_t i=0; i<DATA_length; i+=3) {
359         UErrorCode status = U_ZERO_ERROR;
360         UnicodeString a(DATA[i], "");
361         a = a.unescape();
362         UnicodeString b;
363         Normalizer::normalize(a, UNORM_NFKC, 0, b, status);
364         if (U_FAILURE(status)) {
365             dataerrln("Error calling normalize UNORM_NFKC: %s", u_errorName(status));
366         } else {
367             UnicodeString exp(DATA[i+1], "");
368             exp = exp.unescape();
369             if (b == exp) {
370                 logln((UnicodeString)"Ok: " + hex(a) + " x COMPOSE_COMPAT => " + hex(b));
371             } else {
372                 errln((UnicodeString)"FAIL: " + hex(a) + " x COMPOSE_COMPAT => " + hex(b) +
373                       ", expect " + hex(exp));
374             }
375         }
376         Normalizer::normalize(b, UNORM_NFD, 0, a, status);
377         if (U_FAILURE(status)) {
378             dataerrln("Error calling normalize UNORM_NFD: %s", u_errorName(status));
379         } else {
380             UnicodeString exp = UnicodeString(DATA[i+2], "").unescape();
381             if (a == exp) {
382                 logln((UnicodeString)"Ok: " + hex(b) + " x DECOMP => " + hex(a));
383             } else {
384                 errln((UnicodeString)"FAIL: " + hex(b) + " x DECOMP => " + hex(a) +
385                       ", expect " + hex(exp));
386             }
387         }
388     }
389 }
390 
391 /**
392  * Run a few specific cases that are failing for Verisign.
393  */
TestVerisign(void)394 void BasicNormalizerTest::TestVerisign(void) {
395     /*
396       > Their input:
397       > 05B8 05B9 05B1 0591 05C3 05B0 05AC 059F
398       > Their output (supposedly from ICU):
399       > 05B8 05B1 05B9 0591 05C3 05B0 05AC 059F
400       > My output from charlint:
401       > 05B1 05B8 05B9 0591 05C3 05B0 05AC 059F
402 
403       05B8 05B9 05B1 0591 05C3 05B0 05AC 059F => 05B1 05B8 05B9 0591 05C3 05B0
404       05AC 059F
405 
406       U+05B8  18  E HEBREW POINT QAMATS
407       U+05B9  19  F HEBREW POINT HOLAM
408       U+05B1  11 HEBREW POINT HATAF SEGOL
409       U+0591 220 HEBREW ACCENT ETNAHTA
410       U+05C3   0 HEBREW PUNCTUATION SOF PASUQ
411       U+05B0  10 HEBREW POINT SHEVA
412       U+05AC 230 HEBREW ACCENT ILUY
413       U+059F 230 HEBREW ACCENT QARNEY PARA
414 
415       U+05B1  11 HEBREW POINT HATAF SEGOL
416       U+05B8  18 HEBREW POINT QAMATS
417       U+05B9  19 HEBREW POINT HOLAM
418       U+0591 220 HEBREW ACCENT ETNAHTA
419       U+05C3   0 HEBREW PUNCTUATION SOF PASUQ
420       U+05B0  10 HEBREW POINT SHEVA
421       U+05AC 230 HEBREW ACCENT ILUY
422       U+059F 230 HEBREW ACCENT QARNEY PARA
423 
424       Wrong result:
425       U+05B8  18 HEBREW POINT QAMATS
426       U+05B1  11 HEBREW POINT HATAF SEGOL
427       U+05B9  19 HEBREW POINT HOLAM
428       U+0591 220 HEBREW ACCENT ETNAHTA
429       U+05C3   0 HEBREW PUNCTUATION SOF PASUQ
430       U+05B0  10 HEBREW POINT SHEVA
431       U+05AC 230 HEBREW ACCENT ILUY
432       U+059F 230 HEBREW ACCENT QARNEY PARA
433 
434 
435       > Their input:
436       >0592 05B7 05BC 05A5 05B0 05C0 05C4 05AD
437       >Their output (supposedly from ICU):
438       >0592 05B0 05B7 05BC 05A5 05C0 05AD 05C4
439       >My output from charlint:
440       >05B0 05B7 05BC 05A5 0592 05C0 05AD 05C4
441 
442       0592 05B7 05BC 05A5 05B0 05C0 05C4 05AD => 05B0 05B7 05BC 05A5 0592 05C0
443       05AD 05C4
444 
445       U+0592 230 HEBREW ACCENT SEGOL
446       U+05B7  17 HEBREW POINT PATAH
447       U+05BC  21 HEBREW POINT DAGESH OR MAPIQ
448       U+05A5 220 HEBREW ACCENT MERKHA
449       U+05B0  10 HEBREW POINT SHEVA
450       U+05C0   0 HEBREW PUNCTUATION PASEQ
451       U+05C4 230 HEBREW MARK UPPER DOT
452       U+05AD 222 HEBREW ACCENT DEHI
453 
454       U+05B0  10 HEBREW POINT SHEVA
455       U+05B7  17 HEBREW POINT PATAH
456       U+05BC  21 HEBREW POINT DAGESH OR MAPIQ
457       U+05A5 220 HEBREW ACCENT MERKHA
458       U+0592 230 HEBREW ACCENT SEGOL
459       U+05C0   0 HEBREW PUNCTUATION PASEQ
460       U+05AD 222 HEBREW ACCENT DEHI
461       U+05C4 230 HEBREW MARK UPPER DOT
462 
463       Wrong result:
464       U+0592 230 HEBREW ACCENT SEGOL
465       U+05B0  10 HEBREW POINT SHEVA
466       U+05B7  17 HEBREW POINT PATAH
467       U+05BC  21 HEBREW POINT DAGESH OR MAPIQ
468       U+05A5 220 HEBREW ACCENT MERKHA
469       U+05C0   0 HEBREW PUNCTUATION PASEQ
470       U+05AD 222 HEBREW ACCENT DEHI
471       U+05C4 230 HEBREW MARK UPPER DOT
472     */
473     UnicodeString data[2][3];
474     data[0][0] = str("\\u05B8\\u05B9\\u05B1\\u0591\\u05C3\\u05B0\\u05AC\\u059F");
475     data[0][1] = str("\\u05B1\\u05B8\\u05B9\\u0591\\u05C3\\u05B0\\u05AC\\u059F");
476     data[0][2] = str("");
477     data[1][0] = str("\\u0592\\u05B7\\u05BC\\u05A5\\u05B0\\u05C0\\u05C4\\u05AD");
478     data[1][1] = str("\\u05B0\\u05B7\\u05BC\\u05A5\\u0592\\u05C0\\u05AD\\u05C4");
479     data[1][2] = str("");
480 
481     staticTest(UNORM_NFD, 0, data, ARRAY_LENGTH(data), 1);
482     staticTest(UNORM_NFC, 0, data, ARRAY_LENGTH(data), 1);
483 }
484 
485 //------------------------------------------------------------------------
486 // Internal utilities
487 //
488 
hex(UChar ch)489 UnicodeString BasicNormalizerTest::hex(UChar ch) {
490     UnicodeString result;
491     return appendHex(ch, 4, result);
492 }
493 
hex(const UnicodeString & s)494 UnicodeString BasicNormalizerTest::hex(const UnicodeString& s) {
495     UnicodeString result;
496     for (int i = 0; i < s.length(); ++i) {
497         if (i != 0) result += (UChar)0x2c/*,*/;
498         appendHex(s[i], 4, result);
499     }
500     return result;
501 }
502 
503 
insert(UnicodeString & dest,int pos,UChar32 ch)504 inline static void insert(UnicodeString& dest, int pos, UChar32 ch)
505 {
506     dest.replace(pos, 0, ch);
507 }
508 
backAndForth(Normalizer * iter,const UnicodeString & input)509 void BasicNormalizerTest::backAndForth(Normalizer* iter, const UnicodeString& input)
510 {
511     UChar32 ch;
512     UErrorCode status = U_ZERO_ERROR;
513     iter->setText(input, status);
514 
515     // Run through the iterator forwards and stick it into a StringBuffer
516     UnicodeString forward;
517     for (ch = iter->first(); ch != iter->DONE; ch = iter->next()) {
518         forward += ch;
519     }
520 
521     // Now do it backwards
522     UnicodeString reverse;
523     for (ch = iter->last(); ch != iter->DONE; ch = iter->previous()) {
524         insert(reverse, 0, ch);
525     }
526 
527     if (forward != reverse) {
528         errln("Forward/reverse mismatch for input " + hex(input)
529               + ", forward: " + hex(forward) + ", backward: " + hex(reverse));
530     }
531 }
532 
staticTest(UNormalizationMode mode,int options,UnicodeString tests[][3],int length,int outCol)533 void BasicNormalizerTest::staticTest(UNormalizationMode mode, int options,
534                      UnicodeString tests[][3], int length,
535                      int outCol)
536 {
537     UErrorCode status = U_ZERO_ERROR;
538     for (int i = 0; i < length; i++)
539     {
540         UnicodeString& input = tests[i][0];
541         UnicodeString& expect = tests[i][outCol];
542 
543         logln("Normalizing '" + input + "' (" + hex(input) + ")" );
544 
545         UnicodeString output;
546         Normalizer::normalize(input, mode, options, output, status);
547 
548         if (output != expect) {
549             dataerrln(UnicodeString("ERROR: case ") + i + " normalized " + hex(input) + "\n"
550                 + "                expected " + hex(expect) + "\n"
551                 + "              static got " + hex(output) );
552         }
553     }
554 }
555 
iterateTest(Normalizer * iter,UnicodeString tests[][3],int length,int outCol)556 void BasicNormalizerTest::iterateTest(Normalizer* iter,
557                                       UnicodeString tests[][3], int length,
558                                       int outCol)
559 {
560     UErrorCode status = U_ZERO_ERROR;
561     for (int i = 0; i < length; i++)
562     {
563         UnicodeString& input = tests[i][0];
564         UnicodeString& expect = tests[i][outCol];
565 
566         logln("Normalizing '" + input + "' (" + hex(input) + ")" );
567 
568         iter->setText(input, status);
569         assertEqual(input, expect, iter, UnicodeString("ERROR: case ") + i + " ");
570     }
571 }
572 
assertEqual(const UnicodeString & input,const UnicodeString & expected,Normalizer * iter,const UnicodeString & errPrefix)573 void BasicNormalizerTest::assertEqual(const UnicodeString&    input,
574                       const UnicodeString&    expected,
575                       Normalizer*        iter,
576                       const UnicodeString&    errPrefix)
577 {
578     UnicodeString result;
579 
580     for (UChar32 ch = iter->first(); ch != iter->DONE; ch = iter->next()) {
581         result += ch;
582     }
583     if (result != expected) {
584         dataerrln(errPrefix + "normalized " + hex(input) + "\n"
585             + "                expected " + hex(expected) + "\n"
586             + "             iterate got " + hex(result) );
587     }
588 }
589 
590 // helper class for TestPreviousNext()
591 // simple UTF-32 character iterator
592 class UChar32Iterator {
593 public:
UChar32Iterator(const UChar32 * text,int32_t len,int32_t index)594     UChar32Iterator(const UChar32 *text, int32_t len, int32_t index) :
595         s(text), length(len), i(index) {}
596 
current()597     UChar32 current() {
598         if(i<length) {
599             return s[i];
600         } else {
601             return 0xffff;
602         }
603     }
604 
next()605     UChar32 next() {
606         if(i<length) {
607             return s[i++];
608         } else {
609             return 0xffff;
610         }
611     }
612 
previous()613     UChar32 previous() {
614         if(i>0) {
615             return s[--i];
616         } else {
617             return 0xffff;
618         }
619     }
620 
getIndex()621     int32_t getIndex() {
622         return i;
623     }
624 private:
625     const UChar32 *s;
626     int32_t length, i;
627 };
628 
629 void
TestPreviousNext(const UChar * src,int32_t srcLength,const UChar32 * expect,int32_t expectLength,const int32_t * expectIndex,int32_t srcMiddle,int32_t expectMiddle,const char * moves,UNormalizationMode mode,const char * name)630 BasicNormalizerTest::TestPreviousNext(const UChar *src, int32_t srcLength,
631                                       const UChar32 *expect, int32_t expectLength,
632                                       const int32_t *expectIndex, // its length=expectLength+1
633                                       int32_t srcMiddle, int32_t expectMiddle,
634                                       const char *moves,
635                                       UNormalizationMode mode,
636                                       const char *name) {
637     // Sanity check non-iterative normalization.
638     {
639         IcuTestErrorCode errorCode(*this, "TestPreviousNext");
640         UnicodeString result;
641         Normalizer::normalize(UnicodeString(src, srcLength), mode, 0, result, errorCode);
642         if (errorCode.isFailure()) {
643             dataerrln("error: non-iterative normalization of %s failed: %s",
644                       name, errorCode.errorName());
645             errorCode.reset();
646             return;
647         }
648         // UnicodeString::fromUTF32(expect, expectLength)
649         // would turn unpaired surrogates into U+FFFD.
650         for (int32_t i = 0, j = 0; i < result.length(); ++j) {
651             UChar32 c = result.char32At(i);
652             if (c != expect[j]) {
653                 errln("error: non-iterative normalization of %s did not yield the expected result",
654                       name);
655             }
656             i += U16_LENGTH(c);
657         }
658     }
659 
660     // iterators
661     Normalizer iter(src, srcLength, mode);
662 
663     // test getStaticClassID and getDynamicClassID
664     if(iter.getDynamicClassID() != Normalizer::getStaticClassID()) {
665         errln("getStaticClassID != getDynamicClassID for Normalizer.");
666     }
667 
668     UChar32Iterator iter32(expect, expectLength, expectMiddle);
669 
670     UChar32 c1, c2;
671     char m;
672 
673     // initially set the indexes into the middle of the strings
674     iter.setIndexOnly(srcMiddle);
675 
676     // move around and compare the iteration code points with
677     // the expected ones
678     const char *move=moves;
679     while((m=*move++)!=0) {
680         if(m=='-') {
681             c1=iter.previous();
682             c2=iter32.previous();
683         } else if(m=='0') {
684             c1=iter.current();
685             c2=iter32.current();
686         } else /* m=='+' */ {
687             c1=iter.next();
688             c2=iter32.next();
689         }
690 
691         // compare results
692         if(c1!=c2) {
693             // copy the moves until the current (m) move, and terminate
694             char history[64];
695             uprv_strcpy(history, moves);
696             history[move-moves]=0;
697             dataerrln("error: mismatch in Normalizer iteration (%s) at %s: "
698                   "got c1=U+%04lx != expected c2=U+%04lx",
699                   name, history, c1, c2);
700             break;
701         }
702 
703         // compare indexes
704         if(iter.getIndex()!=expectIndex[iter32.getIndex()]) {
705             // copy the moves until the current (m) move, and terminate
706             char history[64];
707             uprv_strcpy(history, moves);
708             history[move-moves]=0;
709             errln("error: index mismatch in Normalizer iteration (%s) at %s: "
710                   "Normalizer index %ld expected %ld\n",
711                   name, history, iter.getIndex(), expectIndex[iter32.getIndex()]);
712             break;
713         }
714     }
715 }
716 
717 void
TestPreviousNext()718 BasicNormalizerTest::TestPreviousNext() {
719     // src and expect strings
720     static const UChar src[]={
721         U16_LEAD(0x2f999), U16_TRAIL(0x2f999),
722         U16_LEAD(0x1d15f), U16_TRAIL(0x1d15f),
723         0xc4,
724         0x1ed0
725     };
726     static const UChar32 expect[]={
727         0x831d,
728         0x1d158, 0x1d165,
729         0x41, 0x308,
730         0x4f, 0x302, 0x301
731     };
732 
733     // expected src indexes corresponding to expect indexes
734     static const int32_t expectIndex[]={
735         0,
736         2, 2,
737         4, 4,
738         5, 5, 5,
739         6 // behind last character
740     };
741 
742     // src and expect strings for regression test for j2911
743     static const UChar src_j2911[]={
744         U16_LEAD(0x2f999), U16_TRAIL(0x2f999),
745         0xdd00, 0xd900, // unpaired surrogates - regression test for j2911
746         0xc4,
747         0x4f, 0x302, 0x301
748     };
749     static const UChar32 expect_j2911[]={
750         0x831d,
751         0xdd00, 0xd900, // unpaired surrogates - regression test for j2911
752         0xc4,
753         0x1ed0
754     };
755 
756     // expected src indexes corresponding to expect indexes
757     static const int32_t expectIndex_j2911[]={
758         0,
759         2, 3,
760         4,
761         5,
762         8 // behind last character
763     };
764 
765     // initial indexes into the src and expect strings
766     // for both sets of test data
767     enum {
768         SRC_MIDDLE=4,
769         EXPECT_MIDDLE=3,
770         SRC_MIDDLE_2=2,
771         EXPECT_MIDDLE_2=1
772     };
773 
774     // movement vector
775     // - for previous(), 0 for current(), + for next()
776     // for both sets of test data
777     static const char *const moves="0+0+0--0-0-+++0--+++++++0--------";
778 
779     TestPreviousNext(src, UPRV_LENGTHOF(src),
780                      expect, UPRV_LENGTHOF(expect),
781                      expectIndex,
782                      SRC_MIDDLE, EXPECT_MIDDLE,
783                      moves, UNORM_NFD, "basic");
784 
785     TestPreviousNext(src_j2911, UPRV_LENGTHOF(src_j2911),
786                      expect_j2911, UPRV_LENGTHOF(expect_j2911),
787                      expectIndex_j2911,
788                      SRC_MIDDLE, EXPECT_MIDDLE,
789                      moves, UNORM_NFKC, "j2911");
790 
791     // try again from different "middle" indexes
792     TestPreviousNext(src, UPRV_LENGTHOF(src),
793                      expect, UPRV_LENGTHOF(expect),
794                      expectIndex,
795                      SRC_MIDDLE_2, EXPECT_MIDDLE_2,
796                      moves, UNORM_NFD, "basic_2");
797 
798     TestPreviousNext(src_j2911, UPRV_LENGTHOF(src_j2911),
799                      expect_j2911, UPRV_LENGTHOF(expect_j2911),
800                      expectIndex_j2911,
801                      SRC_MIDDLE_2, EXPECT_MIDDLE_2,
802                      moves, UNORM_NFKC, "j2911_2");
803 }
804 
TestConcatenate()805 void BasicNormalizerTest::TestConcatenate() {
806     static const char *const
807     cases[][4]={
808         /* mode, left, right, result */
809         {
810             "C",
811             "re",
812             "\\u0301sum\\u00e9",
813             "r\\u00e9sum\\u00e9"
814         },
815         {
816             "C",
817             "a\\u1100",
818             "\\u1161bcdefghijk",
819             "a\\uac00bcdefghijk"
820         },
821         /* ### TODO: add more interesting cases */
822         {
823             "D",
824             "\\u03B1\\u0345",
825             "\\u0C4D\\U000110BA\\U0001D169",
826             "\\u03B1\\U0001D169\\U000110BA\\u0C4D\\u0345"
827         }
828     };
829 
830     UnicodeString left, right, expect, result, r;
831     UErrorCode errorCode;
832     UNormalizationMode mode;
833     int32_t i;
834 
835     /* test concatenation */
836     for(i=0; i<UPRV_LENGTHOF(cases); ++i) {
837         switch(*cases[i][0]) {
838         case 'C': mode=UNORM_NFC; break;
839         case 'D': mode=UNORM_NFD; break;
840         case 'c': mode=UNORM_NFKC; break;
841         case 'd': mode=UNORM_NFKD; break;
842         default: mode=UNORM_NONE; break;
843         }
844 
845         left=UnicodeString(cases[i][1], "").unescape();
846         right=UnicodeString(cases[i][2], "").unescape();
847         expect=UnicodeString(cases[i][3], "").unescape();
848 
849         //result=r=UnicodeString();
850         errorCode=U_ZERO_ERROR;
851 
852         r=Normalizer::concatenate(left, right, result, mode, 0, errorCode);
853         if(U_FAILURE(errorCode) || /*result!=r ||*/ result!=expect) {
854             dataerrln("error in Normalizer::concatenate(), cases[] fails with "+
855                 UnicodeString(u_errorName(errorCode))+", result==expect: expected: "+
856                 hex(expect)+" =========> got: " + hex(result));
857         }
858     }
859 
860     /* test error cases */
861 
862     /* left.getBuffer()==result.getBuffer() */
863     result=r=expect=UnicodeString("zz", "");
864     errorCode=U_UNEXPECTED_TOKEN;
865     r=Normalizer::concatenate(left, right, result, mode, 0, errorCode);
866     if(errorCode!=U_UNEXPECTED_TOKEN || result!=r || !result.isBogus()) {
867         errln("error in Normalizer::concatenate(), violates UErrorCode protocol");
868     }
869 
870     left.setToBogus();
871     errorCode=U_ZERO_ERROR;
872     r=Normalizer::concatenate(left, right, result, mode, 0, errorCode);
873     if(errorCode!=U_ILLEGAL_ARGUMENT_ERROR || result!=r || !result.isBogus()) {
874         errln("error in Normalizer::concatenate(), does not detect left.isBogus()");
875     }
876 }
877 
878 // reference implementation of Normalizer::compare
879 static int32_t
ref_norm_compare(const UnicodeString & s1,const UnicodeString & s2,uint32_t options,UErrorCode & errorCode)880 ref_norm_compare(const UnicodeString &s1, const UnicodeString &s2, uint32_t options, UErrorCode &errorCode) {
881     UnicodeString r1, r2, t1, t2;
882     int32_t normOptions=(int32_t)(options>>UNORM_COMPARE_NORM_OPTIONS_SHIFT);
883 
884     if(options&U_COMPARE_IGNORE_CASE) {
885         Normalizer::decompose(s1, FALSE, normOptions, r1, errorCode);
886         Normalizer::decompose(s2, FALSE, normOptions, r2, errorCode);
887 
888         r1.foldCase(options);
889         r2.foldCase(options);
890     } else {
891         r1=s1;
892         r2=s2;
893     }
894 
895     Normalizer::decompose(r1, FALSE, normOptions, t1, errorCode);
896     Normalizer::decompose(r2, FALSE, normOptions, t2, errorCode);
897 
898     if(options&U_COMPARE_CODE_POINT_ORDER) {
899         return t1.compareCodePointOrder(t2);
900     } else {
901         return t1.compare(t2);
902     }
903 }
904 
905 // test wrapper for Normalizer::compare, sets UNORM_INPUT_IS_FCD appropriately
906 static int32_t
_norm_compare(const UnicodeString & s1,const UnicodeString & s2,uint32_t options,UErrorCode & errorCode)907 _norm_compare(const UnicodeString &s1, const UnicodeString &s2, uint32_t options, UErrorCode &errorCode) {
908     int32_t normOptions=(int32_t)(options>>UNORM_COMPARE_NORM_OPTIONS_SHIFT);
909 
910     if( UNORM_YES==Normalizer::quickCheck(s1, UNORM_FCD, normOptions, errorCode) &&
911         UNORM_YES==Normalizer::quickCheck(s2, UNORM_FCD, normOptions, errorCode)) {
912         options|=UNORM_INPUT_IS_FCD;
913     }
914 
915     return Normalizer::compare(s1, s2, options, errorCode);
916 }
917 
918 // reference implementation of UnicodeString::caseCompare
919 static int32_t
ref_case_compare(const UnicodeString & s1,const UnicodeString & s2,uint32_t options)920 ref_case_compare(const UnicodeString &s1, const UnicodeString &s2, uint32_t options) {
921     UnicodeString t1, t2;
922 
923     t1=s1;
924     t2=s2;
925 
926     t1.foldCase(options);
927     t2.foldCase(options);
928 
929     if(options&U_COMPARE_CODE_POINT_ORDER) {
930         return t1.compareCodePointOrder(t2);
931     } else {
932         return t1.compare(t2);
933     }
934 }
935 
936 // reduce an integer to -1/0/1
937 static inline int32_t
_sign(int32_t value)938 _sign(int32_t value) {
939     if(value==0) {
940         return 0;
941     } else {
942         return (value>>31)|1;
943     }
944 }
945 
946 static const char *
_signString(int32_t value)947 _signString(int32_t value) {
948     if(value<0) {
949         return "<0";
950     } else if(value==0) {
951         return "=0";
952     } else /* value>0 */ {
953         return ">0";
954     }
955 }
956 
957 void
TestCompare()958 BasicNormalizerTest::TestCompare() {
959     // test Normalizer::compare and unorm_compare (thinly wrapped by the former)
960     // by comparing it with its semantic equivalent
961     // since we trust the pieces, this is sufficient
962 
963     // test each string with itself and each other
964     // each time with all options
965     static const char *const
966     strings[]={
967         // some cases from NormalizationTest.txt
968         // 0..3
969         "D\\u031B\\u0307\\u0323",
970         "\\u1E0C\\u031B\\u0307",
971         "D\\u031B\\u0323\\u0307",
972         "d\\u031B\\u0323\\u0307",
973 
974         // 4..6
975         "\\u00E4",
976         "a\\u0308",
977         "A\\u0308",
978 
979         // Angstrom sign = A ring
980         // 7..10
981         "\\u212B",
982         "\\u00C5",
983         "A\\u030A",
984         "a\\u030A",
985 
986         // 11.14
987         "a\\u059A\\u0316\\u302A\\u032Fb",
988         "a\\u302A\\u0316\\u032F\\u059Ab",
989         "a\\u302A\\u0316\\u032F\\u059Ab",
990         "A\\u059A\\u0316\\u302A\\u032Fb",
991 
992         // from ICU case folding tests
993         // 15..20
994         "A\\u00df\\u00b5\\ufb03\\U0001040c\\u0131",
995         "ass\\u03bcffi\\U00010434i",
996         "\\u0061\\u0042\\u0131\\u03a3\\u00df\\ufb03\\ud93f\\udfff",
997         "\\u0041\\u0062\\u0069\\u03c3\\u0073\\u0053\\u0046\\u0066\\u0049\\ud93f\\udfff",
998         "\\u0041\\u0062\\u0131\\u03c3\\u0053\\u0073\\u0066\\u0046\\u0069\\ud93f\\udfff",
999         "\\u0041\\u0062\\u0069\\u03c3\\u0073\\u0053\\u0046\\u0066\\u0049\\ud93f\\udffd",
1000 
1001         //     U+d800 U+10001   see implementation comment in unorm_cmpEquivFold
1002         // vs. U+10000          at bottom - code point order
1003         // 21..22
1004         "\\ud800\\ud800\\udc01",
1005         "\\ud800\\udc00",
1006 
1007         // other code point order tests from ustrtest.cpp
1008         // 23..31
1009         "\\u20ac\\ud801",
1010         "\\u20ac\\ud800\\udc00",
1011         "\\ud800",
1012         "\\ud800\\uff61",
1013         "\\udfff",
1014         "\\uff61\\udfff",
1015         "\\uff61\\ud800\\udc02",
1016         "\\ud800\\udc02",
1017         "\\ud84d\\udc56",
1018 
1019         // long strings, see cnormtst.c/TestNormCoverage()
1020         // equivalent if case-insensitive
1021         // 32..33
1022         "\\uAD8B\\uAD8B\\uAD8B\\uAD8B"
1023         "\\U0001d15e\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1024         "\\U0001d15e\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1025         "\\U0001d15e\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1026         "\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1027         "\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1028         "aaaaaaaaaaaaaaaaaazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
1029         "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
1030         "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
1031         "ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
1032         "\\uAD8B\\uAD8B\\uAD8B\\uAD8B"
1033         "d\\u031B\\u0307\\u0323",
1034 
1035         "\\u1100\\u116f\\u11aa\\uAD8B\\uAD8B\\u1100\\u116f\\u11aa"
1036         "\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1037         "\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1038         "\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1039         "\\U0001d15e\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1040         "\\U0001d15e\\U0001d157\\U0001d165\\U0001d15e\\U0001d15e\\U0001d15e\\U0001d15e"
1041         "aaaaaaaaaaAAAAAAAAZZZZZZZZZZZZZZZZzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
1042         "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
1043         "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
1044         "ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
1045         "\\u1100\\u116f\\u11aa\\uAD8B\\uAD8B\\u1100\\u116f\\u11aa"
1046         "\\u1E0C\\u031B\\u0307",
1047 
1048         // some strings that may make a difference whether the compare function
1049         // case-folds or decomposes first
1050         // 34..41
1051         "\\u0360\\u0345\\u0334",
1052         "\\u0360\\u03b9\\u0334",
1053 
1054         "\\u0360\\u1f80\\u0334",
1055         "\\u0360\\u03b1\\u0313\\u03b9\\u0334",
1056 
1057         "\\u0360\\u1ffc\\u0334",
1058         "\\u0360\\u03c9\\u03b9\\u0334",
1059 
1060         "a\\u0360\\u0345\\u0360\\u0345b",
1061         "a\\u0345\\u0360\\u0345\\u0360b",
1062 
1063         // interesting cases for canonical caseless match with turkic i handling
1064         // 42..43
1065         "\\u00cc",
1066         "\\u0069\\u0300",
1067 
1068         // strings with post-Unicode 3.2 normalization or normalization corrections
1069         // 44..45
1070         "\\u00e4\\u193b\\U0002f868",
1071         "\\u0061\\u193b\\u0308\\u36fc",
1072 
1073         // empty string
1074         // 46
1075         ""
1076     };
1077 
1078     UnicodeString s[100]; // at least as many items as in strings[] !
1079 
1080     // all combinations of options
1081     // UNORM_INPUT_IS_FCD is set automatically if both input strings fulfill FCD conditions
1082     // set UNORM_UNICODE_3_2 in one additional combination
1083     static const struct {
1084         uint32_t options;
1085         const char *name;
1086     } opt[]={
1087         { 0, "default" },
1088         { U_COMPARE_CODE_POINT_ORDER, "c.p. order" },
1089         { U_COMPARE_IGNORE_CASE, "ignore case" },
1090         { U_COMPARE_CODE_POINT_ORDER|U_COMPARE_IGNORE_CASE, "c.p. order & ignore case" },
1091         { U_COMPARE_IGNORE_CASE|U_FOLD_CASE_EXCLUDE_SPECIAL_I, "ignore case & special i" },
1092         { U_COMPARE_CODE_POINT_ORDER|U_COMPARE_IGNORE_CASE|U_FOLD_CASE_EXCLUDE_SPECIAL_I, "c.p. order & ignore case & special i" },
1093         { UNORM_UNICODE_3_2<<UNORM_COMPARE_NORM_OPTIONS_SHIFT, "Unicode 3.2" }
1094     };
1095 
1096     int32_t i, j, k, count=UPRV_LENGTHOF(strings);
1097     int32_t result, refResult;
1098 
1099     UErrorCode errorCode;
1100 
1101     // create the UnicodeStrings
1102     for(i=0; i<count; ++i) {
1103         s[i]=UnicodeString(strings[i], "").unescape();
1104     }
1105 
1106     // test them each with each other
1107     for(i=0; i<count; ++i) {
1108         for(j=i; j<count; ++j) {
1109             for(k=0; k<UPRV_LENGTHOF(opt); ++k) {
1110                 // test Normalizer::compare
1111                 errorCode=U_ZERO_ERROR;
1112                 result=_norm_compare(s[i], s[j], opt[k].options, errorCode);
1113                 refResult=ref_norm_compare(s[i], s[j], opt[k].options, errorCode);
1114                 if(_sign(result)!=_sign(refResult)) {
1115                     errln("Normalizer::compare(%d, %d, %s)%s should be %s %s",
1116                         i, j, opt[k].name, _signString(result), _signString(refResult),
1117                         U_SUCCESS(errorCode) ? "" : u_errorName(errorCode));
1118                 }
1119 
1120                 // test UnicodeString::caseCompare - same internal implementation function
1121                 if(opt[k].options&U_COMPARE_IGNORE_CASE) {
1122                     errorCode=U_ZERO_ERROR;
1123                     result=s[i].caseCompare(s[j], opt[k].options);
1124                     refResult=ref_case_compare(s[i], s[j], opt[k].options);
1125                     if(_sign(result)!=_sign(refResult)) {
1126                         errln("UniStr::caseCompare(%d, %d, %s)%s should be %s %s",
1127                             i, j, opt[k].name, _signString(result), _signString(refResult),
1128                             U_SUCCESS(errorCode) ? "" : u_errorName(errorCode));
1129                     }
1130                 }
1131             }
1132         }
1133     }
1134 
1135     // test cases with i and I to make sure Turkic works
1136     static const UChar iI[]={ 0x49, 0x69, 0x130, 0x131 };
1137     UnicodeSet iSet, set;
1138 
1139     UnicodeString s1, s2;
1140 
1141     const Normalizer2Impl *nfcImpl=Normalizer2Factory::getNFCImpl(errorCode);
1142     if(U_FAILURE(errorCode) || !nfcImpl->ensureCanonIterData(errorCode)) {
1143         dataerrln("Normalizer2Factory::getNFCImpl().ensureCanonIterData() failed: %s",
1144               u_errorName(errorCode));
1145         return;
1146     }
1147 
1148     // collect all sets into one for contiguous output
1149     for(i=0; i<UPRV_LENGTHOF(iI); ++i) {
1150         if(nfcImpl->getCanonStartSet(iI[i], iSet)) {
1151             set.addAll(iSet);
1152         }
1153     }
1154 
1155     // test all of these precomposed characters
1156     const Normalizer2 *nfcNorm2=Normalizer2::getNFCInstance(errorCode);
1157     UnicodeSetIterator it(set);
1158     while(it.next() && !it.isString()) {
1159         UChar32 c=it.getCodepoint();
1160         if(!nfcNorm2->getDecomposition(c, s2)) {
1161             dataerrln("NFC.getDecomposition(i-composite U+%04lx) failed", (long)c);
1162             return;
1163         }
1164 
1165         s1.setTo(c);
1166         for(k=0; k<UPRV_LENGTHOF(opt); ++k) {
1167             // test Normalizer::compare
1168             errorCode=U_ZERO_ERROR;
1169             result=_norm_compare(s1, s2, opt[k].options, errorCode);
1170             refResult=ref_norm_compare(s1, s2, opt[k].options, errorCode);
1171             if(_sign(result)!=_sign(refResult)) {
1172                 errln("Normalizer::compare(U+%04x with its NFD, %s)%s should be %s %s",
1173                     c, opt[k].name, _signString(result), _signString(refResult),
1174                     U_SUCCESS(errorCode) ? "" : u_errorName(errorCode));
1175             }
1176 
1177             // test UnicodeString::caseCompare - same internal implementation function
1178             if(opt[k].options&U_COMPARE_IGNORE_CASE) {
1179                 errorCode=U_ZERO_ERROR;
1180                 result=s1.caseCompare(s2, opt[k].options);
1181                 refResult=ref_case_compare(s1, s2, opt[k].options);
1182                 if(_sign(result)!=_sign(refResult)) {
1183                     errln("UniStr::caseCompare(U+%04x with its NFD, %s)%s should be %s %s",
1184                         c, opt[k].name, _signString(result), _signString(refResult),
1185                         U_SUCCESS(errorCode) ? "" : u_errorName(errorCode));
1186                 }
1187             }
1188         }
1189     }
1190 
1191     // test getDecomposition() for some characters that do not decompose
1192     if( nfcNorm2->getDecomposition(0x20, s2) ||
1193         nfcNorm2->getDecomposition(0x4e00, s2) ||
1194         nfcNorm2->getDecomposition(0x20002, s2)
1195     ) {
1196         errln("NFC.getDecomposition() returns TRUE for characters which do not have decompositions");
1197     }
1198 
1199     // test getRawDecomposition() for some characters that do not decompose
1200     if( nfcNorm2->getRawDecomposition(0x20, s2) ||
1201         nfcNorm2->getRawDecomposition(0x4e00, s2) ||
1202         nfcNorm2->getRawDecomposition(0x20002, s2)
1203     ) {
1204         errln("NFC.getRawDecomposition() returns TRUE for characters which do not have decompositions");
1205     }
1206 
1207     // test composePair() for some pairs of characters that do not compose
1208     if( nfcNorm2->composePair(0x20, 0x301)>=0 ||
1209         nfcNorm2->composePair(0x61, 0x305)>=0 ||
1210         nfcNorm2->composePair(0x1100, 0x1160)>=0 ||
1211         nfcNorm2->composePair(0xac00, 0x11a7)>=0
1212     ) {
1213         errln("NFC.composePair() incorrectly composes some pairs of characters");
1214     }
1215 
1216     // test FilteredNormalizer2::getDecomposition()
1217     UnicodeSet filter(UNICODE_STRING_SIMPLE("[^\\u00a0-\\u00ff]"), errorCode);
1218     FilteredNormalizer2 fn2(*nfcNorm2, filter);
1219     if( fn2.getDecomposition(0xe4, s1) || !fn2.getDecomposition(0x100, s2) ||
1220         s2.length()!=2 || s2[0]!=0x41 || s2[1]!=0x304
1221     ) {
1222         errln("FilteredNormalizer2(NFC, ^A0-FF).getDecomposition() failed");
1223     }
1224 
1225     // test FilteredNormalizer2::getRawDecomposition()
1226     if( fn2.getRawDecomposition(0xe4, s1) || !fn2.getRawDecomposition(0x100, s2) ||
1227         s2.length()!=2 || s2[0]!=0x41 || s2[1]!=0x304
1228     ) {
1229         errln("FilteredNormalizer2(NFC, ^A0-FF).getRawDecomposition() failed");
1230     }
1231 
1232     // test FilteredNormalizer2::composePair()
1233     if( 0x100!=fn2.composePair(0x41, 0x304) ||
1234         fn2.composePair(0xc7, 0x301)>=0 // unfiltered result: U+1E08
1235     ) {
1236         errln("FilteredNormalizer2(NFC, ^A0-FF).composePair() failed");
1237     }
1238 }
1239 
1240 // verify that case-folding does not un-FCD strings
1241 int32_t
countFoldFCDExceptions(uint32_t foldingOptions)1242 BasicNormalizerTest::countFoldFCDExceptions(uint32_t foldingOptions) {
1243     UnicodeString s, fold, d;
1244     UChar32 c;
1245     int32_t count;
1246     uint8_t cc, trailCC, foldCC, foldTrailCC;
1247     UNormalizationCheckResult qcResult;
1248     int8_t category;
1249     UBool isNFD;
1250     UErrorCode errorCode;
1251 
1252     logln("Test if case folding may un-FCD a string (folding options %04lx)", foldingOptions);
1253 
1254     count=0;
1255     for(c=0; c<=0x10ffff; ++c) {
1256         errorCode = U_ZERO_ERROR;
1257         category=u_charType(c);
1258         if(category==U_UNASSIGNED) {
1259             continue; // skip unassigned code points
1260         }
1261         if(c==0xac00) {
1262             c=0xd7a3; // skip Hangul - no case folding there
1263             continue;
1264         }
1265         // skip Han blocks - no case folding there either
1266         if(c==0x3400) {
1267             c=0x4db5;
1268             continue;
1269         }
1270         if(c==0x4e00) {
1271             c=0x9fa5;
1272             continue;
1273         }
1274         if(c==0x20000) {
1275             c=0x2a6d6;
1276             continue;
1277         }
1278 
1279         s.setTo(c);
1280 
1281         // get leading and trailing cc for c
1282         Normalizer::decompose(s, FALSE, 0, d, errorCode);
1283         isNFD= s==d;
1284         cc=u_getCombiningClass(d.char32At(0));
1285         trailCC=u_getCombiningClass(d.char32At(d.length()-1));
1286 
1287         // get leading and trailing cc for the case-folding of c
1288         s.foldCase(foldingOptions);
1289         Normalizer::decompose(s, FALSE, 0, d, errorCode);
1290         foldCC=u_getCombiningClass(d.char32At(0));
1291         foldTrailCC=u_getCombiningClass(d.char32At(d.length()-1));
1292 
1293         qcResult=Normalizer::quickCheck(s, UNORM_FCD, errorCode);
1294 
1295         if (U_FAILURE(errorCode)) {
1296             ++count;
1297             dataerrln("U+%04lx: Failed with error %s", u_errorName(errorCode));
1298         }
1299 
1300         // bad:
1301         // - character maps to empty string: adjacent characters may then need reordering
1302         // - folding has different leading/trailing cc's, and they don't become just 0
1303         // - folding itself is not FCD
1304         if( qcResult!=UNORM_YES ||
1305             s.isEmpty() ||
1306             (cc!=foldCC && foldCC!=0) || (trailCC!=foldTrailCC && foldTrailCC!=0)
1307         ) {
1308             ++count;
1309             dataerrln("U+%04lx: case-folding may un-FCD a string (folding options %04lx)", c, foldingOptions);
1310             dataerrln("  cc %02x trailCC %02x    foldCC(U+%04lx) %02x foldTrailCC(U+%04lx) %02x   quickCheck(folded)=%d", cc, trailCC, d.char32At(0), foldCC, d.char32At(d.length()-1), foldTrailCC, qcResult);
1311             continue;
1312         }
1313 
1314         // also bad:
1315         // if a code point is in NFD but its case folding is not, then
1316         // unorm_compare will also fail
1317         if(isNFD && UNORM_YES!=Normalizer::quickCheck(s, UNORM_NFD, errorCode)) {
1318             ++count;
1319             errln("U+%04lx: case-folding un-NFDs this character (folding options %04lx)", c, foldingOptions);
1320         }
1321     }
1322 
1323     logln("There are %ld code points for which case-folding may un-FCD a string (folding options %04lx)", count, foldingOptions);
1324     return count;
1325 }
1326 
1327 void
FindFoldFCDExceptions()1328 BasicNormalizerTest::FindFoldFCDExceptions() {
1329     int32_t count;
1330 
1331     count=countFoldFCDExceptions(0);
1332     count+=countFoldFCDExceptions(U_FOLD_CASE_EXCLUDE_SPECIAL_I);
1333     if(count>0) {
1334         /*
1335          * If case-folding un-FCDs any strings, then unorm_compare() must be
1336          * re-implemented.
1337          * It currently assumes that one can check for FCD then case-fold
1338          * and then still have FCD strings for raw decomposition without reordering.
1339          */
1340         dataerrln("error: There are %ld code points for which case-folding may un-FCD a string for all folding options.\n"
1341               "See comment in BasicNormalizerTest::FindFoldFCDExceptions()!", count);
1342     }
1343 }
1344 
1345 static void
initExpectedSkippables(UnicodeSet skipSets[UNORM_MODE_COUNT],UErrorCode & errorCode)1346 initExpectedSkippables(UnicodeSet skipSets[UNORM_MODE_COUNT], UErrorCode &errorCode) {
1347     skipSets[UNORM_NFD].applyPattern(
1348         UNICODE_STRING_SIMPLE("[[:NFD_QC=Yes:]&[:ccc=0:]]"), errorCode);
1349     skipSets[UNORM_NFC].applyPattern(
1350         UNICODE_STRING_SIMPLE("[[:NFC_QC=Yes:]&[:ccc=0:]-[:HST=LV:]]"), errorCode);
1351     skipSets[UNORM_NFKD].applyPattern(
1352         UNICODE_STRING_SIMPLE("[[:NFKD_QC=Yes:]&[:ccc=0:]]"), errorCode);
1353     skipSets[UNORM_NFKC].applyPattern(
1354         UNICODE_STRING_SIMPLE("[[:NFKC_QC=Yes:]&[:ccc=0:]-[:HST=LV:]]"), errorCode);
1355 
1356     // Remove from the NFC and NFKC sets all those characters that change
1357     // when a back-combining character is added.
1358     // First, get all of the back-combining characters and their combining classes.
1359     UnicodeSet combineBack("[:NFC_QC=Maybe:]", errorCode);
1360     int32_t numCombineBack=combineBack.size();
1361     int32_t *combineBackCharsAndCc=new int32_t[numCombineBack*2];
1362     UnicodeSetIterator iter(combineBack);
1363     for(int32_t i=0; i<numCombineBack; ++i) {
1364         iter.next();
1365         UChar32 c=iter.getCodepoint();
1366         combineBackCharsAndCc[2*i]=c;
1367         combineBackCharsAndCc[2*i+1]=u_getCombiningClass(c);
1368     }
1369 
1370     // We need not look at control codes, Han characters nor Hangul LVT syllables because they
1371     // do not combine forward. LV syllables are already removed.
1372     UnicodeSet notInteresting("[[:C:][:Unified_Ideograph:][:HST=LVT:]]", errorCode);
1373     LocalPointer<UnicodeSet> unsure(&(skipSets[UNORM_NFC].clone())->removeAll(notInteresting));
1374     // System.out.format("unsure.size()=%d\n", unsure.size());
1375 
1376     // For each character about which we are unsure, see if it changes when we add
1377     // one of the back-combining characters.
1378     const Normalizer2 *norm2=Normalizer2::getNFCInstance(errorCode);
1379     UnicodeString s;
1380     iter.reset(*unsure);
1381     while(iter.next()) {
1382         UChar32 c=iter.getCodepoint();
1383         s.setTo(c);
1384         int32_t cLength=s.length();
1385         int32_t tccc=u_getIntPropertyValue(c, UCHAR_TRAIL_CANONICAL_COMBINING_CLASS);
1386         for(int32_t i=0; i<numCombineBack; ++i) {
1387             // If c's decomposition ends with a character with non-zero combining class, then
1388             // c can only change if it combines with a character with a non-zero combining class.
1389             int32_t cc2=combineBackCharsAndCc[2*i+1];
1390             if(tccc==0 || cc2!=0) {
1391                 UChar32 c2=combineBackCharsAndCc[2*i];
1392                 s.append(c2);
1393                 if(!norm2->isNormalized(s, errorCode)) {
1394                     // System.out.format("remove U+%04x (tccc=%d) + U+%04x (cc=%d)\n", c, tccc, c2, cc2);
1395                     skipSets[UNORM_NFC].remove(c);
1396                     skipSets[UNORM_NFKC].remove(c);
1397                     break;
1398                 }
1399                 s.truncate(cLength);
1400             }
1401         }
1402     }
1403     delete [] combineBackCharsAndCc;
1404 }
1405 
1406 static const char *const kModeStrings[UNORM_MODE_COUNT] = {
1407     "?", "none", "D", "KD", "C", "KC", "FCD"
1408 };
1409 
1410 void
TestSkippable()1411 BasicNormalizerTest::TestSkippable() {
1412     UnicodeSet diff, skipSets[UNORM_MODE_COUNT], expectSets[UNORM_MODE_COUNT];
1413     UnicodeString s, pattern;
1414 
1415     /* build NF*Skippable sets from runtime data */
1416     IcuTestErrorCode errorCode(*this, "TestSkippable");
1417     skipSets[UNORM_NFD].applyPattern(UNICODE_STRING_SIMPLE("[:NFD_Inert:]"), errorCode);
1418     skipSets[UNORM_NFKD].applyPattern(UNICODE_STRING_SIMPLE("[:NFKD_Inert:]"), errorCode);
1419     skipSets[UNORM_NFC].applyPattern(UNICODE_STRING_SIMPLE("[:NFC_Inert:]"), errorCode);
1420     skipSets[UNORM_NFKC].applyPattern(UNICODE_STRING_SIMPLE("[:NFKC_Inert:]"), errorCode);
1421     if(errorCode.errDataIfFailureAndReset("UnicodeSet(NF..._Inert) failed")) {
1422         return;
1423     }
1424 
1425     /* get expected sets from hardcoded patterns */
1426     initExpectedSkippables(expectSets, errorCode);
1427     errorCode.assertSuccess();
1428 
1429     for(int32_t i=UNORM_NONE; i<UNORM_MODE_COUNT; ++i) {
1430         if(skipSets[i]!=expectSets[i]) {
1431             const char *ms=kModeStrings[i];
1432             errln("error: TestSkippable skipSets[%s]!=expectedSets[%s]\n", ms, ms);
1433             // Note: This used to depend on hardcoded UnicodeSet patterns generated by
1434             // Mark's unicodetools.com.ibm.text.UCD.NFSkippable, by
1435             // running com.ibm.text.UCD.Main with the option NFSkippable.
1436             // Since ICU 4.6/Unicode 6, we are generating the
1437             // expectSets ourselves in initSkippables().
1438 
1439             s=UNICODE_STRING_SIMPLE("skip-expect=");
1440             (diff=skipSets[i]).removeAll(expectSets[i]).toPattern(pattern, TRUE);
1441             s.append(pattern);
1442 
1443             pattern.remove();
1444             s.append(UNICODE_STRING_SIMPLE("\n\nexpect-skip="));
1445             (diff=expectSets[i]).removeAll(skipSets[i]).toPattern(pattern, TRUE);
1446             s.append(pattern);
1447             s.append(UNICODE_STRING_SIMPLE("\n\n"));
1448 
1449             errln(s);
1450         }
1451     }
1452 }
1453 
1454 struct StringPair { const char *input, *expected; };
1455 
1456 void
TestCustomComp()1457 BasicNormalizerTest::TestCustomComp() {
1458     static const StringPair pairs[]={
1459         // ICU 63 normalization with UCPTrie requires inert surrogate code points.
1460         // { "\\uD801\\uE000\\uDFFE", "" },
1461         // { "\\uD800\\uD801\\uE000\\uDFFE\\uDFFF", "\\uD7FF\\uFFFF" },
1462         // { "\\uD800\\uD801\\uDFFE\\uDFFF", "\\uD7FF\\U000107FE\\uFFFF" },
1463         { "\\uD801\\uE000\\uDFFE", "\\uD801\\uDFFE" },
1464         { "\\uD800\\uD801\\uE000\\uDFFE\\uDFFF", "\\uD800\\uD801\\uDFFE\\uDFFF" },
1465         { "\\uD800\\uD801\\uDFFE\\uDFFF", "\\uD800\\U000107FE\\uDFFF" },
1466 
1467         { "\\uE001\\U000110B9\\u0345\\u0308\\u0327", "\\uE002\\U000110B9\\u0327\\u0345" },
1468         { "\\uE010\\U000F0011\\uE012", "\\uE011\\uE012" },
1469         { "\\uE010\\U000F0011\\U000F0011\\uE012", "\\uE011\\U000F0010" },
1470         { "\\uE111\\u1161\\uE112\\u1162", "\\uAE4C\\u1102\\u0062\\u1162" },
1471         { "\\uFFF3\\uFFF7\\U00010036\\U00010077", "\\U00010037\\U00010037\\uFFF6\\U00010037" }
1472     };
1473     IcuTestErrorCode errorCode(*this, "BasicNormalizerTest/TestCustomComp");
1474     const Normalizer2 *customNorm2=
1475         Normalizer2::getInstance(loadTestData(errorCode), "testnorm",
1476                                  UNORM2_COMPOSE, errorCode);
1477     if(errorCode.errDataIfFailureAndReset("unable to load testdata/testnorm.nrm")) {
1478         return;
1479     }
1480     for(int32_t i=0; i<UPRV_LENGTHOF(pairs); ++i) {
1481         const StringPair &pair=pairs[i];
1482         UnicodeString input=UnicodeString(pair.input, -1, US_INV).unescape();
1483         UnicodeString expected=UnicodeString(pair.expected, -1, US_INV).unescape();
1484         UnicodeString result=customNorm2->normalize(input, errorCode);
1485         if(result!=expected) {
1486             errln("custom compose Normalizer2 did not normalize input %d as expected", i);
1487         }
1488     }
1489 }
1490 
1491 void
TestCustomFCC()1492 BasicNormalizerTest::TestCustomFCC() {
1493     static const StringPair pairs[]={
1494         // ICU 63 normalization with UCPTrie requires inert surrogate code points.
1495         // { "\\uD801\\uE000\\uDFFE", "" },
1496         // { "\\uD800\\uD801\\uE000\\uDFFE\\uDFFF", "\\uD7FF\\uFFFF" },
1497         // { "\\uD800\\uD801\\uDFFE\\uDFFF", "\\uD7FF\\U000107FE\\uFFFF" },
1498         { "\\uD801\\uE000\\uDFFE", "\\uD801\\uDFFE" },
1499         { "\\uD800\\uD801\\uE000\\uDFFE\\uDFFF", "\\uD800\\uD801\\uDFFE\\uDFFF" },
1500         { "\\uD800\\uD801\\uDFFE\\uDFFF", "\\uD800\\U000107FE\\uDFFF" },
1501 
1502         // The following expected result is different from CustomComp
1503         // because of only-contiguous composition.
1504         { "\\uE001\\U000110B9\\u0345\\u0308\\u0327", "\\uE001\\U000110B9\\u0327\\u0308\\u0345" },
1505         { "\\uE010\\U000F0011\\uE012", "\\uE011\\uE012" },
1506         { "\\uE010\\U000F0011\\U000F0011\\uE012", "\\uE011\\U000F0010" },
1507         { "\\uE111\\u1161\\uE112\\u1162", "\\uAE4C\\u1102\\u0062\\u1162" },
1508         { "\\uFFF3\\uFFF7\\U00010036\\U00010077", "\\U00010037\\U00010037\\uFFF6\\U00010037" }
1509     };
1510     IcuTestErrorCode errorCode(*this, "BasicNormalizerTest/TestCustomFCC");
1511     const Normalizer2 *customNorm2=
1512         Normalizer2::getInstance(loadTestData(errorCode), "testnorm",
1513                                  UNORM2_COMPOSE_CONTIGUOUS, errorCode);
1514     if(errorCode.errDataIfFailureAndReset("unable to load testdata/testnorm.nrm")) {
1515         return;
1516     }
1517     for(int32_t i=0; i<UPRV_LENGTHOF(pairs); ++i) {
1518         const StringPair &pair=pairs[i];
1519         UnicodeString input=UnicodeString(pair.input, -1, US_INV).unescape();
1520         UnicodeString expected=UnicodeString(pair.expected, -1, US_INV).unescape();
1521         UnicodeString result=customNorm2->normalize(input, errorCode);
1522         if(result!=expected) {
1523             errln("custom FCC Normalizer2 did not normalize input %d as expected", i);
1524         }
1525     }
1526 }
1527 
1528 /* Improve code coverage of Normalizer2 */
1529 void
TestFilteredNormalizer2Coverage()1530 BasicNormalizerTest::TestFilteredNormalizer2Coverage() {
1531     UErrorCode errorCode = U_ZERO_ERROR;
1532     const Normalizer2 *nfcNorm2=Normalizer2::getNFCInstance(errorCode);
1533     if (U_FAILURE(errorCode)) {
1534         dataerrln("Normalizer2::getNFCInstance() call failed - %s", u_errorName(errorCode));
1535         return;
1536     }
1537     UnicodeSet filter(UNICODE_STRING_SIMPLE("[^\\u00a0-\\u00ff\\u0310-\\u031f]"), errorCode);
1538     FilteredNormalizer2 fn2(*nfcNorm2, filter);
1539 
1540     UChar32 char32 = 0x0054;
1541 
1542     if (fn2.isInert(char32)) {
1543         errln("FilteredNormalizer2.isInert() failed.");
1544     }
1545 
1546     if (fn2.hasBoundaryAfter(char32)) {
1547         errln("FilteredNormalizer2.hasBoundaryAfter() failed.");
1548     }
1549 
1550     UChar32 c;
1551     for(c=0; c<=0x3ff; ++c) {
1552         uint8_t expectedCC= filter.contains(c) ? nfcNorm2->getCombiningClass(c) : 0;
1553         uint8_t cc=fn2.getCombiningClass(c);
1554         if(cc!=expectedCC) {
1555             errln(
1556                 UnicodeString("FilteredNormalizer2(NFC, ^A0-FF,310-31F).getCombiningClass(U+")+
1557                 hex(c)+
1558                 ")==filtered NFC.getCC()");
1559         }
1560     }
1561 
1562     UnicodeString newString1 = UNICODE_STRING_SIMPLE("[^\\u0100-\\u01ff]");
1563     UnicodeString newString2 = UNICODE_STRING_SIMPLE("[^\\u0200-\\u02ff]");
1564     fn2.append(newString1, newString2, errorCode);
1565     if (U_FAILURE(errorCode)) {
1566         errln("FilteredNormalizer2.append() failed.");
1567     }
1568 }
1569 
1570 void
TestNormalizeUTF8WithEdits()1571 BasicNormalizerTest::TestNormalizeUTF8WithEdits() {
1572     IcuTestErrorCode errorCode(*this, "TestNormalizeUTF8WithEdits");
1573     const Normalizer2 *nfkc_cf=Normalizer2::getNFKCCasefoldInstance(errorCode);
1574     if(errorCode.errDataIfFailureAndReset("Normalizer2::getNFKCCasefoldInstance() call failed")) {
1575         return;
1576     }
1577     static const StringPiece src =
1578         u8"  AÄA\u0308A\u0308\u00ad\u0323Ä\u0323,\u00ad\u1100\u1161가\u11A8가\u3133  ";
1579     StringPiece expected = u8"  aääạ\u0308ạ\u0308,가각갃  ";
1580     std::string result;
1581     StringByteSink<std::string> sink(&result, static_cast<int32_t>(expected.length()));
1582     Edits edits;
1583     nfkc_cf->normalizeUTF8(0, src, sink, &edits, errorCode);
1584     assertSuccess("normalizeUTF8 with Edits", errorCode.get());
1585     assertEquals("normalizeUTF8 with Edits", expected.data(), result.c_str());
1586     static const EditChange expectedChanges[] = {
1587         { FALSE, 2, 2 },  // 2 spaces
1588         { TRUE, 1, 1 },  // A→a
1589         { TRUE, 2, 2 },  // Ä→ä
1590         { TRUE, 3, 2 },  // A\u0308→ä
1591         { TRUE, 7, 5 },  // A\u0308\u00ad\u0323→ạ\u0308 removes the soft hyphen
1592         { TRUE, 4, 5 },  // Ä\u0323→ ạ\u0308
1593         { FALSE, 1, 1 },  // comma
1594         { TRUE, 2, 0 },  // U+00AD soft hyphen maps to empty
1595         { TRUE, 6, 3 },  // \u1100\u1161→ 가
1596         { TRUE, 6, 3 },  // 가\u11A8→ 각
1597         { TRUE, 6, 3 },  // 가\u3133→ 갃
1598         { FALSE, 2, 2 }  // 2 spaces
1599     };
1600     assertTrue("normalizeUTF8 with Edits hasChanges", edits.hasChanges());
1601     assertEquals("normalizeUTF8 with Edits numberOfChanges", 9, edits.numberOfChanges());
1602     TestUtility::checkEditsIter(*this, u"normalizeUTF8 with Edits",
1603             edits.getFineIterator(), edits.getFineIterator(),
1604             expectedChanges, UPRV_LENGTHOF(expectedChanges),
1605             TRUE, errorCode);
1606 
1607     assertFalse("isNormalizedUTF8(source)", nfkc_cf->isNormalizedUTF8(src, errorCode));
1608     assertTrue("isNormalizedUTF8(normalized)", nfkc_cf->isNormalizedUTF8(result, errorCode));
1609 
1610     // Omit unchanged text.
1611     expected = u8"aääạ\u0308ạ\u0308가각갃";
1612     result.clear();
1613     edits.reset();
1614     nfkc_cf->normalizeUTF8(U_OMIT_UNCHANGED_TEXT, src, sink, &edits, errorCode);
1615     assertSuccess("normalizeUTF8 omit unchanged", errorCode.get());
1616     assertEquals("normalizeUTF8 omit unchanged", expected.data(), result.c_str());
1617     assertTrue("normalizeUTF8 omit unchanged hasChanges", edits.hasChanges());
1618     assertEquals("normalizeUTF8 omit unchanged numberOfChanges", 9, edits.numberOfChanges());
1619     TestUtility::checkEditsIter(*this, u"normalizeUTF8 omit unchanged",
1620             edits.getFineIterator(), edits.getFineIterator(),
1621             expectedChanges, UPRV_LENGTHOF(expectedChanges),
1622             TRUE, errorCode);
1623 
1624     // With filter: The normalization code does not see the "A" substrings.
1625     UnicodeSet filter(u"[^A]", errorCode);
1626     FilteredNormalizer2 fn2(*nfkc_cf, filter);
1627     expected = u8"  AäA\u0308A\u0323\u0308ạ\u0308,가각갃  ";
1628     result.clear();
1629     edits.reset();
1630     fn2.normalizeUTF8(0, src, sink, &edits, errorCode);
1631     assertSuccess("filtered normalizeUTF8", errorCode.get());
1632     assertEquals("filtered normalizeUTF8", expected.data(), result.c_str());
1633     static const EditChange filteredChanges[] = {
1634         { FALSE, 3, 3 },  // 2 spaces + A
1635         { TRUE, 2, 2 },  // Ä→ä
1636         { FALSE, 4, 4 },  // A\u0308A
1637         { TRUE, 6, 4 },  // \u0308\u00ad\u0323→\u0323\u0308 removes the soft hyphen
1638         { TRUE, 4, 5 },  // Ä\u0323→ ạ\u0308
1639         { FALSE, 1, 1 },  // comma
1640         { TRUE, 2, 0 },  // U+00AD soft hyphen maps to empty
1641         { TRUE, 6, 3 },  // \u1100\u1161→ 가
1642         { TRUE, 6, 3 },  // 가\u11A8→ 각
1643         { TRUE, 6, 3 },  // 가\u3133→ 갃
1644         { FALSE, 2, 2 }  // 2 spaces
1645     };
1646     assertTrue("filtered normalizeUTF8 hasChanges", edits.hasChanges());
1647     assertEquals("filtered normalizeUTF8 numberOfChanges", 7, edits.numberOfChanges());
1648     TestUtility::checkEditsIter(*this, u"filtered normalizeUTF8",
1649             edits.getFineIterator(), edits.getFineIterator(),
1650             filteredChanges, UPRV_LENGTHOF(filteredChanges),
1651             TRUE, errorCode);
1652 
1653     assertFalse("filtered isNormalizedUTF8(source)", fn2.isNormalizedUTF8(src, errorCode));
1654     assertTrue("filtered isNormalizedUTF8(normalized)", fn2.isNormalizedUTF8(result, errorCode));
1655 
1656     // Omit unchanged text.
1657     // Note that the result is not normalized because the inner normalizer
1658     // does not see text across filter spans.
1659     expected = u8"ä\u0323\u0308ạ\u0308가각갃";
1660     result.clear();
1661     edits.reset();
1662     fn2.normalizeUTF8(U_OMIT_UNCHANGED_TEXT, src, sink, &edits, errorCode);
1663     assertSuccess("filtered normalizeUTF8 omit unchanged", errorCode.get());
1664     assertEquals("filtered normalizeUTF8 omit unchanged", expected.data(), result.c_str());
1665     assertTrue("filtered normalizeUTF8 omit unchanged hasChanges", edits.hasChanges());
1666     assertEquals("filtered normalizeUTF8 omit unchanged numberOfChanges", 7, edits.numberOfChanges());
1667     TestUtility::checkEditsIter(*this, u"filtered normalizeUTF8 omit unchanged",
1668             edits.getFineIterator(), edits.getFineIterator(),
1669             filteredChanges, UPRV_LENGTHOF(filteredChanges),
1670             TRUE, errorCode);
1671 }
1672 
1673 void
TestLowMappingToEmpty_D()1674 BasicNormalizerTest::TestLowMappingToEmpty_D() {
1675     IcuTestErrorCode errorCode(*this, "TestLowMappingToEmpty_D");
1676     const Normalizer2 *n2 = Normalizer2::getInstance(
1677         nullptr, "nfkc_cf", UNORM2_DECOMPOSE, errorCode);
1678     if (errorCode.errDataIfFailureAndReset("Normalizer2::getInstance() call failed")) {
1679         return;
1680     }
1681     checkLowMappingToEmpty(*n2);
1682 
1683     UnicodeString sh(u'\u00AD');
1684     assertFalse("soft hyphen is not normalized", n2->isNormalized(sh, errorCode));
1685     UnicodeString result = n2->normalize(sh, errorCode);
1686     assertTrue("soft hyphen normalizes to empty", result.isEmpty());
1687     assertEquals("soft hyphen QC=No", UNORM_NO, n2->quickCheck(sh, errorCode));
1688     assertEquals("soft hyphen spanQuickCheckYes", 0, n2->spanQuickCheckYes(sh, errorCode));
1689 
1690     UnicodeString s(u"\u00ADÄ\u00AD\u0323");
1691     result = n2->normalize(s, errorCode);
1692     assertEquals("normalize string with soft hyphens", u"a\u0323\u0308", result);
1693 }
1694 
1695 void
TestLowMappingToEmpty_FCD()1696 BasicNormalizerTest::TestLowMappingToEmpty_FCD() {
1697     IcuTestErrorCode errorCode(*this, "TestLowMappingToEmpty_FCD");
1698     const Normalizer2 *n2 = Normalizer2::getInstance(
1699         nullptr, "nfkc_cf", UNORM2_FCD, errorCode);
1700     if (errorCode.errDataIfFailureAndReset("Normalizer2::getInstance() call failed")) {
1701         return;
1702     }
1703     checkLowMappingToEmpty(*n2);
1704 
1705     UnicodeString sh(u'\u00AD');
1706     assertTrue("soft hyphen is FCD", n2->isNormalized(sh, errorCode));
1707 
1708     UnicodeString s(u"\u00ADÄ\u00AD\u0323");
1709     UnicodeString result = n2->normalize(s, errorCode);
1710     assertEquals("normalize string with soft hyphens", u"\u00ADa\u0323\u0308", result);
1711 }
1712 
1713 void
checkLowMappingToEmpty(const Normalizer2 & n2)1714 BasicNormalizerTest::checkLowMappingToEmpty(const Normalizer2 &n2) {
1715     UnicodeString mapping;
1716     assertTrue("getDecomposition(soft hyphen)", n2.getDecomposition(0xad, mapping));
1717     assertTrue("soft hyphen maps to empty", mapping.isEmpty());
1718     assertFalse("soft hyphen has no boundary before", n2.hasBoundaryBefore(0xad));
1719     assertFalse("soft hyphen has no boundary after", n2.hasBoundaryAfter(0xad));
1720     assertFalse("soft hyphen is not inert", n2.isInert(0xad));
1721 }
1722 
1723 void
TestNormalizeIllFormedText()1724 BasicNormalizerTest::TestNormalizeIllFormedText() {
1725     IcuTestErrorCode errorCode(*this, "TestNormalizeIllFormedText");
1726     const Normalizer2 *nfkc_cf = Normalizer2::getNFKCCasefoldInstance(errorCode);
1727     if(errorCode.errDataIfFailureAndReset("Normalizer2::getNFKCCasefoldInstance() call failed")) {
1728         return;
1729     }
1730     // Normalization behavior for ill-formed text is not defined.
1731     // ICU currently treats ill-formed sequences as normalization-inert
1732     // and copies them unchanged.
1733     UnicodeString src(u"  A");
1734     src.append((char16_t)0xD800).append(u"ÄA\u0308").append((char16_t)0xD900).
1735         append(u"A\u0308\u00ad\u0323").append((char16_t)0xDBFF).
1736         append(u"Ä\u0323,\u00ad").append((char16_t)0xDC00).
1737         append(u"\u1100\u1161가\u11A8가\u3133  ").append((char16_t)0xDFFF);
1738     UnicodeString expected(u"  a");
1739     expected.append((char16_t)0xD800).append(u"ää").append((char16_t)0xD900).
1740         append(u"ạ\u0308").append((char16_t)0xDBFF).
1741         append(u"ạ\u0308,").append((char16_t)0xDC00).
1742         append(u"가각갃  ").append((char16_t)0xDFFF);
1743     UnicodeString result = nfkc_cf->normalize(src, errorCode);
1744     assertSuccess("normalize", errorCode.get());
1745     assertEquals("normalize", expected, result);
1746 
1747     std::string src8(reinterpret_cast<const char*>(u8"  A"));
1748     src8.append("\x80").append(reinterpret_cast<const char*>(u8"ÄA\u0308")).append("\xC0\x80").
1749         append(reinterpret_cast<const char*>(u8"A\u0308\u00ad\u0323")).append("\xED\xA0\x80").
1750         append(reinterpret_cast<const char*>(u8"Ä\u0323,\u00ad")).append("\xF4\x90\x80\x80").
1751         append(reinterpret_cast<const char*>(u8"\u1100\u1161가\u11A8가\u3133  ")).append("\xF0");
1752     std::string expected8(reinterpret_cast<const char*>(u8"  a"));
1753     expected8.append("\x80").append(reinterpret_cast<const char*>(u8"ää")).append("\xC0\x80").
1754         append(reinterpret_cast<const char*>(u8"ạ\u0308")).append("\xED\xA0\x80").
1755         append(reinterpret_cast<const char*>(u8"ạ\u0308,")).append("\xF4\x90\x80\x80").
1756         append(reinterpret_cast<const char*>(u8"가각갃  ")).append("\xF0");
1757     std::string result8;
1758     StringByteSink<std::string> sink(&result8);
1759     nfkc_cf->normalizeUTF8(0, src8, sink, nullptr, errorCode);
1760     assertSuccess("normalizeUTF8", errorCode.get());
1761     assertEquals("normalizeUTF8", expected8.c_str(), result8.c_str());
1762 }
1763 
1764 void
TestComposeJamoTBase()1765 BasicNormalizerTest::TestComposeJamoTBase() {
1766     // Algorithmic composition of Hangul syllables must not combine with JAMO_T_BASE = U+11A7
1767     // which is not a conjoining Jamo Trailing consonant.
1768     IcuTestErrorCode errorCode(*this, "TestComposeJamoTBase");
1769     const Normalizer2 *nfkc = Normalizer2::getNFKCInstance(errorCode);
1770     if(errorCode.errDataIfFailureAndReset("Normalizer2::getNFKCInstance() call failed")) {
1771         return;
1772     }
1773     UnicodeString s(u"\u1100\u1161\u11A7\u1100\u314F\u11A7가\u11A7");
1774     UnicodeString expected(u"가\u11A7가\u11A7가\u11A7");
1775     UnicodeString result = nfkc->normalize(s, errorCode);
1776     assertSuccess("normalize(LV+11A7)", errorCode.get());
1777     assertEquals("normalize(LV+11A7)", expected, result);
1778     assertFalse("isNormalized(LV+11A7)", nfkc->isNormalized(s, errorCode));
1779     assertTrue("isNormalized(normalized)", nfkc->isNormalized(result, errorCode));
1780 
1781     StringPiece s8(u8"\u1100\u1161\u11A7\u1100\u314F\u11A7가\u11A7");
1782     StringPiece expected8(u8"가\u11A7가\u11A7가\u11A7");
1783     std::string result8;
1784     StringByteSink<std::string> sink(&result8, expected8.length());
1785     nfkc->normalizeUTF8(0, s8, sink, nullptr, errorCode);
1786     assertSuccess("normalizeUTF8(LV+11A7)", errorCode.get());
1787     assertEquals("normalizeUTF8(LV+11A7)", expected8.data(), result8.c_str());
1788     assertFalse("isNormalizedUTF8(LV+11A7)", nfkc->isNormalizedUTF8(s8, errorCode));
1789     assertTrue("isNormalizedUTF8(normalized)", nfkc->isNormalizedUTF8(result8, errorCode));
1790 }
1791 
1792 void
TestComposeBoundaryAfter()1793 BasicNormalizerTest::TestComposeBoundaryAfter() {
1794     IcuTestErrorCode errorCode(*this, "TestComposeBoundaryAfter");
1795     const Normalizer2 *nfkc = Normalizer2::getNFKCInstance(errorCode);
1796     if(errorCode.errDataIfFailureAndReset("Normalizer2::getNFKCInstance() call failed")) {
1797         return;
1798     }
1799     // U+02DA and U+FB2C do not have compose-boundaries-after.
1800     UnicodeString s(u"\u02DA\u0339 \uFB2C\u05B6");
1801     UnicodeString expected(u" \u0339\u030A \u05E9\u05B6\u05BC\u05C1");
1802     UnicodeString result = nfkc->normalize(s, errorCode);
1803     assertSuccess("nfkc", errorCode.get());
1804     assertEquals("nfkc", expected, result);
1805     assertFalse("U+02DA boundary-after", nfkc->hasBoundaryAfter(0x2DA));
1806     assertFalse("U+FB2C boundary-after", nfkc->hasBoundaryAfter(0xFB2C));
1807 }
1808 
1809 #endif /* #if !UCONFIG_NO_NORMALIZATION */
1810