1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 **********************************************************************
5 * Copyright (c) 2001-2014, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 * Date Name Description
9 * 08/10/2001 aliu Creation.
10 **********************************************************************
11 */
12
13 #include "unicode/utypes.h"
14
15 #if !UCONFIG_NO_TRANSLITERATION
16
17 #include "unicode/translit.h"
18 #include "unicode/resbund.h"
19 #include "unicode/uniset.h"
20 #include "unicode/uscript.h"
21 #include "rbt.h"
22 #include "cpdtrans.h"
23 #include "nultrans.h"
24 #include "transreg.h"
25 #include "rbt_data.h"
26 #include "rbt_pars.h"
27 #include "tridpars.h"
28 #include "charstr.h"
29 #include "uassert.h"
30 #include "locutil.h"
31
32 // Enable the following symbol to add debugging code that tracks the
33 // allocation, deletion, and use of Entry objects. BoundsChecker has
34 // reported dangling pointer errors with these objects, but I have
35 // been unable to confirm them. I suspect BoundsChecker is getting
36 // confused with pointers going into and coming out of a UHashtable,
37 // despite the hinting code that is designed to help it.
38 // #define DEBUG_MEM
39 #ifdef DEBUG_MEM
40 #include <stdio.h>
41 #endif
42
43 // char16_t constants
44 static const char16_t LOCALE_SEP = 95; // '_'
45 //static const char16_t ID_SEP = 0x002D; /*-*/
46 //static const char16_t VARIANT_SEP = 0x002F; // '/'
47
48 // String constants
49 static const char16_t ANY[] = { 0x41, 0x6E, 0x79, 0 }; // Any
50 static const char16_t LAT[] = { 0x4C, 0x61, 0x74, 0 }; // Lat
51
52 // empty string
53 #define NO_VARIANT UnicodeString()
54
55 // initial estimate for specDAG size
56 // ICU 60 Transliterator::countAvailableSources()
57 #define SPECDAG_INIT_SIZE 149
58
59 // initial estimate for number of variant names
60 #define VARIANT_LIST_INIT_SIZE 11
61 #define VARIANT_LIST_MAX_SIZE 31
62
63 // initial estimate for availableIDs count (default estimate is 8 => multiple reallocs)
64 // ICU 60 Transliterator::countAvailableIDs()
65 #define AVAILABLE_IDS_INIT_SIZE 641
66
67 // initial estimate for number of targets for source "Any", "Lat"
68 // ICU 60 Transliterator::countAvailableTargets("Any")/("Latn")
69 #define ANY_TARGETS_INIT_SIZE 125
70 #define LAT_TARGETS_INIT_SIZE 23
71
72 /**
73 * Resource bundle key for the RuleBasedTransliterator rule.
74 */
75 //static const char RB_RULE[] = "Rule";
76
77 U_NAMESPACE_BEGIN
78
79 //------------------------------------------------------------------
80 // Alias
81 //------------------------------------------------------------------
82
TransliteratorAlias(const UnicodeString & theAliasID,const UnicodeSet * cpdFilter)83 TransliteratorAlias::TransliteratorAlias(const UnicodeString& theAliasID,
84 const UnicodeSet* cpdFilter) :
85 ID(),
86 aliasesOrRules(theAliasID),
87 transes(0),
88 compoundFilter(cpdFilter),
89 direction(UTRANS_FORWARD),
90 type(TransliteratorAlias::SIMPLE) {
91 }
92
TransliteratorAlias(const UnicodeString & theID,const UnicodeString & idBlocks,UVector * adoptedTransliterators,const UnicodeSet * cpdFilter)93 TransliteratorAlias::TransliteratorAlias(const UnicodeString& theID,
94 const UnicodeString& idBlocks,
95 UVector* adoptedTransliterators,
96 const UnicodeSet* cpdFilter) :
97 ID(theID),
98 aliasesOrRules(idBlocks),
99 transes(adoptedTransliterators),
100 compoundFilter(cpdFilter),
101 direction(UTRANS_FORWARD),
102 type(TransliteratorAlias::COMPOUND) {
103 }
104
TransliteratorAlias(const UnicodeString & theID,const UnicodeString & rules,UTransDirection dir)105 TransliteratorAlias::TransliteratorAlias(const UnicodeString& theID,
106 const UnicodeString& rules,
107 UTransDirection dir) :
108 ID(theID),
109 aliasesOrRules(rules),
110 transes(0),
111 compoundFilter(0),
112 direction(dir),
113 type(TransliteratorAlias::RULES) {
114 }
115
~TransliteratorAlias()116 TransliteratorAlias::~TransliteratorAlias() {
117 delete transes;
118 }
119
120
create(UParseError & pe,UErrorCode & ec)121 Transliterator* TransliteratorAlias::create(UParseError& pe,
122 UErrorCode& ec) {
123 if (U_FAILURE(ec)) {
124 return 0;
125 }
126 Transliterator *t = nullptr;
127 switch (type) {
128 case SIMPLE:
129 t = Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec);
130 if(U_FAILURE(ec)){
131 return 0;
132 }
133 if (compoundFilter != 0)
134 t->adoptFilter(compoundFilter->clone());
135 break;
136 case COMPOUND:
137 {
138 // the total number of transliterators in the compound is the total number of anonymous transliterators
139 // plus the total number of ID blocks-- we start by assuming the list begins and ends with an ID
140 // block and that each pair anonymous transliterators has an ID block between them. Then we go back
141 // to see whether there really are ID blocks at the beginning and end (by looking for U+FFFF, which
142 // marks the position where an anonymous transliterator goes) and adjust accordingly
143 int32_t anonymousRBTs = transes->size();
144 UnicodeString noIDBlock((char16_t)(0xffff));
145 noIDBlock += ((char16_t)(0xffff));
146 int32_t pos = aliasesOrRules.indexOf(noIDBlock);
147 while (pos >= 0) {
148 pos = aliasesOrRules.indexOf(noIDBlock, pos + 1);
149 }
150
151 UVector transliterators(uprv_deleteUObject, nullptr, ec);
152 UnicodeString idBlock;
153 int32_t blockSeparatorPos = aliasesOrRules.indexOf((char16_t)(0xffff));
154 while (blockSeparatorPos >= 0) {
155 aliasesOrRules.extract(0, blockSeparatorPos, idBlock);
156 aliasesOrRules.remove(0, blockSeparatorPos + 1);
157 if (!idBlock.isEmpty())
158 transliterators.adoptElement(Transliterator::createInstance(idBlock, UTRANS_FORWARD, pe, ec), ec);
159 if (!transes->isEmpty())
160 transliterators.adoptElement(transes->orphanElementAt(0), ec);
161 blockSeparatorPos = aliasesOrRules.indexOf((char16_t)(0xffff));
162 }
163 if (!aliasesOrRules.isEmpty())
164 transliterators.adoptElement(Transliterator::createInstance(aliasesOrRules, UTRANS_FORWARD, pe, ec), ec);
165 while (!transes->isEmpty())
166 transliterators.adoptElement(transes->orphanElementAt(0), ec);
167 transliterators.setDeleter(nullptr);
168
169 if (U_SUCCESS(ec)) {
170 t = new CompoundTransliterator(ID, transliterators,
171 (compoundFilter ? compoundFilter->clone() : nullptr),
172 anonymousRBTs, pe, ec);
173 if (t == 0) {
174 ec = U_MEMORY_ALLOCATION_ERROR;
175 return 0;
176 }
177 } else {
178 for (int32_t i = 0; i < transliterators.size(); i++)
179 delete (Transliterator*)(transliterators.elementAt(i));
180 }
181 }
182 break;
183 case RULES:
184 UPRV_UNREACHABLE_EXIT; // don't call create() if isRuleBased() returns true!
185 }
186 return t;
187 }
188
isRuleBased() const189 UBool TransliteratorAlias::isRuleBased() const {
190 return type == RULES;
191 }
192
parse(TransliteratorParser & parser,UParseError & pe,UErrorCode & ec) const193 void TransliteratorAlias::parse(TransliteratorParser& parser,
194 UParseError& pe, UErrorCode& ec) const {
195 U_ASSERT(type == RULES);
196 if (U_FAILURE(ec)) {
197 return;
198 }
199
200 parser.parse(aliasesOrRules, direction, pe, ec);
201 }
202
203 //----------------------------------------------------------------------
204 // class TransliteratorSpec
205 //----------------------------------------------------------------------
206
207 /**
208 * A TransliteratorSpec is a string specifying either a source or a target. In more
209 * general terms, it may also specify a variant, but we only use the
210 * Spec class for sources and targets.
211 *
212 * A Spec may be a locale or a script. If it is a locale, it has a
213 * fallback chain that goes xx_YY_ZZZ -> xx_YY -> xx -> ssss, where
214 * ssss is the script mapping of xx_YY_ZZZ. The Spec API methods
215 * hasFallback(), next(), and reset() iterate over this fallback
216 * sequence.
217 *
218 * The Spec class canonicalizes itself, so the locale is put into
219 * canonical form, or the script is transformed from an abbreviation
220 * to a full name.
221 */
222 class TransliteratorSpec : public UMemory {
223 public:
224 TransliteratorSpec(const UnicodeString& spec);
225 ~TransliteratorSpec();
226
227 const UnicodeString& get() const;
228 UBool hasFallback() const;
229 const UnicodeString& next();
230 void reset();
231
232 UBool isLocale() const;
233 ResourceBundle& getBundle() const;
234
operator const UnicodeString&() const235 operator const UnicodeString&() const { return get(); }
getTop() const236 const UnicodeString& getTop() const { return top; }
237
238 private:
239 void setupNext();
240
241 UnicodeString top;
242 UnicodeString spec;
243 UnicodeString nextSpec;
244 UnicodeString scriptName;
245 UBool isSpecLocale; // true if spec is a locale
246 UBool isNextLocale; // true if nextSpec is a locale
247 ResourceBundle* res;
248
249 TransliteratorSpec(const TransliteratorSpec &other); // forbid copying of this class
250 TransliteratorSpec &operator=(const TransliteratorSpec &other); // forbid copying of this class
251 };
252
TransliteratorSpec(const UnicodeString & theSpec)253 TransliteratorSpec::TransliteratorSpec(const UnicodeString& theSpec)
254 : top(theSpec),
255 res(0)
256 {
257 UErrorCode status = U_ZERO_ERROR;
258 Locale topLoc("");
259 LocaleUtility::initLocaleFromName(theSpec, topLoc);
260 if (!topLoc.isBogus()) {
261 res = new ResourceBundle(U_ICUDATA_TRANSLIT, topLoc, status);
262 /* test for nullptr */
263 if (res == 0) {
264 return;
265 }
266 if (U_FAILURE(status) || status == U_USING_DEFAULT_WARNING) {
267 delete res;
268 res = 0;
269 }
270 }
271
272 // Canonicalize script name -or- do locale->script mapping
273 status = U_ZERO_ERROR;
274 static const int32_t capacity = 10;
275 UScriptCode script[capacity]={USCRIPT_INVALID_CODE};
276 int32_t num = uscript_getCode(CharString().appendInvariantChars(theSpec, status).data(),
277 script, capacity, &status);
278 if (num > 0 && script[0] != USCRIPT_INVALID_CODE) {
279 scriptName = UnicodeString(uscript_getName(script[0]), -1, US_INV);
280 }
281
282 // Canonicalize top
283 if (res != 0) {
284 // Canonicalize locale name
285 UnicodeString locStr;
286 LocaleUtility::initNameFromLocale(topLoc, locStr);
287 if (!locStr.isBogus()) {
288 top = locStr;
289 }
290 } else if (scriptName.length() != 0) {
291 // We are a script; use canonical name
292 top = scriptName;
293 }
294
295 // assert(spec != top);
296 reset();
297 }
298
~TransliteratorSpec()299 TransliteratorSpec::~TransliteratorSpec() {
300 delete res;
301 }
302
hasFallback() const303 UBool TransliteratorSpec::hasFallback() const {
304 return nextSpec.length() != 0;
305 }
306
reset()307 void TransliteratorSpec::reset() {
308 if (spec != top) {
309 spec = top;
310 isSpecLocale = (res != 0);
311 setupNext();
312 }
313 }
314
setupNext()315 void TransliteratorSpec::setupNext() {
316 isNextLocale = false;
317 if (isSpecLocale) {
318 nextSpec = spec;
319 int32_t i = nextSpec.lastIndexOf(LOCALE_SEP);
320 // If i == 0 then we have _FOO, so we fall through
321 // to the scriptName.
322 if (i > 0) {
323 nextSpec.truncate(i);
324 isNextLocale = true;
325 } else {
326 nextSpec = scriptName; // scriptName may be empty
327 }
328 } else {
329 // spec is a script, so we are at the end
330 nextSpec.truncate(0);
331 }
332 }
333
334 // Protocol:
335 // for(const UnicodeString& s(spec.get());
336 // spec.hasFallback(); s(spec.next())) { ...
337
next()338 const UnicodeString& TransliteratorSpec::next() {
339 spec = nextSpec;
340 isSpecLocale = isNextLocale;
341 setupNext();
342 return spec;
343 }
344
get() const345 const UnicodeString& TransliteratorSpec::get() const {
346 return spec;
347 }
348
isLocale() const349 UBool TransliteratorSpec::isLocale() const {
350 return isSpecLocale;
351 }
352
getBundle() const353 ResourceBundle& TransliteratorSpec::getBundle() const {
354 return *res;
355 }
356
357 //----------------------------------------------------------------------
358
359 #ifdef DEBUG_MEM
360
361 // Vector of Entry pointers currently in use
362 static UVector* DEBUG_entries = nullptr;
363
DEBUG_setup()364 static void DEBUG_setup() {
365 if (DEBUG_entries == nullptr) {
366 UErrorCode ec = U_ZERO_ERROR;
367 DEBUG_entries = new UVector(ec);
368 }
369 }
370
371 // Caller must call DEBUG_setup first. Return index of given Entry,
372 // if it is in use (not deleted yet), or -1 if not found.
DEBUG_findEntry(TransliteratorEntry * e)373 static int DEBUG_findEntry(TransliteratorEntry* e) {
374 for (int i=0; i<DEBUG_entries->size(); ++i) {
375 if (e == (TransliteratorEntry*) DEBUG_entries->elementAt(i)) {
376 return i;
377 }
378 }
379 return -1;
380 }
381
382 // Track object creation
DEBUG_newEntry(TransliteratorEntry * e)383 static void DEBUG_newEntry(TransliteratorEntry* e) {
384 DEBUG_setup();
385 if (DEBUG_findEntry(e) >= 0) {
386 // This should really never happen unless the heap is broken
387 printf("ERROR DEBUG_newEntry duplicate new pointer %08X\n", e);
388 return;
389 }
390 UErrorCode ec = U_ZERO_ERROR;
391 DEBUG_entries->addElement(e, ec);
392 }
393
394 // Track object deletion
DEBUG_delEntry(TransliteratorEntry * e)395 static void DEBUG_delEntry(TransliteratorEntry* e) {
396 DEBUG_setup();
397 int i = DEBUG_findEntry(e);
398 if (i < 0) {
399 printf("ERROR DEBUG_delEntry possible double deletion %08X\n", e);
400 return;
401 }
402 DEBUG_entries->removeElementAt(i);
403 }
404
405 // Track object usage
DEBUG_useEntry(TransliteratorEntry * e)406 static void DEBUG_useEntry(TransliteratorEntry* e) {
407 if (e == nullptr) return;
408 DEBUG_setup();
409 int i = DEBUG_findEntry(e);
410 if (i < 0) {
411 printf("ERROR DEBUG_useEntry possible dangling pointer %08X\n", e);
412 }
413 }
414
415 #else
416 // If we're not debugging then make these macros into NOPs
417 #define DEBUG_newEntry(x)
418 #define DEBUG_delEntry(x)
419 #define DEBUG_useEntry(x)
420 #endif
421
422 //----------------------------------------------------------------------
423 // class Entry
424 //----------------------------------------------------------------------
425
426 /**
427 * The Entry object stores objects of different types and
428 * singleton objects as placeholders for rule-based transliterators to
429 * be built as needed. Instances of this struct can be placeholders,
430 * can represent prototype transliterators to be cloned, or can
431 * represent TransliteratorData objects. We don't support storing
432 * classes in the registry because we don't have the rtti infrastructure
433 * for it. We could easily add this if there is a need for it in the
434 * future.
435 */
436 class TransliteratorEntry : public UMemory {
437 public:
438 enum Type {
439 RULES_FORWARD,
440 RULES_REVERSE,
441 LOCALE_RULES,
442 PROTOTYPE,
443 RBT_DATA,
444 COMPOUND_RBT,
445 ALIAS,
446 FACTORY,
447 NONE // Only used for uninitialized entries
448 } entryType;
449 // NOTE: stringArg cannot go inside the union because
450 // it has a copy constructor
451 UnicodeString stringArg; // For RULES_*, ALIAS, COMPOUND_RBT
452 int32_t intArg; // For COMPOUND_RBT, LOCALE_RULES
453 UnicodeSet* compoundFilter; // For COMPOUND_RBT
454 union {
455 Transliterator* prototype; // For PROTOTYPE
456 TransliterationRuleData* data; // For RBT_DATA
457 UVector* dataVector; // For COMPOUND_RBT
458 struct {
459 Transliterator::Factory function;
460 Transliterator::Token context;
461 } factory; // For FACTORY
462 } u;
463 TransliteratorEntry();
464 ~TransliteratorEntry();
465 void adoptPrototype(Transliterator* adopted);
466 void setFactory(Transliterator::Factory factory,
467 Transliterator::Token context);
468
469 private:
470
471 TransliteratorEntry(const TransliteratorEntry &other); // forbid copying of this class
472 TransliteratorEntry &operator=(const TransliteratorEntry &other); // forbid copying of this class
473 };
474
TransliteratorEntry()475 TransliteratorEntry::TransliteratorEntry() {
476 u.prototype = 0;
477 compoundFilter = nullptr;
478 entryType = NONE;
479 DEBUG_newEntry(this);
480 }
481
~TransliteratorEntry()482 TransliteratorEntry::~TransliteratorEntry() {
483 DEBUG_delEntry(this);
484 if (entryType == PROTOTYPE) {
485 delete u.prototype;
486 } else if (entryType == RBT_DATA) {
487 // The data object is shared between instances of RBT. The
488 // entry object owns it. It should only be deleted when the
489 // transliterator component is being cleaned up. Doing so
490 // invalidates any RBTs that the user has instantiated.
491 delete u.data;
492 } else if (entryType == COMPOUND_RBT) {
493 while (u.dataVector != nullptr && !u.dataVector->isEmpty())
494 delete (TransliterationRuleData*)u.dataVector->orphanElementAt(0);
495 delete u.dataVector;
496 }
497 delete compoundFilter;
498 }
499
adoptPrototype(Transliterator * adopted)500 void TransliteratorEntry::adoptPrototype(Transliterator* adopted) {
501 if (entryType == PROTOTYPE) {
502 delete u.prototype;
503 }
504 entryType = PROTOTYPE;
505 u.prototype = adopted;
506 }
507
setFactory(Transliterator::Factory factory,Transliterator::Token context)508 void TransliteratorEntry::setFactory(Transliterator::Factory factory,
509 Transliterator::Token context) {
510 if (entryType == PROTOTYPE) {
511 delete u.prototype;
512 }
513 entryType = FACTORY;
514 u.factory.function = factory;
515 u.factory.context = context;
516 }
517
518 // UObjectDeleter for Hashtable::setValueDeleter
519 U_CDECL_BEGIN
520 static void U_CALLCONV
deleteEntry(void * obj)521 deleteEntry(void* obj) {
522 delete (TransliteratorEntry*) obj;
523 }
524 U_CDECL_END
525
526 //----------------------------------------------------------------------
527 // class TransliteratorRegistry: Basic public API
528 //----------------------------------------------------------------------
529
TransliteratorRegistry(UErrorCode & status)530 TransliteratorRegistry::TransliteratorRegistry(UErrorCode& status) :
531 registry(true, status),
532 specDAG(true, SPECDAG_INIT_SIZE, status),
533 variantList(VARIANT_LIST_INIT_SIZE, status),
534 availableIDs(AVAILABLE_IDS_INIT_SIZE, status)
535 {
536 registry.setValueDeleter(deleteEntry);
537 variantList.setDeleter(uprv_deleteUObject);
538 variantList.setComparer(uhash_compareCaselessUnicodeString);
539 UnicodeString *emptyString = new UnicodeString();
540 if (emptyString != nullptr) {
541 variantList.adoptElement(emptyString, status);
542 }
543 availableIDs.setDeleter(uprv_deleteUObject);
544 availableIDs.setComparer(uhash_compareCaselessUnicodeString);
545 specDAG.setValueDeleter(uhash_deleteHashtable);
546 }
547
~TransliteratorRegistry()548 TransliteratorRegistry::~TransliteratorRegistry() {
549 // Through the magic of C++, everything cleans itself up
550 }
551
get(const UnicodeString & ID,TransliteratorAlias * & aliasReturn,UErrorCode & status)552 Transliterator* TransliteratorRegistry::get(const UnicodeString& ID,
553 TransliteratorAlias*& aliasReturn,
554 UErrorCode& status) {
555 U_ASSERT(aliasReturn == nullptr);
556 TransliteratorEntry *entry = find(ID);
557 return (entry == 0) ? 0
558 : instantiateEntry(ID, entry, aliasReturn, status);
559 }
560
reget(const UnicodeString & ID,TransliteratorParser & parser,TransliteratorAlias * & aliasReturn,UErrorCode & status)561 Transliterator* TransliteratorRegistry::reget(const UnicodeString& ID,
562 TransliteratorParser& parser,
563 TransliteratorAlias*& aliasReturn,
564 UErrorCode& status) {
565 U_ASSERT(aliasReturn == nullptr);
566 TransliteratorEntry *entry = find(ID);
567
568 if (entry == 0) {
569 // We get to this point if there are two threads, one of which
570 // is instantiating an ID, and another of which is removing
571 // the same ID from the registry, and the timing is just right.
572 return 0;
573 }
574
575 // The usage model for the caller is that they will first call
576 // reg->get() inside the mutex, they'll get back an alias, they call
577 // alias->isRuleBased(), and if they get true, they call alias->parse()
578 // outside the mutex, then reg->reget() inside the mutex again. A real
579 // mess, but it gets things working for ICU 3.0. [alan].
580
581 // Note: It's possible that in between the caller calling
582 // alias->parse() and reg->reget(), that another thread will have
583 // called reg->reget(), and the entry will already have been fixed up.
584 // We have to detect this so we don't stomp over existing entry
585 // data members and potentially leak memory (u.data and compoundFilter).
586
587 if (entry->entryType == TransliteratorEntry::RULES_FORWARD ||
588 entry->entryType == TransliteratorEntry::RULES_REVERSE ||
589 entry->entryType == TransliteratorEntry::LOCALE_RULES) {
590
591 if (parser.idBlockVector.isEmpty() && parser.dataVector.isEmpty()) {
592 entry->u.data = 0;
593 entry->entryType = TransliteratorEntry::ALIAS;
594 entry->stringArg = UNICODE_STRING_SIMPLE("Any-nullptr");
595 }
596 else if (parser.idBlockVector.isEmpty() && parser.dataVector.size() == 1) {
597 entry->u.data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0);
598 entry->entryType = TransliteratorEntry::RBT_DATA;
599 }
600 else if (parser.idBlockVector.size() == 1 && parser.dataVector.isEmpty()) {
601 entry->stringArg = *(UnicodeString*)(parser.idBlockVector.elementAt(0));
602 entry->compoundFilter = parser.orphanCompoundFilter();
603 entry->entryType = TransliteratorEntry::ALIAS;
604 }
605 else {
606 entry->entryType = TransliteratorEntry::COMPOUND_RBT;
607 entry->compoundFilter = parser.orphanCompoundFilter();
608 entry->u.dataVector = new UVector(status);
609 // TODO ICU-21701: missing check for nullptr and failed status.
610 // Unclear how best to bail out.
611 entry->stringArg.remove();
612
613 int32_t limit = parser.idBlockVector.size();
614 if (parser.dataVector.size() > limit)
615 limit = parser.dataVector.size();
616
617 for (int32_t i = 0; i < limit; i++) {
618 if (i < parser.idBlockVector.size()) {
619 UnicodeString* idBlock = (UnicodeString*)parser.idBlockVector.elementAt(i);
620 if (!idBlock->isEmpty())
621 entry->stringArg += *idBlock;
622 }
623 if (!parser.dataVector.isEmpty()) {
624 TransliterationRuleData* data = (TransliterationRuleData*)parser.dataVector.orphanElementAt(0);
625 entry->u.dataVector->addElement(data, status);
626 if (U_FAILURE(status)) {
627 delete data;
628 }
629 entry->stringArg += (char16_t)0xffff; // use U+FFFF to mark position of RBTs in ID block
630 }
631 }
632 }
633 }
634
635 Transliterator *t =
636 instantiateEntry(ID, entry, aliasReturn, status);
637 return t;
638 }
639
put(Transliterator * adoptedProto,UBool visible,UErrorCode & ec)640 void TransliteratorRegistry::put(Transliterator* adoptedProto,
641 UBool visible,
642 UErrorCode& ec)
643 {
644 TransliteratorEntry *entry = new TransliteratorEntry();
645 if (entry == nullptr) {
646 ec = U_MEMORY_ALLOCATION_ERROR;
647 return;
648 }
649 entry->adoptPrototype(adoptedProto);
650 registerEntry(adoptedProto->getID(), entry, visible);
651 }
652
put(const UnicodeString & ID,Transliterator::Factory factory,Transliterator::Token context,UBool visible,UErrorCode & ec)653 void TransliteratorRegistry::put(const UnicodeString& ID,
654 Transliterator::Factory factory,
655 Transliterator::Token context,
656 UBool visible,
657 UErrorCode& ec) {
658 TransliteratorEntry *entry = new TransliteratorEntry();
659 if (entry == nullptr) {
660 ec = U_MEMORY_ALLOCATION_ERROR;
661 return;
662 }
663 entry->setFactory(factory, context);
664 registerEntry(ID, entry, visible);
665 }
666
put(const UnicodeString & ID,const UnicodeString & resourceName,UTransDirection dir,UBool readonlyResourceAlias,UBool visible,UErrorCode & ec)667 void TransliteratorRegistry::put(const UnicodeString& ID,
668 const UnicodeString& resourceName,
669 UTransDirection dir,
670 UBool readonlyResourceAlias,
671 UBool visible,
672 UErrorCode& ec) {
673 TransliteratorEntry *entry = new TransliteratorEntry();
674 if (entry == nullptr) {
675 ec = U_MEMORY_ALLOCATION_ERROR;
676 return;
677 }
678 entry->entryType = (dir == UTRANS_FORWARD) ? TransliteratorEntry::RULES_FORWARD
679 : TransliteratorEntry::RULES_REVERSE;
680 if (readonlyResourceAlias) {
681 entry->stringArg.setTo(true, resourceName.getBuffer(), -1);
682 }
683 else {
684 entry->stringArg = resourceName;
685 }
686 registerEntry(ID, entry, visible);
687 }
688
put(const UnicodeString & ID,const UnicodeString & alias,UBool readonlyAliasAlias,UBool visible,UErrorCode &)689 void TransliteratorRegistry::put(const UnicodeString& ID,
690 const UnicodeString& alias,
691 UBool readonlyAliasAlias,
692 UBool visible,
693 UErrorCode& /*ec*/) {
694 TransliteratorEntry *entry = new TransliteratorEntry();
695 // Null pointer check
696 if (entry != nullptr) {
697 entry->entryType = TransliteratorEntry::ALIAS;
698 if (readonlyAliasAlias) {
699 entry->stringArg.setTo(true, alias.getBuffer(), -1);
700 }
701 else {
702 entry->stringArg = alias;
703 }
704 registerEntry(ID, entry, visible);
705 }
706 }
707
remove(const UnicodeString & ID)708 void TransliteratorRegistry::remove(const UnicodeString& ID) {
709 UnicodeString source, target, variant;
710 UBool sawSource;
711 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
712 // Only need to do this if ID.indexOf('-') < 0
713 UnicodeString id;
714 TransliteratorIDParser::STVtoID(source, target, variant, id);
715 registry.remove(id);
716 removeSTV(source, target, variant);
717 availableIDs.removeElement((void*) &id);
718 }
719
720 //----------------------------------------------------------------------
721 // class TransliteratorRegistry: Public ID and spec management
722 //----------------------------------------------------------------------
723
724 /**
725 * == OBSOLETE - remove in ICU 3.4 ==
726 * Return the number of IDs currently registered with the system.
727 * To retrieve the actual IDs, call getAvailableID(i) with
728 * i from 0 to countAvailableIDs() - 1.
729 */
countAvailableIDs() const730 int32_t TransliteratorRegistry::countAvailableIDs() const {
731 return availableIDs.size();
732 }
733
734 /**
735 * == OBSOLETE - remove in ICU 3.4 ==
736 * Return the index-th available ID. index must be between 0
737 * and countAvailableIDs() - 1, inclusive. If index is out of
738 * range, the result of getAvailableID(0) is returned.
739 */
getAvailableID(int32_t index) const740 const UnicodeString& TransliteratorRegistry::getAvailableID(int32_t index) const {
741 if (index < 0 || index >= availableIDs.size()) {
742 index = 0;
743 }
744 return *(const UnicodeString*) availableIDs[index];
745 }
746
getAvailableIDs() const747 StringEnumeration* TransliteratorRegistry::getAvailableIDs() const {
748 return new Enumeration(*this);
749 }
750
countAvailableSources() const751 int32_t TransliteratorRegistry::countAvailableSources() const {
752 return specDAG.count();
753 }
754
getAvailableSource(int32_t index,UnicodeString & result) const755 UnicodeString& TransliteratorRegistry::getAvailableSource(int32_t index,
756 UnicodeString& result) const {
757 int32_t pos = UHASH_FIRST;
758 const UHashElement *e = 0;
759 while (index-- >= 0) {
760 e = specDAG.nextElement(pos);
761 if (e == 0) {
762 break;
763 }
764 }
765 if (e == 0) {
766 result.truncate(0);
767 } else {
768 result = *(UnicodeString*) e->key.pointer;
769 }
770 return result;
771 }
772
countAvailableTargets(const UnicodeString & source) const773 int32_t TransliteratorRegistry::countAvailableTargets(const UnicodeString& source) const {
774 Hashtable *targets = (Hashtable*) specDAG.get(source);
775 return (targets == 0) ? 0 : targets->count();
776 }
777
getAvailableTarget(int32_t index,const UnicodeString & source,UnicodeString & result) const778 UnicodeString& TransliteratorRegistry::getAvailableTarget(int32_t index,
779 const UnicodeString& source,
780 UnicodeString& result) const {
781 Hashtable *targets = (Hashtable*) specDAG.get(source);
782 if (targets == 0) {
783 result.truncate(0); // invalid source
784 return result;
785 }
786 int32_t pos = UHASH_FIRST;
787 const UHashElement *e = 0;
788 while (index-- >= 0) {
789 e = targets->nextElement(pos);
790 if (e == 0) {
791 break;
792 }
793 }
794 if (e == 0) {
795 result.truncate(0); // invalid index
796 } else {
797 result = *(UnicodeString*) e->key.pointer;
798 }
799 return result;
800 }
801
countAvailableVariants(const UnicodeString & source,const UnicodeString & target) const802 int32_t TransliteratorRegistry::countAvailableVariants(const UnicodeString& source,
803 const UnicodeString& target) const {
804 Hashtable *targets = (Hashtable*) specDAG.get(source);
805 if (targets == 0) {
806 return 0;
807 }
808 uint32_t varMask = targets->geti(target);
809 int32_t varCount = 0;
810 while (varMask > 0) {
811 if (varMask & 1) {
812 varCount++;
813 }
814 varMask >>= 1;
815 }
816 return varCount;
817 }
818
getAvailableVariant(int32_t index,const UnicodeString & source,const UnicodeString & target,UnicodeString & result) const819 UnicodeString& TransliteratorRegistry::getAvailableVariant(int32_t index,
820 const UnicodeString& source,
821 const UnicodeString& target,
822 UnicodeString& result) const {
823 Hashtable *targets = (Hashtable*) specDAG.get(source);
824 if (targets == 0) {
825 result.truncate(0); // invalid source
826 return result;
827 }
828 uint32_t varMask = targets->geti(target);
829 int32_t varCount = 0;
830 int32_t varListIndex = 0;
831 while (varMask > 0) {
832 if (varMask & 1) {
833 if (varCount == index) {
834 UnicodeString *v = (UnicodeString*) variantList.elementAt(varListIndex);
835 if (v != nullptr) {
836 result = *v;
837 return result;
838 }
839 break;
840 }
841 varCount++;
842 }
843 varMask >>= 1;
844 varListIndex++;
845 }
846 result.truncate(0); // invalid target or index
847 return result;
848 }
849
850 //----------------------------------------------------------------------
851 // class TransliteratorRegistry::Enumeration
852 //----------------------------------------------------------------------
853
Enumeration(const TransliteratorRegistry & _reg)854 TransliteratorRegistry::Enumeration::Enumeration(const TransliteratorRegistry& _reg) :
855 index(0), reg(_reg) {
856 }
857
~Enumeration()858 TransliteratorRegistry::Enumeration::~Enumeration() {
859 }
860
count(UErrorCode &) const861 int32_t TransliteratorRegistry::Enumeration::count(UErrorCode& /*status*/) const {
862 return reg.availableIDs.size();
863 }
864
snext(UErrorCode & status)865 const UnicodeString* TransliteratorRegistry::Enumeration::snext(UErrorCode& status) {
866 // This is sloppy but safe -- if we get out of sync with the underlying
867 // registry, we will still return legal strings, but they might not
868 // correspond to the snapshot at construction time. So there could be
869 // duplicate IDs or omitted IDs if insertions or deletions occur in one
870 // thread while another is iterating. To be more rigorous, add a timestamp,
871 // which is incremented with any modification, and validate this iterator
872 // against the timestamp at construction time. This probably isn't worth
873 // doing as long as there is some possibility of removing this code in favor
874 // of some new code based on Doug's service framework.
875 if (U_FAILURE(status)) {
876 return nullptr;
877 }
878 int32_t n = reg.availableIDs.size();
879 if (index > n) {
880 status = U_ENUM_OUT_OF_SYNC_ERROR;
881 }
882 // index == n is okay -- this means we've reached the end
883 if (index < n) {
884 // Copy the string! This avoids lifetime problems.
885 unistr = *(const UnicodeString*)reg.availableIDs[index++];
886 return &unistr;
887 } else {
888 return nullptr;
889 }
890 }
891
reset(UErrorCode &)892 void TransliteratorRegistry::Enumeration::reset(UErrorCode& /*status*/) {
893 index = 0;
894 }
895
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration)896 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(TransliteratorRegistry::Enumeration)
897
898 //----------------------------------------------------------------------
899 // class TransliteratorRegistry: internal
900 //----------------------------------------------------------------------
901
902 /**
903 * Convenience method. Calls 6-arg registerEntry().
904 */
905 void TransliteratorRegistry::registerEntry(const UnicodeString& source,
906 const UnicodeString& target,
907 const UnicodeString& variant,
908 TransliteratorEntry* adopted,
909 UBool visible) {
910 UnicodeString ID;
911 UnicodeString s(source);
912 if (s.length() == 0) {
913 s.setTo(true, ANY, 3);
914 }
915 TransliteratorIDParser::STVtoID(source, target, variant, ID);
916 registerEntry(ID, s, target, variant, adopted, visible);
917 }
918
919 /**
920 * Convenience method. Calls 6-arg registerEntry().
921 */
registerEntry(const UnicodeString & ID,TransliteratorEntry * adopted,UBool visible)922 void TransliteratorRegistry::registerEntry(const UnicodeString& ID,
923 TransliteratorEntry* adopted,
924 UBool visible) {
925 UnicodeString source, target, variant;
926 UBool sawSource;
927 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
928 // Only need to do this if ID.indexOf('-') < 0
929 UnicodeString id;
930 TransliteratorIDParser::STVtoID(source, target, variant, id);
931 registerEntry(id, source, target, variant, adopted, visible);
932 }
933
934 /**
935 * Register an entry object (adopted) with the given ID, source,
936 * target, and variant strings.
937 */
registerEntry(const UnicodeString & ID,const UnicodeString & source,const UnicodeString & target,const UnicodeString & variant,TransliteratorEntry * adopted,UBool visible)938 void TransliteratorRegistry::registerEntry(const UnicodeString& ID,
939 const UnicodeString& source,
940 const UnicodeString& target,
941 const UnicodeString& variant,
942 TransliteratorEntry* adopted,
943 UBool visible) {
944 UErrorCode status = U_ZERO_ERROR;
945 registry.put(ID, adopted, status);
946 if (visible) {
947 registerSTV(source, target, variant);
948 if (!availableIDs.contains((void*) &ID)) {
949 UnicodeString *newID = ID.clone();
950 // Check to make sure newID was created.
951 if (newID != nullptr) {
952 // NUL-terminate the ID string
953 newID->getTerminatedBuffer();
954 availableIDs.adoptElement(newID, status);
955 }
956 }
957 } else {
958 removeSTV(source, target, variant);
959 availableIDs.removeElement((void*) &ID);
960 }
961 }
962
963 /**
964 * Register a source-target/variant in the specDAG. Variant may be
965 * empty, but source and target must not be.
966 */
registerSTV(const UnicodeString & source,const UnicodeString & target,const UnicodeString & variant)967 void TransliteratorRegistry::registerSTV(const UnicodeString& source,
968 const UnicodeString& target,
969 const UnicodeString& variant) {
970 // assert(source.length() > 0);
971 // assert(target.length() > 0);
972 UErrorCode status = U_ZERO_ERROR;
973 Hashtable *targets = (Hashtable*) specDAG.get(source);
974 if (targets == 0) {
975 int32_t size = 3;
976 if (source.compare(ANY,3) == 0) {
977 size = ANY_TARGETS_INIT_SIZE;
978 } else if (source.compare(LAT,3) == 0) {
979 size = LAT_TARGETS_INIT_SIZE;
980 }
981 targets = new Hashtable(true, size, status);
982 if (U_FAILURE(status) || targets == nullptr) {
983 return;
984 }
985 specDAG.put(source, targets, status);
986 }
987 int32_t variantListIndex = variantList.indexOf((void*) &variant, 0);
988 if (variantListIndex < 0) {
989 if (variantList.size() >= VARIANT_LIST_MAX_SIZE) {
990 // can't handle any more variants
991 return;
992 }
993 UnicodeString *variantEntry = new UnicodeString(variant);
994 if (variantEntry != nullptr) {
995 variantList.adoptElement(variantEntry, status);
996 if (U_SUCCESS(status)) {
997 variantListIndex = variantList.size() - 1;
998 }
999 }
1000 if (variantListIndex < 0) {
1001 return;
1002 }
1003 }
1004 uint32_t addMask = 1 << variantListIndex;
1005 uint32_t varMask = targets->geti(target);
1006 targets->puti(target, varMask | addMask, status);
1007 }
1008
1009 /**
1010 * Remove a source-target/variant from the specDAG.
1011 */
removeSTV(const UnicodeString & source,const UnicodeString & target,const UnicodeString & variant)1012 void TransliteratorRegistry::removeSTV(const UnicodeString& source,
1013 const UnicodeString& target,
1014 const UnicodeString& variant) {
1015 // assert(source.length() > 0);
1016 // assert(target.length() > 0);
1017 UErrorCode status = U_ZERO_ERROR;
1018 Hashtable *targets = (Hashtable*) specDAG.get(source);
1019 if (targets == nullptr) {
1020 return; // should never happen for valid s-t/v
1021 }
1022 uint32_t varMask = targets->geti(target);
1023 if (varMask == 0) {
1024 return; // should never happen for valid s-t/v
1025 }
1026 int32_t variantListIndex = variantList.indexOf((void*) &variant, 0);
1027 if (variantListIndex < 0) {
1028 return; // should never happen for valid s-t/v
1029 }
1030 int32_t remMask = 1 << variantListIndex;
1031 varMask &= (~remMask);
1032 if (varMask != 0) {
1033 targets->puti(target, varMask, status);
1034 } else {
1035 targets->remove(target); // should delete variants
1036 if (targets->count() == 0) {
1037 specDAG.remove(source); // should delete targets
1038 }
1039 }
1040 }
1041
1042 /**
1043 * Attempt to find a source-target/variant in the dynamic registry
1044 * store. Return 0 on failure.
1045 *
1046 * Caller does NOT own returned object.
1047 */
findInDynamicStore(const TransliteratorSpec & src,const TransliteratorSpec & trg,const UnicodeString & variant) const1048 TransliteratorEntry* TransliteratorRegistry::findInDynamicStore(const TransliteratorSpec& src,
1049 const TransliteratorSpec& trg,
1050 const UnicodeString& variant) const {
1051 UnicodeString ID;
1052 TransliteratorIDParser::STVtoID(src, trg, variant, ID);
1053 TransliteratorEntry *e = (TransliteratorEntry*) registry.get(ID);
1054 DEBUG_useEntry(e);
1055 return e;
1056 }
1057
1058 /**
1059 * Attempt to find a source-target/variant in the static locale
1060 * resource store. Do not perform fallback. Return 0 on failure.
1061 *
1062 * On success, create a new entry object, register it in the dynamic
1063 * store, and return a pointer to it, but do not make it public --
1064 * just because someone requested something, we do not expand the
1065 * available ID list (or spec DAG).
1066 *
1067 * Caller does NOT own returned object.
1068 */
findInStaticStore(const TransliteratorSpec & src,const TransliteratorSpec & trg,const UnicodeString & variant)1069 TransliteratorEntry* TransliteratorRegistry::findInStaticStore(const TransliteratorSpec& src,
1070 const TransliteratorSpec& trg,
1071 const UnicodeString& variant) {
1072 TransliteratorEntry* entry = 0;
1073 if (src.isLocale()) {
1074 entry = findInBundle(src, trg, variant, UTRANS_FORWARD);
1075 } else if (trg.isLocale()) {
1076 entry = findInBundle(trg, src, variant, UTRANS_REVERSE);
1077 }
1078
1079 // If we found an entry, store it in the Hashtable for next
1080 // time.
1081 if (entry != 0) {
1082 registerEntry(src.getTop(), trg.getTop(), variant, entry, false);
1083 }
1084
1085 return entry;
1086 }
1087
1088 // As of 2.0, resource bundle keys cannot contain '_'
1089 static const char16_t TRANSLITERATE_TO[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,84,111,0}; // "TransliterateTo"
1090
1091 static const char16_t TRANSLITERATE_FROM[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,70,114,111,109,0}; // "TransliterateFrom"
1092
1093 static const char16_t TRANSLITERATE[] = {84,114,97,110,115,108,105,116,101,114,97,116,101,0}; // "Transliterate"
1094
1095 /**
1096 * Attempt to find an entry in a single resource bundle. This is
1097 * a one-sided lookup. findInStaticStore() performs up to two such
1098 * lookups, one for the source, and one for the target.
1099 *
1100 * Do not perform fallback. Return 0 on failure.
1101 *
1102 * On success, create a new Entry object, populate it, and return it.
1103 * The caller owns the returned object.
1104 */
findInBundle(const TransliteratorSpec & specToOpen,const TransliteratorSpec & specToFind,const UnicodeString & variant,UTransDirection direction)1105 TransliteratorEntry* TransliteratorRegistry::findInBundle(const TransliteratorSpec& specToOpen,
1106 const TransliteratorSpec& specToFind,
1107 const UnicodeString& variant,
1108 UTransDirection direction)
1109 {
1110 UnicodeString utag;
1111 UnicodeString resStr;
1112 int32_t pass;
1113
1114 for (pass=0; pass<2; ++pass) {
1115 utag.truncate(0);
1116 // First try either TransliteratorTo_xxx or
1117 // TransliterateFrom_xxx, then try the bidirectional
1118 // Transliterate_xxx. This precedence order is arbitrary
1119 // but must be consistent and documented.
1120 if (pass == 0) {
1121 utag.append(direction == UTRANS_FORWARD ?
1122 TRANSLITERATE_TO : TRANSLITERATE_FROM, -1);
1123 } else {
1124 utag.append(TRANSLITERATE, -1);
1125 }
1126 UnicodeString s(specToFind.get());
1127 utag.append(s.toUpper(""));
1128 UErrorCode status = U_ZERO_ERROR;
1129 ResourceBundle subres(specToOpen.getBundle().get(
1130 CharString().appendInvariantChars(utag, status).data(), status));
1131 if (U_FAILURE(status) || status == U_USING_DEFAULT_WARNING) {
1132 continue;
1133 }
1134
1135 s.truncate(0);
1136 if (specToOpen.get() != LocaleUtility::initNameFromLocale(subres.getLocale(), s)) {
1137 continue;
1138 }
1139
1140 if (variant.length() != 0) {
1141 status = U_ZERO_ERROR;
1142 resStr = subres.getStringEx(
1143 CharString().appendInvariantChars(variant, status).data(), status);
1144 if (U_SUCCESS(status)) {
1145 // Exit loop successfully
1146 break;
1147 }
1148 } else {
1149 // Variant is empty, which means match the first variant listed.
1150 status = U_ZERO_ERROR;
1151 resStr = subres.getStringEx(1, status);
1152 if (U_SUCCESS(status)) {
1153 // Exit loop successfully
1154 break;
1155 }
1156 }
1157 }
1158
1159 if (pass==2) {
1160 // Failed
1161 return nullptr;
1162 }
1163
1164 // We have succeeded in loading a string from the locale
1165 // resources. Create a new registry entry to hold it and return it.
1166 TransliteratorEntry *entry = new TransliteratorEntry();
1167 if (entry != 0) {
1168 // The direction is always forward for the
1169 // TransliterateTo_xxx and TransliterateFrom_xxx
1170 // items; those are unidirectional forward rules.
1171 // For the bidirectional Transliterate_xxx items,
1172 // the direction is the value passed in to this
1173 // function.
1174 int32_t dir = (pass == 0) ? UTRANS_FORWARD : direction;
1175 entry->entryType = TransliteratorEntry::LOCALE_RULES;
1176 entry->stringArg = resStr;
1177 entry->intArg = dir;
1178 }
1179
1180 return entry;
1181 }
1182
1183 /**
1184 * Convenience method. Calls 3-arg find().
1185 */
find(const UnicodeString & ID)1186 TransliteratorEntry* TransliteratorRegistry::find(const UnicodeString& ID) {
1187 UnicodeString source, target, variant;
1188 UBool sawSource;
1189 TransliteratorIDParser::IDtoSTV(ID, source, target, variant, sawSource);
1190 return find(source, target, variant);
1191 }
1192
1193 /**
1194 * Top-level find method. Attempt to find a source-target/variant in
1195 * either the dynamic or the static (locale resource) store. Perform
1196 * fallback.
1197 *
1198 * Lookup sequence for ss_SS_SSS-tt_TT_TTT/v:
1199 *
1200 * ss_SS_SSS-tt_TT_TTT/v -- in hashtable
1201 * ss_SS_SSS-tt_TT_TTT/v -- in ss_SS_SSS (no fallback)
1202 *
1203 * repeat with t = tt_TT_TTT, tt_TT, tt, and tscript
1204 *
1205 * ss_SS_SSS-t/ *
1206 * ss_SS-t/ *
1207 * ss-t/ *
1208 * sscript-t/ *
1209 *
1210 * Here * matches the first variant listed.
1211 *
1212 * Caller does NOT own returned object. Return 0 on failure.
1213 */
find(UnicodeString & source,UnicodeString & target,UnicodeString & variant)1214 TransliteratorEntry* TransliteratorRegistry::find(UnicodeString& source,
1215 UnicodeString& target,
1216 UnicodeString& variant) {
1217
1218 TransliteratorSpec src(source);
1219 TransliteratorSpec trg(target);
1220 TransliteratorEntry* entry;
1221
1222 // Seek exact match in hashtable. Temporary fix for ICU 4.6.
1223 // TODO: The general logic for finding a matching transliterator needs to be reviewed.
1224 // ICU ticket #8089
1225 UnicodeString ID;
1226 TransliteratorIDParser::STVtoID(source, target, variant, ID);
1227 entry = (TransliteratorEntry*) registry.get(ID);
1228 if (entry != 0) {
1229 // std::string ss;
1230 // std::cout << ID.toUTF8String(ss) << std::endl;
1231 return entry;
1232 }
1233
1234 if (variant.length() != 0) {
1235
1236 // Seek exact match in hashtable
1237 entry = findInDynamicStore(src, trg, variant);
1238 if (entry != 0) {
1239 return entry;
1240 }
1241
1242 // Seek exact match in locale resources
1243 entry = findInStaticStore(src, trg, variant);
1244 if (entry != 0) {
1245 return entry;
1246 }
1247 }
1248
1249 for (;;) {
1250 src.reset();
1251 for (;;) {
1252 // Seek match in hashtable
1253 entry = findInDynamicStore(src, trg, NO_VARIANT);
1254 if (entry != 0) {
1255 return entry;
1256 }
1257
1258 // Seek match in locale resources
1259 entry = findInStaticStore(src, trg, NO_VARIANT);
1260 if (entry != 0) {
1261 return entry;
1262 }
1263 if (!src.hasFallback()) {
1264 break;
1265 }
1266 src.next();
1267 }
1268 if (!trg.hasFallback()) {
1269 break;
1270 }
1271 trg.next();
1272 }
1273
1274 return 0;
1275 }
1276
1277 /**
1278 * Given an Entry object, instantiate it. Caller owns result. Return
1279 * 0 on failure.
1280 *
1281 * Return a non-empty aliasReturn value if the ID points to an alias.
1282 * We cannot instantiate it ourselves because the alias may contain
1283 * filters or compounds, which we do not understand. Caller should
1284 * make aliasReturn empty before calling.
1285 *
1286 * The entry object is assumed to reside in the dynamic store. It may be
1287 * modified.
1288 */
instantiateEntry(const UnicodeString & ID,TransliteratorEntry * entry,TransliteratorAlias * & aliasReturn,UErrorCode & status)1289 Transliterator* TransliteratorRegistry::instantiateEntry(const UnicodeString& ID,
1290 TransliteratorEntry *entry,
1291 TransliteratorAlias* &aliasReturn,
1292 UErrorCode& status) {
1293 Transliterator *t = 0;
1294 U_ASSERT(aliasReturn == 0);
1295
1296 switch (entry->entryType) {
1297 case TransliteratorEntry::RBT_DATA:
1298 t = new RuleBasedTransliterator(ID, entry->u.data);
1299 if (t == 0) {
1300 status = U_MEMORY_ALLOCATION_ERROR;
1301 }
1302 return t;
1303 case TransliteratorEntry::PROTOTYPE:
1304 t = entry->u.prototype->clone();
1305 if (t == 0) {
1306 status = U_MEMORY_ALLOCATION_ERROR;
1307 }
1308 return t;
1309 case TransliteratorEntry::ALIAS:
1310 aliasReturn = new TransliteratorAlias(entry->stringArg, entry->compoundFilter);
1311 if (aliasReturn == 0) {
1312 status = U_MEMORY_ALLOCATION_ERROR;
1313 }
1314 return 0;
1315 case TransliteratorEntry::FACTORY:
1316 t = entry->u.factory.function(ID, entry->u.factory.context);
1317 if (t == 0) {
1318 status = U_MEMORY_ALLOCATION_ERROR;
1319 }
1320 return t;
1321 case TransliteratorEntry::COMPOUND_RBT:
1322 {
1323 UVector* rbts = new UVector(uprv_deleteUObject, nullptr, entry->u.dataVector->size(), status);
1324 // Check for null pointer
1325 if (rbts == nullptr) {
1326 status = U_MEMORY_ALLOCATION_ERROR;
1327 return nullptr;
1328 }
1329 int32_t passNumber = 1;
1330 for (int32_t i = 0; U_SUCCESS(status) && i < entry->u.dataVector->size(); i++) {
1331 // TODO: Should passNumber be turned into a decimal-string representation (1 -> "1")?
1332 Transliterator* tl = new RuleBasedTransliterator(UnicodeString(CompoundTransliterator::PASS_STRING) + UnicodeString(passNumber++),
1333 (TransliterationRuleData*)(entry->u.dataVector->elementAt(i)), false);
1334 if (tl == 0)
1335 status = U_MEMORY_ALLOCATION_ERROR;
1336 else
1337 rbts->adoptElement(tl, status);
1338 }
1339 if (U_FAILURE(status)) {
1340 delete rbts;
1341 return 0;
1342 }
1343 rbts->setDeleter(nullptr);
1344 aliasReturn = new TransliteratorAlias(ID, entry->stringArg, rbts, entry->compoundFilter);
1345 }
1346 if (aliasReturn == 0) {
1347 status = U_MEMORY_ALLOCATION_ERROR;
1348 }
1349 return 0;
1350 case TransliteratorEntry::LOCALE_RULES:
1351 aliasReturn = new TransliteratorAlias(ID, entry->stringArg,
1352 (UTransDirection) entry->intArg);
1353 if (aliasReturn == 0) {
1354 status = U_MEMORY_ALLOCATION_ERROR;
1355 }
1356 return 0;
1357 case TransliteratorEntry::RULES_FORWARD:
1358 case TransliteratorEntry::RULES_REVERSE:
1359 // Process the rule data into a TransliteratorRuleData object,
1360 // and possibly also into an ::id header and/or footer. Then
1361 // we modify the registry with the parsed data and retry.
1362 {
1363 TransliteratorParser parser(status);
1364
1365 // We use the file name, taken from another resource bundle
1366 // 2-d array at static init time, as a locale language. We're
1367 // just using the locale mechanism to map through to a file
1368 // name; this in no way represents an actual locale.
1369 //CharString ch(entry->stringArg);
1370 //UResourceBundle *bundle = ures_openDirect(0, ch, &status);
1371 UnicodeString rules = entry->stringArg;
1372 //ures_close(bundle);
1373
1374 //if (U_FAILURE(status)) {
1375 // We have a failure of some kind. Remove the ID from the
1376 // registry so we don't keep trying. NOTE: This will throw off
1377 // anyone who is, at the moment, trying to iterate over the
1378 // available IDs. That's acceptable since we should never
1379 // really get here except under installation, configuration,
1380 // or unrecoverable run time memory failures.
1381 // remove(ID);
1382 //} else {
1383
1384 // If the status indicates a failure, then we don't have any
1385 // rules -- there is probably an installation error. The list
1386 // in the root locale should correspond to all the installed
1387 // transliterators; if it lists something that's not
1388 // installed, we'll get an error from ResourceBundle.
1389 aliasReturn = new TransliteratorAlias(ID, rules,
1390 ((entry->entryType == TransliteratorEntry::RULES_REVERSE) ?
1391 UTRANS_REVERSE : UTRANS_FORWARD));
1392 if (aliasReturn == 0) {
1393 status = U_MEMORY_ALLOCATION_ERROR;
1394 }
1395 //}
1396 }
1397 return 0;
1398 default:
1399 UPRV_UNREACHABLE_EXIT; // can't get here
1400 }
1401 }
1402 U_NAMESPACE_END
1403
1404 #endif /* #if !UCONFIG_NO_TRANSLITERATION */
1405
1406 //eof
1407