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