intl/icu/source/i18n/rbt_set.cpp

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

michael@0 1 /*
michael@0 2 **********************************************************************
michael@0 3 * Copyright (C) 1999-2011, International Business Machines
michael@0 4 * Corporation and others. All Rights Reserved.
michael@0 5 **********************************************************************
michael@0 6 * Date Name Description
michael@0 7 * 11/17/99 aliu Creation.
michael@0 8 **********************************************************************
michael@0 9 */
michael@0 10
michael@0 11 #include "unicode/utypes.h"
michael@0 12
michael@0 13 #if !UCONFIG_NO_TRANSLITERATION
michael@0 14
michael@0 15 #include "unicode/unistr.h"
michael@0 16 #include "unicode/uniset.h"
michael@0 17 #include "unicode/utf16.h"
michael@0 18 #include "rbt_set.h"
michael@0 19 #include "rbt_rule.h"
michael@0 20 #include "cmemory.h"
michael@0 21 #include "putilimp.h"
michael@0 22
michael@0 23 U_CDECL_BEGIN
michael@0 24 static void U_CALLCONV _deleteRule(void *rule) {
michael@0 25 delete (icu::TransliterationRule *)rule;
michael@0 26 }
michael@0 27 U_CDECL_END
michael@0 28
michael@0 29 //----------------------------------------------------------------------
michael@0 30 // BEGIN Debugging support
michael@0 31 //----------------------------------------------------------------------
michael@0 32
michael@0 33 // #define DEBUG_RBT
michael@0 34
michael@0 35 #ifdef DEBUG_RBT
michael@0 36 #include <stdio.h>
michael@0 37 #include "charstr.h"
michael@0 38
michael@0 39 /**
michael@0 40 * @param appendTo result is appended to this param.
michael@0 41 * @param input the string being transliterated
michael@0 42 * @param pos the index struct
michael@0 43 */
michael@0 44 static UnicodeString& _formatInput(UnicodeString &appendTo,
michael@0 45 const UnicodeString& input,
michael@0 46 const UTransPosition& pos) {
michael@0 47 // Output a string of the form aaa{bbb|ccc|ddd}eee, where
michael@0 48 // the {} indicate the context start and limit, and the ||
michael@0 49 // indicate the start and limit.
michael@0 50 if (0 <= pos.contextStart &&
michael@0 51 pos.contextStart <= pos.start &&
michael@0 52 pos.start <= pos.limit &&
michael@0 53 pos.limit <= pos.contextLimit &&
michael@0 54 pos.contextLimit <= input.length()) {
michael@0 55
michael@0 56 UnicodeString a, b, c, d, e;
michael@0 57 input.extractBetween(0, pos.contextStart, a);
michael@0 58 input.extractBetween(pos.contextStart, pos.start, b);
michael@0 59 input.extractBetween(pos.start, pos.limit, c);
michael@0 60 input.extractBetween(pos.limit, pos.contextLimit, d);
michael@0 61 input.extractBetween(pos.contextLimit, input.length(), e);
michael@0 62 appendTo.append(a).append((UChar)123/*{*/).append(b).
michael@0 63 append((UChar)124/*|*/).append(c).append((UChar)124/*|*/).append(d).
michael@0 64 append((UChar)125/*}*/).append(e);
michael@0 65 } else {
michael@0 66 appendTo.append("INVALID UTransPosition");
michael@0 67 //appendTo.append((UnicodeString)"INVALID UTransPosition {cs=" +
michael@0 68 // pos.contextStart + ", s=" + pos.start + ", l=" +
michael@0 69 // pos.limit + ", cl=" + pos.contextLimit + "} on " +
michael@0 70 // input);
michael@0 71 }
michael@0 72 return appendTo;
michael@0 73 }
michael@0 74
michael@0 75 // Append a hex string to the target
michael@0 76 UnicodeString& _appendHex(uint32_t number,
michael@0 77 int32_t digits,
michael@0 78 UnicodeString& target) {
michael@0 79 static const UChar digitString[] = {
michael@0 80 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
michael@0 81 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0
michael@0 82 };
michael@0 83 while (digits--) {
michael@0 84 target += digitString[(number >> (digits*4)) & 0xF];
michael@0 85 }
michael@0 86 return target;
michael@0 87 }
michael@0 88
michael@0 89 // Replace nonprintable characters with unicode escapes
michael@0 90 UnicodeString& _escape(const UnicodeString &source,
michael@0 91 UnicodeString &target) {
michael@0 92 for (int32_t i = 0; i < source.length(); ) {
michael@0 93 UChar32 ch = source.char32At(i);
michael@0 94 i += U16_LENGTH(ch);
michael@0 95 if (ch < 0x09 || (ch > 0x0A && ch < 0x20)|| ch > 0x7E) {
michael@0 96 if (ch <= 0xFFFF) {
michael@0 97 target += "\\u";
michael@0 98 _appendHex(ch, 4, target);
michael@0 99 } else {
michael@0 100 target += "\\U";
michael@0 101 _appendHex(ch, 8, target);
michael@0 102 }
michael@0 103 } else {
michael@0 104 target += ch;
michael@0 105 }
michael@0 106 }
michael@0 107 return target;
michael@0 108 }
michael@0 109
michael@0 110 inline void _debugOut(const char* msg, TransliterationRule* rule,
michael@0 111 const Replaceable& theText, UTransPosition& pos) {
michael@0 112 UnicodeString buf(msg, "");
michael@0 113 if (rule) {
michael@0 114 UnicodeString r;
michael@0 115 rule->toRule(r, TRUE);
michael@0 116 buf.append((UChar)32).append(r);
michael@0 117 }
michael@0 118 buf.append(UnicodeString(" => ", ""));
michael@0 119 UnicodeString* text = (UnicodeString*)&theText;
michael@0 120 _formatInput(buf, *text, pos);
michael@0 121 UnicodeString esc;
michael@0 122 _escape(buf, esc);
michael@0 123 CharString cbuf(esc);
michael@0 124 printf("%s\n", (const char*) cbuf);
michael@0 125 }
michael@0 126
michael@0 127 #else
michael@0 128 #define _debugOut(msg, rule, theText, pos)
michael@0 129 #endif
michael@0 130
michael@0 131 //----------------------------------------------------------------------
michael@0 132 // END Debugging support
michael@0 133 //----------------------------------------------------------------------
michael@0 134
michael@0 135 // Fill the precontext and postcontext with the patterns of the rules
michael@0 136 // that are masking one another.
michael@0 137 static void maskingError(const icu::TransliterationRule& rule1,
michael@0 138 const icu::TransliterationRule& rule2,
michael@0 139 UParseError& parseError) {
michael@0 140 icu::UnicodeString r;
michael@0 141 int32_t len;
michael@0 142
michael@0 143 parseError.line = parseError.offset = -1;
michael@0 144
michael@0 145 // for pre-context
michael@0 146 rule1.toRule(r, FALSE);
michael@0 147 len = uprv_min(r.length(), U_PARSE_CONTEXT_LEN-1);
michael@0 148 r.extract(0, len, parseError.preContext);
michael@0 149 parseError.preContext[len] = 0;
michael@0 150
michael@0 151 //for post-context
michael@0 152 r.truncate(0);
michael@0 153 rule2.toRule(r, FALSE);
michael@0 154 len = uprv_min(r.length(), U_PARSE_CONTEXT_LEN-1);
michael@0 155 r.extract(0, len, parseError.postContext);
michael@0 156 parseError.postContext[len] = 0;
michael@0 157 }
michael@0 158
michael@0 159 U_NAMESPACE_BEGIN
michael@0 160
michael@0 161 /**
michael@0 162 * Construct a new empty rule set.
michael@0 163 */
michael@0 164 TransliterationRuleSet::TransliterationRuleSet(UErrorCode& status) : UMemory() {
michael@0 165 ruleVector = new UVector(&_deleteRule, NULL, status);
michael@0 166 if (U_FAILURE(status)) {
michael@0 167 return;
michael@0 168 }
michael@0 169 if (ruleVector == NULL) {
michael@0 170 status = U_MEMORY_ALLOCATION_ERROR;
michael@0 171 }
michael@0 172 rules = NULL;
michael@0 173 maxContextLength = 0;
michael@0 174 }
michael@0 175
michael@0 176 /**
michael@0 177 * Copy constructor.
michael@0 178 */
michael@0 179 TransliterationRuleSet::TransliterationRuleSet(const TransliterationRuleSet& other) :
michael@0 180 UMemory(other),
michael@0 181 ruleVector(0),
michael@0 182 rules(0),
michael@0 183 maxContextLength(other.maxContextLength) {
michael@0 184
michael@0 185 int32_t i, len;
michael@0 186 uprv_memcpy(index, other.index, sizeof(index));
michael@0 187 UErrorCode status = U_ZERO_ERROR;
michael@0 188 ruleVector = new UVector(&_deleteRule, NULL, status);
michael@0 189 if (other.ruleVector != 0 && ruleVector != 0 && U_SUCCESS(status)) {
michael@0 190 len = other.ruleVector->size();
michael@0 191 for (i=0; i<len && U_SUCCESS(status); ++i) {
michael@0 192 TransliterationRule *tempTranslitRule = new TransliterationRule(*(TransliterationRule*)other.ruleVector->elementAt(i));
michael@0 193 // Null pointer test
michael@0 194 if (tempTranslitRule == NULL) {
michael@0 195 status = U_MEMORY_ALLOCATION_ERROR;
michael@0 196 break;
michael@0 197 }
michael@0 198 ruleVector->addElement(tempTranslitRule, status);
michael@0 199 if (U_FAILURE(status)) {
michael@0 200 break;
michael@0 201 }
michael@0 202 }
michael@0 203 }
michael@0 204 if (other.rules != 0 && U_SUCCESS(status)) {
michael@0 205 UParseError p;
michael@0 206 freeze(p, status);
michael@0 207 }
michael@0 208 }
michael@0 209
michael@0 210 /**
michael@0 211 * Destructor.
michael@0 212 */
michael@0 213 TransliterationRuleSet::~TransliterationRuleSet() {
michael@0 214 delete ruleVector; // This deletes the contained rules
michael@0 215 uprv_free(rules);
michael@0 216 }
michael@0 217
michael@0 218 void TransliterationRuleSet::setData(const TransliterationRuleData* d) {
michael@0 219 /**
michael@0 220 * We assume that the ruleset has already been frozen.
michael@0 221 */
michael@0 222 int32_t len = index[256]; // see freeze()
michael@0 223 for (int32_t i=0; i<len; ++i) {
michael@0 224 rules[i]->setData(d);
michael@0 225 }
michael@0 226 }
michael@0 227
michael@0 228 /**
michael@0 229 * Return the maximum context length.
michael@0 230 * @return the length of the longest preceding context.
michael@0 231 */
michael@0 232 int32_t TransliterationRuleSet::getMaximumContextLength(void) const {
michael@0 233 return maxContextLength;
michael@0 234 }
michael@0 235
michael@0 236 /**
michael@0 237 * Add a rule to this set. Rules are added in order, and order is
michael@0 238 * significant. The last call to this method must be followed by
michael@0 239 * a call to <code>freeze()</code> before the rule set is used.
michael@0 240 *
michael@0 241 * <p>If freeze() has already been called, calling addRule()
michael@0 242 * unfreezes the rules, and freeze() must be called again.
michael@0 243 *
michael@0 244 * @param adoptedRule the rule to add
michael@0 245 */
michael@0 246 void TransliterationRuleSet::addRule(TransliterationRule* adoptedRule,
michael@0 247 UErrorCode& status) {
michael@0 248 if (U_FAILURE(status)) {
michael@0 249 delete adoptedRule;
michael@0 250 return;
michael@0 251 }
michael@0 252 ruleVector->addElement(adoptedRule, status);
michael@0 253
michael@0 254 int32_t len;
michael@0 255 if ((len = adoptedRule->getContextLength()) > maxContextLength) {
michael@0 256 maxContextLength = len;
michael@0 257 }
michael@0 258
michael@0 259 uprv_free(rules);
michael@0 260 rules = 0;
michael@0 261 }
michael@0 262
michael@0 263 /**
michael@0 264 * Check this for masked rules and index it to optimize performance.
michael@0 265 * The sequence of operations is: (1) add rules to a set using
michael@0 266 * <code>addRule()</code>; (2) freeze the set using
michael@0 267 * <code>freeze()</code>; (3) use the rule set. If
michael@0 268 * <code>addRule()</code> is called after calling this method, it
michael@0 269 * invalidates this object, and this method must be called again.
michael@0 270 * That is, <code>freeze()</code> may be called multiple times,
michael@0 271 * although for optimal performance it shouldn't be.
michael@0 272 */
michael@0 273 void TransliterationRuleSet::freeze(UParseError& parseError,UErrorCode& status) {
michael@0 274 /* Construct the rule array and index table. We reorder the
michael@0 275 * rules by sorting them into 256 bins. Each bin contains all
michael@0 276 * rules matching the index value for that bin. A rule
michael@0 277 * matches an index value if string whose first key character
michael@0 278 * has a low byte equal to the index value can match the rule.
michael@0 279 *
michael@0 280 * Each bin contains zero or more rules, in the same order
michael@0 281 * they were found originally. However, the total rules in
michael@0 282 * the bins may exceed the number in the original vector,
michael@0 283 * since rules that have a variable as their first key
michael@0 284 * character will generally fall into more than one bin.
michael@0 285 *
michael@0 286 * That is, each bin contains all rules that either have that
michael@0 287 * first index value as their first key character, or have
michael@0 288 * a set containing the index value as their first character.
michael@0 289 */
michael@0 290 int32_t n = ruleVector->size();
michael@0 291 int32_t j;
michael@0 292 int16_t x;
michael@0 293 UVector v(2*n, status); // heuristic; adjust as needed
michael@0 294
michael@0 295 if (U_FAILURE(status)) {
michael@0 296 return;
michael@0 297 }
michael@0 298
michael@0 299 /* Precompute the index values. This saves a LOT of time.
michael@0 300 * Be careful not to call malloc(0).
michael@0 301 */
michael@0 302 int16_t* indexValue = (int16_t*) uprv_malloc( sizeof(int16_t) * (n > 0 ? n : 1) );
michael@0 303 /* test for NULL */
michael@0 304 if (indexValue == 0) {
michael@0 305 status = U_MEMORY_ALLOCATION_ERROR;
michael@0 306 return;
michael@0 307 }
michael@0 308 for (j=0; j<n; ++j) {
michael@0 309 TransliterationRule* r = (TransliterationRule*) ruleVector->elementAt(j);
michael@0 310 indexValue[j] = r->getIndexValue();
michael@0 311 }
michael@0 312 for (x=0; x<256; ++x) {
michael@0 313 index[x] = v.size();
michael@0 314 for (j=0; j<n; ++j) {
michael@0 315 if (indexValue[j] >= 0) {
michael@0 316 if (indexValue[j] == x) {
michael@0 317 v.addElement(ruleVector->elementAt(j), status);
michael@0 318 }
michael@0 319 } else {
michael@0 320 // If the indexValue is < 0, then the first key character is
michael@0 321 // a set, and we must use the more time-consuming
michael@0 322 // matchesIndexValue check. In practice this happens
michael@0 323 // rarely, so we seldom tread this code path.
michael@0 324 TransliterationRule* r = (TransliterationRule*) ruleVector->elementAt(j);
michael@0 325 if (r->matchesIndexValue((uint8_t)x)) {
michael@0 326 v.addElement(r, status);
michael@0 327 }
michael@0 328 }
michael@0 329 }
michael@0 330 }
michael@0 331 uprv_free(indexValue);
michael@0 332 index[256] = v.size();
michael@0 333
michael@0 334 /* Freeze things into an array.
michael@0 335 */
michael@0 336 uprv_free(rules); // Contains alias pointers
michael@0 337
michael@0 338 /* You can't do malloc(0)! */
michael@0 339 if (v.size() == 0) {
michael@0 340 rules = NULL;
michael@0 341 return;
michael@0 342 }
michael@0 343 rules = (TransliterationRule **)uprv_malloc(v.size() * sizeof(TransliterationRule *));
michael@0 344 /* test for NULL */
michael@0 345 if (rules == 0) {
michael@0 346 status = U_MEMORY_ALLOCATION_ERROR;
michael@0 347 return;
michael@0 348 }
michael@0 349 for (j=0; j<v.size(); ++j) {
michael@0 350 rules[j] = (TransliterationRule*) v.elementAt(j);
michael@0 351 }
michael@0 352
michael@0 353 // TODO Add error reporting that indicates the rules that
michael@0 354 // are being masked.
michael@0 355 //UnicodeString errors;
michael@0 356
michael@0 357 /* Check for masking. This is MUCH faster than our old check,
michael@0 358 * which was each rule against each following rule, since we
michael@0 359 * only have to check for masking within each bin now. It's
michael@0 360 * 256*O(n2^2) instead of O(n1^2), where n1 is the total rule
michael@0 361 * count, and n2 is the per-bin rule count. But n2<<n1, so
michael@0 362 * it's a big win.
michael@0 363 */
michael@0 364 for (x=0; x<256; ++x) {
michael@0 365 for (j=index[x]; j<index[x+1]-1; ++j) {
michael@0 366 TransliterationRule* r1 = rules[j];
michael@0 367 for (int32_t k=j+1; k<index[x+1]; ++k) {
michael@0 368 TransliterationRule* r2 = rules[k];
michael@0 369 if (r1->masks(*r2)) {
michael@0 370 //| if (errors == null) {
michael@0 371 //| errors = new StringBuffer();
michael@0 372 //| } else {
michael@0 373 //| errors.append("\n");
michael@0 374 //| }
michael@0 375 //| errors.append("Rule " + r1 + " masks " + r2);
michael@0 376 status = U_RULE_MASK_ERROR;
michael@0 377 maskingError(*r1, *r2, parseError);
michael@0 378 return;
michael@0 379 }
michael@0 380 }
michael@0 381 }
michael@0 382 }
michael@0 383
michael@0 384 //if (errors != null) {
michael@0 385 // throw new IllegalArgumentException(errors.toString());
michael@0 386 //}
michael@0 387 }
michael@0 388
michael@0 389 /**
michael@0 390 * Transliterate the given text with the given UTransPosition
michael@0 391 * indices. Return TRUE if the transliteration should continue
michael@0 392 * or FALSE if it should halt (because of a U_PARTIAL_MATCH match).
michael@0 393 * Note that FALSE is only ever returned if isIncremental is TRUE.
michael@0 394 * @param text the text to be transliterated
michael@0 395 * @param pos the position indices, which will be updated
michael@0 396 * @param incremental if TRUE, assume new text may be inserted
michael@0 397 * at index.limit, and return FALSE if thre is a partial match.
michael@0 398 * @return TRUE unless a U_PARTIAL_MATCH has been obtained,
michael@0 399 * indicating that transliteration should stop until more text
michael@0 400 * arrives.
michael@0 401 */
michael@0 402 UBool TransliterationRuleSet::transliterate(Replaceable& text,
michael@0 403 UTransPosition& pos,
michael@0 404 UBool incremental) {
michael@0 405 int16_t indexByte = (int16_t) (text.char32At(pos.start) & 0xFF);
michael@0 406 for (int32_t i=index[indexByte]; i<index[indexByte+1]; ++i) {
michael@0 407 UMatchDegree m = rules[i]->matchAndReplace(text, pos, incremental);
michael@0 408 switch (m) {
michael@0 409 case U_MATCH:
michael@0 410 _debugOut("match", rules[i], text, pos);
michael@0 411 return TRUE;
michael@0 412 case U_PARTIAL_MATCH:
michael@0 413 _debugOut("partial match", rules[i], text, pos);
michael@0 414 return FALSE;
michael@0 415 default: /* Ram: added default to make GCC happy */
michael@0 416 break;
michael@0 417 }
michael@0 418 }
michael@0 419 // No match or partial match from any rule
michael@0 420 pos.start += U16_LENGTH(text.char32At(pos.start));
michael@0 421 _debugOut("no match", NULL, text, pos);
michael@0 422 return TRUE;
michael@0 423 }
michael@0 424
michael@0 425 /**
michael@0 426 * Create rule strings that represents this rule set.
michael@0 427 */
michael@0 428 UnicodeString& TransliterationRuleSet::toRules(UnicodeString& ruleSource,
michael@0 429 UBool escapeUnprintable) const {
michael@0 430 int32_t i;
michael@0 431 int32_t count = ruleVector->size();
michael@0 432 ruleSource.truncate(0);
michael@0 433 for (i=0; i<count; ++i) {
michael@0 434 if (i != 0) {
michael@0 435 ruleSource.append((UChar) 0x000A /*\n*/);
michael@0 436 }
michael@0 437 TransliterationRule *r =
michael@0 438 (TransliterationRule*) ruleVector->elementAt(i);
michael@0 439 r->toRule(ruleSource, escapeUnprintable);
michael@0 440 }
michael@0 441 return ruleSource;
michael@0 442 }
michael@0 443
michael@0 444 /**
michael@0 445 * Return the set of all characters that may be modified
michael@0 446 * (getTarget=false) or emitted (getTarget=true) by this set.
michael@0 447 */
michael@0 448 UnicodeSet& TransliterationRuleSet::getSourceTargetSet(UnicodeSet& result,
michael@0 449 UBool getTarget) const
michael@0 450 {
michael@0 451 result.clear();
michael@0 452 int32_t count = ruleVector->size();
michael@0 453 for (int32_t i=0; i<count; ++i) {
michael@0 454 TransliterationRule* r =
michael@0 455 (TransliterationRule*) ruleVector->elementAt(i);
michael@0 456 if (getTarget) {
michael@0 457 r->addTargetSetTo(result);
michael@0 458 } else {
michael@0 459 r->addSourceSetTo(result);
michael@0 460 }
michael@0 461 }
michael@0 462 return result;
michael@0 463 }
michael@0 464
michael@0 465 U_NAMESPACE_END
michael@0 466
michael@0 467 #endif /* #if !UCONFIG_NO_TRANSLITERATION */

mercurial