dictbe.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /**
  4. *******************************************************************************
  5. * Copyright (C) 2006-2016, International Business Machines Corporation
  6. * and others. All Rights Reserved.
  7. *******************************************************************************
  8. */
  9. #include <utility>
  10. #include "unicode/utypes.h"
  11. #if !UCONFIG_NO_BREAK_ITERATION
  12. #include "brkeng.h"
  13. #include "dictbe.h"
  14. #include "unicode/uniset.h"
  15. #include "unicode/chariter.h"
  16. #include "unicode/resbund.h"
  17. #include "unicode/ubrk.h"
  18. #include "unicode/usetiter.h"
  19. #include "ubrkimpl.h"
  20. #include "utracimp.h"
  21. #include "uvectr32.h"
  22. #include "uvector.h"
  23. #include "uassert.h"
  24. #include "unicode/normlzr.h"
  25. #include "cmemory.h"
  26. #include "dictionarydata.h"
  27. U_NAMESPACE_BEGIN
  28. /*
  29. ******************************************************************
  30. */
  31. DictionaryBreakEngine::DictionaryBreakEngine() {
  32. }
  33. DictionaryBreakEngine::~DictionaryBreakEngine() {
  34. }
  35. UBool
  36. DictionaryBreakEngine::handles(UChar32 c) const {
  37. return fSet.contains(c);
  38. }
  39. int32_t
  40. DictionaryBreakEngine::findBreaks( UText *text,
  41. int32_t startPos,
  42. int32_t endPos,
  43. UVector32 &foundBreaks,
  44. UBool isPhraseBreaking,
  45. UErrorCode& status) const {
  46. if (U_FAILURE(status)) return 0;
  47. (void)startPos; // TODO: remove this param?
  48. int32_t result = 0;
  49. // Find the span of characters included in the set.
  50. // The span to break begins at the current position in the text, and
  51. // extends towards the start or end of the text, depending on 'reverse'.
  52. int32_t start = (int32_t)utext_getNativeIndex(text);
  53. int32_t current;
  54. int32_t rangeStart;
  55. int32_t rangeEnd;
  56. UChar32 c = utext_current32(text);
  57. while((current = (int32_t)utext_getNativeIndex(text)) < endPos && fSet.contains(c)) {
  58. utext_next32(text); // TODO: recast loop for postincrement
  59. c = utext_current32(text);
  60. }
  61. rangeStart = start;
  62. rangeEnd = current;
  63. result = divideUpDictionaryRange(text, rangeStart, rangeEnd, foundBreaks, isPhraseBreaking, status);
  64. utext_setNativeIndex(text, current);
  65. return result;
  66. }
  67. void
  68. DictionaryBreakEngine::setCharacters( const UnicodeSet &set ) {
  69. fSet = set;
  70. // Compact for caching
  71. fSet.compact();
  72. }
  73. /*
  74. ******************************************************************
  75. * PossibleWord
  76. */
  77. // Helper class for improving readability of the Thai/Lao/Khmer word break
  78. // algorithm. The implementation is completely inline.
  79. // List size, limited by the maximum number of words in the dictionary
  80. // that form a nested sequence.
  81. static const int32_t POSSIBLE_WORD_LIST_MAX = 20;
  82. class PossibleWord {
  83. private:
  84. // list of word candidate lengths, in increasing length order
  85. // TODO: bytes would be sufficient for word lengths.
  86. int32_t count; // Count of candidates
  87. int32_t prefix; // The longest match with a dictionary word
  88. int32_t offset; // Offset in the text of these candidates
  89. int32_t mark; // The preferred candidate's offset
  90. int32_t current; // The candidate we're currently looking at
  91. int32_t cuLengths[POSSIBLE_WORD_LIST_MAX]; // Word Lengths, in code units.
  92. int32_t cpLengths[POSSIBLE_WORD_LIST_MAX]; // Word Lengths, in code points.
  93. public:
  94. PossibleWord() : count(0), prefix(0), offset(-1), mark(0), current(0) {}
  95. ~PossibleWord() {}
  96. // Fill the list of candidates if needed, select the longest, and return the number found
  97. int32_t candidates( UText *text, DictionaryMatcher *dict, int32_t rangeEnd );
  98. // Select the currently marked candidate, point after it in the text, and invalidate self
  99. int32_t acceptMarked( UText *text );
  100. // Back up from the current candidate to the next shorter one; return true if that exists
  101. // and point the text after it
  102. UBool backUp( UText *text );
  103. // Return the longest prefix this candidate location shares with a dictionary word
  104. // Return value is in code points.
  105. int32_t longestPrefix() { return prefix; }
  106. // Mark the current candidate as the one we like
  107. void markCurrent() { mark = current; }
  108. // Get length in code points of the marked word.
  109. int32_t markedCPLength() { return cpLengths[mark]; }
  110. };
  111. int32_t PossibleWord::candidates( UText *text, DictionaryMatcher *dict, int32_t rangeEnd ) {
  112. // TODO: If getIndex is too slow, use offset < 0 and add discardAll()
  113. int32_t start = (int32_t)utext_getNativeIndex(text);
  114. if (start != offset) {
  115. offset = start;
  116. count = dict->matches(text, rangeEnd-start, UPRV_LENGTHOF(cuLengths), cuLengths, cpLengths, nullptr, &prefix);
  117. // Dictionary leaves text after longest prefix, not longest word. Back up.
  118. if (count <= 0) {
  119. utext_setNativeIndex(text, start);
  120. }
  121. }
  122. if (count > 0) {
  123. utext_setNativeIndex(text, start+cuLengths[count-1]);
  124. }
  125. current = count-1;
  126. mark = current;
  127. return count;
  128. }
  129. int32_t
  130. PossibleWord::acceptMarked( UText *text ) {
  131. utext_setNativeIndex(text, offset + cuLengths[mark]);
  132. return cuLengths[mark];
  133. }
  134. UBool
  135. PossibleWord::backUp( UText *text ) {
  136. if (current > 0) {
  137. utext_setNativeIndex(text, offset + cuLengths[--current]);
  138. return true;
  139. }
  140. return false;
  141. }
  142. /*
  143. ******************************************************************
  144. * ThaiBreakEngine
  145. */
  146. // How many words in a row are "good enough"?
  147. static const int32_t THAI_LOOKAHEAD = 3;
  148. // Will not combine a non-word with a preceding dictionary word longer than this
  149. static const int32_t THAI_ROOT_COMBINE_THRESHOLD = 3;
  150. // Will not combine a non-word that shares at least this much prefix with a
  151. // dictionary word, with a preceding word
  152. static const int32_t THAI_PREFIX_COMBINE_THRESHOLD = 3;
  153. // Elision character
  154. static const int32_t THAI_PAIYANNOI = 0x0E2F;
  155. // Repeat character
  156. static const int32_t THAI_MAIYAMOK = 0x0E46;
  157. // Minimum word size
  158. static const int32_t THAI_MIN_WORD = 2;
  159. // Minimum number of characters for two words
  160. static const int32_t THAI_MIN_WORD_SPAN = THAI_MIN_WORD * 2;
  161. ThaiBreakEngine::ThaiBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
  162. : DictionaryBreakEngine(),
  163. fDictionary(adoptDictionary)
  164. {
  165. UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
  166. UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Thai");
  167. UnicodeSet thaiWordSet(UnicodeString(u"[[:Thai:]&[:LineBreak=SA:]]"), status);
  168. if (U_SUCCESS(status)) {
  169. setCharacters(thaiWordSet);
  170. }
  171. fMarkSet.applyPattern(UnicodeString(u"[[:Thai:]&[:LineBreak=SA:]&[:M:]]"), status);
  172. fMarkSet.add(0x0020);
  173. fEndWordSet = thaiWordSet;
  174. fEndWordSet.remove(0x0E31); // MAI HAN-AKAT
  175. fEndWordSet.remove(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
  176. fBeginWordSet.add(0x0E01, 0x0E2E); // KO KAI through HO NOKHUK
  177. fBeginWordSet.add(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
  178. fSuffixSet.add(THAI_PAIYANNOI);
  179. fSuffixSet.add(THAI_MAIYAMOK);
  180. // Compact for caching.
  181. fMarkSet.compact();
  182. fEndWordSet.compact();
  183. fBeginWordSet.compact();
  184. fSuffixSet.compact();
  185. UTRACE_EXIT_STATUS(status);
  186. }
  187. ThaiBreakEngine::~ThaiBreakEngine() {
  188. delete fDictionary;
  189. }
  190. int32_t
  191. ThaiBreakEngine::divideUpDictionaryRange( UText *text,
  192. int32_t rangeStart,
  193. int32_t rangeEnd,
  194. UVector32 &foundBreaks,
  195. UBool /* isPhraseBreaking */,
  196. UErrorCode& status) const {
  197. if (U_FAILURE(status)) return 0;
  198. utext_setNativeIndex(text, rangeStart);
  199. utext_moveIndex32(text, THAI_MIN_WORD_SPAN);
  200. if (utext_getNativeIndex(text) >= rangeEnd) {
  201. return 0; // Not enough characters for two words
  202. }
  203. utext_setNativeIndex(text, rangeStart);
  204. uint32_t wordsFound = 0;
  205. int32_t cpWordLength = 0; // Word Length in Code Points.
  206. int32_t cuWordLength = 0; // Word length in code units (UText native indexing)
  207. int32_t current;
  208. PossibleWord words[THAI_LOOKAHEAD];
  209. utext_setNativeIndex(text, rangeStart);
  210. while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
  211. cpWordLength = 0;
  212. cuWordLength = 0;
  213. // Look for candidate words at the current position
  214. int32_t candidates = words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  215. // If we found exactly one, use that
  216. if (candidates == 1) {
  217. cuWordLength = words[wordsFound % THAI_LOOKAHEAD].acceptMarked(text);
  218. cpWordLength = words[wordsFound % THAI_LOOKAHEAD].markedCPLength();
  219. wordsFound += 1;
  220. }
  221. // If there was more than one, see which one can take us forward the most words
  222. else if (candidates > 1) {
  223. // If we're already at the end of the range, we're done
  224. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  225. goto foundBest;
  226. }
  227. do {
  228. if (words[(wordsFound + 1) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
  229. // Followed by another dictionary word; mark first word as a good candidate
  230. words[wordsFound%THAI_LOOKAHEAD].markCurrent();
  231. // If we're already at the end of the range, we're done
  232. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  233. goto foundBest;
  234. }
  235. // See if any of the possible second words is followed by a third word
  236. do {
  237. // If we find a third word, stop right away
  238. if (words[(wordsFound + 2) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
  239. words[wordsFound % THAI_LOOKAHEAD].markCurrent();
  240. goto foundBest;
  241. }
  242. }
  243. while (words[(wordsFound + 1) % THAI_LOOKAHEAD].backUp(text));
  244. }
  245. }
  246. while (words[wordsFound % THAI_LOOKAHEAD].backUp(text));
  247. foundBest:
  248. // Set UText position to after the accepted word.
  249. cuWordLength = words[wordsFound % THAI_LOOKAHEAD].acceptMarked(text);
  250. cpWordLength = words[wordsFound % THAI_LOOKAHEAD].markedCPLength();
  251. wordsFound += 1;
  252. }
  253. // We come here after having either found a word or not. We look ahead to the
  254. // next word. If it's not a dictionary word, we will combine it with the word we
  255. // just found (if there is one), but only if the preceding word does not exceed
  256. // the threshold.
  257. // The text iterator should now be positioned at the end of the word we found.
  258. UChar32 uc = 0;
  259. if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < THAI_ROOT_COMBINE_THRESHOLD) {
  260. // if it is a dictionary word, do nothing. If it isn't, then if there is
  261. // no preceding word, or the non-word shares less than the minimum threshold
  262. // of characters with a dictionary word, then scan to resynchronize
  263. if (words[wordsFound % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  264. && (cuWordLength == 0
  265. || words[wordsFound%THAI_LOOKAHEAD].longestPrefix() < THAI_PREFIX_COMBINE_THRESHOLD)) {
  266. // Look for a plausible word boundary
  267. int32_t remaining = rangeEnd - (current+cuWordLength);
  268. UChar32 pc;
  269. int32_t chars = 0;
  270. for (;;) {
  271. int32_t pcIndex = (int32_t)utext_getNativeIndex(text);
  272. pc = utext_next32(text);
  273. int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex;
  274. chars += pcSize;
  275. remaining -= pcSize;
  276. if (remaining <= 0) {
  277. break;
  278. }
  279. uc = utext_current32(text);
  280. if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
  281. // Maybe. See if it's in the dictionary.
  282. // NOTE: In the original Apple code, checked that the next
  283. // two characters after uc were not 0x0E4C THANTHAKHAT before
  284. // checking the dictionary. That is just a performance filter,
  285. // but it's not clear it's faster than checking the trie.
  286. int32_t num_candidates = words[(wordsFound + 1) % THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  287. utext_setNativeIndex(text, current + cuWordLength + chars);
  288. if (num_candidates > 0) {
  289. break;
  290. }
  291. }
  292. }
  293. // Bump the word count if there wasn't already one
  294. if (cuWordLength <= 0) {
  295. wordsFound += 1;
  296. }
  297. // Update the length with the passed-over characters
  298. cuWordLength += chars;
  299. }
  300. else {
  301. // Back up to where we were for next iteration
  302. utext_setNativeIndex(text, current+cuWordLength);
  303. }
  304. }
  305. // Never stop before a combining mark.
  306. int32_t currPos;
  307. while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
  308. utext_next32(text);
  309. cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos;
  310. }
  311. // Look ahead for possible suffixes if a dictionary word does not follow.
  312. // We do this in code rather than using a rule so that the heuristic
  313. // resynch continues to function. For example, one of the suffix characters
  314. // could be a typo in the middle of a word.
  315. if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cuWordLength > 0) {
  316. if (words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  317. && fSuffixSet.contains(uc = utext_current32(text))) {
  318. if (uc == THAI_PAIYANNOI) {
  319. if (!fSuffixSet.contains(utext_previous32(text))) {
  320. // Skip over previous end and PAIYANNOI
  321. utext_next32(text);
  322. int32_t paiyannoiIndex = (int32_t)utext_getNativeIndex(text);
  323. utext_next32(text);
  324. cuWordLength += (int32_t)utext_getNativeIndex(text) - paiyannoiIndex; // Add PAIYANNOI to word
  325. uc = utext_current32(text); // Fetch next character
  326. }
  327. else {
  328. // Restore prior position
  329. utext_next32(text);
  330. }
  331. }
  332. if (uc == THAI_MAIYAMOK) {
  333. if (utext_previous32(text) != THAI_MAIYAMOK) {
  334. // Skip over previous end and MAIYAMOK
  335. utext_next32(text);
  336. int32_t maiyamokIndex = (int32_t)utext_getNativeIndex(text);
  337. utext_next32(text);
  338. cuWordLength += (int32_t)utext_getNativeIndex(text) - maiyamokIndex; // Add MAIYAMOK to word
  339. }
  340. else {
  341. // Restore prior position
  342. utext_next32(text);
  343. }
  344. }
  345. }
  346. else {
  347. utext_setNativeIndex(text, current+cuWordLength);
  348. }
  349. }
  350. // Did we find a word on this iteration? If so, push it on the break stack
  351. if (cuWordLength > 0) {
  352. foundBreaks.push((current+cuWordLength), status);
  353. }
  354. }
  355. // Don't return a break for the end of the dictionary range if there is one there.
  356. if (foundBreaks.peeki() >= rangeEnd) {
  357. (void) foundBreaks.popi();
  358. wordsFound -= 1;
  359. }
  360. return wordsFound;
  361. }
  362. /*
  363. ******************************************************************
  364. * LaoBreakEngine
  365. */
  366. // How many words in a row are "good enough"?
  367. static const int32_t LAO_LOOKAHEAD = 3;
  368. // Will not combine a non-word with a preceding dictionary word longer than this
  369. static const int32_t LAO_ROOT_COMBINE_THRESHOLD = 3;
  370. // Will not combine a non-word that shares at least this much prefix with a
  371. // dictionary word, with a preceding word
  372. static const int32_t LAO_PREFIX_COMBINE_THRESHOLD = 3;
  373. // Minimum word size
  374. static const int32_t LAO_MIN_WORD = 2;
  375. // Minimum number of characters for two words
  376. static const int32_t LAO_MIN_WORD_SPAN = LAO_MIN_WORD * 2;
  377. LaoBreakEngine::LaoBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
  378. : DictionaryBreakEngine(),
  379. fDictionary(adoptDictionary)
  380. {
  381. UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
  382. UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Laoo");
  383. UnicodeSet laoWordSet(UnicodeString(u"[[:Laoo:]&[:LineBreak=SA:]]"), status);
  384. if (U_SUCCESS(status)) {
  385. setCharacters(laoWordSet);
  386. }
  387. fMarkSet.applyPattern(UnicodeString(u"[[:Laoo:]&[:LineBreak=SA:]&[:M:]]"), status);
  388. fMarkSet.add(0x0020);
  389. fEndWordSet = laoWordSet;
  390. fEndWordSet.remove(0x0EC0, 0x0EC4); // prefix vowels
  391. fBeginWordSet.add(0x0E81, 0x0EAE); // basic consonants (including holes for corresponding Thai characters)
  392. fBeginWordSet.add(0x0EDC, 0x0EDD); // digraph consonants (no Thai equivalent)
  393. fBeginWordSet.add(0x0EC0, 0x0EC4); // prefix vowels
  394. // Compact for caching.
  395. fMarkSet.compact();
  396. fEndWordSet.compact();
  397. fBeginWordSet.compact();
  398. UTRACE_EXIT_STATUS(status);
  399. }
  400. LaoBreakEngine::~LaoBreakEngine() {
  401. delete fDictionary;
  402. }
  403. int32_t
  404. LaoBreakEngine::divideUpDictionaryRange( UText *text,
  405. int32_t rangeStart,
  406. int32_t rangeEnd,
  407. UVector32 &foundBreaks,
  408. UBool /* isPhraseBreaking */,
  409. UErrorCode& status) const {
  410. if (U_FAILURE(status)) return 0;
  411. if ((rangeEnd - rangeStart) < LAO_MIN_WORD_SPAN) {
  412. return 0; // Not enough characters for two words
  413. }
  414. uint32_t wordsFound = 0;
  415. int32_t cpWordLength = 0;
  416. int32_t cuWordLength = 0;
  417. int32_t current;
  418. PossibleWord words[LAO_LOOKAHEAD];
  419. utext_setNativeIndex(text, rangeStart);
  420. while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
  421. cuWordLength = 0;
  422. cpWordLength = 0;
  423. // Look for candidate words at the current position
  424. int32_t candidates = words[wordsFound%LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  425. // If we found exactly one, use that
  426. if (candidates == 1) {
  427. cuWordLength = words[wordsFound % LAO_LOOKAHEAD].acceptMarked(text);
  428. cpWordLength = words[wordsFound % LAO_LOOKAHEAD].markedCPLength();
  429. wordsFound += 1;
  430. }
  431. // If there was more than one, see which one can take us forward the most words
  432. else if (candidates > 1) {
  433. // If we're already at the end of the range, we're done
  434. if (utext_getNativeIndex(text) >= rangeEnd) {
  435. goto foundBest;
  436. }
  437. do {
  438. if (words[(wordsFound + 1) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
  439. // Followed by another dictionary word; mark first word as a good candidate
  440. words[wordsFound%LAO_LOOKAHEAD].markCurrent();
  441. // If we're already at the end of the range, we're done
  442. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  443. goto foundBest;
  444. }
  445. // See if any of the possible second words is followed by a third word
  446. do {
  447. // If we find a third word, stop right away
  448. if (words[(wordsFound + 2) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
  449. words[wordsFound % LAO_LOOKAHEAD].markCurrent();
  450. goto foundBest;
  451. }
  452. }
  453. while (words[(wordsFound + 1) % LAO_LOOKAHEAD].backUp(text));
  454. }
  455. }
  456. while (words[wordsFound % LAO_LOOKAHEAD].backUp(text));
  457. foundBest:
  458. cuWordLength = words[wordsFound % LAO_LOOKAHEAD].acceptMarked(text);
  459. cpWordLength = words[wordsFound % LAO_LOOKAHEAD].markedCPLength();
  460. wordsFound += 1;
  461. }
  462. // We come here after having either found a word or not. We look ahead to the
  463. // next word. If it's not a dictionary word, we will combine it with the word we
  464. // just found (if there is one), but only if the preceding word does not exceed
  465. // the threshold.
  466. // The text iterator should now be positioned at the end of the word we found.
  467. if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < LAO_ROOT_COMBINE_THRESHOLD) {
  468. // if it is a dictionary word, do nothing. If it isn't, then if there is
  469. // no preceding word, or the non-word shares less than the minimum threshold
  470. // of characters with a dictionary word, then scan to resynchronize
  471. if (words[wordsFound % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  472. && (cuWordLength == 0
  473. || words[wordsFound%LAO_LOOKAHEAD].longestPrefix() < LAO_PREFIX_COMBINE_THRESHOLD)) {
  474. // Look for a plausible word boundary
  475. int32_t remaining = rangeEnd - (current + cuWordLength);
  476. UChar32 pc;
  477. UChar32 uc;
  478. int32_t chars = 0;
  479. for (;;) {
  480. int32_t pcIndex = (int32_t)utext_getNativeIndex(text);
  481. pc = utext_next32(text);
  482. int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex;
  483. chars += pcSize;
  484. remaining -= pcSize;
  485. if (remaining <= 0) {
  486. break;
  487. }
  488. uc = utext_current32(text);
  489. if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
  490. // Maybe. See if it's in the dictionary.
  491. // TODO: this looks iffy; compare with old code.
  492. int32_t num_candidates = words[(wordsFound + 1) % LAO_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  493. utext_setNativeIndex(text, current + cuWordLength + chars);
  494. if (num_candidates > 0) {
  495. break;
  496. }
  497. }
  498. }
  499. // Bump the word count if there wasn't already one
  500. if (cuWordLength <= 0) {
  501. wordsFound += 1;
  502. }
  503. // Update the length with the passed-over characters
  504. cuWordLength += chars;
  505. }
  506. else {
  507. // Back up to where we were for next iteration
  508. utext_setNativeIndex(text, current + cuWordLength);
  509. }
  510. }
  511. // Never stop before a combining mark.
  512. int32_t currPos;
  513. while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
  514. utext_next32(text);
  515. cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos;
  516. }
  517. // Look ahead for possible suffixes if a dictionary word does not follow.
  518. // We do this in code rather than using a rule so that the heuristic
  519. // resynch continues to function. For example, one of the suffix characters
  520. // could be a typo in the middle of a word.
  521. // NOT CURRENTLY APPLICABLE TO LAO
  522. // Did we find a word on this iteration? If so, push it on the break stack
  523. if (cuWordLength > 0) {
  524. foundBreaks.push((current+cuWordLength), status);
  525. }
  526. }
  527. // Don't return a break for the end of the dictionary range if there is one there.
  528. if (foundBreaks.peeki() >= rangeEnd) {
  529. (void) foundBreaks.popi();
  530. wordsFound -= 1;
  531. }
  532. return wordsFound;
  533. }
  534. /*
  535. ******************************************************************
  536. * BurmeseBreakEngine
  537. */
  538. // How many words in a row are "good enough"?
  539. static const int32_t BURMESE_LOOKAHEAD = 3;
  540. // Will not combine a non-word with a preceding dictionary word longer than this
  541. static const int32_t BURMESE_ROOT_COMBINE_THRESHOLD = 3;
  542. // Will not combine a non-word that shares at least this much prefix with a
  543. // dictionary word, with a preceding word
  544. static const int32_t BURMESE_PREFIX_COMBINE_THRESHOLD = 3;
  545. // Minimum word size
  546. static const int32_t BURMESE_MIN_WORD = 2;
  547. // Minimum number of characters for two words
  548. static const int32_t BURMESE_MIN_WORD_SPAN = BURMESE_MIN_WORD * 2;
  549. BurmeseBreakEngine::BurmeseBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
  550. : DictionaryBreakEngine(),
  551. fDictionary(adoptDictionary)
  552. {
  553. UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
  554. UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Mymr");
  555. fBeginWordSet.add(0x1000, 0x102A); // basic consonants and independent vowels
  556. fEndWordSet.applyPattern(UnicodeString(u"[[:Mymr:]&[:LineBreak=SA:]]"), status);
  557. fMarkSet.applyPattern(UnicodeString(u"[[:Mymr:]&[:LineBreak=SA:]&[:M:]]"), status);
  558. fMarkSet.add(0x0020);
  559. if (U_SUCCESS(status)) {
  560. setCharacters(fEndWordSet);
  561. }
  562. // Compact for caching.
  563. fMarkSet.compact();
  564. fEndWordSet.compact();
  565. fBeginWordSet.compact();
  566. UTRACE_EXIT_STATUS(status);
  567. }
  568. BurmeseBreakEngine::~BurmeseBreakEngine() {
  569. delete fDictionary;
  570. }
  571. int32_t
  572. BurmeseBreakEngine::divideUpDictionaryRange( UText *text,
  573. int32_t rangeStart,
  574. int32_t rangeEnd,
  575. UVector32 &foundBreaks,
  576. UBool /* isPhraseBreaking */,
  577. UErrorCode& status ) const {
  578. if (U_FAILURE(status)) return 0;
  579. if ((rangeEnd - rangeStart) < BURMESE_MIN_WORD_SPAN) {
  580. return 0; // Not enough characters for two words
  581. }
  582. uint32_t wordsFound = 0;
  583. int32_t cpWordLength = 0;
  584. int32_t cuWordLength = 0;
  585. int32_t current;
  586. PossibleWord words[BURMESE_LOOKAHEAD];
  587. utext_setNativeIndex(text, rangeStart);
  588. while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
  589. cuWordLength = 0;
  590. cpWordLength = 0;
  591. // Look for candidate words at the current position
  592. int32_t candidates = words[wordsFound%BURMESE_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  593. // If we found exactly one, use that
  594. if (candidates == 1) {
  595. cuWordLength = words[wordsFound % BURMESE_LOOKAHEAD].acceptMarked(text);
  596. cpWordLength = words[wordsFound % BURMESE_LOOKAHEAD].markedCPLength();
  597. wordsFound += 1;
  598. }
  599. // If there was more than one, see which one can take us forward the most words
  600. else if (candidates > 1) {
  601. // If we're already at the end of the range, we're done
  602. if (utext_getNativeIndex(text) >= rangeEnd) {
  603. goto foundBest;
  604. }
  605. do {
  606. if (words[(wordsFound + 1) % BURMESE_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
  607. // Followed by another dictionary word; mark first word as a good candidate
  608. words[wordsFound%BURMESE_LOOKAHEAD].markCurrent();
  609. // If we're already at the end of the range, we're done
  610. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  611. goto foundBest;
  612. }
  613. // See if any of the possible second words is followed by a third word
  614. do {
  615. // If we find a third word, stop right away
  616. if (words[(wordsFound + 2) % BURMESE_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
  617. words[wordsFound % BURMESE_LOOKAHEAD].markCurrent();
  618. goto foundBest;
  619. }
  620. }
  621. while (words[(wordsFound + 1) % BURMESE_LOOKAHEAD].backUp(text));
  622. }
  623. }
  624. while (words[wordsFound % BURMESE_LOOKAHEAD].backUp(text));
  625. foundBest:
  626. cuWordLength = words[wordsFound % BURMESE_LOOKAHEAD].acceptMarked(text);
  627. cpWordLength = words[wordsFound % BURMESE_LOOKAHEAD].markedCPLength();
  628. wordsFound += 1;
  629. }
  630. // We come here after having either found a word or not. We look ahead to the
  631. // next word. If it's not a dictionary word, we will combine it with the word we
  632. // just found (if there is one), but only if the preceding word does not exceed
  633. // the threshold.
  634. // The text iterator should now be positioned at the end of the word we found.
  635. if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < BURMESE_ROOT_COMBINE_THRESHOLD) {
  636. // if it is a dictionary word, do nothing. If it isn't, then if there is
  637. // no preceding word, or the non-word shares less than the minimum threshold
  638. // of characters with a dictionary word, then scan to resynchronize
  639. if (words[wordsFound % BURMESE_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  640. && (cuWordLength == 0
  641. || words[wordsFound%BURMESE_LOOKAHEAD].longestPrefix() < BURMESE_PREFIX_COMBINE_THRESHOLD)) {
  642. // Look for a plausible word boundary
  643. int32_t remaining = rangeEnd - (current + cuWordLength);
  644. UChar32 pc;
  645. UChar32 uc;
  646. int32_t chars = 0;
  647. for (;;) {
  648. int32_t pcIndex = (int32_t)utext_getNativeIndex(text);
  649. pc = utext_next32(text);
  650. int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex;
  651. chars += pcSize;
  652. remaining -= pcSize;
  653. if (remaining <= 0) {
  654. break;
  655. }
  656. uc = utext_current32(text);
  657. if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
  658. // Maybe. See if it's in the dictionary.
  659. // TODO: this looks iffy; compare with old code.
  660. int32_t num_candidates = words[(wordsFound + 1) % BURMESE_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  661. utext_setNativeIndex(text, current + cuWordLength + chars);
  662. if (num_candidates > 0) {
  663. break;
  664. }
  665. }
  666. }
  667. // Bump the word count if there wasn't already one
  668. if (cuWordLength <= 0) {
  669. wordsFound += 1;
  670. }
  671. // Update the length with the passed-over characters
  672. cuWordLength += chars;
  673. }
  674. else {
  675. // Back up to where we were for next iteration
  676. utext_setNativeIndex(text, current + cuWordLength);
  677. }
  678. }
  679. // Never stop before a combining mark.
  680. int32_t currPos;
  681. while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
  682. utext_next32(text);
  683. cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos;
  684. }
  685. // Look ahead for possible suffixes if a dictionary word does not follow.
  686. // We do this in code rather than using a rule so that the heuristic
  687. // resynch continues to function. For example, one of the suffix characters
  688. // could be a typo in the middle of a word.
  689. // NOT CURRENTLY APPLICABLE TO BURMESE
  690. // Did we find a word on this iteration? If so, push it on the break stack
  691. if (cuWordLength > 0) {
  692. foundBreaks.push((current+cuWordLength), status);
  693. }
  694. }
  695. // Don't return a break for the end of the dictionary range if there is one there.
  696. if (foundBreaks.peeki() >= rangeEnd) {
  697. (void) foundBreaks.popi();
  698. wordsFound -= 1;
  699. }
  700. return wordsFound;
  701. }
  702. /*
  703. ******************************************************************
  704. * KhmerBreakEngine
  705. */
  706. // How many words in a row are "good enough"?
  707. static const int32_t KHMER_LOOKAHEAD = 3;
  708. // Will not combine a non-word with a preceding dictionary word longer than this
  709. static const int32_t KHMER_ROOT_COMBINE_THRESHOLD = 3;
  710. // Will not combine a non-word that shares at least this much prefix with a
  711. // dictionary word, with a preceding word
  712. static const int32_t KHMER_PREFIX_COMBINE_THRESHOLD = 3;
  713. // Minimum word size
  714. static const int32_t KHMER_MIN_WORD = 2;
  715. // Minimum number of characters for two words
  716. static const int32_t KHMER_MIN_WORD_SPAN = KHMER_MIN_WORD * 2;
  717. KhmerBreakEngine::KhmerBreakEngine(DictionaryMatcher *adoptDictionary, UErrorCode &status)
  718. : DictionaryBreakEngine(),
  719. fDictionary(adoptDictionary)
  720. {
  721. UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
  722. UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Khmr");
  723. UnicodeSet khmerWordSet(UnicodeString(u"[[:Khmr:]&[:LineBreak=SA:]]"), status);
  724. if (U_SUCCESS(status)) {
  725. setCharacters(khmerWordSet);
  726. }
  727. fMarkSet.applyPattern(UnicodeString(u"[[:Khmr:]&[:LineBreak=SA:]&[:M:]]"), status);
  728. fMarkSet.add(0x0020);
  729. fEndWordSet = khmerWordSet;
  730. fBeginWordSet.add(0x1780, 0x17B3);
  731. //fBeginWordSet.add(0x17A3, 0x17A4); // deprecated vowels
  732. //fEndWordSet.remove(0x17A5, 0x17A9); // Khmer independent vowels that can't end a word
  733. //fEndWordSet.remove(0x17B2); // Khmer independent vowel that can't end a word
  734. fEndWordSet.remove(0x17D2); // KHMER SIGN COENG that combines some following characters
  735. //fEndWordSet.remove(0x17B6, 0x17C5); // Remove dependent vowels
  736. // fEndWordSet.remove(0x0E31); // MAI HAN-AKAT
  737. // fEndWordSet.remove(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
  738. // fBeginWordSet.add(0x0E01, 0x0E2E); // KO KAI through HO NOKHUK
  739. // fBeginWordSet.add(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
  740. // fSuffixSet.add(THAI_PAIYANNOI);
  741. // fSuffixSet.add(THAI_MAIYAMOK);
  742. // Compact for caching.
  743. fMarkSet.compact();
  744. fEndWordSet.compact();
  745. fBeginWordSet.compact();
  746. // fSuffixSet.compact();
  747. UTRACE_EXIT_STATUS(status);
  748. }
  749. KhmerBreakEngine::~KhmerBreakEngine() {
  750. delete fDictionary;
  751. }
  752. int32_t
  753. KhmerBreakEngine::divideUpDictionaryRange( UText *text,
  754. int32_t rangeStart,
  755. int32_t rangeEnd,
  756. UVector32 &foundBreaks,
  757. UBool /* isPhraseBreaking */,
  758. UErrorCode& status ) const {
  759. if (U_FAILURE(status)) return 0;
  760. if ((rangeEnd - rangeStart) < KHMER_MIN_WORD_SPAN) {
  761. return 0; // Not enough characters for two words
  762. }
  763. uint32_t wordsFound = 0;
  764. int32_t cpWordLength = 0;
  765. int32_t cuWordLength = 0;
  766. int32_t current;
  767. PossibleWord words[KHMER_LOOKAHEAD];
  768. utext_setNativeIndex(text, rangeStart);
  769. while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
  770. cuWordLength = 0;
  771. cpWordLength = 0;
  772. // Look for candidate words at the current position
  773. int32_t candidates = words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  774. // If we found exactly one, use that
  775. if (candidates == 1) {
  776. cuWordLength = words[wordsFound % KHMER_LOOKAHEAD].acceptMarked(text);
  777. cpWordLength = words[wordsFound % KHMER_LOOKAHEAD].markedCPLength();
  778. wordsFound += 1;
  779. }
  780. // If there was more than one, see which one can take us forward the most words
  781. else if (candidates > 1) {
  782. // If we're already at the end of the range, we're done
  783. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  784. goto foundBest;
  785. }
  786. do {
  787. if (words[(wordsFound + 1) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
  788. // Followed by another dictionary word; mark first word as a good candidate
  789. words[wordsFound % KHMER_LOOKAHEAD].markCurrent();
  790. // If we're already at the end of the range, we're done
  791. if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
  792. goto foundBest;
  793. }
  794. // See if any of the possible second words is followed by a third word
  795. do {
  796. // If we find a third word, stop right away
  797. if (words[(wordsFound + 2) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
  798. words[wordsFound % KHMER_LOOKAHEAD].markCurrent();
  799. goto foundBest;
  800. }
  801. }
  802. while (words[(wordsFound + 1) % KHMER_LOOKAHEAD].backUp(text));
  803. }
  804. }
  805. while (words[wordsFound % KHMER_LOOKAHEAD].backUp(text));
  806. foundBest:
  807. cuWordLength = words[wordsFound % KHMER_LOOKAHEAD].acceptMarked(text);
  808. cpWordLength = words[wordsFound % KHMER_LOOKAHEAD].markedCPLength();
  809. wordsFound += 1;
  810. }
  811. // We come here after having either found a word or not. We look ahead to the
  812. // next word. If it's not a dictionary word, we will combine it with the word we
  813. // just found (if there is one), but only if the preceding word does not exceed
  814. // the threshold.
  815. // The text iterator should now be positioned at the end of the word we found.
  816. if ((int32_t)utext_getNativeIndex(text) < rangeEnd && cpWordLength < KHMER_ROOT_COMBINE_THRESHOLD) {
  817. // if it is a dictionary word, do nothing. If it isn't, then if there is
  818. // no preceding word, or the non-word shares less than the minimum threshold
  819. // of characters with a dictionary word, then scan to resynchronize
  820. if (words[wordsFound % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  821. && (cuWordLength == 0
  822. || words[wordsFound % KHMER_LOOKAHEAD].longestPrefix() < KHMER_PREFIX_COMBINE_THRESHOLD)) {
  823. // Look for a plausible word boundary
  824. int32_t remaining = rangeEnd - (current+cuWordLength);
  825. UChar32 pc;
  826. UChar32 uc;
  827. int32_t chars = 0;
  828. for (;;) {
  829. int32_t pcIndex = (int32_t)utext_getNativeIndex(text);
  830. pc = utext_next32(text);
  831. int32_t pcSize = (int32_t)utext_getNativeIndex(text) - pcIndex;
  832. chars += pcSize;
  833. remaining -= pcSize;
  834. if (remaining <= 0) {
  835. break;
  836. }
  837. uc = utext_current32(text);
  838. if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
  839. // Maybe. See if it's in the dictionary.
  840. int32_t num_candidates = words[(wordsFound + 1) % KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
  841. utext_setNativeIndex(text, current+cuWordLength+chars);
  842. if (num_candidates > 0) {
  843. break;
  844. }
  845. }
  846. }
  847. // Bump the word count if there wasn't already one
  848. if (cuWordLength <= 0) {
  849. wordsFound += 1;
  850. }
  851. // Update the length with the passed-over characters
  852. cuWordLength += chars;
  853. }
  854. else {
  855. // Back up to where we were for next iteration
  856. utext_setNativeIndex(text, current+cuWordLength);
  857. }
  858. }
  859. // Never stop before a combining mark.
  860. int32_t currPos;
  861. while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
  862. utext_next32(text);
  863. cuWordLength += (int32_t)utext_getNativeIndex(text) - currPos;
  864. }
  865. // Look ahead for possible suffixes if a dictionary word does not follow.
  866. // We do this in code rather than using a rule so that the heuristic
  867. // resynch continues to function. For example, one of the suffix characters
  868. // could be a typo in the middle of a word.
  869. // if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength > 0) {
  870. // if (words[wordsFound%KHMER_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
  871. // && fSuffixSet.contains(uc = utext_current32(text))) {
  872. // if (uc == KHMER_PAIYANNOI) {
  873. // if (!fSuffixSet.contains(utext_previous32(text))) {
  874. // // Skip over previous end and PAIYANNOI
  875. // utext_next32(text);
  876. // utext_next32(text);
  877. // wordLength += 1; // Add PAIYANNOI to word
  878. // uc = utext_current32(text); // Fetch next character
  879. // }
  880. // else {
  881. // // Restore prior position
  882. // utext_next32(text);
  883. // }
  884. // }
  885. // if (uc == KHMER_MAIYAMOK) {
  886. // if (utext_previous32(text) != KHMER_MAIYAMOK) {
  887. // // Skip over previous end and MAIYAMOK
  888. // utext_next32(text);
  889. // utext_next32(text);
  890. // wordLength += 1; // Add MAIYAMOK to word
  891. // }
  892. // else {
  893. // // Restore prior position
  894. // utext_next32(text);
  895. // }
  896. // }
  897. // }
  898. // else {
  899. // utext_setNativeIndex(text, current+wordLength);
  900. // }
  901. // }
  902. // Did we find a word on this iteration? If so, push it on the break stack
  903. if (cuWordLength > 0) {
  904. foundBreaks.push((current+cuWordLength), status);
  905. }
  906. }
  907. // Don't return a break for the end of the dictionary range if there is one there.
  908. if (foundBreaks.peeki() >= rangeEnd) {
  909. (void) foundBreaks.popi();
  910. wordsFound -= 1;
  911. }
  912. return wordsFound;
  913. }
  914. #if !UCONFIG_NO_NORMALIZATION
  915. /*
  916. ******************************************************************
  917. * CjkBreakEngine
  918. */
  919. static const uint32_t kuint32max = 0xFFFFFFFF;
  920. CjkBreakEngine::CjkBreakEngine(DictionaryMatcher *adoptDictionary, LanguageType type, UErrorCode &status)
  921. : DictionaryBreakEngine(), fDictionary(adoptDictionary), isCj(false) {
  922. UTRACE_ENTRY(UTRACE_UBRK_CREATE_BREAK_ENGINE);
  923. UTRACE_DATA1(UTRACE_INFO, "dictbe=%s", "Hani");
  924. fMlBreakEngine = nullptr;
  925. nfkcNorm2 = Normalizer2::getNFKCInstance(status);
  926. // Korean dictionary only includes Hangul syllables
  927. fHangulWordSet.applyPattern(UnicodeString(u"[\\uac00-\\ud7a3]"), status);
  928. fHangulWordSet.compact();
  929. // Digits, open puncutation and Alphabetic characters.
  930. fDigitOrOpenPunctuationOrAlphabetSet.applyPattern(
  931. UnicodeString(u"[[:Nd:][:Pi:][:Ps:][:Alphabetic:]]"), status);
  932. fDigitOrOpenPunctuationOrAlphabetSet.compact();
  933. fClosePunctuationSet.applyPattern(UnicodeString(u"[[:Pc:][:Pd:][:Pe:][:Pf:][:Po:]]"), status);
  934. fClosePunctuationSet.compact();
  935. // handle Korean and Japanese/Chinese using different dictionaries
  936. if (type == kKorean) {
  937. if (U_SUCCESS(status)) {
  938. setCharacters(fHangulWordSet);
  939. }
  940. } else { // Chinese and Japanese
  941. UnicodeSet cjSet(UnicodeString(u"[[:Han:][:Hiragana:][:Katakana:]\\u30fc\\uff70\\uff9e\\uff9f]"), status);
  942. isCj = true;
  943. if (U_SUCCESS(status)) {
  944. setCharacters(cjSet);
  945. #if UCONFIG_USE_ML_PHRASE_BREAKING
  946. fMlBreakEngine = new MlBreakEngine(fDigitOrOpenPunctuationOrAlphabetSet,
  947. fClosePunctuationSet, status);
  948. if (fMlBreakEngine == nullptr) {
  949. status = U_MEMORY_ALLOCATION_ERROR;
  950. }
  951. #else
  952. initJapanesePhraseParameter(status);
  953. #endif
  954. }
  955. }
  956. UTRACE_EXIT_STATUS(status);
  957. }
  958. CjkBreakEngine::~CjkBreakEngine(){
  959. delete fDictionary;
  960. delete fMlBreakEngine;
  961. }
  962. // The katakanaCost values below are based on the length frequencies of all
  963. // katakana phrases in the dictionary
  964. static const int32_t kMaxKatakanaLength = 8;
  965. static const int32_t kMaxKatakanaGroupLength = 20;
  966. static const uint32_t maxSnlp = 255;
  967. static inline uint32_t getKatakanaCost(int32_t wordLength){
  968. //TODO: fill array with actual values from dictionary!
  969. static const uint32_t katakanaCost[kMaxKatakanaLength + 1]
  970. = {8192, 984, 408, 240, 204, 252, 300, 372, 480};
  971. return (wordLength > kMaxKatakanaLength) ? 8192 : katakanaCost[wordLength];
  972. }
  973. static inline bool isKatakana(UChar32 value) {
  974. return (value >= 0x30A1 && value <= 0x30FE && value != 0x30FB) ||
  975. (value >= 0xFF66 && value <= 0xFF9f);
  976. }
  977. // Function for accessing internal utext flags.
  978. // Replicates an internal UText function.
  979. static inline int32_t utext_i32_flag(int32_t bitIndex) {
  980. return (int32_t)1 << bitIndex;
  981. }
  982. /*
  983. * @param text A UText representing the text
  984. * @param rangeStart The start of the range of dictionary characters
  985. * @param rangeEnd The end of the range of dictionary characters
  986. * @param foundBreaks vector<int32> to receive the break positions
  987. * @return The number of breaks found
  988. */
  989. int32_t
  990. CjkBreakEngine::divideUpDictionaryRange( UText *inText,
  991. int32_t rangeStart,
  992. int32_t rangeEnd,
  993. UVector32 &foundBreaks,
  994. UBool isPhraseBreaking,
  995. UErrorCode& status) const {
  996. if (U_FAILURE(status)) return 0;
  997. if (rangeStart >= rangeEnd) {
  998. return 0;
  999. }
  1000. // UnicodeString version of input UText, NFKC normalized if necessary.
  1001. UnicodeString inString;
  1002. // inputMap[inStringIndex] = corresponding native index from UText inText.
  1003. // If nullptr then mapping is 1:1
  1004. LocalPointer<UVector32> inputMap;
  1005. // if UText has the input string as one contiguous UTF-16 chunk
  1006. if ((inText->providerProperties & utext_i32_flag(UTEXT_PROVIDER_STABLE_CHUNKS)) &&
  1007. inText->chunkNativeStart <= rangeStart &&
  1008. inText->chunkNativeLimit >= rangeEnd &&
  1009. inText->nativeIndexingLimit >= rangeEnd - inText->chunkNativeStart) {
  1010. // Input UText is in one contiguous UTF-16 chunk.
  1011. // Use Read-only aliasing UnicodeString.
  1012. inString.setTo(false,
  1013. inText->chunkContents + rangeStart - inText->chunkNativeStart,
  1014. rangeEnd - rangeStart);
  1015. } else {
  1016. // Copy the text from the original inText (UText) to inString (UnicodeString).
  1017. // Create a map from UnicodeString indices -> UText offsets.
  1018. utext_setNativeIndex(inText, rangeStart);
  1019. int32_t limit = rangeEnd;
  1020. U_ASSERT(limit <= utext_nativeLength(inText));
  1021. if (limit > utext_nativeLength(inText)) {
  1022. limit = (int32_t)utext_nativeLength(inText);
  1023. }
  1024. inputMap.adoptInsteadAndCheckErrorCode(new UVector32(status), status);
  1025. if (U_FAILURE(status)) {
  1026. return 0;
  1027. }
  1028. while (utext_getNativeIndex(inText) < limit) {
  1029. int32_t nativePosition = (int32_t)utext_getNativeIndex(inText);
  1030. UChar32 c = utext_next32(inText);
  1031. U_ASSERT(c != U_SENTINEL);
  1032. inString.append(c);
  1033. while (inputMap->size() < inString.length()) {
  1034. inputMap->addElement(nativePosition, status);
  1035. }
  1036. }
  1037. inputMap->addElement(limit, status);
  1038. }
  1039. if (!nfkcNorm2->isNormalized(inString, status)) {
  1040. UnicodeString normalizedInput;
  1041. // normalizedMap[normalizedInput position] == original UText position.
  1042. LocalPointer<UVector32> normalizedMap(new UVector32(status), status);
  1043. if (U_FAILURE(status)) {
  1044. return 0;
  1045. }
  1046. UnicodeString fragment;
  1047. UnicodeString normalizedFragment;
  1048. for (int32_t srcI = 0; srcI < inString.length();) { // Once per normalization chunk
  1049. fragment.remove();
  1050. int32_t fragmentStartI = srcI;
  1051. UChar32 c = inString.char32At(srcI);
  1052. for (;;) {
  1053. fragment.append(c);
  1054. srcI = inString.moveIndex32(srcI, 1);
  1055. if (srcI == inString.length()) {
  1056. break;
  1057. }
  1058. c = inString.char32At(srcI);
  1059. if (nfkcNorm2->hasBoundaryBefore(c)) {
  1060. break;
  1061. }
  1062. }
  1063. nfkcNorm2->normalize(fragment, normalizedFragment, status);
  1064. normalizedInput.append(normalizedFragment);
  1065. // Map every position in the normalized chunk to the start of the chunk
  1066. // in the original input.
  1067. int32_t fragmentOriginalStart = inputMap.isValid() ?
  1068. inputMap->elementAti(fragmentStartI) : fragmentStartI+rangeStart;
  1069. while (normalizedMap->size() < normalizedInput.length()) {
  1070. normalizedMap->addElement(fragmentOriginalStart, status);
  1071. if (U_FAILURE(status)) {
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. U_ASSERT(normalizedMap->size() == normalizedInput.length());
  1077. int32_t nativeEnd = inputMap.isValid() ?
  1078. inputMap->elementAti(inString.length()) : inString.length()+rangeStart;
  1079. normalizedMap->addElement(nativeEnd, status);
  1080. inputMap = std::move(normalizedMap);
  1081. inString = std::move(normalizedInput);
  1082. }
  1083. int32_t numCodePts = inString.countChar32();
  1084. if (numCodePts != inString.length()) {
  1085. // There are supplementary characters in the input.
  1086. // The dictionary will produce boundary positions in terms of code point indexes,
  1087. // not in terms of code unit string indexes.
  1088. // Use the inputMap mechanism to take care of this in addition to indexing differences
  1089. // from normalization and/or UTF-8 input.
  1090. UBool hadExistingMap = inputMap.isValid();
  1091. if (!hadExistingMap) {
  1092. inputMap.adoptInsteadAndCheckErrorCode(new UVector32(status), status);
  1093. if (U_FAILURE(status)) {
  1094. return 0;
  1095. }
  1096. }
  1097. int32_t cpIdx = 0;
  1098. for (int32_t cuIdx = 0; ; cuIdx = inString.moveIndex32(cuIdx, 1)) {
  1099. U_ASSERT(cuIdx >= cpIdx);
  1100. if (hadExistingMap) {
  1101. inputMap->setElementAt(inputMap->elementAti(cuIdx), cpIdx);
  1102. } else {
  1103. inputMap->addElement(cuIdx+rangeStart, status);
  1104. }
  1105. cpIdx++;
  1106. if (cuIdx == inString.length()) {
  1107. break;
  1108. }
  1109. }
  1110. }
  1111. #if UCONFIG_USE_ML_PHRASE_BREAKING
  1112. // PhraseBreaking is supported in ja and ko; MlBreakEngine only supports ja.
  1113. if (isPhraseBreaking && isCj) {
  1114. return fMlBreakEngine->divideUpRange(inText, rangeStart, rangeEnd, foundBreaks, inString,
  1115. inputMap, status);
  1116. }
  1117. #endif
  1118. // bestSnlp[i] is the snlp of the best segmentation of the first i
  1119. // code points in the range to be matched.
  1120. UVector32 bestSnlp(numCodePts + 1, status);
  1121. bestSnlp.addElement(0, status);
  1122. for(int32_t i = 1; i <= numCodePts; i++) {
  1123. bestSnlp.addElement(kuint32max, status);
  1124. }
  1125. // prev[i] is the index of the last CJK code point in the previous word in
  1126. // the best segmentation of the first i characters.
  1127. UVector32 prev(numCodePts + 1, status);
  1128. for(int32_t i = 0; i <= numCodePts; i++){
  1129. prev.addElement(-1, status);
  1130. }
  1131. const int32_t maxWordSize = 20;
  1132. UVector32 values(numCodePts, status);
  1133. values.setSize(numCodePts);
  1134. UVector32 lengths(numCodePts, status);
  1135. lengths.setSize(numCodePts);
  1136. UText fu = UTEXT_INITIALIZER;
  1137. utext_openUnicodeString(&fu, &inString, &status);
  1138. // Dynamic programming to find the best segmentation.
  1139. // In outer loop, i is the code point index,
  1140. // ix is the corresponding string (code unit) index.
  1141. // They differ when the string contains supplementary characters.
  1142. int32_t ix = 0;
  1143. bool is_prev_katakana = false;
  1144. for (int32_t i = 0; i < numCodePts; ++i, ix = inString.moveIndex32(ix, 1)) {
  1145. if ((uint32_t)bestSnlp.elementAti(i) == kuint32max) {
  1146. continue;
  1147. }
  1148. int32_t count;
  1149. utext_setNativeIndex(&fu, ix);
  1150. count = fDictionary->matches(&fu, maxWordSize, numCodePts,
  1151. nullptr, lengths.getBuffer(), values.getBuffer(), nullptr);
  1152. // Note: lengths is filled with code point lengths
  1153. // The nullptr parameter is the ignored code unit lengths.
  1154. // if there are no single character matches found in the dictionary
  1155. // starting with this character, treat character as a 1-character word
  1156. // with the highest value possible, i.e. the least likely to occur.
  1157. // Exclude Korean characters from this treatment, as they should be left
  1158. // together by default.
  1159. if ((count == 0 || lengths.elementAti(0) != 1) &&
  1160. !fHangulWordSet.contains(inString.char32At(ix))) {
  1161. values.setElementAt(maxSnlp, count); // 255
  1162. lengths.setElementAt(1, count++);
  1163. }
  1164. for (int32_t j = 0; j < count; j++) {
  1165. uint32_t newSnlp = (uint32_t)bestSnlp.elementAti(i) + (uint32_t)values.elementAti(j);
  1166. int32_t ln_j_i = lengths.elementAti(j) + i;
  1167. if (newSnlp < (uint32_t)bestSnlp.elementAti(ln_j_i)) {
  1168. bestSnlp.setElementAt(newSnlp, ln_j_i);
  1169. prev.setElementAt(i, ln_j_i);
  1170. }
  1171. }
  1172. // In Japanese,
  1173. // Katakana word in single character is pretty rare. So we apply
  1174. // the following heuristic to Katakana: any continuous run of Katakana
  1175. // characters is considered a candidate word with a default cost
  1176. // specified in the katakanaCost table according to its length.
  1177. bool is_katakana = isKatakana(inString.char32At(ix));
  1178. int32_t katakanaRunLength = 1;
  1179. if (!is_prev_katakana && is_katakana) {
  1180. int32_t j = inString.moveIndex32(ix, 1);
  1181. // Find the end of the continuous run of Katakana characters
  1182. while (j < inString.length() && katakanaRunLength < kMaxKatakanaGroupLength &&
  1183. isKatakana(inString.char32At(j))) {
  1184. j = inString.moveIndex32(j, 1);
  1185. katakanaRunLength++;
  1186. }
  1187. if (katakanaRunLength < kMaxKatakanaGroupLength) {
  1188. uint32_t newSnlp = bestSnlp.elementAti(i) + getKatakanaCost(katakanaRunLength);
  1189. if (newSnlp < (uint32_t)bestSnlp.elementAti(i+katakanaRunLength)) {
  1190. bestSnlp.setElementAt(newSnlp, i+katakanaRunLength);
  1191. prev.setElementAt(i, i+katakanaRunLength); // prev[j] = i;
  1192. }
  1193. }
  1194. }
  1195. is_prev_katakana = is_katakana;
  1196. }
  1197. utext_close(&fu);
  1198. // Start pushing the optimal offset index into t_boundary (t for tentative).
  1199. // prev[numCodePts] is guaranteed to be meaningful.
  1200. // We'll first push in the reverse order, i.e.,
  1201. // t_boundary[0] = numCodePts, and afterwards do a swap.
  1202. UVector32 t_boundary(numCodePts+1, status);
  1203. int32_t numBreaks = 0;
  1204. // No segmentation found, set boundary to end of range
  1205. if ((uint32_t)bestSnlp.elementAti(numCodePts) == kuint32max) {
  1206. t_boundary.addElement(numCodePts, status);
  1207. numBreaks++;
  1208. } else if (isPhraseBreaking) {
  1209. t_boundary.addElement(numCodePts, status);
  1210. if(U_SUCCESS(status)) {
  1211. numBreaks++;
  1212. int32_t prevIdx = numCodePts;
  1213. int32_t codeUnitIdx = -1;
  1214. int32_t prevCodeUnitIdx = -1;
  1215. int32_t length = -1;
  1216. for (int32_t i = prev.elementAti(numCodePts); i > 0; i = prev.elementAti(i)) {
  1217. codeUnitIdx = inString.moveIndex32(0, i);
  1218. prevCodeUnitIdx = inString.moveIndex32(0, prevIdx);
  1219. // Calculate the length by using the code unit.
  1220. length = prevCodeUnitIdx - codeUnitIdx;
  1221. prevIdx = i;
  1222. // Keep the breakpoint if the pattern is not in the fSkipSet and continuous Katakana
  1223. // characters don't occur.
  1224. if (!fSkipSet.containsKey(inString.tempSubString(codeUnitIdx, length))
  1225. && (!isKatakana(inString.char32At(inString.moveIndex32(codeUnitIdx, -1)))
  1226. || !isKatakana(inString.char32At(codeUnitIdx)))) {
  1227. t_boundary.addElement(i, status);
  1228. numBreaks++;
  1229. }
  1230. }
  1231. }
  1232. } else {
  1233. for (int32_t i = numCodePts; i > 0; i = prev.elementAti(i)) {
  1234. t_boundary.addElement(i, status);
  1235. numBreaks++;
  1236. }
  1237. U_ASSERT(prev.elementAti(t_boundary.elementAti(numBreaks - 1)) == 0);
  1238. }
  1239. // Add a break for the start of the dictionary range if there is not one
  1240. // there already.
  1241. if (foundBreaks.size() == 0 || foundBreaks.peeki() < rangeStart) {
  1242. t_boundary.addElement(0, status);
  1243. numBreaks++;
  1244. }
  1245. // Now that we're done, convert positions in t_boundary[] (indices in
  1246. // the normalized input string) back to indices in the original input UText
  1247. // while reversing t_boundary and pushing values to foundBreaks.
  1248. int32_t prevCPPos = -1;
  1249. int32_t prevUTextPos = -1;
  1250. int32_t correctedNumBreaks = 0;
  1251. for (int32_t i = numBreaks - 1; i >= 0; i--) {
  1252. int32_t cpPos = t_boundary.elementAti(i);
  1253. U_ASSERT(cpPos > prevCPPos);
  1254. int32_t utextPos = inputMap.isValid() ? inputMap->elementAti(cpPos) : cpPos + rangeStart;
  1255. U_ASSERT(utextPos >= prevUTextPos);
  1256. if (utextPos > prevUTextPos) {
  1257. // Boundaries are added to foundBreaks output in ascending order.
  1258. U_ASSERT(foundBreaks.size() == 0 || foundBreaks.peeki() < utextPos);
  1259. // In phrase breaking, there has to be a breakpoint between Cj character and close
  1260. // punctuation.
  1261. // E.g.[携帯電話]正しい選択 -> [携帯▁電話]▁正しい▁選択 -> breakpoint between ] and 正
  1262. if (utextPos != rangeStart
  1263. || (isPhraseBreaking && utextPos > 0
  1264. && fClosePunctuationSet.contains(utext_char32At(inText, utextPos - 1)))) {
  1265. foundBreaks.push(utextPos, status);
  1266. correctedNumBreaks++;
  1267. }
  1268. } else {
  1269. // Normalization expanded the input text, the dictionary found a boundary
  1270. // within the expansion, giving two boundaries with the same index in the
  1271. // original text. Ignore the second. See ticket #12918.
  1272. --numBreaks;
  1273. }
  1274. prevCPPos = cpPos;
  1275. prevUTextPos = utextPos;
  1276. }
  1277. (void)prevCPPos; // suppress compiler warnings about unused variable
  1278. UChar32 nextChar = utext_char32At(inText, rangeEnd);
  1279. if (!foundBreaks.isEmpty() && foundBreaks.peeki() == rangeEnd) {
  1280. // In phrase breaking, there has to be a breakpoint between Cj character and
  1281. // the number/open punctuation.
  1282. // E.g. る文字「そうだ、京都」->る▁文字▁「そうだ、▁京都」-> breakpoint between 字 and「
  1283. // E.g. 乗車率90%程度だろうか -> 乗車▁率▁90%▁程度だろうか -> breakpoint between 率 and 9
  1284. // E.g. しかもロゴがUnicode! -> しかも▁ロゴが▁Unicode!-> breakpoint between が and U
  1285. if (isPhraseBreaking) {
  1286. if (!fDigitOrOpenPunctuationOrAlphabetSet.contains(nextChar)) {
  1287. foundBreaks.popi();
  1288. correctedNumBreaks--;
  1289. }
  1290. } else {
  1291. foundBreaks.popi();
  1292. correctedNumBreaks--;
  1293. }
  1294. }
  1295. // inString goes out of scope
  1296. // inputMap goes out of scope
  1297. return correctedNumBreaks;
  1298. }
  1299. void CjkBreakEngine::initJapanesePhraseParameter(UErrorCode& error) {
  1300. loadJapaneseExtensions(error);
  1301. loadHiragana(error);
  1302. }
  1303. void CjkBreakEngine::loadJapaneseExtensions(UErrorCode& error) {
  1304. const char* tag = "extensions";
  1305. ResourceBundle ja(U_ICUDATA_BRKITR, "ja", error);
  1306. if (U_SUCCESS(error)) {
  1307. ResourceBundle bundle = ja.get(tag, error);
  1308. while (U_SUCCESS(error) && bundle.hasNext()) {
  1309. fSkipSet.puti(bundle.getNextString(error), 1, error);
  1310. }
  1311. }
  1312. }
  1313. void CjkBreakEngine::loadHiragana(UErrorCode& error) {
  1314. UnicodeSet hiraganaWordSet(UnicodeString(u"[:Hiragana:]"), error);
  1315. hiraganaWordSet.compact();
  1316. UnicodeSetIterator iterator(hiraganaWordSet);
  1317. while (iterator.next()) {
  1318. fSkipSet.puti(UnicodeString(iterator.getCodepoint()), 1, error);
  1319. }
  1320. }
  1321. #endif
  1322. U_NAMESPACE_END
  1323. #endif /* #if !UCONFIG_NO_BREAK_ITERATION */