1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ***************************************************************************
5 * Copyright (C) 1999-2016 International Business Machines Corporation
6 * and others. All rights reserved.
7 ***************************************************************************
10 // file: rbbi.cpp Contains the implementation of the rule based break iterator
11 // runtime engine and the API implementation for
12 // class RuleBasedBreakIterator
15 #include "utypeinfo.h" // for 'typeid' to work
17 #include "unicode/utypes.h"
19 #if !UCONFIG_NO_BREAK_ITERATION
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"
35 #include "rbbi_cache.h"
42 static UBool gTrace
= FALSE
;
47 // The state number of the starting state
48 constexpr int32_t START_STATE
= 1;
50 // The state-transition value indicating "stop"
51 constexpr int32_t STOP_STATE
= 0;
54 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedBreakIterator
)
57 //=======================================================================
59 //=======================================================================
62 * Constructs a RuleBasedBreakIterator that uses the already-created
63 * tables object that is passed in as a parameter.
65 RuleBasedBreakIterator::RuleBasedBreakIterator(RBBIDataHeader
* data
, UErrorCode
&status
)
66 : fSCharIter(UnicodeString())
69 fData
= new RBBIDataWrapper(data
, status
); // status checked in constructor
70 if (U_FAILURE(status
)) {return;}
72 status
= U_MEMORY_ALLOCATION_ERROR
;
78 // Construct from precompiled binary rules (tables). This constructor is public API,
79 // taking the rules as a (const uint8_t *) to match the type produced by getBinaryRules().
81 RuleBasedBreakIterator::RuleBasedBreakIterator(const uint8_t *compiledRules
,
84 : fSCharIter(UnicodeString())
87 if (U_FAILURE(status
)) {
90 if (compiledRules
== NULL
|| ruleLength
< sizeof(RBBIDataHeader
)) {
91 status
= U_ILLEGAL_ARGUMENT_ERROR
;
94 const RBBIDataHeader
*data
= (const RBBIDataHeader
*)compiledRules
;
95 if (data
->fLength
> ruleLength
) {
96 status
= U_ILLEGAL_ARGUMENT_ERROR
;
99 fData
= new RBBIDataWrapper(data
, RBBIDataWrapper::kDontAdopt
, status
);
100 if (U_FAILURE(status
)) {return;}
102 status
= U_MEMORY_ALLOCATION_ERROR
;
108 //-------------------------------------------------------------------------------
110 // Constructor from a UDataMemory handle to precompiled break rules
111 // stored in an ICU data file.
113 //-------------------------------------------------------------------------------
114 RuleBasedBreakIterator::RuleBasedBreakIterator(UDataMemory
* udm
, UErrorCode
&status
)
115 : fSCharIter(UnicodeString())
118 fData
= new RBBIDataWrapper(udm
, status
); // status checked in constructor
119 if (U_FAILURE(status
)) {return;}
121 status
= U_MEMORY_ALLOCATION_ERROR
;
128 //-------------------------------------------------------------------------------
130 // Constructor from a set of rules supplied as a string.
132 //-------------------------------------------------------------------------------
133 RuleBasedBreakIterator::RuleBasedBreakIterator( const UnicodeString
&rules
,
134 UParseError
&parseError
,
136 : fSCharIter(UnicodeString())
139 if (U_FAILURE(status
)) {return;}
140 RuleBasedBreakIterator
*bi
= (RuleBasedBreakIterator
*)
141 RBBIRuleBuilder::createRuleBasedBreakIterator(rules
, &parseError
, status
);
142 // Note: This is a bit awkward. The RBBI ruleBuilder has a factory method that
143 // creates and returns a complete RBBI. From here, in a constructor, we
144 // can't just return the object created by the builder factory, hence
145 // the assignment of the factory created object to "this".
146 if (U_SUCCESS(status
)) {
153 //-------------------------------------------------------------------------------
155 // Default Constructor. Create an empty shell that can be set up later.
156 // Used when creating a RuleBasedBreakIterator from a set
158 //-------------------------------------------------------------------------------
159 RuleBasedBreakIterator::RuleBasedBreakIterator()
160 : fSCharIter(UnicodeString())
162 UErrorCode status
= U_ZERO_ERROR
;
167 //-------------------------------------------------------------------------------
169 // Copy constructor. Will produce a break iterator with the same behavior,
170 // and which iterates over the same text, as the one passed in.
172 //-------------------------------------------------------------------------------
173 RuleBasedBreakIterator::RuleBasedBreakIterator(const RuleBasedBreakIterator
& other
)
174 : BreakIterator(other
),
175 fSCharIter(UnicodeString())
177 UErrorCode status
= U_ZERO_ERROR
;
186 RuleBasedBreakIterator::~RuleBasedBreakIterator() {
187 if (fCharIter
!= &fSCharIter
) {
188 // fCharIter was adopted from the outside.
196 fData
->removeReference();
202 delete fDictionaryCache
;
203 fDictionaryCache
= NULL
;
205 delete fLanguageBreakEngines
;
206 fLanguageBreakEngines
= NULL
;
208 delete fUnhandledBreakEngine
;
209 fUnhandledBreakEngine
= NULL
;
211 delete [] fLatin1Cat
;
216 * Assignment operator. Sets this iterator to have the same behavior,
217 * and iterate over the same text, as the one passed in.
219 RuleBasedBreakIterator
&
220 RuleBasedBreakIterator::operator=(const RuleBasedBreakIterator
& that
) {
224 BreakIterator::operator=(that
);
225 fLineWordOpts
= that
.fLineWordOpts
;
227 if (fLanguageBreakEngines
!= NULL
) {
228 delete fLanguageBreakEngines
;
229 fLanguageBreakEngines
= NULL
; // Just rebuild for now
231 // TODO: clone fLanguageBreakEngines from "that"
232 UErrorCode status
= U_ZERO_ERROR
;
233 utext_clone(&fText
, &that
.fText
, FALSE
, TRUE
, &status
);
235 if (fCharIter
!= &fSCharIter
) {
238 fCharIter
= &fSCharIter
;
240 if (that
.fCharIter
!= NULL
&& that
.fCharIter
!= &that
.fSCharIter
) {
241 // This is a little bit tricky - it will intially appear that
242 // this->fCharIter is adopted, even if that->fCharIter was
243 // not adopted. That's ok.
244 fCharIter
= that
.fCharIter
->clone();
246 fSCharIter
= that
.fSCharIter
;
247 if (fCharIter
== NULL
) {
248 fCharIter
= &fSCharIter
;
252 fData
->removeReference();
255 if (that
.fData
!= NULL
) {
256 fData
= that
.fData
->addReference();
259 delete [] fLatin1Cat
;
262 fPosition
= that
.fPosition
;
263 fRuleStatusIndex
= that
.fRuleStatusIndex
;
266 // TODO: both the dictionary and the main cache need to be copied.
267 // Current position could be within a dictionary range. Trying to continue
268 // the iteration without the caches present would go to the rules, with
269 // the assumption that the current position is on a rule boundary.
270 fBreakCache
->reset(fPosition
, fRuleStatusIndex
);
271 fDictionaryCache
->reset();
278 //-----------------------------------------------------------------------------
280 // init() Shared initialization routine. Used by all the constructors.
281 // Initializes all fields, leaving the object in a consistent state.
283 //-----------------------------------------------------------------------------
284 void RuleBasedBreakIterator::init(UErrorCode
&status
) {
289 fRuleStatusIndex
= 0;
291 fDictionaryCharCount
= 0;
292 fLanguageBreakEngines
= NULL
;
293 fUnhandledBreakEngine
= NULL
;
295 fDictionaryCache
= NULL
;
297 // Note: IBM xlC is unable to assign or initialize member fText from UTEXT_INITIALIZER.
298 // fText = UTEXT_INITIALIZER;
299 static const UText initializedUText
= UTEXT_INITIALIZER
;
300 uprv_memcpy(&fText
, &initializedUText
, sizeof(UText
));
302 if (U_FAILURE(status
)) {
306 utext_openUChars(&fText
, NULL
, 0, &status
);
307 fDictionaryCache
= new DictionaryCache(this, status
);
308 fBreakCache
= new BreakCache(this, status
);
309 if (U_SUCCESS(status
) && (fDictionaryCache
== NULL
|| fBreakCache
== NULL
)) {
310 status
= U_MEMORY_ALLOCATION_ERROR
;
314 static UBool debugInitDone
= FALSE
;
315 if (debugInitDone
== FALSE
) {
316 char *debugEnv
= getenv("U_RBBIDEBUG");
317 if (debugEnv
&& uprv_strstr(debugEnv
, "trace")) {
320 debugInitDone
= TRUE
;
326 void RuleBasedBreakIterator::initLatin1Cat(void) {
327 fLatin1Cat
= new uint16_t[256];
328 for (UChar32 c
= 0; c
< 256; ++c
) {
329 fLatin1Cat
[c
] = UTRIE2_GET16(fData
->fTrie
, c
);
333 //-----------------------------------------------------------------------------
335 // clone - Returns a newly-constructed RuleBasedBreakIterator with the same
336 // behavior, and iterating over the same text, as this one.
337 // Virtual function: does the right thing with subclasses.
339 //-----------------------------------------------------------------------------
341 RuleBasedBreakIterator::clone(void) const {
342 return new RuleBasedBreakIterator(*this);
346 * Equality operator. Returns TRUE if both BreakIterators are of the
347 * same class, have the same behavior, and iterate over the same text.
350 RuleBasedBreakIterator::operator==(const BreakIterator
& that
) const {
351 if (typeid(*this) != typeid(that
)) {
358 // The base class BreakIterator carries no state that participates in equality,
359 // and does not implement an equality function that would otherwise be
360 // checked at this point.
362 const RuleBasedBreakIterator
& that2
= (const RuleBasedBreakIterator
&) that
;
363 if (that2
.fLineWordOpts
!= fLineWordOpts
) {
367 if (!utext_equals(&fText
, &that2
.fText
)) {
368 // The two break iterators are operating on different text,
369 // or have a different iteration position.
370 // Note that fText's position is always the same as the break iterator's position.
374 if (!(fPosition
== that2
.fPosition
&&
375 fRuleStatusIndex
== that2
.fRuleStatusIndex
&&
376 fDone
== that2
.fDone
)) {
380 if (that2
.fData
== fData
||
381 (fData
!= NULL
&& that2
.fData
!= NULL
&& *that2
.fData
== *fData
)) {
382 // The two break iterators are using the same rules.
389 * Compute a hash code for this BreakIterator
390 * @return A hash code
393 RuleBasedBreakIterator::hashCode(void) const {
396 hash
= fData
->hashCode();
402 void RuleBasedBreakIterator::setText(UText
*ut
, UErrorCode
&status
) {
403 if (U_FAILURE(status
)) {
406 fBreakCache
->reset();
407 fDictionaryCache
->reset();
408 utext_clone(&fText
, ut
, FALSE
, TRUE
, &status
);
410 // Set up a dummy CharacterIterator to be returned if anyone
411 // calls getText(). With input from UText, there is no reasonable
412 // way to return a characterIterator over the actual input text.
413 // Return one over an empty string instead - this is the closest
414 // we can come to signaling a failure.
415 // (GetText() is obsolete, this failure is sort of OK)
416 fSCharIter
.setText(UnicodeString());
418 if (fCharIter
!= &fSCharIter
) {
419 // existing fCharIter was adopted from the outside. Delete it now.
422 fCharIter
= &fSCharIter
;
428 UText
*RuleBasedBreakIterator::getUText(UText
*fillIn
, UErrorCode
&status
) const {
429 UText
*result
= utext_clone(fillIn
, &fText
, FALSE
, TRUE
, &status
);
434 //=======================================================================
435 // BreakIterator overrides
436 //=======================================================================
439 * Return a CharacterIterator over the text being analyzed.
442 RuleBasedBreakIterator::getText() const {
447 * Set the iterator to analyze a new piece of text. This function resets
448 * the current iteration position to the beginning of the text.
449 * @param newText An iterator over the text to analyze.
452 RuleBasedBreakIterator::adoptText(CharacterIterator
* newText
) {
453 // If we are holding a CharacterIterator adopted from a
454 // previous call to this function, delete it now.
455 if (fCharIter
!= &fSCharIter
) {
460 UErrorCode status
= U_ZERO_ERROR
;
461 fBreakCache
->reset();
462 fDictionaryCache
->reset();
463 if (newText
==NULL
|| newText
->startIndex() != 0) {
464 // startIndex !=0 wants to be an error, but there's no way to report it.
465 // Make the iterator text be an empty string.
466 utext_openUChars(&fText
, NULL
, 0, &status
);
468 utext_openCharacterIterator(&fText
, newText
, &status
);
474 * Set the iterator to analyze a new piece of text. This function resets
475 * the current iteration position to the beginning of the text.
476 * @param newText An iterator over the text to analyze.
479 RuleBasedBreakIterator::setText(const UnicodeString
& newText
) {
480 UErrorCode status
= U_ZERO_ERROR
;
481 fBreakCache
->reset();
482 fDictionaryCache
->reset();
483 utext_openConstUnicodeString(&fText
, &newText
, &status
);
485 // Set up a character iterator on the string.
486 // Needed in case someone calls getText().
487 // Can not, unfortunately, do this lazily on the (probably never)
488 // call to getText(), because getText is const.
489 fSCharIter
.setText(newText
);
491 if (fCharIter
!= &fSCharIter
) {
492 // old fCharIter was adopted from the outside. Delete it.
495 fCharIter
= &fSCharIter
;
502 * Provide a new UText for the input text. Must reference text with contents identical
504 * Intended for use with text data originating in Java (garbage collected) environments
505 * where the data may be moved in memory at arbitrary times.
507 RuleBasedBreakIterator
&RuleBasedBreakIterator::refreshInputText(UText
*input
, UErrorCode
&status
) {
508 if (U_FAILURE(status
)) {
512 status
= U_ILLEGAL_ARGUMENT_ERROR
;
515 int64_t pos
= utext_getNativeIndex(&fText
);
516 // Shallow read-only clone of the new UText into the existing input UText
517 utext_clone(&fText
, input
, FALSE
, TRUE
, &status
);
518 if (U_FAILURE(status
)) {
521 utext_setNativeIndex(&fText
, pos
);
522 if (utext_getNativeIndex(&fText
) != pos
) {
523 // Sanity check. The new input utext is supposed to have the exact same
524 // contents as the old. If we can't set to the same position, it doesn't.
525 // The contents underlying the old utext might be invalid at this point,
526 // so it's not safe to check directly.
527 status
= U_ILLEGAL_ARGUMENT_ERROR
;
534 * Sets the current iteration position to the beginning of the text, position zero.
535 * @return The new iterator position, which is zero.
537 int32_t RuleBasedBreakIterator::first(void) {
538 UErrorCode status
= U_ZERO_ERROR
;
539 if (!fBreakCache
->seek(0)) {
540 fBreakCache
->populateNear(0, status
);
542 fBreakCache
->current();
543 U_ASSERT(fPosition
== 0);
548 * Sets the current iteration position to the end of the text.
549 * @return The text's past-the-end offset.
551 int32_t RuleBasedBreakIterator::last(void) {
552 int32_t endPos
= (int32_t)utext_nativeLength(&fText
);
553 UBool endShouldBeBoundary
= isBoundary(endPos
); // Has side effect of setting iterator position.
554 (void)endShouldBeBoundary
;
555 U_ASSERT(endShouldBeBoundary
);
556 U_ASSERT(fPosition
== endPos
);
561 * Advances the iterator either forward or backward the specified number of steps.
562 * Negative values move backward, and positive values move forward. This is
563 * equivalent to repeatedly calling next() or previous().
564 * @param n The number of steps to move. The sign indicates the direction
565 * (negative is backwards, and positive is forwards).
566 * @return The character offset of the boundary position n boundaries away from
569 int32_t RuleBasedBreakIterator::next(int32_t n
) {
572 for (; n
> 0 && result
!= UBRK_DONE
; --n
) {
576 for (; n
< 0 && result
!= UBRK_DONE
; ++n
) {
586 * Advances the iterator to the next boundary position.
587 * @return The position of the first boundary after this one.
589 int32_t RuleBasedBreakIterator::next(void) {
591 return fDone
? UBRK_DONE
: fPosition
;
595 * Move the iterator backwards, to the boundary preceding the current one.
597 * Starts from the current position within fText.
598 * Starting position need not be on a boundary.
600 * @return The position of the boundary position immediately preceding the starting position.
602 int32_t RuleBasedBreakIterator::previous(void) {
603 UErrorCode status
= U_ZERO_ERROR
;
604 fBreakCache
->previous(status
);
605 return fDone
? UBRK_DONE
: fPosition
;
609 * Sets the iterator to refer to the first boundary position following
610 * the specified position.
611 * @param startPos The position from which to begin searching for a break position.
612 * @return The position of the first break after the current position.
614 int32_t RuleBasedBreakIterator::following(int32_t startPos
) {
615 // if the supplied position is before the beginning, return the
616 // text's starting offset
621 // Move requested offset to a code point start. It might be on a trail surrogate,
622 // or on a trail byte if the input is UTF-8. Or it may be beyond the end of the text.
623 utext_setNativeIndex(&fText
, startPos
);
624 startPos
= (int32_t)utext_getNativeIndex(&fText
);
626 UErrorCode status
= U_ZERO_ERROR
;
627 fBreakCache
->following(startPos
, status
);
628 return fDone
? UBRK_DONE
: fPosition
;
632 * Sets the iterator to refer to the last boundary position before the
633 * specified position.
634 * @param offset The position to begin searching for a break from.
635 * @return The position of the last boundary before the starting position.
637 int32_t RuleBasedBreakIterator::preceding(int32_t offset
) {
638 if (offset
> utext_nativeLength(&fText
)) {
642 // Move requested offset to a code point start. It might be on a trail surrogate,
643 // or on a trail byte if the input is UTF-8.
645 utext_setNativeIndex(&fText
, offset
);
646 int32_t adjustedOffset
= static_cast<int32_t>(utext_getNativeIndex(&fText
));
648 UErrorCode status
= U_ZERO_ERROR
;
649 fBreakCache
->preceding(adjustedOffset
, status
);
650 return fDone
? UBRK_DONE
: fPosition
;
654 * Returns true if the specfied position is a boundary position. As a side
655 * effect, leaves the iterator pointing to the first boundary position at
658 * @param offset the offset to check.
659 * @return True if "offset" is a boundary position.
661 UBool
RuleBasedBreakIterator::isBoundary(int32_t offset
) {
662 // out-of-range indexes are never boundary positions
664 first(); // For side effects on current position, tag values.
668 // Adjust offset to be on a code point boundary and not beyond the end of the text.
669 // Note that isBoundary() is always false for offsets that are not on code point boundaries.
670 // But we still need the side effect of leaving iteration at the following boundary.
672 utext_setNativeIndex(&fText
, offset
);
673 int32_t adjustedOffset
= static_cast<int32_t>(utext_getNativeIndex(&fText
));
676 UErrorCode status
= U_ZERO_ERROR
;
677 if (fBreakCache
->seek(adjustedOffset
) || fBreakCache
->populateNear(adjustedOffset
, status
)) {
678 result
= (fBreakCache
->current() == offset
);
681 if (result
&& adjustedOffset
< offset
&& utext_char32At(&fText
, offset
) == U_SENTINEL
) {
682 // Original offset is beyond the end of the text. Return FALSE, it's not a boundary,
683 // but the iteration position remains set to the end of the text, which is a boundary.
687 // Not on a boundary. isBoundary() must leave iterator on the following boundary.
688 // Cache->seek(), above, left us on the preceding boundary, so advance one.
696 * Returns the current iteration position.
697 * @return The current iteration position.
699 int32_t RuleBasedBreakIterator::current(void) const {
704 //=======================================================================
706 //=======================================================================
709 // RBBIRunMode - the state machine runs an extra iteration at the beginning and end
710 // of user text. A variable with this enum type keeps track of where we
711 // are. The state machine only fetches user input while in the RUN mode.
714 RBBI_START
, // state machine processing is before first char of input
715 RBBI_RUN
, // state machine processing is in the user text
716 RBBI_END
// state machine processing is after end of user text.
720 // Map from look-ahead break states (corresponds to rules) to boundary positions.
721 // Allows multiple lookahead break rules to be in flight at the same time.
723 // This is a temporary approach for ICU 57. A better fix is to make the look-ahead numbers
724 // in the state table be sequential, then we can just index an array. And the
725 // table could also tell us in advance how big that array needs to be.
727 // Before ICU 57 there was just a single simple variable for a look-ahead match that
728 // was in progress. Two rules at once did not work.
730 static const int32_t kMaxLookaheads
= 8;
731 struct LookAheadResults
{
732 int32_t fUsedSlotLimit
;
733 int32_t fPositions
[8];
736 LookAheadResults() : fUsedSlotLimit(0), fPositions(), fKeys() {}
738 int32_t getPosition(int16_t key
) {
739 for (int32_t i
=0; i
<fUsedSlotLimit
; ++i
) {
740 if (fKeys
[i
] == key
) {
741 return fPositions
[i
];
744 // with NLLT source rules, Latn sample and ubrk_next, we see a request for key 79 here
745 // near the end of text, when setPosition has only ever set positions for key 80 or 82.
750 void setPosition(int16_t key
, int32_t position
) {
752 for (i
=0; i
<fUsedSlotLimit
; ++i
) {
753 if (fKeys
[i
] == key
) {
754 fPositions
[i
] = position
;
758 if (i
>= kMaxLookaheads
) {
760 i
= kMaxLookaheads
- 1; // Apple addition
763 fPositions
[i
] = position
;
764 U_ASSERT(fUsedSlotLimit
== i
);
765 fUsedSlotLimit
= i
+ 1;
770 //-----------------------------------------------------------------------------------
773 // Run the state machine to find a boundary
775 //-----------------------------------------------------------------------------------
776 // Route handleNext calls through the following to handleNextInternal,
777 // in order to handle fLineWordOpts.
778 int32_t RuleBasedBreakIterator::handleNext() {
779 int32_t result
= handleNextInternal();
780 while (fLineWordOpts
!= UBRK_LINEWORD_NORMAL
) {
781 UChar32 prevChr
= utext_char32At(&fText
, result
-1);
782 UChar32 currChr
= utext_char32At(&fText
, result
);
783 if (currChr
== U_SENTINEL
|| prevChr
== U_SENTINEL
) {
786 if (fLineWordOpts
== UBRK_LINEWORD_KEEP_HANGUL
) {
787 UErrorCode status
= U_ZERO_ERROR
;
788 if (uscript_getScript(currChr
, &status
) != USCRIPT_HANGUL
|| uscript_getScript(prevChr
, &status
) != USCRIPT_HANGUL
) {
792 if (!u_isalpha(currChr
) || !u_isalpha(prevChr
)) {
796 int32_t nextResult
= handleNextInternal();
797 if (nextResult
<= result
) {
805 int32_t RuleBasedBreakIterator::handleNextInternal() {
807 uint16_t category
= 0;
810 RBBIStateTableRow
*row
;
812 LookAheadResults lookAheadMatches
;
814 int32_t initialPosition
= 0;
815 const RBBIStateTable
*statetable
= fData
->fForwardTable
;
816 const char *tableData
= statetable
->fTableData
;
817 uint32_t tableRowLen
= statetable
->fRowLen
;
820 RBBIDebugPuts("Handle Next pos char state category");
824 // handleNext alway sets the break tag value.
825 // Set the default for it.
826 fRuleStatusIndex
= 0;
828 fDictionaryCharCount
= 0;
830 // if we're already at the end of the text, return DONE.
831 initialPosition
= fPosition
;
832 UTEXT_SETNATIVEINDEX(&fText
, initialPosition
);
833 result
= initialPosition
;
834 c
= UTEXT_NEXT32(&fText
);
840 // Set the initial state for the state machine
842 row
= (RBBIStateTableRow
*)
843 //(statetable->fTableData + (statetable->fRowLen * state));
844 (tableData
+ tableRowLen
* state
);
848 if (statetable
->fFlags
& RBBI_BOF_REQUIRED
) {
854 // loop until we reach the end of the text or transition to state 0
857 if (c
== U_SENTINEL
) {
858 // Reached end of input string.
859 if (mode
== RBBI_END
) {
860 // We have already run the loop one last time with the
861 // character set to the psueudo {eof} value. Now it is time
862 // to unconditionally bail out.
865 // Run the loop one last time with the fake end-of-input character category.
871 // Get the char category. An incoming category of 1 or 2 means that
872 // we are preset for doing the beginning or end of input, and
873 // that we shouldn't get a category from an actual text input character.
875 if (mode
== RBBI_RUN
) {
876 // look up the current character's character category, which tells us
877 // which column in the state table to look at.
878 // Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
879 // not the size of the character going in, which is a UChar32.
881 category
= (fLatin1Cat
!=NULL
&& c
<0x100)? fLatin1Cat
[c
]: UTRIE2_GET16(fData
->fTrie
, c
);
883 // Check the dictionary bit in the character's category.
884 // Counter is only used by dictionary based iteration.
885 // Chars that need to be handled by a dictionary have a flag bit set
886 // in their category values.
888 if ((category
& 0x4000) != 0) {
889 fDictionaryCharCount
++;
890 // And off the dictionary flag bit.
897 RBBIDebugPrintf(" %4" PRId64
" ", utext_getNativeIndex(&fText
));
898 if (0x20<=c
&& c
<0x7f) {
899 RBBIDebugPrintf("\"%c\" ", c
);
901 RBBIDebugPrintf("%5x ", c
);
903 RBBIDebugPrintf("%3d %3d\n", state
, category
);
907 // State Transition - move machine to its next state
910 // fNextState is a variable-length array.
911 U_ASSERT(category
<fData
->fHeader
->fCatCount
);
912 state
= row
->fNextState
[category
]; /*Not accessing beyond memory*/
913 row
= (RBBIStateTableRow
*)
914 // (statetable->fTableData + (statetable->fRowLen * state));
915 (tableData
+ tableRowLen
* state
);
918 if (row
->fAccepting
== -1) {
919 // Match found, common case.
920 if (mode
!= RBBI_START
) {
921 result
= (int32_t)UTEXT_GETNATIVEINDEX(&fText
);
923 fRuleStatusIndex
= row
->fTagIdx
; // Remember the break status (tag) values.
926 int16_t completedRule
= row
->fAccepting
;
927 if (completedRule
> 0) {
928 // Lookahead match is completed.
929 int32_t lookaheadResult
= lookAheadMatches
.getPosition(completedRule
);
930 if (lookaheadResult
>= 0) {
931 fRuleStatusIndex
= row
->fTagIdx
;
932 fPosition
= lookaheadResult
;
933 return lookaheadResult
;
936 int16_t rule
= row
->fLookAhead
;
938 // At the position of a '/' in a look-ahead match. Record it.
939 int32_t pos
= (int32_t)UTEXT_GETNATIVEINDEX(&fText
);
940 lookAheadMatches
.setPosition(rule
, pos
);
943 if (state
== STOP_STATE
) {
944 // This is the normal exit from the lookup state machine.
945 // We have advanced through the string until it is certain that no
946 // longer match is possible, no matter what characters follow.
950 // Advance to the next character.
951 // If this is a beginning-of-input loop iteration, don't advance
952 // the input position. The next iteration will be processing the
953 // first real input character.
954 if (mode
== RBBI_RUN
) {
955 c
= UTEXT_NEXT32(&fText
);
957 if (mode
== RBBI_START
) {
963 // The state machine is done. Check whether it found a match...
965 // If the iterator failed to advance in the match engine, force it ahead by one.
966 // (This really indicates a defect in the break rules. They should always match
967 // at least one character.)
968 if (result
== initialPosition
) {
969 utext_setNativeIndex(&fText
, initialPosition
);
970 utext_next32(&fText
);
971 result
= (int32_t)utext_getNativeIndex(&fText
);
972 fRuleStatusIndex
= 0;
975 // Leave the iterator at our result position.
979 RBBIDebugPrintf("result = %d\n\n", result
);
986 //-----------------------------------------------------------------------------------
988 // handleSafePrevious()
990 // Iterate backwards using the safe reverse rules.
991 // The logic of this function is similar to handleNext(), but simpler
992 // because the safe table does not require as many options.
994 //-----------------------------------------------------------------------------------
995 int32_t RuleBasedBreakIterator::handleSafePrevious(int32_t fromPosition
) {
997 uint16_t category
= 0;
998 RBBIStateTableRow
*row
;
1002 const RBBIStateTable
*stateTable
= fData
->fReverseTable
;
1003 UTEXT_SETNATIVEINDEX(&fText
, fromPosition
);
1006 RBBIDebugPuts("Handle Previous pos char state category");
1010 // if we're already at the start of the text, return DONE.
1011 if (fData
== NULL
|| UTEXT_GETNATIVEINDEX(&fText
)==0) {
1012 return BreakIterator::DONE
;
1015 // Set the initial state for the state machine
1016 c
= UTEXT_PREVIOUS32(&fText
);
1017 state
= START_STATE
;
1018 row
= (RBBIStateTableRow
*)
1019 (stateTable
->fTableData
+ (stateTable
->fRowLen
* state
));
1021 // loop until we reach the start of the text or transition to state 0
1023 for (; c
!= U_SENTINEL
; c
= UTEXT_PREVIOUS32(&fText
)) {
1025 // look up the current character's character category, which tells us
1026 // which column in the state table to look at.
1027 // Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
1028 // not the size of the character going in, which is a UChar32.
1030 // And off the dictionary flag bit. For reverse iteration it is not used.
1031 category
= UTRIE2_GET16(fData
->fTrie
, c
);
1032 category
&= ~0x4000;
1036 RBBIDebugPrintf(" %4d ", (int32_t)utext_getNativeIndex(&fText
));
1037 if (0x20<=c
&& c
<0x7f) {
1038 RBBIDebugPrintf("\"%c\" ", c
);
1040 RBBIDebugPrintf("%5x ", c
);
1042 RBBIDebugPrintf("%3d %3d\n", state
, category
);
1046 // State Transition - move machine to its next state
1048 // fNextState is a variable-length array.
1049 U_ASSERT(category
<fData
->fHeader
->fCatCount
);
1050 state
= row
->fNextState
[category
]; /*Not accessing beyond memory*/
1051 row
= (RBBIStateTableRow
*)
1052 (stateTable
->fTableData
+ (stateTable
->fRowLen
* state
));
1054 if (state
== STOP_STATE
) {
1055 // This is the normal exit from the lookup state machine.
1056 // Transistion to state zero means we have found a safe point.
1061 // The state machine is done. Check whether it found a match...
1062 result
= (int32_t)UTEXT_GETNATIVEINDEX(&fText
);
1065 RBBIDebugPrintf("result = %d\n\n", result
);
1071 //-------------------------------------------------------------------------------
1073 // getRuleStatus() Return the break rule tag associated with the current
1074 // iterator position. If the iterator arrived at its current
1075 // position by iterating forwards, the value will have been
1076 // cached by the handleNext() function.
1078 //-------------------------------------------------------------------------------
1080 int32_t RuleBasedBreakIterator::getRuleStatus() const {
1082 // fLastRuleStatusIndex indexes to the start of the appropriate status record
1083 // (the number of status values.)
1084 // This function returns the last (largest) of the array of status values.
1085 int32_t idx
= fRuleStatusIndex
+ fData
->fRuleStatusTable
[fRuleStatusIndex
];
1086 int32_t tagVal
= fData
->fRuleStatusTable
[idx
];
1092 int32_t RuleBasedBreakIterator::getRuleStatusVec(
1093 int32_t *fillInVec
, int32_t capacity
, UErrorCode
&status
) {
1094 if (U_FAILURE(status
)) {
1098 int32_t numVals
= fData
->fRuleStatusTable
[fRuleStatusIndex
];
1099 int32_t numValsToCopy
= numVals
;
1100 if (numVals
> capacity
) {
1101 status
= U_BUFFER_OVERFLOW_ERROR
;
1102 numValsToCopy
= capacity
;
1105 for (i
=0; i
<numValsToCopy
; i
++) {
1106 fillInVec
[i
] = fData
->fRuleStatusTable
[fRuleStatusIndex
+ i
+ 1];
1111 // Apple custom addition
1112 int32_t RuleBasedBreakIterator::tokenize(int32_t maxTokens
, RuleBasedTokenRange
*outTokenRanges
, unsigned long *outTokenFlags
)
1117 RuleBasedTokenRange
*outTokenLimit
= outTokenRanges
+ maxTokens
;
1118 RuleBasedTokenRange
*outTokenP
= outTokenRanges
;
1119 int32_t lastOffset
= fPosition
;
1120 while (outTokenP
< outTokenLimit
) {
1121 // start portion from inlining populateFollowing()
1123 int32_t ruleStatusIdx
= 0;
1124 int32_t startPos
= fPosition
;
1126 if (fDictionaryCache
->following(startPos
, &pos
, &ruleStatusIdx
)) {
1128 fRuleStatusIndex
= ruleStatusIdx
;
1130 pos
= handleNextInternal(); // sets fRuleStatusIndex for the pos it returns, updates fPosition
1131 if (pos
== UBRK_DONE
) {
1132 // fDone = TRUE; already set by handleNextInternal
1135 // Use current result from handleNextInternal(), including fRuleStatusIndex,
1136 // unless overridden by dictionary subdivisions
1138 if (fDictionaryCharCount
> 0) {
1139 // The text segment obtained from the rules includes dictionary characters.
1140 // Subdivide it, with subdivided results going into the dictionary cache.
1141 fDictionaryCache
->populateDictionary(startPos
, pos
, fRuleStatusIndex
, fRuleStatusIndex
);
1142 if (fDictionaryCache
->following(startPos
, &pos
, &ruleStatusIdx
)) {
1144 fRuleStatusIndex
= ruleStatusIdx
;
1148 // end portion from inlining populateFollowing()
1149 int32_t flagCount
= fData
->fRuleStatusTable
[fRuleStatusIndex
];
1150 const int32_t* flagPtr
= fData
->fRuleStatusTable
+ fRuleStatusIndex
+ flagCount
;
1151 int32_t flagSet
= *flagPtr
; // if -1 then skip token
1152 if (flagSet
!= -1) {
1153 outTokenP
->location
= lastOffset
;
1154 outTokenP
++->length
= fPosition
- lastOffset
;
1155 if (outTokenFlags
) {
1156 // flagSet should be the OR of all flags returned by getRuleStatusVec;
1157 // here we collect from high-order to low-order.
1158 while (--flagCount
> 0) {
1159 flagSet
|= *--flagPtr
;
1161 *outTokenFlags
++ = (unsigned long)flagSet
;
1164 lastOffset
= fPosition
;
1166 return (outTokenP
- outTokenRanges
);
1169 //-------------------------------------------------------------------------------
1171 // getBinaryRules Access to the compiled form of the rules,
1172 // for use by build system tools that save the data
1173 // for standard iterator types.
1175 //-------------------------------------------------------------------------------
1176 const uint8_t *RuleBasedBreakIterator::getBinaryRules(uint32_t &length
) {
1177 const uint8_t *retPtr
= NULL
;
1180 if (fData
!= NULL
) {
1181 retPtr
= (const uint8_t *)fData
->fHeader
;
1182 length
= fData
->fHeader
->fLength
;
1188 BreakIterator
* RuleBasedBreakIterator::createBufferClone(void * /*stackBuffer*/,
1189 int32_t &bufferSize
,
1192 if (U_FAILURE(status
)){
1196 if (bufferSize
== 0) {
1197 bufferSize
= 1; // preflighting for deprecated functionality
1201 BreakIterator
*clonedBI
= clone();
1202 if (clonedBI
== NULL
) {
1203 status
= U_MEMORY_ALLOCATION_ERROR
;
1205 status
= U_SAFECLONE_ALLOCATED_WARNING
;
1207 return (RuleBasedBreakIterator
*)clonedBI
;
1213 static icu::UStack
*gLanguageBreakFactories
= nullptr;
1214 static const icu::UnicodeString
*gEmptyString
= nullptr;
1215 static icu::UInitOnce gLanguageBreakFactoriesInitOnce
= U_INITONCE_INITIALIZER
;
1216 static icu::UInitOnce gRBBIInitOnce
= U_INITONCE_INITIALIZER
;
1219 * Release all static memory held by breakiterator.
1222 static UBool U_CALLCONV
rbbi_cleanup(void) {
1223 delete gLanguageBreakFactories
;
1224 gLanguageBreakFactories
= nullptr;
1225 delete gEmptyString
;
1226 gEmptyString
= nullptr;
1227 gLanguageBreakFactoriesInitOnce
.reset();
1228 gRBBIInitOnce
.reset();
1234 static void U_CALLCONV
_deleteFactory(void *obj
) {
1235 delete (icu::LanguageBreakFactory
*) obj
;
1240 static void U_CALLCONV
rbbiInit() {
1241 gEmptyString
= new UnicodeString();
1242 ucln_common_registerCleanup(UCLN_COMMON_RBBI
, rbbi_cleanup
);
1245 static void U_CALLCONV
initLanguageFactories() {
1246 UErrorCode status
= U_ZERO_ERROR
;
1247 U_ASSERT(gLanguageBreakFactories
== NULL
);
1248 gLanguageBreakFactories
= new UStack(_deleteFactory
, NULL
, status
);
1249 if (gLanguageBreakFactories
!= NULL
&& U_SUCCESS(status
)) {
1250 ICULanguageBreakFactory
*builtIn
= new ICULanguageBreakFactory(status
);
1251 gLanguageBreakFactories
->push(builtIn
, status
);
1252 #ifdef U_LOCAL_SERVICE_HOOK
1253 LanguageBreakFactory
*extra
= (LanguageBreakFactory
*)uprv_svc_hook("languageBreakFactory", &status
);
1254 if (extra
!= NULL
) {
1255 gLanguageBreakFactories
->push(extra
, status
);
1259 ucln_common_registerCleanup(UCLN_COMMON_RBBI
, rbbi_cleanup
);
1263 static const LanguageBreakEngine
*
1264 getLanguageBreakEngineFromFactory(UChar32 c
)
1266 umtx_initOnce(gLanguageBreakFactoriesInitOnce
, &initLanguageFactories
);
1267 if (gLanguageBreakFactories
== NULL
) {
1271 int32_t i
= gLanguageBreakFactories
->size();
1272 const LanguageBreakEngine
*lbe
= NULL
;
1274 LanguageBreakFactory
*factory
= (LanguageBreakFactory
*)(gLanguageBreakFactories
->elementAt(i
));
1275 lbe
= factory
->getEngineFor(c
);
1284 //-------------------------------------------------------------------------------
1286 // getLanguageBreakEngine Find an appropriate LanguageBreakEngine for the
1289 //-------------------------------------------------------------------------------
1290 const LanguageBreakEngine
*
1291 RuleBasedBreakIterator::getLanguageBreakEngine(UChar32 c
) {
1292 const LanguageBreakEngine
*lbe
= NULL
;
1293 UErrorCode status
= U_ZERO_ERROR
;
1295 if (fLanguageBreakEngines
== NULL
) {
1296 fLanguageBreakEngines
= new UStack(status
);
1297 if (fLanguageBreakEngines
== NULL
|| U_FAILURE(status
)) {
1298 delete fLanguageBreakEngines
;
1299 fLanguageBreakEngines
= 0;
1304 int32_t i
= fLanguageBreakEngines
->size();
1306 lbe
= (const LanguageBreakEngine
*)(fLanguageBreakEngines
->elementAt(i
));
1307 if (lbe
->handles(c
)) {
1312 // No existing dictionary took the character. See if a factory wants to
1313 // give us a new LanguageBreakEngine for this character.
1314 lbe
= getLanguageBreakEngineFromFactory(c
);
1316 // If we got one, use it and push it on our stack.
1318 fLanguageBreakEngines
->push((void *)lbe
, status
);
1319 // Even if we can't remember it, we can keep looking it up, so
1320 // return it even if the push fails.
1324 // No engine is forthcoming for this character. Add it to the
1325 // reject set. Create the reject break engine if needed.
1326 if (fUnhandledBreakEngine
== NULL
) {
1327 fUnhandledBreakEngine
= new UnhandledEngine(status
);
1328 if (U_SUCCESS(status
) && fUnhandledBreakEngine
== NULL
) {
1329 status
= U_MEMORY_ALLOCATION_ERROR
;
1332 // Put it last so that scripts for which we have an engine get tried
1334 fLanguageBreakEngines
->insertElementAt(fUnhandledBreakEngine
, 0, status
);
1335 // If we can't insert it, or creation failed, get rid of it
1336 if (U_FAILURE(status
)) {
1337 delete fUnhandledBreakEngine
;
1338 fUnhandledBreakEngine
= 0;
1343 // Tell the reject engine about the character; at its discretion, it may
1344 // add more than just the one character.
1345 fUnhandledBreakEngine
->handleCharacter(c
);
1347 return fUnhandledBreakEngine
;
1350 void RuleBasedBreakIterator::dumpCache() {
1351 fBreakCache
->dumpCache();
1354 void RuleBasedBreakIterator::dumpTables() {
1359 * Returns the description used to create this iterator
1362 const UnicodeString
&
1363 RuleBasedBreakIterator::getRules() const {
1364 if (fData
!= NULL
) {
1365 return fData
->getRuleSourceString();
1367 umtx_initOnce(gRBBIInitOnce
, &rbbiInit
);
1368 return *gEmptyString
;
1374 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */