2 **********************************************************************
3 * Copyright (C) 1999-2008, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Date Name Description
7 * 11/17/99 aliu Creation.
8 **********************************************************************
11 #include "unicode/utypes.h"
13 #if !UCONFIG_NO_TRANSLITERATION
15 #include "unicode/unistr.h"
16 #include "unicode/uniset.h"
23 static void U_CALLCONV
_deleteRule(void *rule
) {
24 delete (U_NAMESPACE_QUALIFIER TransliterationRule
*)rule
;
28 //----------------------------------------------------------------------
29 // BEGIN Debugging support
30 //----------------------------------------------------------------------
39 * @param appendTo result is appended to this param.
40 * @param input the string being transliterated
41 * @param pos the index struct
43 static UnicodeString
& _formatInput(UnicodeString
&appendTo
,
44 const UnicodeString
& input
,
45 const UTransPosition
& pos
) {
46 // Output a string of the form aaa{bbb|ccc|ddd}eee, where
47 // the {} indicate the context start and limit, and the ||
48 // indicate the start and limit.
49 if (0 <= pos
.contextStart
&&
50 pos
.contextStart
<= pos
.start
&&
51 pos
.start
<= pos
.limit
&&
52 pos
.limit
<= pos
.contextLimit
&&
53 pos
.contextLimit
<= input
.length()) {
55 UnicodeString a
, b
, c
, d
, e
;
56 input
.extractBetween(0, pos
.contextStart
, a
);
57 input
.extractBetween(pos
.contextStart
, pos
.start
, b
);
58 input
.extractBetween(pos
.start
, pos
.limit
, c
);
59 input
.extractBetween(pos
.limit
, pos
.contextLimit
, d
);
60 input
.extractBetween(pos
.contextLimit
, input
.length(), e
);
61 appendTo
.append(a
).append((UChar
)123/*{*/).append(b
).
62 append((UChar
)124/*|*/).append(c
).append((UChar
)124/*|*/).append(d
).
63 append((UChar
)125/*}*/).append(e
);
65 appendTo
.append("INVALID UTransPosition");
66 //appendTo.append((UnicodeString)"INVALID UTransPosition {cs=" +
67 // pos.contextStart + ", s=" + pos.start + ", l=" +
68 // pos.limit + ", cl=" + pos.contextLimit + "} on " +
74 // Append a hex string to the target
75 UnicodeString
& _appendHex(uint32_t number
,
77 UnicodeString
& target
) {
78 static const UChar digitString
[] = {
79 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
80 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0
83 target
+= digitString
[(number
>> (digits
*4)) & 0xF];
88 // Replace nonprintable characters with unicode escapes
89 UnicodeString
& _escape(const UnicodeString
&source
,
90 UnicodeString
&target
) {
91 for (int32_t i
= 0; i
< source
.length(); ) {
92 UChar32 ch
= source
.char32At(i
);
93 i
+= UTF_CHAR_LENGTH(ch
);
94 if (ch
< 0x09 || (ch
> 0x0A && ch
< 0x20)|| ch
> 0x7E) {
97 _appendHex(ch
, 4, target
);
100 _appendHex(ch
, 8, target
);
109 inline void _debugOut(const char* msg
, TransliterationRule
* rule
,
110 const Replaceable
& theText
, UTransPosition
& pos
) {
111 UnicodeString
buf(msg
, "");
114 rule
->toRule(r
, TRUE
);
115 buf
.append((UChar
)32).append(r
);
117 buf
.append(UnicodeString(" => ", ""));
118 UnicodeString
* text
= (UnicodeString
*)&theText
;
119 _formatInput(buf
, *text
, pos
);
122 CharString
cbuf(esc
);
123 printf("%s\n", (const char*) cbuf
);
127 #define _debugOut(msg, rule, theText, pos)
130 //----------------------------------------------------------------------
131 // END Debugging support
132 //----------------------------------------------------------------------
134 // Fill the precontext and postcontext with the patterns of the rules
135 // that are masking one another.
136 static void maskingError(const U_NAMESPACE_QUALIFIER TransliterationRule
& rule1
,
137 const U_NAMESPACE_QUALIFIER TransliterationRule
& rule2
,
138 UParseError
& parseError
) {
139 U_NAMESPACE_QUALIFIER UnicodeString r
;
142 parseError
.line
= parseError
.offset
= -1;
145 rule1
.toRule(r
, FALSE
);
146 len
= uprv_min(r
.length(), U_PARSE_CONTEXT_LEN
-1);
147 r
.extract(0, len
, parseError
.preContext
);
148 parseError
.preContext
[len
] = 0;
152 rule2
.toRule(r
, FALSE
);
153 len
= uprv_min(r
.length(), U_PARSE_CONTEXT_LEN
-1);
154 r
.extract(0, len
, parseError
.postContext
);
155 parseError
.postContext
[len
] = 0;
161 * Construct a new empty rule set.
163 TransliterationRuleSet::TransliterationRuleSet(UErrorCode
& status
) : UMemory() {
164 ruleVector
= new UVector(&_deleteRule
, NULL
, status
);
165 if (U_FAILURE(status
)) {
168 if (ruleVector
== NULL
) {
169 status
= U_MEMORY_ALLOCATION_ERROR
;
172 maxContextLength
= 0;
178 TransliterationRuleSet::TransliterationRuleSet(const TransliterationRuleSet
& other
) :
182 maxContextLength(other
.maxContextLength
) {
185 uprv_memcpy(index
, other
.index
, sizeof(index
));
186 UErrorCode status
= U_ZERO_ERROR
;
187 ruleVector
= new UVector(&_deleteRule
, NULL
, status
);
188 if (other
.ruleVector
!= 0 && ruleVector
!= 0 && U_SUCCESS(status
)) {
189 len
= other
.ruleVector
->size();
190 for (i
=0; i
<len
&& U_SUCCESS(status
); ++i
) {
191 TransliterationRule
*tempTranslitRule
= new TransliterationRule(*(TransliterationRule
*)other
.ruleVector
->elementAt(i
));
193 if (tempTranslitRule
== NULL
) {
194 status
= U_MEMORY_ALLOCATION_ERROR
;
197 ruleVector
->addElement(tempTranslitRule
, status
);
198 if (U_FAILURE(status
)) {
203 if (other
.rules
!= 0 && U_SUCCESS(status
)) {
212 TransliterationRuleSet::~TransliterationRuleSet() {
213 delete ruleVector
; // This deletes the contained rules
217 void TransliterationRuleSet::setData(const TransliterationRuleData
* d
) {
219 * We assume that the ruleset has already been frozen.
221 int32_t len
= index
[256]; // see freeze()
222 for (int32_t i
=0; i
<len
; ++i
) {
223 rules
[i
]->setData(d
);
228 * Return the maximum context length.
229 * @return the length of the longest preceding context.
231 int32_t TransliterationRuleSet::getMaximumContextLength(void) const {
232 return maxContextLength
;
236 * Add a rule to this set. Rules are added in order, and order is
237 * significant. The last call to this method must be followed by
238 * a call to <code>freeze()</code> before the rule set is used.
240 * <p>If freeze() has already been called, calling addRule()
241 * unfreezes the rules, and freeze() must be called again.
243 * @param adoptedRule the rule to add
245 void TransliterationRuleSet::addRule(TransliterationRule
* adoptedRule
,
246 UErrorCode
& status
) {
247 if (U_FAILURE(status
)) {
251 ruleVector
->addElement(adoptedRule
, status
);
254 if ((len
= adoptedRule
->getContextLength()) > maxContextLength
) {
255 maxContextLength
= len
;
263 * Check this for masked rules and index it to optimize performance.
264 * The sequence of operations is: (1) add rules to a set using
265 * <code>addRule()</code>; (2) freeze the set using
266 * <code>freeze()</code>; (3) use the rule set. If
267 * <code>addRule()</code> is called after calling this method, it
268 * invalidates this object, and this method must be called again.
269 * That is, <code>freeze()</code> may be called multiple times,
270 * although for optimal performance it shouldn't be.
272 void TransliterationRuleSet::freeze(UParseError
& parseError
,UErrorCode
& status
) {
273 /* Construct the rule array and index table. We reorder the
274 * rules by sorting them into 256 bins. Each bin contains all
275 * rules matching the index value for that bin. A rule
276 * matches an index value if string whose first key character
277 * has a low byte equal to the index value can match the rule.
279 * Each bin contains zero or more rules, in the same order
280 * they were found originally. However, the total rules in
281 * the bins may exceed the number in the original vector,
282 * since rules that have a variable as their first key
283 * character will generally fall into more than one bin.
285 * That is, each bin contains all rules that either have that
286 * first index value as their first key character, or have
287 * a set containing the index value as their first character.
289 int32_t n
= ruleVector
->size();
292 UVector
v(2*n
, status
); // heuristic; adjust as needed
294 if (U_FAILURE(status
)) {
298 /* Precompute the index values. This saves a LOT of time.
299 * Be careful not to call malloc(0).
301 int16_t* indexValue
= (int16_t*) uprv_malloc( sizeof(int16_t) * (n
> 0 ? n
: 1) );
303 if (indexValue
== 0) {
304 status
= U_MEMORY_ALLOCATION_ERROR
;
307 for (j
=0; j
<n
; ++j
) {
308 TransliterationRule
* r
= (TransliterationRule
*) ruleVector
->elementAt(j
);
309 indexValue
[j
] = r
->getIndexValue();
311 for (x
=0; x
<256; ++x
) {
313 for (j
=0; j
<n
; ++j
) {
314 if (indexValue
[j
] >= 0) {
315 if (indexValue
[j
] == x
) {
316 v
.addElement(ruleVector
->elementAt(j
), status
);
319 // If the indexValue is < 0, then the first key character is
320 // a set, and we must use the more time-consuming
321 // matchesIndexValue check. In practice this happens
322 // rarely, so we seldom tread this code path.
323 TransliterationRule
* r
= (TransliterationRule
*) ruleVector
->elementAt(j
);
324 if (r
->matchesIndexValue((uint8_t)x
)) {
325 v
.addElement(r
, status
);
330 uprv_free(indexValue
);
331 index
[256] = v
.size();
333 /* Freeze things into an array.
335 uprv_free(rules
); // Contains alias pointers
337 /* You can't do malloc(0)! */
342 rules
= (TransliterationRule
**)uprv_malloc(v
.size() * sizeof(TransliterationRule
*));
345 status
= U_MEMORY_ALLOCATION_ERROR
;
348 for (j
=0; j
<v
.size(); ++j
) {
349 rules
[j
] = (TransliterationRule
*) v
.elementAt(j
);
352 // TODO Add error reporting that indicates the rules that
354 //UnicodeString errors;
356 /* Check for masking. This is MUCH faster than our old check,
357 * which was each rule against each following rule, since we
358 * only have to check for masking within each bin now. It's
359 * 256*O(n2^2) instead of O(n1^2), where n1 is the total rule
360 * count, and n2 is the per-bin rule count. But n2<<n1, so
363 for (x
=0; x
<256; ++x
) {
364 for (j
=index
[x
]; j
<index
[x
+1]-1; ++j
) {
365 TransliterationRule
* r1
= rules
[j
];
366 for (int32_t k
=j
+1; k
<index
[x
+1]; ++k
) {
367 TransliterationRule
* r2
= rules
[k
];
368 if (r1
->masks(*r2
)) {
369 //| if (errors == null) {
370 //| errors = new StringBuffer();
372 //| errors.append("\n");
374 //| errors.append("Rule " + r1 + " masks " + r2);
375 status
= U_RULE_MASK_ERROR
;
376 maskingError(*r1
, *r2
, parseError
);
383 //if (errors != null) {
384 // throw new IllegalArgumentException(errors.toString());
389 * Transliterate the given text with the given UTransPosition
390 * indices. Return TRUE if the transliteration should continue
391 * or FALSE if it should halt (because of a U_PARTIAL_MATCH match).
392 * Note that FALSE is only ever returned if isIncremental is TRUE.
393 * @param text the text to be transliterated
394 * @param pos the position indices, which will be updated
395 * @param incremental if TRUE, assume new text may be inserted
396 * at index.limit, and return FALSE if thre is a partial match.
397 * @return TRUE unless a U_PARTIAL_MATCH has been obtained,
398 * indicating that transliteration should stop until more text
401 UBool
TransliterationRuleSet::transliterate(Replaceable
& text
,
404 int16_t indexByte
= (int16_t) (text
.char32At(pos
.start
) & 0xFF);
405 for (int32_t i
=index
[indexByte
]; i
<index
[indexByte
+1]; ++i
) {
406 UMatchDegree m
= rules
[i
]->matchAndReplace(text
, pos
, incremental
);
409 _debugOut("match", rules
[i
], text
, pos
);
411 case U_PARTIAL_MATCH
:
412 _debugOut("partial match", rules
[i
], text
, pos
);
414 default: /* Ram: added default to make GCC happy */
418 // No match or partial match from any rule
419 pos
.start
+= UTF_CHAR_LENGTH(text
.char32At(pos
.start
));
420 _debugOut("no match", NULL
, text
, pos
);
425 * Create rule strings that represents this rule set.
427 UnicodeString
& TransliterationRuleSet::toRules(UnicodeString
& ruleSource
,
428 UBool escapeUnprintable
) const {
430 int32_t count
= ruleVector
->size();
431 ruleSource
.truncate(0);
432 for (i
=0; i
<count
; ++i
) {
434 ruleSource
.append((UChar
) 0x000A /*\n*/);
436 TransliterationRule
*r
=
437 (TransliterationRule
*) ruleVector
->elementAt(i
);
438 r
->toRule(ruleSource
, escapeUnprintable
);
444 * Return the set of all characters that may be modified
445 * (getTarget=false) or emitted (getTarget=true) by this set.
447 UnicodeSet
& TransliterationRuleSet::getSourceTargetSet(UnicodeSet
& result
,
448 UBool getTarget
) const
451 int32_t count
= ruleVector
->size();
452 for (int32_t i
=0; i
<count
; ++i
) {
453 TransliterationRule
* r
=
454 (TransliterationRule
*) ruleVector
->elementAt(i
);
456 r
->addTargetSetTo(result
);
458 r
->addSourceSetTo(result
);
466 #endif /* #if !UCONFIG_NO_TRANSLITERATION */