]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/cpdtrans.cpp
ICU-8.11.4.tar.gz
[apple/icu.git] / icuSources / i18n / cpdtrans.cpp
CommitLineData
b75a7d8f
A
1/*
2**********************************************************************
73c04bcf 3* Copyright (C) 1999-2006, International Business Machines
b75a7d8f
A
4* Corporation and others. All Rights Reserved.
5**********************************************************************
6* Date Name Description
7* 11/17/99 aliu Creation.
8**********************************************************************
9*/
10
11#include "unicode/utypes.h"
12
13#if !UCONFIG_NO_TRANSLITERATION
14
15#include "unicode/unifilt.h"
b75a7d8f
A
16#include "unicode/uniset.h"
17#include "cpdtrans.h"
18#include "uvector.h"
19#include "tridpars.h"
20#include "cmemory.h"
21
22// keep in sync with Transliterator
73c04bcf 23//static const UChar ID_SEP = 0x002D; /*-*/
b75a7d8f
A
24static const UChar ID_DELIM = 0x003B; /*;*/
25static const UChar NEWLINE = 10;
26
27// Empty string
28static const UChar EMPTY[] = {0}; //""
374ca955 29static const UChar COLON_COLON[] = {0x3A, 0x3A, 0}; //"::"
b75a7d8f
A
30
31U_NAMESPACE_BEGIN
32
73c04bcf
A
33const UChar CompoundTransliterator::PASS_STRING[] = { 0x0025, 0x0050, 0x0061, 0x0073, 0x0073, 0 }; // "%Pass"
34
374ca955 35UOBJECT_DEFINE_RTTI_IMPLEMENTATION(CompoundTransliterator)
b75a7d8f
A
36
37/**
38 * Constructs a new compound transliterator given an array of
39 * transliterators. The array of transliterators may be of any
40 * length, including zero or one, however, useful compound
41 * transliterators have at least two components.
42 * @param transliterators array of <code>Transliterator</code>
43 * objects
44 * @param transliteratorCount The number of
45 * <code>Transliterator</code> objects in transliterators.
46 * @param filter the filter. Any character for which
47 * <tt>filter.contains()</tt> returns <tt>false</tt> will not be
48 * altered by this transliterator. If <tt>filter</tt> is
49 * <tt>null</tt> then no filtering is applied.
50 */
51CompoundTransliterator::CompoundTransliterator(
52 Transliterator* const transliterators[],
53 int32_t transliteratorCount,
54 UnicodeFilter* adoptedFilter) :
55 Transliterator(joinIDs(transliterators, transliteratorCount), adoptedFilter),
73c04bcf 56 trans(0), count(0), numAnonymousRBTs(0) {
b75a7d8f
A
57 setTransliterators(transliterators, transliteratorCount);
58}
59
60/**
61 * Splits an ID of the form "ID;ID;..." into a compound using each
62 * of the IDs.
63 * @param id of above form
64 * @param forward if false, does the list in reverse order, and
65 * takes the inverse of each ID.
66 */
67CompoundTransliterator::CompoundTransliterator(const UnicodeString& id,
68 UTransDirection direction,
69 UnicodeFilter* adoptedFilter,
70 UParseError& /*parseError*/,
71 UErrorCode& status) :
72 Transliterator(id, adoptedFilter),
73c04bcf 73 trans(0), numAnonymousRBTs(0) {
b75a7d8f
A
74 // TODO add code for parseError...currently unused, but
75 // later may be used by parsing code...
73c04bcf 76 init(id, direction, TRUE, status);
b75a7d8f
A
77}
78
79CompoundTransliterator::CompoundTransliterator(const UnicodeString& id,
80 UParseError& /*parseError*/,
81 UErrorCode& status) :
82 Transliterator(id, 0), // set filter to 0 here!
73c04bcf 83 trans(0), numAnonymousRBTs(0) {
b75a7d8f
A
84 // TODO add code for parseError...currently unused, but
85 // later may be used by parsing code...
73c04bcf
A
86 init(id, UTRANS_FORWARD, TRUE, status);
87}
88
89
90/**
91 * Private constructor for use of TransliteratorAlias
92 */
93CompoundTransliterator::CompoundTransliterator(const UnicodeString& newID,
94 UVector& list,
95 UnicodeFilter* adoptedFilter,
96 int32_t anonymousRBTs,
97 UParseError& /*parseError*/,
98 UErrorCode& status) :
99 Transliterator(newID, adoptedFilter),
100 trans(0), numAnonymousRBTs(anonymousRBTs)
101{
102 init(list, UTRANS_FORWARD, FALSE, status);
b75a7d8f
A
103}
104
105/**
106 * Private constructor for Transliterator from a vector of
107 * transliterators. The caller is responsible for fixing up the
108 * ID.
109 */
110CompoundTransliterator::CompoundTransliterator(UVector& list,
111 UParseError& /*parseError*/,
112 UErrorCode& status) :
113 Transliterator(EMPTY, NULL),
73c04bcf 114 trans(0), numAnonymousRBTs(0)
b75a7d8f
A
115{
116 // TODO add code for parseError...currently unused, but
117 // later may be used by parsing code...
118 init(list, UTRANS_FORWARD, FALSE, status);
119 // assume caller will fixup ID
120}
121
73c04bcf
A
122CompoundTransliterator::CompoundTransliterator(UVector& list,
123 int32_t anonymousRBTs,
124 UParseError& /*parseError*/,
b75a7d8f 125 UErrorCode& status) :
73c04bcf
A
126 Transliterator(EMPTY, NULL),
127 trans(0), numAnonymousRBTs(anonymousRBTs)
b75a7d8f 128{
73c04bcf 129 init(list, UTRANS_FORWARD, FALSE, status);
b75a7d8f
A
130}
131
132/**
133 * Finish constructing a transliterator: only to be called by
134 * constructors. Before calling init(), set trans and filter to NULL.
135 * @param id the id containing ';'-separated entries
136 * @param direction either FORWARD or REVERSE
137 * @param idSplitPoint the index into id at which the
138 * adoptedSplitTransliterator should be inserted, if there is one, or
139 * -1 if there is none.
140 * @param adoptedSplitTransliterator a transliterator to be inserted
141 * before the entry at offset idSplitPoint in the id string. May be
142 * NULL to insert no entry.
143 * @param fixReverseID if TRUE, then reconstruct the ID of reverse
144 * entries by calling getID() of component entries. Some constructors
145 * do not require this because they apply a facade ID anyway.
146 * @param status the error code indicating success or failure
147 */
148void CompoundTransliterator::init(const UnicodeString& id,
149 UTransDirection direction,
b75a7d8f
A
150 UBool fixReverseID,
151 UErrorCode& status) {
152 // assert(trans == 0);
153
154 if (U_FAILURE(status)) {
b75a7d8f
A
155 return;
156 }
157
158 UVector list(status);
159 UnicodeSet* compoundFilter = NULL;
160 UnicodeString regenID;
161 if (!TransliteratorIDParser::parseCompoundID(id, direction,
162 regenID, list, compoundFilter)) {
163 status = U_INVALID_ID;
b75a7d8f
A
164 delete compoundFilter;
165 return;
166 }
167
73c04bcf 168 TransliteratorIDParser::instantiateList(list, status);
b75a7d8f
A
169
170 init(list, direction, fixReverseID, status);
171
172 if (compoundFilter != NULL) {
173 adoptFilter(compoundFilter);
174 }
175}
176
177/**
178 * Finish constructing a transliterator: only to be called by
179 * constructors. Before calling init(), set trans and filter to NULL.
180 * @param list a vector of transliterator objects to be adopted. It
181 * should NOT be empty. The list should be in declared order. That
182 * is, it should be in the FORWARD order; if direction is REVERSE then
183 * the list order will be reversed.
184 * @param direction either FORWARD or REVERSE
185 * @param fixReverseID if TRUE, then reconstruct the ID of reverse
186 * entries by calling getID() of component entries. Some constructors
187 * do not require this because they apply a facade ID anyway.
188 * @param status the error code indicating success or failure
189 */
190void CompoundTransliterator::init(UVector& list,
191 UTransDirection direction,
192 UBool fixReverseID,
193 UErrorCode& status) {
194 // assert(trans == 0);
195
196 // Allocate array
197 if (U_SUCCESS(status)) {
198 count = list.size();
199 trans = (Transliterator **)uprv_malloc(count * sizeof(Transliterator *));
200 /* test for NULL */
201 if (trans == 0) {
202 status = U_MEMORY_ALLOCATION_ERROR;
203 return;
204 }
205 }
206
207 if (U_FAILURE(status) || trans == 0) {
208 // assert(trans == 0);
209 return;
210 }
211
212 // Move the transliterators from the vector into an array.
213 // Reverse the order if necessary.
214 int32_t i;
215 for (i=0; i<count; ++i) {
216 int32_t j = (direction == UTRANS_FORWARD) ? i : count - 1 - i;
217 trans[i] = (Transliterator*) list.elementAt(j);
218 }
219
b75a7d8f
A
220 // If the direction is UTRANS_REVERSE then we may need to fix the
221 // ID.
222 if (direction == UTRANS_REVERSE && fixReverseID) {
223 UnicodeString newID;
224 for (i=0; i<count; ++i) {
225 if (i > 0) {
226 newID.append(ID_DELIM);
227 }
228 newID.append(trans[i]->getID());
229 }
230 setID(newID);
231 }
232
233 computeMaximumContextLength();
234}
235
236/**
237 * Return the IDs of the given list of transliterators, concatenated
238 * with ID_DELIM delimiting them. Equivalent to the perlish expression
239 * join(ID_DELIM, map($_.getID(), transliterators).
240 */
241UnicodeString CompoundTransliterator::joinIDs(Transliterator* const transliterators[],
242 int32_t transCount) {
243 UnicodeString id;
244 for (int32_t i=0; i<transCount; ++i) {
245 if (i > 0) {
246 id.append(ID_DELIM);
247 }
248 id.append(transliterators[i]->getID());
249 }
250 return id; // Return temporary
251}
252
253/**
254 * Copy constructor.
255 */
256CompoundTransliterator::CompoundTransliterator(const CompoundTransliterator& t) :
73c04bcf 257 Transliterator(t), trans(0), count(0), numAnonymousRBTs(-1) {
b75a7d8f
A
258 *this = t;
259}
260
261/**
262 * Destructor
263 */
264CompoundTransliterator::~CompoundTransliterator() {
265 freeTransliterators();
266}
267
268void CompoundTransliterator::freeTransliterators(void) {
269 if (trans != 0) {
270 for (int32_t i=0; i<count; ++i) {
271 delete trans[i];
272 }
273 uprv_free(trans);
274 }
275 trans = 0;
276 count = 0;
277}
278
279/**
280 * Assignment operator.
281 */
282CompoundTransliterator& CompoundTransliterator::operator=(
283 const CompoundTransliterator& t) {
284 Transliterator::operator=(t);
285 int32_t i;
286 for (i=0; i<count; ++i) {
287 delete trans[i];
288 trans[i] = 0;
289 }
290 if (t.count > count) {
291 uprv_free(trans);
292 trans = (Transliterator **)uprv_malloc(t.count * sizeof(Transliterator *));
293 }
294 count = t.count;
295 for (i=0; i<count; ++i) {
296 trans[i] = t.trans[i]->clone();
297 }
73c04bcf 298 numAnonymousRBTs = t.numAnonymousRBTs;
b75a7d8f
A
299 return *this;
300}
301
302/**
303 * Transliterator API.
304 */
305Transliterator* CompoundTransliterator::clone(void) const {
306 return new CompoundTransliterator(*this);
307}
308
309/**
310 * Returns the number of transliterators in this chain.
311 * @return number of transliterators in this chain.
312 */
313int32_t CompoundTransliterator::getCount(void) const {
314 return count;
315}
316
317/**
318 * Returns the transliterator at the given index in this chain.
319 * @param index index into chain, from 0 to <code>getCount() - 1</code>
320 * @return transliterator at the given index
321 */
322const Transliterator& CompoundTransliterator::getTransliterator(int32_t index) const {
323 return *trans[index];
324}
325
326void CompoundTransliterator::setTransliterators(Transliterator* const transliterators[],
327 int32_t transCount) {
328 Transliterator** a = (Transliterator **)uprv_malloc(transCount * sizeof(Transliterator *));
329 for (int32_t i=0; i<transCount; ++i) {
330 a[i] = transliterators[i]->clone();
331 }
332 adoptTransliterators(a, transCount);
333}
334
335void CompoundTransliterator::adoptTransliterators(Transliterator* adoptedTransliterators[],
336 int32_t transCount) {
337 // First free trans[] and set count to zero. Once this is done,
338 // orphan the filter. Set up the new trans[].
339 freeTransliterators();
340 trans = adoptedTransliterators;
341 count = transCount;
342 computeMaximumContextLength();
343 setID(joinIDs(trans, count));
344}
345
346/**
347 * Append c to buf, unless buf is empty or buf already ends in c.
348 */
349static void _smartAppend(UnicodeString& buf, UChar c) {
350 if (buf.length() != 0 &&
351 buf.charAt(buf.length() - 1) != c) {
352 buf.append(c);
353 }
354}
355
356UnicodeString& CompoundTransliterator::toRules(UnicodeString& rulesSource,
357 UBool escapeUnprintable) const {
358 // We do NOT call toRules() on our component transliterators, in
359 // general. If we have several rule-based transliterators, this
360 // yields a concatenation of the rules -- not what we want. We do
361 // handle compound RBT transliterators specially -- those for which
362 // compoundRBTIndex >= 0. For the transliterator at compoundRBTIndex,
363 // we do call toRules() recursively.
364 rulesSource.truncate(0);
73c04bcf 365 if (numAnonymousRBTs >= 1 && getFilter() != NULL) {
b75a7d8f
A
366 // If we are a compound RBT and if we have a global
367 // filter, then emit it at the top.
368 UnicodeString pat;
374ca955 369 rulesSource.append(COLON_COLON).append(getFilter()->toPattern(pat, escapeUnprintable)).append(ID_DELIM);
b75a7d8f
A
370 }
371 for (int32_t i=0; i<count; ++i) {
372 UnicodeString rule;
73c04bcf
A
373
374 // Anonymous RuleBasedTransliterators (inline rules and
375 // ::BEGIN/::END blocks) are given IDs that begin with
376 // "%Pass": use toRules() to write all the rules to the output
377 // (and insert "::Null;" if we have two in a row)
378 if (trans[i]->getID().startsWith(PASS_STRING)) {
b75a7d8f 379 trans[i]->toRules(rule, escapeUnprintable);
73c04bcf
A
380 if (numAnonymousRBTs > 1 && i > 0 && trans[i - 1]->getID().startsWith(PASS_STRING))
381 rule = UNICODE_STRING_SIMPLE("::Null;") + rule;
382
383 // we also use toRules() on CompoundTransliterators (which we
384 // check for by looking for a semicolon in the ID)-- this gets
385 // the list of their child transliterators output in the right
386 // format
387 } else if (trans[i]->getID().indexOf(ID_DELIM) >= 0) {
388 trans[i]->toRules(rule, escapeUnprintable);
389
390 // for everything else, use Transliterator::toRules()
b75a7d8f
A
391 } else {
392 trans[i]->Transliterator::toRules(rule, escapeUnprintable);
393 }
394 _smartAppend(rulesSource, NEWLINE);
395 rulesSource.append(rule);
396 _smartAppend(rulesSource, ID_DELIM);
397 }
398 return rulesSource;
399}
400
401/**
402 * Implement Transliterator framework
403 */
404void CompoundTransliterator::handleGetSourceSet(UnicodeSet& result) const {
405 UnicodeSet set;
406 result.clear();
407 for (int32_t i=0; i<count; ++i) {
408 result.addAll(trans[i]->getSourceSet(set));
409 // Take the example of Hiragana-Latin. This is really
410 // Hiragana-Katakana; Katakana-Latin. The source set of
411 // these two is roughly [:Hiragana:] and [:Katakana:].
412 // But the source set for the entire transliterator is
413 // actually [:Hiragana:] ONLY -- that is, the first
414 // non-empty source set.
415
416 // This is a heuristic, and not 100% reliable.
417 if (!result.isEmpty()) {
418 break;
419 }
420 }
421}
422
423/**
424 * Override Transliterator framework
425 */
426UnicodeSet& CompoundTransliterator::getTargetSet(UnicodeSet& result) const {
427 UnicodeSet set;
428 result.clear();
429 for (int32_t i=0; i<count; ++i) {
430 // This is a heuristic, and not 100% reliable.
431 result.addAll(trans[i]->getTargetSet(set));
432 }
433 return result;
434}
435
436/**
437 * Implements {@link Transliterator#handleTransliterate}.
438 */
439void CompoundTransliterator::handleTransliterate(Replaceable& text, UTransPosition& index,
440 UBool incremental) const {
441 /* Call each transliterator with the same contextStart and
442 * start, but with the limit as modified
443 * by preceding transliterators. The start index must be
444 * reset for each transliterator to give each a chance to
445 * transliterate the text. The initial contextStart index is known
446 * to still point to the same place after each transliterator
447 * is called because each transliterator will not change the
448 * text between contextStart and the initial start index.
449 *
450 * IMPORTANT: After the first transliterator, each subsequent
451 * transliterator only gets to transliterate text committed by
452 * preceding transliterators; that is, the start (output
453 * value) of transliterator i becomes the limit (input value)
454 * of transliterator i+1. Finally, the overall limit is fixed
455 * up before we return.
456 *
457 * Assumptions we make here:
458 * (1) contextStart <= start <= limit <= contextLimit <= text.length()
459 * (2) start <= start' <= limit' ;cursor doesn't move back
460 * (3) start <= limit' ;text before cursor unchanged
461 * - start' is the value of start after calling handleKT
462 * - limit' is the value of limit after calling handleKT
463 */
464
465 /**
466 * Example: 3 transliterators. This example illustrates the
467 * mechanics we need to implement. C, S, and L are the contextStart,
468 * start, and limit. gl is the globalLimit. contextLimit is
469 * equal to limit throughout.
470 *
471 * 1. h-u, changes hex to Unicode
472 *
473 * 4 7 a d 0 4 7 a
474 * abc/u0061/u => abca/u
475 * C S L C S L gl=f->a
476 *
477 * 2. upup, changes "x" to "XX"
478 *
479 * 4 7 a 4 7 a
480 * abca/u => abcAA/u
481 * C SL C S
482 * L gl=a->b
483 * 3. u-h, changes Unicode to hex
484 *
485 * 4 7 a 4 7 a d 0 3
486 * abcAA/u => abc/u0041/u0041/u
487 * C S L C S
488 * L gl=b->15
489 * 4. return
490 *
491 * 4 7 a d 0 3
492 * abc/u0041/u0041/u
493 * C S L
494 */
495
496 if (count < 1) {
497 index.start = index.limit;
498 return; // Short circuit for empty compound transliterators
499 }
500
501 // compoundLimit is the limit value for the entire compound
502 // operation. We overwrite index.limit with the previous
503 // index.start. After each transliteration, we update
504 // compoundLimit for insertions or deletions that have happened.
505 int32_t compoundLimit = index.limit;
506
507 // compoundStart is the start for the entire compound
508 // operation.
509 int32_t compoundStart = index.start;
510
511 int32_t delta = 0; // delta in length
512
513 // Give each transliterator a crack at the run of characters.
514 // See comments at the top of the method for more detail.
515 for (int32_t i=0; i<count; ++i) {
516 index.start = compoundStart; // Reset start
517 int32_t limit = index.limit;
518
519 if (index.start == index.limit) {
520 // Short circuit for empty range
521 break;
522 }
523
524 trans[i]->filteredTransliterate(text, index, incremental);
525
526 // In a properly written transliterator, start == limit after
527 // handleTransliterate() returns when incremental is false.
528 // Catch cases where the subclass doesn't do this, and throw
529 // an exception. (Just pinning start to limit is a bad idea,
530 // because what's probably happening is that the subclass
531 // isn't transliterating all the way to the end, and it should
532 // in non-incremental mode.)
533 if (!incremental && index.start != index.limit) {
534 // We can't throw an exception, so just fudge things
535 index.start = index.limit;
536 }
537
538 // Cumulative delta for insertions/deletions
539 delta += index.limit - limit;
540
541 if (incremental) {
542 // In the incremental case, only allow subsequent
543 // transliterators to modify what has already been
544 // completely processed by prior transliterators. In the
545 // non-incrmental case, allow each transliterator to
546 // process the entire text.
547 index.limit = index.start;
548 }
549 }
550
551 compoundLimit += delta;
552
553 // Start is good where it is -- where the last transliterator left
554 // it. Limit needs to be put back where it was, modulo
555 // adjustments for deletions/insertions.
556 index.limit = compoundLimit;
557}
558
559/**
560 * Sets the length of the longest context required by this transliterator.
561 * This is <em>preceding</em> context.
562 */
563void CompoundTransliterator::computeMaximumContextLength(void) {
564 int32_t max = 0;
565 for (int32_t i=0; i<count; ++i) {
566 int32_t len = trans[i]->getMaximumContextLength();
567 if (len > max) {
568 max = len;
569 }
570 }
571 setMaximumContextLength(max);
572}
573
574U_NAMESPACE_END
575
576#endif /* #if !UCONFIG_NO_TRANSLITERATION */
577
578/* eof */