transreg.cpp 49 KB

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