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