ICU-66108.tar.gz
[apple/icu.git] / icuSources / common / rbbi.cpp
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ***************************************************************************
5 * Copyright (C) 1999-2016 International Business Machines Corporation
6 * and others. All rights reserved.
7 ***************************************************************************
8 */
9 //
10 // file: rbbi.cpp Contains the implementation of the rule based break iterator
11 // runtime engine and the API implementation for
12 // class RuleBasedBreakIterator
13 //
14
15 #include "utypeinfo.h" // for 'typeid' to work
16
17 #include "unicode/utypes.h"
18
19 #if !UCONFIG_NO_BREAK_ITERATION
20
21 #include <cinttypes>
22
23 #include "unicode/rbbi.h"
24 #include "unicode/schriter.h"
25 #include "unicode/uchriter.h"
26 #include "unicode/uclean.h"
27 #include "unicode/udata.h"
28 // for <rdar://problem/51193810>
29 #include "unicode/ulocdata.h"
30
31
32 #include "brkeng.h"
33 #include "ucln_cmn.h"
34 #include "cmemory.h"
35 #include "cstring.h"
36 #include "localsvc.h"
37 #include "rbbidata.h"
38 #include "rbbi_cache.h"
39 #include "rbbirb.h"
40 #include "uassert.h"
41 #include "umutex.h"
42 #include "uvectr32.h"
43
44 #ifdef RBBI_DEBUG
45 static UBool gTrace = FALSE;
46 #endif
47
48 U_NAMESPACE_BEGIN
49
50 // The state number of the starting state
51 constexpr int32_t START_STATE = 1;
52
53 // The state-transition value indicating "stop"
54 constexpr int32_t STOP_STATE = 0;
55
56
57 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedBreakIterator)
58
59
60 //=======================================================================
61 // constructors
62 //=======================================================================
63
64 /**
65 * Constructs a RuleBasedBreakIterator that uses the already-created
66 * tables object that is passed in as a parameter.
67 */
68 RuleBasedBreakIterator::RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status)
69 : fSCharIter(UnicodeString())
70 {
71 init(status);
72 fData = new RBBIDataWrapper(data, status); // status checked in constructor
73 if (U_FAILURE(status)) {return;}
74 if(fData == 0) {
75 status = U_MEMORY_ALLOCATION_ERROR;
76 return;
77 }
78 }
79
80 //
81 // Construct from precompiled binary rules (tables). This constructor is public API,
82 // taking the rules as a (const uint8_t *) to match the type produced by getBinaryRules().
83 //
84 RuleBasedBreakIterator::RuleBasedBreakIterator(const uint8_t *compiledRules,
85 uint32_t ruleLength,
86 UErrorCode &status)
87 : fSCharIter(UnicodeString())
88 {
89 init(status);
90 if (U_FAILURE(status)) {
91 return;
92 }
93 if (compiledRules == NULL || ruleLength < sizeof(RBBIDataHeader)) {
94 status = U_ILLEGAL_ARGUMENT_ERROR;
95 return;
96 }
97 const RBBIDataHeader *data = (const RBBIDataHeader *)compiledRules;
98 if (data->fLength > ruleLength) {
99 status = U_ILLEGAL_ARGUMENT_ERROR;
100 return;
101 }
102 fData = new RBBIDataWrapper(data, RBBIDataWrapper::kDontAdopt, status);
103 if (U_FAILURE(status)) {return;}
104 if(fData == 0) {
105 status = U_MEMORY_ALLOCATION_ERROR;
106 return;
107 }
108 }
109
110
111 //-------------------------------------------------------------------------------
112 //
113 // Constructor from a UDataMemory handle to precompiled break rules
114 // stored in an ICU data file.
115 //
116 //-------------------------------------------------------------------------------
117 RuleBasedBreakIterator::RuleBasedBreakIterator(UDataMemory* udm, UErrorCode &status)
118 : fSCharIter(UnicodeString())
119 {
120 init(status);
121 fData = new RBBIDataWrapper(udm, status); // status checked in constructor
122 if (U_FAILURE(status)) {return;}
123 if(fData == 0) {
124 status = U_MEMORY_ALLOCATION_ERROR;
125 return;
126 }
127 }
128
129
130
131 //-------------------------------------------------------------------------------
132 //
133 // Constructor from a set of rules supplied as a string.
134 //
135 //-------------------------------------------------------------------------------
136 RuleBasedBreakIterator::RuleBasedBreakIterator( const UnicodeString &rules,
137 UParseError &parseError,
138 UErrorCode &status)
139 : fSCharIter(UnicodeString())
140 {
141 init(status);
142 if (U_FAILURE(status)) {return;}
143 RuleBasedBreakIterator *bi = (RuleBasedBreakIterator *)
144 RBBIRuleBuilder::createRuleBasedBreakIterator(rules, &parseError, status);
145 // Note: This is a bit awkward. The RBBI ruleBuilder has a factory method that
146 // creates and returns a complete RBBI. From here, in a constructor, we
147 // can't just return the object created by the builder factory, hence
148 // the assignment of the factory created object to "this".
149 if (U_SUCCESS(status)) {
150 *this = *bi;
151 delete bi;
152 }
153 }
154
155
156 //-------------------------------------------------------------------------------
157 //
158 // Default Constructor. Create an empty shell that can be set up later.
159 // Used when creating a RuleBasedBreakIterator from a set
160 // of rules.
161 //-------------------------------------------------------------------------------
162 RuleBasedBreakIterator::RuleBasedBreakIterator()
163 : fSCharIter(UnicodeString())
164 {
165 UErrorCode status = U_ZERO_ERROR;
166 init(status);
167 }
168
169
170 //-------------------------------------------------------------------------------
171 //
172 // Copy constructor. Will produce a break iterator with the same behavior,
173 // and which iterates over the same text, as the one passed in.
174 //
175 //-------------------------------------------------------------------------------
176 RuleBasedBreakIterator::RuleBasedBreakIterator(const RuleBasedBreakIterator& other)
177 : BreakIterator(other),
178 fSCharIter(UnicodeString())
179 {
180 UErrorCode status = U_ZERO_ERROR;
181 this->init(status);
182 *this = other;
183 }
184
185
186 /**
187 * Destructor
188 */
189 RuleBasedBreakIterator::~RuleBasedBreakIterator() {
190 if (fCharIter != &fSCharIter) {
191 // fCharIter was adopted from the outside.
192 delete fCharIter;
193 }
194 fCharIter = NULL;
195
196 utext_close(&fText);
197
198 if (fData != NULL) {
199 fData->removeReference();
200 fData = NULL;
201 }
202 delete fBreakCache;
203 fBreakCache = NULL;
204
205 delete fDictionaryCache;
206 fDictionaryCache = NULL;
207
208 delete fLanguageBreakEngines;
209 fLanguageBreakEngines = NULL;
210
211 delete fUnhandledBreakEngine;
212 fUnhandledBreakEngine = NULL;
213
214 delete [] fLatin1Cat;
215 fLatin1Cat = NULL;
216
217 // <rdar://problem/51193810>
218 delete [] fCatOverrides;
219 fCatOverrides = NULL;
220 fCatOverrideCount = 0;
221 }
222
223 /**
224 * Assignment operator. Sets this iterator to have the same behavior,
225 * and iterate over the same text, as the one passed in.
226 */
227 RuleBasedBreakIterator&
228 RuleBasedBreakIterator::operator=(const RuleBasedBreakIterator& that) {
229 if (this == &that) {
230 return *this;
231 }
232 BreakIterator::operator=(that);
233 fLineWordOpts = that.fLineWordOpts;
234
235 if (fLanguageBreakEngines != NULL) {
236 delete fLanguageBreakEngines;
237 fLanguageBreakEngines = NULL; // Just rebuild for now
238 }
239 // TODO: clone fLanguageBreakEngines from "that"
240 UErrorCode status = U_ZERO_ERROR;
241 utext_clone(&fText, &that.fText, FALSE, TRUE, &status);
242
243 if (fCharIter != &fSCharIter) {
244 delete fCharIter;
245 }
246 fCharIter = &fSCharIter;
247
248 if (that.fCharIter != NULL && that.fCharIter != &that.fSCharIter) {
249 // This is a little bit tricky - it will intially appear that
250 // this->fCharIter is adopted, even if that->fCharIter was
251 // not adopted. That's ok.
252 fCharIter = that.fCharIter->clone();
253 }
254 fSCharIter = that.fSCharIter;
255 if (fCharIter == NULL) {
256 fCharIter = &fSCharIter;
257 }
258
259 if (fData != NULL) {
260 fData->removeReference();
261 fData = NULL;
262 }
263 if (that.fData != NULL) {
264 fData = that.fData->addReference();
265 }
266
267 delete [] fLatin1Cat;
268 fLatin1Cat = NULL;
269
270 // <rdar://problem/51193810>
271 delete [] fCatOverrides;
272 fCatOverrides = NULL;
273 fCatOverrideCount = that.fCatOverrideCount;
274 if (fCatOverrideCount != 0) {
275 fCatOverrides = new CategoryOverride[fCatOverrideCount];
276 for (int32_t orItem = 0; orItem < fCatOverrideCount; ++orItem) {
277 fCatOverrides[orItem] = that.fCatOverrides[orItem];
278 }
279 }
280
281 fPosition = that.fPosition;
282 fRuleStatusIndex = that.fRuleStatusIndex;
283 fDone = that.fDone;
284
285 // TODO: both the dictionary and the main cache need to be copied.
286 // Current position could be within a dictionary range. Trying to continue
287 // the iteration without the caches present would go to the rules, with
288 // the assumption that the current position is on a rule boundary.
289 fBreakCache->reset(fPosition, fRuleStatusIndex);
290 fDictionaryCache->reset();
291
292 return *this;
293 }
294
295
296
297 //-----------------------------------------------------------------------------
298 //
299 // init() Shared initialization routine. Used by all the constructors.
300 // Initializes all fields, leaving the object in a consistent state.
301 //
302 //-----------------------------------------------------------------------------
303 void RuleBasedBreakIterator::init(UErrorCode &status) {
304 fCharIter = NULL;
305 fData = NULL;
306 fLatin1Cat = NULL;
307 fCatOverrides = NULL;
308 fCatOverrideCount = 0;
309 fPosition = 0;
310 fRuleStatusIndex = 0;
311 fDone = false;
312 fDictionaryCharCount = 0;
313 fLanguageBreakEngines = NULL;
314 fUnhandledBreakEngine = NULL;
315 fBreakCache = NULL;
316 fDictionaryCache = NULL;
317
318 // Note: IBM xlC is unable to assign or initialize member fText from UTEXT_INITIALIZER.
319 // fText = UTEXT_INITIALIZER;
320 static const UText initializedUText = UTEXT_INITIALIZER;
321 uprv_memcpy(&fText, &initializedUText, sizeof(UText));
322
323 if (U_FAILURE(status)) {
324 return;
325 }
326
327 utext_openUChars(&fText, NULL, 0, &status);
328 fDictionaryCache = new DictionaryCache(this, status);
329 fBreakCache = new BreakCache(this, status);
330 if (U_SUCCESS(status) && (fDictionaryCache == NULL || fBreakCache == NULL)) {
331 status = U_MEMORY_ALLOCATION_ERROR;
332 }
333
334 #ifdef RBBI_DEBUG
335 static UBool debugInitDone = FALSE;
336 if (debugInitDone == FALSE) {
337 char *debugEnv = getenv("U_RBBIDEBUG");
338 if (debugEnv && uprv_strstr(debugEnv, "trace")) {
339 gTrace = TRUE;
340 }
341 debugInitDone = TRUE;
342 }
343 #endif
344 }
345
346
347 void RuleBasedBreakIterator::initLatin1Cat(void) {
348 fLatin1Cat = new uint16_t[256];
349 for (UChar32 c = 0; c < 256; ++c) {
350 fLatin1Cat[c] = UTRIE2_GET16(fData->fTrie, c);
351 }
352 }
353
354 // <rdar://problem/51193810>
355 enum {
356 kUDelimBuf = 3, // maximum UTF16 length of delimiter to get (1 for all delimiters in ICU 66)
357 kUDelimCount = 4, // maximum number of category overrides for delimiters
358 kPrototypeForOP = 0x007B, // prototype character for linebreak class OP (in Unicode 13)
359 kPrototypeForCL = 0x007D, // prototype character for linebreak class CL (in Unicode 13)
360 kTrueApostrophe = 0x2019, // U+2019 true apostrophe, glottal stop
361 };
362 void RuleBasedBreakIterator::setCategoryOverrides(Locale locale) {
363 delete [] fCatOverrides;
364 fCatOverrides = NULL;
365 fCatOverrideCount = 0;
366
367 if (uprv_strcmp(locale.getLanguage(),"da") == 0) { // rdar://66836891
368 return; // skip all remapping; U+201C/U+201D and U+2018/U+2019 can be open or close
369 }
370 UErrorCode status = U_ZERO_ERROR;
371 ULocaleData* uldata = ulocdata_open(locale.getName(), &status);
372 if (U_SUCCESS(status)) {
373 static const ULocaleDataDelimiterType delimTypes[][2] = {
374 { ULOCDATA_QUOTATION_START, ULOCDATA_QUOTATION_END },
375 { ULOCDATA_ALT_QUOTATION_START, ULOCDATA_ALT_QUOTATION_END }
376 };
377 CategoryOverride catOverrides[kUDelimCount];
378 int32_t catOverrideCount = 0;
379
380 for (int32_t delimIndex = 0; delimIndex < UPRV_LENGTHOF(delimTypes); delimIndex++) {
381 UChar32 quotOpen = 0, quotClose = 0;
382 UChar uDelim[kUDelimBuf];
383 int32_t uDelimLen;
384
385 // TODO: Currently we assume all delimiters in CLDR data are single BMP characters.
386 // That is currently true but we should at least expand this in the future to handle single
387 // UTF32 characters.
388 status = U_ZERO_ERROR;
389 uDelimLen = ulocdata_getDelimiter(uldata, delimTypes[delimIndex][0], uDelim, kUDelimBuf, &status);
390 if (U_SUCCESS(status) && uDelimLen==1) {
391 quotOpen = uDelim[0];
392 }
393 status = U_ZERO_ERROR;
394 uDelimLen = ulocdata_getDelimiter(uldata, delimTypes[delimIndex][1], uDelim, kUDelimBuf, &status);
395 if (U_SUCCESS(status) && uDelimLen==1) {
396 quotClose = uDelim[0];
397 if (quotClose == 0x201C && // rdar://67787054, rdar://67804156
398 (uprv_strcmp(locale.getLanguage(),"de") == 0 || uprv_strcmp(locale.getLanguage(),"hr") == 0)) {
399 quotClose = 0x201D; // In de/hr, 0x201C can be ambiguous, 0x201D is unambiguously close if used
400 }
401 }
402 if (quotOpen != quotClose) { // if they are the same we cannot distinguish OP and CL !
403 // only remap the classes for characters that currently have linebreak class QU
404 // and are not U+2019 (true apostrophe / glottal stop); need to wait to check here
405 // so that the test quotOpen != quotClose is valid.
406 if (u_getIntPropertyValue(quotOpen, UCHAR_LINE_BREAK) == U_LB_QUOTATION && quotOpen != kTrueApostrophe) {
407 catOverrides[catOverrideCount].c = quotOpen;
408 catOverrides[catOverrideCount++].category = UTRIE2_GET16(fData->fTrie, kPrototypeForOP);
409 }
410 if (u_getIntPropertyValue(quotClose, UCHAR_LINE_BREAK) == U_LB_QUOTATION && quotClose != kTrueApostrophe) {
411 catOverrides[catOverrideCount].c = quotClose;
412 catOverrides[catOverrideCount++].category = UTRIE2_GET16(fData->fTrie, kPrototypeForCL);
413 }
414 }
415 }
416 ulocdata_close(uldata);
417
418 if (catOverrideCount > 0) {
419 fCatOverrideCount = catOverrideCount;
420 fCatOverrides = new CategoryOverride[catOverrideCount];
421 for (int32_t orItem = 0; orItem < catOverrideCount; ++orItem) {
422 fCatOverrides[orItem] = catOverrides[orItem];
423 }
424 }
425 }
426 }
427
428 //-----------------------------------------------------------------------------
429 //
430 // clone - Returns a newly-constructed RuleBasedBreakIterator with the same
431 // behavior, and iterating over the same text, as this one.
432 // Virtual function: does the right thing with subclasses.
433 //
434 //-----------------------------------------------------------------------------
435 RuleBasedBreakIterator*
436 RuleBasedBreakIterator::clone() const {
437 return new RuleBasedBreakIterator(*this);
438 }
439
440 /**
441 * Equality operator. Returns TRUE if both BreakIterators are of the
442 * same class, have the same behavior, and iterate over the same text.
443 */
444 UBool
445 RuleBasedBreakIterator::operator==(const BreakIterator& that) const {
446 if (typeid(*this) != typeid(that)) {
447 return FALSE;
448 }
449 if (this == &that) {
450 return TRUE;
451 }
452
453 // The base class BreakIterator carries no state that participates in equality,
454 // and does not implement an equality function that would otherwise be
455 // checked at this point.
456
457 const RuleBasedBreakIterator& that2 = (const RuleBasedBreakIterator&) that;
458 if (that2.fLineWordOpts != fLineWordOpts) {
459 return FALSE;
460 }
461
462 if (!utext_equals(&fText, &that2.fText)) {
463 // The two break iterators are operating on different text,
464 // or have a different iteration position.
465 // Note that fText's position is always the same as the break iterator's position.
466 return FALSE;
467 }
468
469 if (!(fPosition == that2.fPosition &&
470 fRuleStatusIndex == that2.fRuleStatusIndex &&
471 fDone == that2.fDone)) {
472 return FALSE;
473 }
474
475 if (that2.fData == fData ||
476 (fData != NULL && that2.fData != NULL && *that2.fData == *fData)) {
477 // The two break iterators are using the same rules.
478 return TRUE;
479 }
480 return FALSE;
481 }
482
483 /**
484 * Compute a hash code for this BreakIterator
485 * @return A hash code
486 */
487 int32_t
488 RuleBasedBreakIterator::hashCode(void) const {
489 int32_t hash = 0;
490 if (fData != NULL) {
491 hash = fData->hashCode();
492 }
493 return hash;
494 }
495
496
497 void RuleBasedBreakIterator::setText(UText *ut, UErrorCode &status) {
498 if (U_FAILURE(status)) {
499 return;
500 }
501 fBreakCache->reset();
502 fDictionaryCache->reset();
503 utext_clone(&fText, ut, FALSE, TRUE, &status);
504
505 // Set up a dummy CharacterIterator to be returned if anyone
506 // calls getText(). With input from UText, there is no reasonable
507 // way to return a characterIterator over the actual input text.
508 // Return one over an empty string instead - this is the closest
509 // we can come to signaling a failure.
510 // (GetText() is obsolete, this failure is sort of OK)
511 fSCharIter.setText(UnicodeString());
512
513 if (fCharIter != &fSCharIter) {
514 // existing fCharIter was adopted from the outside. Delete it now.
515 delete fCharIter;
516 }
517 fCharIter = &fSCharIter;
518
519 this->first();
520 }
521
522
523 UText *RuleBasedBreakIterator::getUText(UText *fillIn, UErrorCode &status) const {
524 UText *result = utext_clone(fillIn, &fText, FALSE, TRUE, &status);
525 return result;
526 }
527
528
529 //=======================================================================
530 // BreakIterator overrides
531 //=======================================================================
532
533 /**
534 * Return a CharacterIterator over the text being analyzed.
535 */
536 CharacterIterator&
537 RuleBasedBreakIterator::getText() const {
538 return *fCharIter;
539 }
540
541 /**
542 * Set the iterator to analyze a new piece of text. This function resets
543 * the current iteration position to the beginning of the text.
544 * @param newText An iterator over the text to analyze.
545 */
546 void
547 RuleBasedBreakIterator::adoptText(CharacterIterator* newText) {
548 // If we are holding a CharacterIterator adopted from a
549 // previous call to this function, delete it now.
550 if (fCharIter != &fSCharIter) {
551 delete fCharIter;
552 }
553
554 fCharIter = newText;
555 UErrorCode status = U_ZERO_ERROR;
556 fBreakCache->reset();
557 fDictionaryCache->reset();
558 if (newText==NULL || newText->startIndex() != 0) {
559 // startIndex !=0 wants to be an error, but there's no way to report it.
560 // Make the iterator text be an empty string.
561 utext_openUChars(&fText, NULL, 0, &status);
562 } else {
563 utext_openCharacterIterator(&fText, newText, &status);
564 }
565 this->first();
566 }
567
568 /**
569 * Set the iterator to analyze a new piece of text. This function resets
570 * the current iteration position to the beginning of the text.
571 * @param newText An iterator over the text to analyze.
572 */
573 void
574 RuleBasedBreakIterator::setText(const UnicodeString& newText) {
575 UErrorCode status = U_ZERO_ERROR;
576 fBreakCache->reset();
577 fDictionaryCache->reset();
578 utext_openConstUnicodeString(&fText, &newText, &status);
579
580 // Set up a character iterator on the string.
581 // Needed in case someone calls getText().
582 // Can not, unfortunately, do this lazily on the (probably never)
583 // call to getText(), because getText is const.
584 fSCharIter.setText(newText);
585
586 if (fCharIter != &fSCharIter) {
587 // old fCharIter was adopted from the outside. Delete it.
588 delete fCharIter;
589 }
590 fCharIter = &fSCharIter;
591
592 this->first();
593 }
594
595
596 /**
597 * Provide a new UText for the input text. Must reference text with contents identical
598 * to the original.
599 * Intended for use with text data originating in Java (garbage collected) environments
600 * where the data may be moved in memory at arbitrary times.
601 */
602 RuleBasedBreakIterator &RuleBasedBreakIterator::refreshInputText(UText *input, UErrorCode &status) {
603 if (U_FAILURE(status)) {
604 return *this;
605 }
606 if (input == NULL) {
607 status = U_ILLEGAL_ARGUMENT_ERROR;
608 return *this;
609 }
610 int64_t pos = utext_getNativeIndex(&fText);
611 // Shallow read-only clone of the new UText into the existing input UText
612 utext_clone(&fText, input, FALSE, TRUE, &status);
613 if (U_FAILURE(status)) {
614 return *this;
615 }
616 utext_setNativeIndex(&fText, pos);
617 if (utext_getNativeIndex(&fText) != pos) {
618 // Sanity check. The new input utext is supposed to have the exact same
619 // contents as the old. If we can't set to the same position, it doesn't.
620 // The contents underlying the old utext might be invalid at this point,
621 // so it's not safe to check directly.
622 status = U_ILLEGAL_ARGUMENT_ERROR;
623 }
624 return *this;
625 }
626
627
628 /**
629 * Sets the current iteration position to the beginning of the text, position zero.
630 * @return The new iterator position, which is zero.
631 */
632 int32_t RuleBasedBreakIterator::first(void) {
633 UErrorCode status = U_ZERO_ERROR;
634 if (!fBreakCache->seek(0)) {
635 fBreakCache->populateNear(0, status);
636 }
637 fBreakCache->current();
638 U_ASSERT(fPosition == 0);
639 return 0;
640 }
641
642 /**
643 * Sets the current iteration position to the end of the text.
644 * @return The text's past-the-end offset.
645 */
646 int32_t RuleBasedBreakIterator::last(void) {
647 int32_t endPos = (int32_t)utext_nativeLength(&fText);
648 UBool endShouldBeBoundary = isBoundary(endPos); // Has side effect of setting iterator position.
649 (void)endShouldBeBoundary;
650 U_ASSERT(endShouldBeBoundary);
651 U_ASSERT(fPosition == endPos);
652 return endPos;
653 }
654
655 /**
656 * Advances the iterator either forward or backward the specified number of steps.
657 * Negative values move backward, and positive values move forward. This is
658 * equivalent to repeatedly calling next() or previous().
659 * @param n The number of steps to move. The sign indicates the direction
660 * (negative is backwards, and positive is forwards).
661 * @return The character offset of the boundary position n boundaries away from
662 * the current one.
663 */
664 int32_t RuleBasedBreakIterator::next(int32_t n) {
665 int32_t result = 0;
666 if (n > 0) {
667 for (; n > 0 && result != UBRK_DONE; --n) {
668 result = next();
669 }
670 } else if (n < 0) {
671 for (; n < 0 && result != UBRK_DONE; ++n) {
672 result = previous();
673 }
674 } else {
675 result = current();
676 }
677 return result;
678 }
679
680 /**
681 * Advances the iterator to the next boundary position.
682 * @return The position of the first boundary after this one.
683 */
684 int32_t RuleBasedBreakIterator::next(void) {
685 fBreakCache->next();
686 return fDone ? UBRK_DONE : fPosition;
687 }
688
689 /**
690 * Move the iterator backwards, to the boundary preceding the current one.
691 *
692 * Starts from the current position within fText.
693 * Starting position need not be on a boundary.
694 *
695 * @return The position of the boundary position immediately preceding the starting position.
696 */
697 int32_t RuleBasedBreakIterator::previous(void) {
698 UErrorCode status = U_ZERO_ERROR;
699 fBreakCache->previous(status);
700 return fDone ? UBRK_DONE : fPosition;
701 }
702
703 /**
704 * Sets the iterator to refer to the first boundary position following
705 * the specified position.
706 * @param startPos The position from which to begin searching for a break position.
707 * @return The position of the first break after the current position.
708 */
709 int32_t RuleBasedBreakIterator::following(int32_t startPos) {
710 // if the supplied position is before the beginning, return the
711 // text's starting offset
712 if (startPos < 0) {
713 return first();
714 }
715
716 // Move requested offset to a code point start. It might be on a trail surrogate,
717 // or on a trail byte if the input is UTF-8. Or it may be beyond the end of the text.
718 utext_setNativeIndex(&fText, startPos);
719 startPos = (int32_t)utext_getNativeIndex(&fText);
720
721 UErrorCode status = U_ZERO_ERROR;
722 fBreakCache->following(startPos, status);
723 return fDone ? UBRK_DONE : fPosition;
724 }
725
726 /**
727 * Sets the iterator to refer to the last boundary position before the
728 * specified position.
729 * @param offset The position to begin searching for a break from.
730 * @return The position of the last boundary before the starting position.
731 */
732 int32_t RuleBasedBreakIterator::preceding(int32_t offset) {
733 if (offset > utext_nativeLength(&fText)) {
734 return last();
735 }
736
737 // Move requested offset to a code point start. It might be on a trail surrogate,
738 // or on a trail byte if the input is UTF-8.
739
740 utext_setNativeIndex(&fText, offset);
741 int32_t adjustedOffset = static_cast<int32_t>(utext_getNativeIndex(&fText));
742
743 UErrorCode status = U_ZERO_ERROR;
744 fBreakCache->preceding(adjustedOffset, status);
745 return fDone ? UBRK_DONE : fPosition;
746 }
747
748 /**
749 * Returns true if the specfied position is a boundary position. As a side
750 * effect, leaves the iterator pointing to the first boundary position at
751 * or after "offset".
752 *
753 * @param offset the offset to check.
754 * @return True if "offset" is a boundary position.
755 */
756 UBool RuleBasedBreakIterator::isBoundary(int32_t offset) {
757 // out-of-range indexes are never boundary positions
758 if (offset < 0) {
759 first(); // For side effects on current position, tag values.
760 return FALSE;
761 }
762
763 // Adjust offset to be on a code point boundary and not beyond the end of the text.
764 // Note that isBoundary() is always false for offsets that are not on code point boundaries.
765 // But we still need the side effect of leaving iteration at the following boundary.
766
767 utext_setNativeIndex(&fText, offset);
768 int32_t adjustedOffset = static_cast<int32_t>(utext_getNativeIndex(&fText));
769
770 bool result = false;
771 UErrorCode status = U_ZERO_ERROR;
772 if (fBreakCache->seek(adjustedOffset) || fBreakCache->populateNear(adjustedOffset, status)) {
773 result = (fBreakCache->current() == offset);
774 }
775
776 if (result && adjustedOffset < offset && utext_char32At(&fText, offset) == U_SENTINEL) {
777 // Original offset is beyond the end of the text. Return FALSE, it's not a boundary,
778 // but the iteration position remains set to the end of the text, which is a boundary.
779 return FALSE;
780 }
781 if (!result) {
782 // Not on a boundary. isBoundary() must leave iterator on the following boundary.
783 // Cache->seek(), above, left us on the preceding boundary, so advance one.
784 next();
785 }
786 return result;
787 }
788
789
790 /**
791 * Returns the current iteration position.
792 * @return The current iteration position.
793 */
794 int32_t RuleBasedBreakIterator::current(void) const {
795 return fPosition;
796 }
797
798
799 //=======================================================================
800 // implementation
801 //=======================================================================
802
803 //
804 // RBBIRunMode - the state machine runs an extra iteration at the beginning and end
805 // of user text. A variable with this enum type keeps track of where we
806 // are. The state machine only fetches user input while in the RUN mode.
807 //
808 enum RBBIRunMode {
809 RBBI_START, // state machine processing is before first char of input
810 RBBI_RUN, // state machine processing is in the user text
811 RBBI_END // state machine processing is after end of user text.
812 };
813
814
815 // Map from look-ahead break states (corresponds to rules) to boundary positions.
816 // Allows multiple lookahead break rules to be in flight at the same time.
817 //
818 // This is a temporary approach for ICU 57. A better fix is to make the look-ahead numbers
819 // in the state table be sequential, then we can just index an array. And the
820 // table could also tell us in advance how big that array needs to be.
821 //
822 // Before ICU 57 there was just a single simple variable for a look-ahead match that
823 // was in progress. Two rules at once did not work.
824
825 static const int32_t kMaxLookaheads = 8;
826 struct LookAheadResults {
827 int32_t fUsedSlotLimit;
828 int32_t fPositions[8];
829 int16_t fKeys[8];
830
831 LookAheadResults() : fUsedSlotLimit(0), fPositions(), fKeys() {}
832
833 int32_t getPosition(int16_t key) {
834 for (int32_t i=0; i<fUsedSlotLimit; ++i) {
835 if (fKeys[i] == key) {
836 return fPositions[i];
837 }
838 }
839 // with NLLT source rules, Latn sample and ubrk_next, we see a request for key 79 here
840 // near the end of text, when setPosition has only ever set positions for key 80 or 82.
841 //UPRV_UNREACHABLE;
842 return -1;
843 }
844
845 void setPosition(int16_t key, int32_t position) {
846 int32_t i;
847 for (i=0; i<fUsedSlotLimit; ++i) {
848 if (fKeys[i] == key) {
849 fPositions[i] = position;
850 return;
851 }
852 }
853 if (i >= kMaxLookaheads) {
854 UPRV_UNREACHABLE;
855 i = kMaxLookaheads - 1; // Apple addition
856 }
857 fKeys[i] = key;
858 fPositions[i] = position;
859 U_ASSERT(fUsedSlotLimit == i);
860 fUsedSlotLimit = i + 1;
861 }
862 };
863
864
865 //-----------------------------------------------------------------------------------
866 //
867 // handleNext()
868 // Run the state machine to find a boundary
869 //
870 //-----------------------------------------------------------------------------------
871 // Route handleNext calls through the following to handleNextInternal,
872 // in order to handle fLineWordOpts.
873 int32_t RuleBasedBreakIterator::handleNext() {
874 int32_t result = handleNextInternal();
875 while (fLineWordOpts != UBRK_LINEWORD_NORMAL) {
876 UChar32 prevChr = utext_char32At(&fText, result-1);
877 UChar32 currChr = utext_char32At(&fText, result);
878 if (currChr == U_SENTINEL || prevChr == U_SENTINEL) {
879 break;
880 }
881 if (fLineWordOpts == UBRK_LINEWORD_KEEP_HANGUL) {
882 UErrorCode status = U_ZERO_ERROR;
883 if (uscript_getScript(currChr, &status) != USCRIPT_HANGUL || uscript_getScript(prevChr, &status) != USCRIPT_HANGUL) {
884 break;
885 }
886 } else {
887 if (!u_isalpha(currChr) || !u_isalpha(prevChr)) {
888 break;
889 }
890 }
891 int32_t nextResult = handleNextInternal();
892 if (nextResult <= result) {
893 break;
894 }
895 result = nextResult;
896 }
897 return result;
898 }
899
900 int32_t RuleBasedBreakIterator::handleNextInternal() {
901 int32_t state;
902 uint16_t category = 0;
903 RBBIRunMode mode;
904
905 RBBIStateTableRow *row;
906 UChar32 c;
907 LookAheadResults lookAheadMatches;
908 int32_t result = 0;
909 int32_t initialPosition = 0;
910 const RBBIStateTable *statetable = fData->fForwardTable;
911 const char *tableData = statetable->fTableData;
912 uint32_t tableRowLen = statetable->fRowLen;
913 #ifdef RBBI_DEBUG
914 if (gTrace) {
915 RBBIDebugPuts("Handle Next pos char state category");
916 }
917 #endif
918
919 // handleNext alway sets the break tag value.
920 // Set the default for it.
921 fRuleStatusIndex = 0;
922
923 fDictionaryCharCount = 0;
924
925 // if we're already at the end of the text, return DONE.
926 initialPosition = fPosition;
927 UTEXT_SETNATIVEINDEX(&fText, initialPosition);
928 result = initialPosition;
929 c = UTEXT_NEXT32(&fText);
930 if (c==U_SENTINEL) {
931 fDone = TRUE;
932 return UBRK_DONE;
933 }
934
935 // Set the initial state for the state machine
936 state = START_STATE;
937 row = (RBBIStateTableRow *)
938 //(statetable->fTableData + (statetable->fRowLen * state));
939 (tableData + tableRowLen * state);
940
941
942 mode = RBBI_RUN;
943 if (statetable->fFlags & RBBI_BOF_REQUIRED) {
944 category = 2;
945 mode = RBBI_START;
946 }
947
948
949 // loop until we reach the end of the text or transition to state 0
950 //
951 for (;;) {
952 if (c == U_SENTINEL) {
953 // Reached end of input string.
954 if (mode == RBBI_END) {
955 // We have already run the loop one last time with the
956 // character set to the psueudo {eof} value. Now it is time
957 // to unconditionally bail out.
958 break;
959 }
960 // Run the loop one last time with the fake end-of-input character category.
961 mode = RBBI_END;
962 category = 1;
963 }
964
965 //
966 // Get the char category. An incoming category of 1 or 2 means that
967 // we are preset for doing the beginning or end of input, and
968 // that we shouldn't get a category from an actual text input character.
969 //
970 if (mode == RBBI_RUN) {
971 // look up the current character's character category, which tells us
972 // which column in the state table to look at.
973 // Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
974 // not the size of the character going in, which is a UChar32.
975 //
976 if (fLatin1Cat!=NULL && c<0x100) {
977 category = fLatin1Cat[c]; // fast Latin1 class lookup used for urbtok
978 } else {
979 UBool didOverride = FALSE;
980 for (int32_t orItem = 0; orItem < fCatOverrideCount; ++orItem) {
981 // <rdar://problem/51193810> delimiter category overrides, max of 4
982 if (c == fCatOverrides[orItem].c) {
983 category = fCatOverrides[orItem].category;
984 didOverride = TRUE;
985 break;
986 }
987 }
988 if (!didOverride) {
989 category = UTRIE2_GET16(fData->fTrie, c);
990 }
991 }
992
993 // Check the dictionary bit in the character's category.
994 // Counter is only used by dictionary based iteration.
995 // Chars that need to be handled by a dictionary have a flag bit set
996 // in their category values.
997 //
998 if ((category & 0x4000) != 0) {
999 fDictionaryCharCount++;
1000 // And off the dictionary flag bit.
1001 category &= ~0x4000;
1002 }
1003 }
1004
1005 #ifdef RBBI_DEBUG
1006 if (gTrace) {
1007 RBBIDebugPrintf(" %4" PRId64 " ", utext_getNativeIndex(&fText));
1008 if (0x20<=c && c<0x7f) {
1009 RBBIDebugPrintf("\"%c\" ", c);
1010 } else {
1011 RBBIDebugPrintf("%5x ", c);
1012 }
1013 RBBIDebugPrintf("%3d %3d\n", state, category);
1014 }
1015 #endif
1016
1017 // State Transition - move machine to its next state
1018 //
1019
1020 // fNextState is a variable-length array.
1021 U_ASSERT(category<fData->fHeader->fCatCount);
1022 state = row->fNextState[category]; /*Not accessing beyond memory*/
1023 row = (RBBIStateTableRow *)
1024 // (statetable->fTableData + (statetable->fRowLen * state));
1025 (tableData + tableRowLen * state);
1026
1027
1028 if (row->fAccepting == -1) {
1029 // Match found, common case.
1030 if (mode != RBBI_START) {
1031 result = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
1032 }
1033 fRuleStatusIndex = row->fTagIdx; // Remember the break status (tag) values.
1034 }
1035
1036 int16_t completedRule = row->fAccepting;
1037 if (completedRule > 0) {
1038 // Lookahead match is completed.
1039 int32_t lookaheadResult = lookAheadMatches.getPosition(completedRule);
1040 if (lookaheadResult >= 0) {
1041 fRuleStatusIndex = row->fTagIdx;
1042 fPosition = lookaheadResult;
1043 return lookaheadResult;
1044 }
1045 }
1046 int16_t rule = row->fLookAhead;
1047 if (rule != 0) {
1048 // At the position of a '/' in a look-ahead match. Record it.
1049 int32_t pos = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
1050 lookAheadMatches.setPosition(rule, pos);
1051 }
1052
1053 if (state == STOP_STATE) {
1054 // This is the normal exit from the lookup state machine.
1055 // We have advanced through the string until it is certain that no
1056 // longer match is possible, no matter what characters follow.
1057 break;
1058 }
1059
1060 // Advance to the next character.
1061 // If this is a beginning-of-input loop iteration, don't advance
1062 // the input position. The next iteration will be processing the
1063 // first real input character.
1064 if (mode == RBBI_RUN) {
1065 c = UTEXT_NEXT32(&fText);
1066 } else {
1067 if (mode == RBBI_START) {
1068 mode = RBBI_RUN;
1069 }
1070 }
1071 }
1072
1073 // The state machine is done. Check whether it found a match...
1074
1075 // If the iterator failed to advance in the match engine, force it ahead by one.
1076 // (This really indicates a defect in the break rules. They should always match
1077 // at least one character.)
1078 if (result == initialPosition) {
1079 utext_setNativeIndex(&fText, initialPosition);
1080 utext_next32(&fText);
1081 result = (int32_t)utext_getNativeIndex(&fText);
1082 fRuleStatusIndex = 0;
1083 }
1084
1085 // Leave the iterator at our result position.
1086 fPosition = result;
1087 #ifdef RBBI_DEBUG
1088 if (gTrace) {
1089 RBBIDebugPrintf("result = %d\n\n", result);
1090 }
1091 #endif
1092 return result;
1093 }
1094
1095
1096 //-----------------------------------------------------------------------------------
1097 //
1098 // handleSafePrevious()
1099 //
1100 // Iterate backwards using the safe reverse rules.
1101 // The logic of this function is similar to handleNext(), but simpler
1102 // because the safe table does not require as many options.
1103 //
1104 //-----------------------------------------------------------------------------------
1105 int32_t RuleBasedBreakIterator::handleSafePrevious(int32_t fromPosition) {
1106 int32_t state;
1107 uint16_t category = 0;
1108 RBBIStateTableRow *row;
1109 UChar32 c;
1110 int32_t result = 0;
1111
1112 const RBBIStateTable *stateTable = fData->fReverseTable;
1113 UTEXT_SETNATIVEINDEX(&fText, fromPosition);
1114 #ifdef RBBI_DEBUG
1115 if (gTrace) {
1116 RBBIDebugPuts("Handle Previous pos char state category");
1117 }
1118 #endif
1119
1120 // if we're already at the start of the text, return DONE.
1121 if (fData == NULL || UTEXT_GETNATIVEINDEX(&fText)==0) {
1122 return BreakIterator::DONE;
1123 }
1124
1125 // Set the initial state for the state machine
1126 c = UTEXT_PREVIOUS32(&fText);
1127 state = START_STATE;
1128 row = (RBBIStateTableRow *)
1129 (stateTable->fTableData + (stateTable->fRowLen * state));
1130
1131 // loop until we reach the start of the text or transition to state 0
1132 //
1133 for (; c != U_SENTINEL; c = UTEXT_PREVIOUS32(&fText)) {
1134
1135 // look up the current character's character category, which tells us
1136 // which column in the state table to look at.
1137 // Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
1138 // not the size of the character going in, which is a UChar32.
1139 //
1140 // And off the dictionary flag bit. For reverse iteration it is not used.
1141 category = UTRIE2_GET16(fData->fTrie, c);
1142 category &= ~0x4000;
1143
1144 #ifdef RBBI_DEBUG
1145 if (gTrace) {
1146 RBBIDebugPrintf(" %4d ", (int32_t)utext_getNativeIndex(&fText));
1147 if (0x20<=c && c<0x7f) {
1148 RBBIDebugPrintf("\"%c\" ", c);
1149 } else {
1150 RBBIDebugPrintf("%5x ", c);
1151 }
1152 RBBIDebugPrintf("%3d %3d\n", state, category);
1153 }
1154 #endif
1155
1156 // State Transition - move machine to its next state
1157 //
1158 // fNextState is a variable-length array.
1159 U_ASSERT(category<fData->fHeader->fCatCount);
1160 state = row->fNextState[category]; /*Not accessing beyond memory*/
1161 row = (RBBIStateTableRow *)
1162 (stateTable->fTableData + (stateTable->fRowLen * state));
1163
1164 if (state == STOP_STATE) {
1165 // This is the normal exit from the lookup state machine.
1166 // Transistion to state zero means we have found a safe point.
1167 break;
1168 }
1169 }
1170
1171 // The state machine is done. Check whether it found a match...
1172 result = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
1173 #ifdef RBBI_DEBUG
1174 if (gTrace) {
1175 RBBIDebugPrintf("result = %d\n\n", result);
1176 }
1177 #endif
1178 return result;
1179 }
1180
1181 //-------------------------------------------------------------------------------
1182 //
1183 // getRuleStatus() Return the break rule tag associated with the current
1184 // iterator position. If the iterator arrived at its current
1185 // position by iterating forwards, the value will have been
1186 // cached by the handleNext() function.
1187 //
1188 //-------------------------------------------------------------------------------
1189
1190 int32_t RuleBasedBreakIterator::getRuleStatus() const {
1191
1192 // fLastRuleStatusIndex indexes to the start of the appropriate status record
1193 // (the number of status values.)
1194 // This function returns the last (largest) of the array of status values.
1195 int32_t idx = fRuleStatusIndex + fData->fRuleStatusTable[fRuleStatusIndex];
1196 int32_t tagVal = fData->fRuleStatusTable[idx];
1197
1198 return tagVal;
1199 }
1200
1201
1202 int32_t RuleBasedBreakIterator::getRuleStatusVec(
1203 int32_t *fillInVec, int32_t capacity, UErrorCode &status) {
1204 if (U_FAILURE(status)) {
1205 return 0;
1206 }
1207
1208 int32_t numVals = fData->fRuleStatusTable[fRuleStatusIndex];
1209 int32_t numValsToCopy = numVals;
1210 if (numVals > capacity) {
1211 status = U_BUFFER_OVERFLOW_ERROR;
1212 numValsToCopy = capacity;
1213 }
1214 int i;
1215 for (i=0; i<numValsToCopy; i++) {
1216 fillInVec[i] = fData->fRuleStatusTable[fRuleStatusIndex + i + 1];
1217 }
1218 return numVals;
1219 }
1220
1221 // Apple custom addition
1222 int32_t RuleBasedBreakIterator::tokenize(int32_t maxTokens, RuleBasedTokenRange *outTokenRanges, unsigned long *outTokenFlags)
1223 {
1224 if (fDone) {
1225 return 0;
1226 }
1227 RuleBasedTokenRange *outTokenLimit = outTokenRanges + maxTokens;
1228 RuleBasedTokenRange *outTokenP = outTokenRanges;
1229 int32_t lastOffset = fPosition;
1230 while (outTokenP < outTokenLimit) {
1231 // start portion from inlining populateFollowing()
1232 int32_t pos = 0;
1233 int32_t ruleStatusIdx = 0;
1234 int32_t startPos = fPosition;
1235
1236 if (fDictionaryCache->following(startPos, &pos, &ruleStatusIdx)) {
1237 fPosition = pos;
1238 fRuleStatusIndex = ruleStatusIdx;
1239 } else {
1240 pos = handleNextInternal(); // sets fRuleStatusIndex for the pos it returns, updates fPosition
1241 if (pos == UBRK_DONE) {
1242 // fDone = TRUE; already set by handleNextInternal
1243 break;
1244 }
1245 // Use current result from handleNextInternal(), including fRuleStatusIndex,
1246 // unless overridden by dictionary subdivisions
1247 fPosition = pos;
1248 if (fDictionaryCharCount > 0) {
1249 // The text segment obtained from the rules includes dictionary characters.
1250 // Subdivide it, with subdivided results going into the dictionary cache.
1251 fDictionaryCache->populateDictionary(startPos, pos, fRuleStatusIndex, fRuleStatusIndex);
1252 if (fDictionaryCache->following(startPos, &pos, &ruleStatusIdx)) {
1253 fPosition = pos;
1254 fRuleStatusIndex = ruleStatusIdx;
1255 }
1256 }
1257 }
1258 // end portion from inlining populateFollowing()
1259 int32_t flagCount = fData->fRuleStatusTable[fRuleStatusIndex];
1260 const int32_t* flagPtr = fData->fRuleStatusTable + fRuleStatusIndex + flagCount;
1261 int32_t flagSet = *flagPtr; // if -1 then skip token
1262 if (flagSet != -1) {
1263 outTokenP->location = lastOffset;
1264 outTokenP++->length = fPosition - lastOffset;
1265 if (outTokenFlags) {
1266 // flagSet should be the OR of all flags returned by getRuleStatusVec;
1267 // here we collect from high-order to low-order.
1268 while (--flagCount > 0) {
1269 flagSet |= *--flagPtr;
1270 }
1271 *outTokenFlags++ = (unsigned long)flagSet;
1272 }
1273 }
1274 lastOffset = fPosition;
1275 }
1276 return (outTokenP - outTokenRanges);
1277 }
1278
1279 //-------------------------------------------------------------------------------
1280 //
1281 // getBinaryRules Access to the compiled form of the rules,
1282 // for use by build system tools that save the data
1283 // for standard iterator types.
1284 //
1285 //-------------------------------------------------------------------------------
1286 const uint8_t *RuleBasedBreakIterator::getBinaryRules(uint32_t &length) {
1287 const uint8_t *retPtr = NULL;
1288 length = 0;
1289
1290 if (fData != NULL) {
1291 retPtr = (const uint8_t *)fData->fHeader;
1292 length = fData->fHeader->fLength;
1293 }
1294 return retPtr;
1295 }
1296
1297
1298 RuleBasedBreakIterator *RuleBasedBreakIterator::createBufferClone(
1299 void * /*stackBuffer*/, int32_t &bufferSize, UErrorCode &status) {
1300 if (U_FAILURE(status)){
1301 return NULL;
1302 }
1303
1304 if (bufferSize == 0) {
1305 bufferSize = 1; // preflighting for deprecated functionality
1306 return NULL;
1307 }
1308
1309 BreakIterator *clonedBI = clone();
1310 if (clonedBI == NULL) {
1311 status = U_MEMORY_ALLOCATION_ERROR;
1312 } else {
1313 status = U_SAFECLONE_ALLOCATED_WARNING;
1314 }
1315 return (RuleBasedBreakIterator *)clonedBI;
1316 }
1317
1318 U_NAMESPACE_END
1319
1320
1321 static icu::UStack *gLanguageBreakFactories = nullptr;
1322 static const icu::UnicodeString *gEmptyString = nullptr;
1323 static icu::UInitOnce gLanguageBreakFactoriesInitOnce = U_INITONCE_INITIALIZER;
1324 static icu::UInitOnce gRBBIInitOnce = U_INITONCE_INITIALIZER;
1325
1326 /**
1327 * Release all static memory held by breakiterator.
1328 */
1329 U_CDECL_BEGIN
1330 static UBool U_CALLCONV rbbi_cleanup(void) {
1331 delete gLanguageBreakFactories;
1332 gLanguageBreakFactories = nullptr;
1333 delete gEmptyString;
1334 gEmptyString = nullptr;
1335 gLanguageBreakFactoriesInitOnce.reset();
1336 gRBBIInitOnce.reset();
1337 return TRUE;
1338 }
1339 U_CDECL_END
1340
1341 U_CDECL_BEGIN
1342 static void U_CALLCONV _deleteFactory(void *obj) {
1343 delete (icu::LanguageBreakFactory *) obj;
1344 }
1345 U_CDECL_END
1346 U_NAMESPACE_BEGIN
1347
1348 static void U_CALLCONV rbbiInit() {
1349 gEmptyString = new UnicodeString();
1350 ucln_common_registerCleanup(UCLN_COMMON_RBBI, rbbi_cleanup);
1351 }
1352
1353 static void U_CALLCONV initLanguageFactories() {
1354 UErrorCode status = U_ZERO_ERROR;
1355 U_ASSERT(gLanguageBreakFactories == NULL);
1356 gLanguageBreakFactories = new UStack(_deleteFactory, NULL, status);
1357 if (gLanguageBreakFactories != NULL && U_SUCCESS(status)) {
1358 ICULanguageBreakFactory *builtIn = new ICULanguageBreakFactory(status);
1359 gLanguageBreakFactories->push(builtIn, status);
1360 #ifdef U_LOCAL_SERVICE_HOOK
1361 LanguageBreakFactory *extra = (LanguageBreakFactory *)uprv_svc_hook("languageBreakFactory", &status);
1362 if (extra != NULL) {
1363 gLanguageBreakFactories->push(extra, status);
1364 }
1365 #endif
1366 }
1367 ucln_common_registerCleanup(UCLN_COMMON_RBBI, rbbi_cleanup);
1368 }
1369
1370
1371 static const LanguageBreakEngine*
1372 getLanguageBreakEngineFromFactory(UChar32 c)
1373 {
1374 umtx_initOnce(gLanguageBreakFactoriesInitOnce, &initLanguageFactories);
1375 if (gLanguageBreakFactories == NULL) {
1376 return NULL;
1377 }
1378
1379 int32_t i = gLanguageBreakFactories->size();
1380 const LanguageBreakEngine *lbe = NULL;
1381 while (--i >= 0) {
1382 LanguageBreakFactory *factory = (LanguageBreakFactory *)(gLanguageBreakFactories->elementAt(i));
1383 lbe = factory->getEngineFor(c);
1384 if (lbe != NULL) {
1385 break;
1386 }
1387 }
1388 return lbe;
1389 }
1390
1391
1392 //-------------------------------------------------------------------------------
1393 //
1394 // getLanguageBreakEngine Find an appropriate LanguageBreakEngine for the
1395 // the character c.
1396 //
1397 //-------------------------------------------------------------------------------
1398 const LanguageBreakEngine *
1399 RuleBasedBreakIterator::getLanguageBreakEngine(UChar32 c) {
1400 const LanguageBreakEngine *lbe = NULL;
1401 UErrorCode status = U_ZERO_ERROR;
1402
1403 if (fLanguageBreakEngines == NULL) {
1404 fLanguageBreakEngines = new UStack(status);
1405 if (fLanguageBreakEngines == NULL || U_FAILURE(status)) {
1406 delete fLanguageBreakEngines;
1407 fLanguageBreakEngines = 0;
1408 return NULL;
1409 }
1410 }
1411
1412 int32_t i = fLanguageBreakEngines->size();
1413 while (--i >= 0) {
1414 lbe = (const LanguageBreakEngine *)(fLanguageBreakEngines->elementAt(i));
1415 if (lbe->handles(c)) {
1416 return lbe;
1417 }
1418 }
1419
1420 // No existing dictionary took the character. See if a factory wants to
1421 // give us a new LanguageBreakEngine for this character.
1422 lbe = getLanguageBreakEngineFromFactory(c);
1423
1424 // If we got one, use it and push it on our stack.
1425 if (lbe != NULL) {
1426 fLanguageBreakEngines->push((void *)lbe, status);
1427 // Even if we can't remember it, we can keep looking it up, so
1428 // return it even if the push fails.
1429 return lbe;
1430 }
1431
1432 // No engine is forthcoming for this character. Add it to the
1433 // reject set. Create the reject break engine if needed.
1434 if (fUnhandledBreakEngine == NULL) {
1435 fUnhandledBreakEngine = new UnhandledEngine(status);
1436 if (U_SUCCESS(status) && fUnhandledBreakEngine == NULL) {
1437 status = U_MEMORY_ALLOCATION_ERROR;
1438 return nullptr;
1439 }
1440 // Put it last so that scripts for which we have an engine get tried
1441 // first.
1442 fLanguageBreakEngines->insertElementAt(fUnhandledBreakEngine, 0, status);
1443 // If we can't insert it, or creation failed, get rid of it
1444 if (U_FAILURE(status)) {
1445 delete fUnhandledBreakEngine;
1446 fUnhandledBreakEngine = 0;
1447 return NULL;
1448 }
1449 }
1450
1451 // Tell the reject engine about the character; at its discretion, it may
1452 // add more than just the one character.
1453 fUnhandledBreakEngine->handleCharacter(c);
1454
1455 return fUnhandledBreakEngine;
1456 }
1457
1458 void RuleBasedBreakIterator::dumpCache() {
1459 fBreakCache->dumpCache();
1460 }
1461
1462 void RuleBasedBreakIterator::dumpTables() {
1463 fData->printData();
1464 }
1465
1466 /**
1467 * Returns the description used to create this iterator
1468 */
1469
1470 const UnicodeString&
1471 RuleBasedBreakIterator::getRules() const {
1472 if (fData != NULL) {
1473 return fData->getRuleSourceString();
1474 } else {
1475 umtx_initOnce(gRBBIInitOnce, &rbbiInit);
1476 return *gEmptyString;
1477 }
1478 }
1479
1480 U_NAMESPACE_END
1481
1482 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */