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