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