5 // Copyright (C) 2002-2004, International Business Machines Corporation and others.
6 // All Rights Reserved.
8 // This file contains the Rule Based Break Iterator Rule Builder functions for
9 // scanning the rules and assembling a parse tree. This is the first phase
10 // of compiling the rules.
12 // The overall of the rules is managed by class RBBIRuleBuilder, which will
13 // create and use an instance of this class as part of the process.
16 #include "unicode/utypes.h"
18 #if !UCONFIG_NO_BREAK_ITERATION
20 #include "unicode/unistr.h"
21 #include "unicode/uniset.h"
22 #include "unicode/uchar.h"
23 #include "unicode/uchriter.h"
24 #include "unicode/parsepos.h"
25 #include "unicode/parseerr.h"
30 #include "rbbirpt.h" // Contains state table for the rbbi rules parser.
31 // generated by a Perl script.
40 //----------------------------------------------------------------------------------------
42 // Unicode Set init strings for each of the character classes needed for parsing a rule file.
43 // (Initialized with hex values for portability to EBCDIC based machines.
44 // Really ugly, but there's no good way to avoid it.)
46 // The sets are referred to by name in the rbbirpt.txt, which is the
47 // source form of the state transition table for the RBBI rule parser.
49 //----------------------------------------------------------------------------------------
50 static const UChar gRuleSet_rule_char_pattern
[] = {
51 // [ ^ [ \ p { Z } \ u 0 0 2 0
52 0x5b, 0x5e, 0x5b, 0x5c, 0x70, 0x7b, 0x5a, 0x7d, 0x5c, 0x75, 0x30, 0x30, 0x32, 0x30,
53 // - \ u 0 0 7 f ] - [ \ p
54 0x2d, 0x5c, 0x75, 0x30, 0x30, 0x37, 0x66, 0x5d, 0x2d, 0x5b, 0x5c, 0x70,
55 // { L } ] - [ \ p { N } ] ]
56 0x7b, 0x4c, 0x7d, 0x5d, 0x2d, 0x5b, 0x5c, 0x70, 0x7b, 0x4e, 0x7d, 0x5d, 0x5d, 0};
58 static const UChar gRuleSet_name_char_pattern
[] = {
59 // [ _ \ p { L } \ p { N } ]
60 0x5b, 0x5f, 0x5c, 0x70, 0x7b, 0x4c, 0x7d, 0x5c, 0x70, 0x7b, 0x4e, 0x7d, 0x5d, 0};
62 static const UChar gRuleSet_digit_char_pattern
[] = {
64 0x5b, 0x30, 0x2d, 0x39, 0x5d, 0};
66 static const UChar gRuleSet_name_start_char_pattern
[] = {
68 0x5b, 0x5f, 0x5c, 0x70, 0x7b, 0x4c, 0x7d, 0x5d, 0 };
70 static const UChar kAny
[] = {0x61, 0x6e, 0x79, 0x00}; // "any"
74 static void U_EXPORT2 U_CALLCONV
RBBISetTable_deleter(void *p
) {
75 RBBISetTableEl
*px
= (RBBISetTableEl
*)p
;
77 // Note: px->val is owned by the linked list "fSetsListHead" in scanner.
78 // Don't delete the value nodes here.
85 //----------------------------------------------------------------------------------------
89 //----------------------------------------------------------------------------------------
90 RBBIRuleScanner::RBBIRuleScanner(RBBIRuleBuilder
*rb
)
94 fStack
[fStackPtr
] = 0;
99 fRuleSets
[kRuleSet_rule_char
-128] = NULL
;
100 fRuleSets
[kRuleSet_white_space
-128] = NULL
;
101 fRuleSets
[kRuleSet_name_char
-128] = NULL
;
102 fRuleSets
[kRuleSet_name_start_char
-128] = NULL
;
103 fRuleSets
[kRuleSet_digit_char
-128] = NULL
;
110 fReverseRule
= FALSE
;
111 fLookAheadRule
= FALSE
;
117 // Do not check status until after all critical fields are sufficiently initialized
118 // that the destructor can run cleanly.
119 if (U_FAILURE(*rb
->fStatus
)) {
124 // Set up the constant Unicode Sets.
125 // Note: These could be made static, lazily initialized, and shared among
126 // all instances of RBBIRuleScanners. BUT this is quite a bit simpler,
127 // and the time to build these few sets should be small compared to a
128 // full break iterator build.
129 fRuleSets
[kRuleSet_rule_char
-128] = new UnicodeSet(gRuleSet_rule_char_pattern
, *rb
->fStatus
);
130 fRuleSets
[kRuleSet_white_space
-128] = (UnicodeSet
*) uprv_openRuleWhiteSpaceSet(rb
->fStatus
);
131 fRuleSets
[kRuleSet_name_char
-128] = new UnicodeSet(gRuleSet_name_char_pattern
, *rb
->fStatus
);
132 fRuleSets
[kRuleSet_name_start_char
-128] = new UnicodeSet(gRuleSet_name_start_char_pattern
, *rb
->fStatus
);
133 fRuleSets
[kRuleSet_digit_char
-128] = new UnicodeSet(gRuleSet_digit_char_pattern
, *rb
->fStatus
);
134 if (*rb
->fStatus
== U_ILLEGAL_ARGUMENT_ERROR
) {
135 // This case happens if ICU's data is missing. UnicodeSet tries to look up property
136 // names from the init string, can't find them, and claims an illegal arguement.
137 // Change the error so that the actual problem will be clearer to users.
138 *rb
->fStatus
= U_BRK_INIT_ERROR
;
140 if (U_FAILURE(*rb
->fStatus
)) {
144 fSymbolTable
= new RBBISymbolTable(this, rb
->fRules
, *rb
->fStatus
);
145 fSetTable
= uhash_open(uhash_hashUnicodeString
, uhash_compareUnicodeString
, rb
->fStatus
);
146 uhash_setValueDeleter(fSetTable
, RBBISetTable_deleter
);
151 //----------------------------------------------------------------------------------------
155 //----------------------------------------------------------------------------------------
156 RBBIRuleScanner::~RBBIRuleScanner() {
157 delete fRuleSets
[kRuleSet_rule_char
-128];
158 delete fRuleSets
[kRuleSet_white_space
-128];
159 delete fRuleSets
[kRuleSet_name_char
-128];
160 delete fRuleSets
[kRuleSet_name_start_char
-128];
161 delete fRuleSets
[kRuleSet_digit_char
-128];
164 if (fSetTable
!= NULL
) {
165 uhash_close(fSetTable
);
172 // Normally has one entry, which is the entire parse tree for the rules.
173 // If errors occured, there may be additional subtrees left on the stack.
174 while (fNodeStackPtr
> 0) {
175 delete fNodeStack
[fNodeStackPtr
];
181 //----------------------------------------------------------------------------------------
183 // doParseAction Do some action during rule parsing.
184 // Called by the parse state machine.
185 // Actions build the parse tree and Unicode Sets,
186 // and maintain the parse stack for nested expressions.
188 // TODO: unify EParseAction and RBBI_RuleParseAction enum types.
189 // They represent exactly the same thing. They're separate
190 // only to work around enum forward declaration restrictions
191 // in some compilers, while at the same time avoiding multiple
192 // definitions problems. I'm sure that there's a better way.
194 //----------------------------------------------------------------------------------------
195 UBool
RBBIRuleScanner::doParseActions(EParseAction action
)
199 UBool returnVal
= TRUE
;
201 switch ((RBBI_RuleParseAction
)action
) {
204 pushNewNode(RBBINode::opStart
);
209 case doExprOrOperator
:
211 fixOpStack(RBBINode::precOpCat
);
212 RBBINode
*operandNode
= fNodeStack
[fNodeStackPtr
--];
213 RBBINode
*orNode
= pushNewNode(RBBINode::opOr
);
214 orNode
->fLeftChild
= operandNode
;
215 operandNode
->fParent
= orNode
;
219 case doExprCatOperator
:
220 // concatenation operator.
221 // For the implicit concatenation of adjacent terms in an expression that are
222 // not separated by any other operator. Action is invoked between the
223 // actions for the two terms.
225 fixOpStack(RBBINode::precOpCat
);
226 RBBINode
*operandNode
= fNodeStack
[fNodeStackPtr
--];
227 RBBINode
*catNode
= pushNewNode(RBBINode::opCat
);
228 catNode
->fLeftChild
= operandNode
;
229 operandNode
->fParent
= catNode
;
235 // The openParen node is a dummy operation type with a low precedence,
236 // which has the affect of ensuring that any real binary op that
237 // follows within the parens binds more tightly to the operands than
238 // stuff outside of the parens.
239 pushNewNode(RBBINode::opLParen
);
243 fixOpStack(RBBINode::precLParen
);
250 // We've just scanned "$variable = "
251 // The top of the node stack has the $variable ref node.
253 // Save the start position of the RHS text in the StartExpression node
254 // that precedes the $variableReference node on the stack.
255 // This will eventually be used when saving the full $variable replacement
257 n
= fNodeStack
[fNodeStackPtr
-1];
258 n
->fFirstPos
= fNextIndex
; // move past the '='
260 // Push a new start-of-expression node; needed to keep parse of the
261 // RHS expression happy.
262 pushNewNode(RBBINode::opStart
);
270 // We have reached the end of an assignement statement.
271 // Current scan char is the ';' that terminates the assignment.
273 // Terminate expression, leaves expression parse tree rooted in TOS node.
274 fixOpStack(RBBINode::precStart
);
276 RBBINode
*startExprNode
= fNodeStack
[fNodeStackPtr
-2];
277 RBBINode
*varRefNode
= fNodeStack
[fNodeStackPtr
-1];
278 RBBINode
*RHSExprNode
= fNodeStack
[fNodeStackPtr
];
280 // Save original text of right side of assignment, excluding the terminating ';'
281 // in the root of the node for the right-hand-side expression.
282 RHSExprNode
->fFirstPos
= startExprNode
->fFirstPos
;
283 RHSExprNode
->fLastPos
= fScanIndex
;
284 fRB
->fRules
.extractBetween(RHSExprNode
->fFirstPos
, RHSExprNode
->fLastPos
, RHSExprNode
->fText
);
286 // Expression parse tree becomes l. child of the $variable reference node.
287 varRefNode
->fLeftChild
= RHSExprNode
;
288 RHSExprNode
->fParent
= varRefNode
;
290 // Make a symbol table entry for the $variableRef node.
291 fSymbolTable
->addEntry(varRefNode
->fText
, varRefNode
, *fRB
->fStatus
);
293 // Clean up the stack.
294 delete startExprNode
;
301 fixOpStack(RBBINode::precStart
); // Terminate expression, leaves expression
302 if (U_FAILURE(*fRB
->fStatus
)) { // parse tree rooted in TOS node.
305 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "rtree")) {printNodeStack("end of rule");}
306 U_ASSERT(fNodeStackPtr
== 1);
308 // If this rule includes a look-ahead '/', add a endMark node to the
310 if (fLookAheadRule
) {
311 RBBINode
*thisRule
= fNodeStack
[fNodeStackPtr
];
312 RBBINode
*endNode
= pushNewNode(RBBINode::endMark
);
313 RBBINode
*catNode
= pushNewNode(RBBINode::opCat
);
315 catNode
->fLeftChild
= thisRule
;
316 catNode
->fRightChild
= endNode
;
317 fNodeStack
[fNodeStackPtr
] = catNode
;
318 endNode
->fVal
= fRuleNum
;
319 endNode
->fLookAheadEnd
= TRUE
;
322 // All rule expressions are ORed together.
323 // The ';' that terminates an expression really just functions as a '|' with
324 // a low operator prededence.
326 // Each of the four sets of rules are collected separately.
327 // (forward, reverse, safe_forward, safe_reverse)
328 // OR this rule into the appropriate group of them.
330 RBBINode
**destRules
= (fReverseRule
? &fRB
->fReverseTree
: fRB
->fDefaultTree
);
332 if (*destRules
!= NULL
) {
333 // This is not the first rule encounted.
334 // OR previous stuff (from *destRules)
335 // with the current rule expression (on the Node Stack)
336 // with the resulting OR expression going to *destRules
338 RBBINode
*thisRule
= fNodeStack
[fNodeStackPtr
];
339 RBBINode
*prevRules
= *destRules
;
340 RBBINode
*orNode
= pushNewNode(RBBINode::opOr
);
341 orNode
->fLeftChild
= prevRules
;
342 prevRules
->fParent
= orNode
;
343 orNode
->fRightChild
= thisRule
;
344 thisRule
->fParent
= orNode
;
349 // This is the first rule encountered (for this direction).
350 // Just move its parse tree from the stack to *destRules.
351 *destRules
= fNodeStack
[fNodeStackPtr
];
353 fReverseRule
= FALSE
; // in preparation for the next rule.
354 fLookAheadRule
= FALSE
;
361 error(U_BRK_RULE_SYNTAX
);
366 case doVariableNameExpectedErr
:
367 error(U_BRK_RULE_SYNTAX
);
372 // Unary operands + ? *
373 // These all appear after the operand to which they apply.
374 // When we hit one, the operand (may be a whole sub expression)
375 // will be on the top of the stack.
376 // Unary Operator becomes TOS, with the old TOS as its one child.
379 RBBINode
*operandNode
= fNodeStack
[fNodeStackPtr
--];
380 RBBINode
*plusNode
= pushNewNode(RBBINode::opPlus
);
381 plusNode
->fLeftChild
= operandNode
;
382 operandNode
->fParent
= plusNode
;
386 case doUnaryOpQuestion
:
388 RBBINode
*operandNode
= fNodeStack
[fNodeStackPtr
--];
389 RBBINode
*qNode
= pushNewNode(RBBINode::opQuestion
);
390 qNode
->fLeftChild
= operandNode
;
391 operandNode
->fParent
= qNode
;
397 RBBINode
*operandNode
= fNodeStack
[fNodeStackPtr
--];
398 RBBINode
*starNode
= pushNewNode(RBBINode::opStar
);
399 starNode
->fLeftChild
= operandNode
;
400 operandNode
->fParent
= starNode
;
405 // A "Rule Character" is any single character that is a literal part
406 // of the regular expression. Like a, b and c in the expression "(abc*) | [:L:]"
407 // These are pretty uncommon in break rules; the terms are more commonly
408 // sets. To keep things uniform, treat these characters like as
409 // sets that just happen to contain only one character.
411 n
= pushNewNode(RBBINode::setRef
);
412 findSetFor(fC
.fChar
, n
);
413 n
->fFirstPos
= fScanIndex
;
414 n
->fLastPos
= fNextIndex
;
415 fRB
->fRules
.extractBetween(n
->fFirstPos
, n
->fLastPos
, n
->fText
);
420 // scanned a ".", meaning match any single character.
422 n
= pushNewNode(RBBINode::setRef
);
424 n
->fFirstPos
= fScanIndex
;
425 n
->fLastPos
= fNextIndex
;
426 fRB
->fRules
.extractBetween(n
->fFirstPos
, n
->fLastPos
, n
->fText
);
432 // Scanned a '/', which identifies a look-ahead break position in a rule.
433 n
= pushNewNode(RBBINode::lookAhead
);
435 n
->fFirstPos
= fScanIndex
;
436 n
->fLastPos
= fNextIndex
;
437 fRB
->fRules
.extractBetween(n
->fFirstPos
, n
->fLastPos
, n
->fText
);
438 fLookAheadRule
= TRUE
;
442 case doStartTagValue
:
443 // Scanned a '{', the opening delimiter for a tag value within a rule.
444 n
= pushNewNode(RBBINode::tag
);
446 n
->fFirstPos
= fScanIndex
;
447 n
->fLastPos
= fNextIndex
;
451 // Just scanned a decimal digit that's part of a tag value
453 n
= fNodeStack
[fNodeStackPtr
];
454 uint32_t v
= u_charDigitValue(fC
.fChar
);
456 n
->fVal
= n
->fVal
*10 + v
;
461 n
= fNodeStack
[fNodeStackPtr
];
462 n
->fLastPos
= fNextIndex
;
463 fRB
->fRules
.extractBetween(n
->fFirstPos
, n
->fLastPos
, n
->fText
);
466 case doTagExpectedError
:
467 error(U_BRK_MALFORMED_RULE_TAG
);
472 // Scanning a !!option. At the start of string.
473 fOptionStart
= fScanIndex
;
478 UnicodeString
opt(fRB
->fRules
, fOptionStart
, fScanIndex
-fOptionStart
);
479 if (opt
== UNICODE_STRING("chain", 5)) {
480 fRB
->fChainRules
= TRUE
;
481 } else if (opt
== UNICODE_STRING("LBCMNoChain", 11)) {
482 fRB
->fLBCMNoChain
= TRUE
;
483 } else if (opt
== UNICODE_STRING("forward", 7)) {
484 fRB
->fDefaultTree
= &fRB
->fForwardTree
;
485 } else if (opt
== UNICODE_STRING("reverse", 7)) {
486 fRB
->fDefaultTree
= &fRB
->fReverseTree
;
487 } else if (opt
== UNICODE_STRING("safe_forward", 12)) {
488 fRB
->fDefaultTree
= &fRB
->fSafeFwdTree
;
489 } else if (opt
== UNICODE_STRING("safe_reverse", 12)) {
490 fRB
->fDefaultTree
= &fRB
->fSafeRevTree
;
491 } else if (opt
== UNICODE_STRING("lookAheadHardBreak", 18)) {
492 fRB
->fLookAheadHardBreak
= TRUE
;
494 error(U_BRK_UNRECOGNIZED_OPTION
);
503 case doStartVariableName
:
504 n
= pushNewNode(RBBINode::varRef
);
505 if (U_FAILURE(*fRB
->fStatus
)) {
508 n
->fFirstPos
= fScanIndex
;
511 case doEndVariableName
:
512 n
= fNodeStack
[fNodeStackPtr
];
513 if (n
==NULL
|| n
->fType
!= RBBINode::varRef
) {
514 error(U_BRK_INTERNAL_ERROR
);
517 n
->fLastPos
= fScanIndex
;
518 fRB
->fRules
.extractBetween(n
->fFirstPos
+1, n
->fLastPos
, n
->fText
);
519 // Look the newly scanned name up in the symbol table
520 // If there's an entry, set the l. child of the var ref to the replacement expression.
521 // (We also pass through here when scanning assignments, but no harm is done, other
522 // than a slight wasted effort that seems hard to avoid. Lookup will be null)
523 n
->fLeftChild
= fSymbolTable
->lookupNode(n
->fText
);
527 n
= fNodeStack
[fNodeStackPtr
];
528 if (n
->fLeftChild
== NULL
) {
529 error(U_BRK_UNDEFINED_VARIABLE
);
537 case doRuleErrorAssignExpr
:
538 error(U_BRK_ASSIGN_ERROR
);
546 case doScanUnicodeSet
:
551 error(U_BRK_INTERNAL_ERROR
);
561 //----------------------------------------------------------------------------------------
563 // Error Report a rule parse error.
564 // Only report it if no previous error has been recorded.
566 //----------------------------------------------------------------------------------------
567 void RBBIRuleScanner::error(UErrorCode e
) {
568 if (U_SUCCESS(*fRB
->fStatus
)) {
570 fRB
->fParseError
->line
= fLineNum
;
571 fRB
->fParseError
->offset
= fCharNum
;
572 fRB
->fParseError
->preContext
[0] = 0;
573 fRB
->fParseError
->preContext
[0] = 0;
580 //----------------------------------------------------------------------------------------
582 // fixOpStack The parse stack holds partially assembled chunks of the parse tree.
583 // An entry on the stack may be as small as a single setRef node,
584 // or as large as the parse tree
585 // for an entire expression (this will be the one item left on the stack
586 // when the parsing of an RBBI rule completes.
588 // This function is called when a binary operator is encountered.
589 // It looks back up the stack for operators that are not yet associated
590 // with a right operand, and if the precedence of the stacked operator >=
591 // the precedence of the current operator, binds the operand left,
592 // to the previously encountered operator.
594 //----------------------------------------------------------------------------------------
595 void RBBIRuleScanner::fixOpStack(RBBINode::OpPrecedence p
) {
597 // printNodeStack("entering fixOpStack()");
599 n
= fNodeStack
[fNodeStackPtr
-1]; // an operator node
600 if (n
->fPrecedence
== 0) {
601 RBBIDebugPuts("RBBIRuleScanner::fixOpStack, bad operator node");
602 error(U_BRK_INTERNAL_ERROR
);
606 if (n
->fPrecedence
< p
|| n
->fPrecedence
<= RBBINode::precLParen
) {
607 // The most recent operand goes with the current operator,
608 // not with the previously stacked one.
611 // Stack operator is a binary op ( '|' or concatenation)
612 // TOS operand becomes right child of this operator.
613 // Resulting subexpression becomes the TOS operand.
614 n
->fRightChild
= fNodeStack
[fNodeStackPtr
];
615 fNodeStack
[fNodeStackPtr
]->fParent
= n
;
617 // printNodeStack("looping in fixOpStack() ");
620 if (p
<= RBBINode::precLParen
) {
621 // Scan is at a right paren or end of expression.
622 // The scanned item must match the stack, or else there was an error.
623 // Discard the left paren (or start expr) node from the stack,
624 // leaving the completed (sub)expression as TOS.
625 if (n
->fPrecedence
!= p
) {
626 // Right paren encountered matched start of expression node, or
627 // end of expression matched with a left paren node.
628 error(U_BRK_MISMATCHED_PAREN
);
630 fNodeStack
[fNodeStackPtr
-1] = fNodeStack
[fNodeStackPtr
];
632 // Delete the now-discarded LParen or Start node.
635 // printNodeStack("leaving fixOpStack()");
641 //----------------------------------------------------------------------------------------
643 // findSetFor given a UnicodeString,
644 // - find the corresponding Unicode Set (uset node)
645 // (create one if necessary)
646 // - Set fLeftChild of the caller's node (should be a setRef node)
648 // Maintain a hash table of uset nodes, so the same one is always used
649 // for the same string.
650 // If a "to adopt" set is provided and we haven't seen this key before,
651 // add the provided set to the hash table.
652 // If the string is one (32 bit) char in length, the set contains
653 // just one element which is the char in question.
654 // If the string is "any", return a set containing all chars.
656 //----------------------------------------------------------------------------------------
657 void RBBIRuleScanner::findSetFor(const UnicodeString
&s
, RBBINode
*node
, UnicodeSet
*setToAdopt
) {
661 // First check whether we've already cached a set for this string.
662 // If so, just use the cached set in the new node.
663 // delete any set provided by the caller, since we own it.
664 el
= (RBBISetTableEl
*)uhash_get(fSetTable
, &s
);
667 node
->fLeftChild
= el
->val
;
668 U_ASSERT(node
->fLeftChild
->fType
== RBBINode::uset
);
672 // Haven't seen this set before.
673 // If the caller didn't provide us with a prebuilt set,
674 // create a new UnicodeSet now.
675 if (setToAdopt
== NULL
) {
676 if (s
.compare(kAny
, -1) == 0) {
677 setToAdopt
= new UnicodeSet(0x000000, 0x10ffff);
681 setToAdopt
= new UnicodeSet(c
, c
);
686 // Make a new uset node to refer to this UnicodeSet
687 // This new uset node becomes the child of the caller's setReference node.
689 RBBINode
*usetNode
= new RBBINode(RBBINode::uset
);
690 usetNode
->fInputSet
= setToAdopt
;
691 usetNode
->fParent
= node
;
692 node
->fLeftChild
= usetNode
;
697 // Add the new uset node to the list of all uset nodes.
699 fRB
->fUSetNodes
->addElement(usetNode
, *fRB
->fStatus
);
703 // Add the new set to the set hash table.
705 el
= (RBBISetTableEl
*)uprv_malloc(sizeof(RBBISetTableEl
));
706 UnicodeString
*tkey
= new UnicodeString(s
);
707 if (tkey
== NULL
|| el
== NULL
|| setToAdopt
== NULL
) {
708 error(U_MEMORY_ALLOCATION_ERROR
);
713 uhash_put(fSetTable
, el
->key
, el
, fRB
->fStatus
);
721 // Assorted Unicode character constants.
722 // Numeric because there is no portable way to enter them as literals.
725 static const UChar chCR
= 0x0d; // New lines, for terminating comments.
726 static const UChar chLF
= 0x0a;
727 static const UChar chNEL
= 0x85; // NEL newline variant
728 static const UChar chLS
= 0x2028; // Unicode Line Separator
729 static const UChar chApos
= 0x27; // single quote, for quoted chars.
730 static const UChar chPound
= 0x23; // '#', introduces a comment.
731 static const UChar chBackSlash
= 0x5c; // '\' introduces a char escape
732 static const UChar chLParen
= 0x28;
733 static const UChar chRParen
= 0x29;
736 //----------------------------------------------------------------------------------------
738 // stripRules Return a rules string without unnecessary
741 //----------------------------------------------------------------------------------------
742 UnicodeString
RBBIRuleScanner::stripRules(const UnicodeString
&rules
) {
743 UnicodeString strippedRules
;
744 int rulesLength
= rules
.length();
745 for (int idx
= 0; idx
< rulesLength
; ) {
746 UChar ch
= rules
[idx
++];
748 while (idx
< rulesLength
749 && ch
!= chCR
&& ch
!= chLF
&& ch
!= chNEL
)
754 if (!u_isISOControl(ch
)) {
755 strippedRules
.append(ch
);
758 // strippedRules = strippedRules.unescape();
759 return strippedRules
;
763 //----------------------------------------------------------------------------------------
765 // nextCharLL Low Level Next Char from rule input source.
766 // Get a char from the input character iterator,
767 // keep track of input position for error reporting.
769 //----------------------------------------------------------------------------------------
770 UChar32
RBBIRuleScanner::nextCharLL() {
773 if (fNextIndex
>= fRB
->fRules
.length()) {
776 ch
= fRB
->fRules
.char32At(fNextIndex
);
777 fNextIndex
= fRB
->fRules
.moveIndex32(fNextIndex
, 1);
782 ch
== chLF
&& fLastChar
!= chCR
) {
783 // Character is starting a new line. Bump up the line number, and
784 // reset the column to 0.
788 error(U_BRK_NEW_LINE_IN_QUOTED_STRING
);
793 // Character is not starting a new line. Except in the case of a
794 // LF following a CR, increment the column position.
804 //---------------------------------------------------------------------------------
806 // nextChar for rules scanning. At this level, we handle stripping
807 // out comments and processing backslash character escapes.
808 // The rest of the rules grammar is handled at the next level up.
810 //---------------------------------------------------------------------------------
811 void RBBIRuleScanner::nextChar(RBBIRuleChar
&c
) {
813 // Unicode Character constants needed for the processing done by nextChar(),
814 // in hex because literals wont work on EBCDIC machines.
816 fScanIndex
= fNextIndex
;
817 c
.fChar
= nextCharLL();
821 // check for '' sequence.
822 // These are recognized in all contexts, whether in quoted text or not.
824 if (c
.fChar
== chApos
) {
825 if (fRB
->fRules
.char32At(fNextIndex
) == chApos
) {
826 c
.fChar
= nextCharLL(); // get nextChar officially so character counts
827 c
.fEscaped
= TRUE
; // stay correct.
831 // Single quote, by itself.
832 // Toggle quoting mode.
833 // Return either '(' or ')', because quotes cause a grouping of the quoted text.
834 fQuoteMode
= !fQuoteMode
;
835 if (fQuoteMode
== TRUE
) {
840 c
.fEscaped
= FALSE
; // The paren that we return is not escaped.
850 // We are not in a 'quoted region' of the source.
852 if (c
.fChar
== chPound
) {
853 // Start of a comment. Consume the rest of it.
854 // The new-line char that terminates the comment is always returned.
855 // It will be treated as white-space, and serves to break up anything
856 // that might otherwise incorrectly clump together with a comment in
857 // the middle (a variable name, for example.)
859 c
.fChar
= nextCharLL();
860 if (c
.fChar
== (UChar32
)-1 || // EOF
864 c
.fChar
== chLS
) {break;}
867 if (c
.fChar
== (UChar32
)-1) {
872 // check for backslash escaped characters.
873 // Use UnicodeString::unescapeAt() to handle them.
875 if (c
.fChar
== chBackSlash
) {
877 int32_t startX
= fNextIndex
;
878 c
.fChar
= fRB
->fRules
.unescapeAt(fNextIndex
);
879 if (fNextIndex
== startX
) {
880 error(U_BRK_HEX_DIGITS_EXPECTED
);
882 fCharNum
+= fNextIndex
-startX
;
885 // putc(c.fChar, stdout);
888 //---------------------------------------------------------------------------------
890 // Parse RBBI rules. The state machine for rules parsing is here.
891 // The state tables are hand-written in the file rbbirpt.txt,
892 // and converted to the form used here by a perl
895 //---------------------------------------------------------------------------------
896 void RBBIRuleScanner::parse() {
898 const RBBIRuleTableEl
*tableEl
;
900 if (U_FAILURE(*fRB
->fStatus
)) {
907 // Main loop for the rule parsing state machine.
908 // Runs once per state transition.
909 // Each time through optionally performs, depending on the state table,
910 // - an advance to the the next input char
911 // - an action to be performed.
912 // - pushing or popping a state to/from the local state return stack.
915 // Bail out if anything has gone wrong.
916 // RBBI rule file parsing stops on the first error encountered.
917 if (U_FAILURE(*fRB
->fStatus
)) {
921 // Quit if state == 0. This is the normal way to exit the state machine.
927 // Find the state table element that matches the input char from the rule, or the
928 // class of the input character. Start with the first table row for this
929 // state, then linearly scan forward until we find a row that matches the
930 // character. The last row for each state always matches all characters, so
931 // the search will stop there, if not before.
933 tableEl
= &gRuleParseStateTable
[state
];
935 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "scan")) {
936 RBBIDebugPrintf("char, line, col = (\'%c\', %d, %d) state=%s ",
937 fC
.fChar
, fLineNum
, fCharNum
, RBBIRuleStateNames
[state
]);
942 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "scan")) { RBBIDebugPrintf(".");}
943 if (tableEl
->fCharClass
< 127 && fC
.fEscaped
== FALSE
&& tableEl
->fCharClass
== fC
.fChar
) {
944 // Table row specified an individual character, not a set, and
945 // the input character is not escaped, and
946 // the input character matched it.
949 if (tableEl
->fCharClass
== 255) {
950 // Table row specified default, match anything character class.
953 if (tableEl
->fCharClass
== 254 && fC
.fEscaped
) {
954 // Table row specified "escaped" and the char was escaped.
957 if (tableEl
->fCharClass
== 253 && fC
.fEscaped
&&
958 (fC
.fChar
== 0x50 || fC
.fChar
== 0x70 )) {
959 // Table row specified "escaped P" and the char is either 'p' or 'P'.
962 if (tableEl
->fCharClass
== 252 && fC
.fChar
== (UChar32
)-1) {
963 // Table row specified eof and we hit eof on the input.
967 if (tableEl
->fCharClass
>= 128 && tableEl
->fCharClass
< 240 && // Table specs a char class &&
968 fC
.fEscaped
== FALSE
&& // char is not escaped &&
969 fC
.fChar
!= (UChar32
)-1) { // char is not EOF
970 UnicodeSet
*uniset
= fRuleSets
[tableEl
->fCharClass
-128];
971 if (uniset
->contains(fC
.fChar
)) {
972 // Table row specified a character class, or set of characters,
973 // and the current char matches it.
978 // No match on this row, advance to the next row for this state,
981 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "scan")) { RBBIDebugPrintf("\n");}
984 // We've found the row of the state table that matches the current input
985 // character from the rules string.
986 // Perform any action specified by this row in the state table.
987 if (doParseActions((EParseAction
)tableEl
->fAction
) == FALSE
) {
988 // Break out of the state machine loop if the
989 // the action signalled some kind of error, or
990 // the action was to exit, occurs on normal end-of-rules-input.
994 if (tableEl
->fPushState
!= 0) {
996 if (fStackPtr
>= kStackSize
) {
997 error(U_BRK_INTERNAL_ERROR
);
998 RBBIDebugPuts("RBBIRuleScanner::parse() - state stack overflow.");
1001 fStack
[fStackPtr
] = tableEl
->fPushState
;
1004 if (tableEl
->fNextChar
) {
1008 // Get the next state from the table entry, or from the
1009 // state stack if the next state was specified as "pop".
1010 if (tableEl
->fNextState
!= 255) {
1011 state
= tableEl
->fNextState
;
1013 state
= fStack
[fStackPtr
];
1015 if (fStackPtr
< 0) {
1016 error(U_BRK_INTERNAL_ERROR
);
1017 RBBIDebugPuts("RBBIRuleScanner::parse() - state stack underflow.");
1025 // If there were NO user specified reverse rules, set up the equivalent of ".*;"
1027 if (fRB
->fReverseTree
== NULL
) {
1028 fRB
->fReverseTree
= pushNewNode(RBBINode::opStar
);
1029 RBBINode
*operand
= pushNewNode(RBBINode::setRef
);
1030 findSetFor(kAny
, operand
);
1031 fRB
->fReverseTree
->fLeftChild
= operand
;
1032 operand
->fParent
= fRB
->fReverseTree
;
1038 // Parsing of the input RBBI rules is complete.
1039 // We now have a parse tree for the rule expressions
1040 // and a list of all UnicodeSets that are referenced.
1043 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "symbols")) {fSymbolTable
->rbbiSymtablePrint();}
1044 if (fRB
->fDebugEnv
&& uprv_strstr(fRB
->fDebugEnv
, "ptree"))
1046 RBBIDebugPrintf("Completed Forward Rules Parse Tree...\n");
1047 fRB
->fForwardTree
->printTree(TRUE
);
1048 RBBIDebugPrintf("\nCompleted Reverse Rules Parse Tree...\n");
1049 fRB
->fReverseTree
->printTree(TRUE
);
1050 RBBIDebugPrintf("\nCompleted Safe Point Forward Rules Parse Tree...\n");
1051 fRB
->fSafeFwdTree
->printTree(TRUE
);
1052 RBBIDebugPrintf("\nCompleted Safe Point Reverse Rules Parse Tree...\n");
1053 fRB
->fSafeRevTree
->printTree(TRUE
);
1059 //---------------------------------------------------------------------------------
1061 // printNodeStack for debugging...
1063 //---------------------------------------------------------------------------------
1065 void RBBIRuleScanner::printNodeStack(const char *) {}
1067 void RBBIRuleScanner::printNodeStack(const char *title
) {
1069 RBBIDebugPrintf("%s. Dumping node stack...\n", title
);
1070 for (i
=fNodeStackPtr
; i
>0; i
--) {fNodeStack
[i
]->printTree(TRUE
);}
1077 //---------------------------------------------------------------------------------
1079 // pushNewNode create a new RBBINode of the specified type and push it
1080 // onto the stack of nodes.
1082 //---------------------------------------------------------------------------------
1083 RBBINode
*RBBIRuleScanner::pushNewNode(RBBINode::NodeType t
) {
1085 if (fNodeStackPtr
>= kStackSize
) {
1086 error(U_BRK_INTERNAL_ERROR
);
1087 RBBIDebugPuts("RBBIRuleScanner::pushNewNode - stack overflow.");
1088 *fRB
->fStatus
= U_BRK_INTERNAL_ERROR
;
1091 fNodeStack
[fNodeStackPtr
] = new RBBINode(t
);
1092 if (fNodeStack
[fNodeStackPtr
] == NULL
) {
1093 *fRB
->fStatus
= U_MEMORY_ALLOCATION_ERROR
;
1095 return fNodeStack
[fNodeStackPtr
];
1100 //---------------------------------------------------------------------------------
1102 // scanSet Construct a UnicodeSet from the text at the current scan
1103 // position. Advance the scan position to the first character
1106 // A new RBBI setref node referring to the set is pushed onto the node
1109 // The scan position is normally under the control of the state machine
1110 // that controls rule parsing. UnicodeSets, however, are parsed by
1111 // the UnicodeSet constructor, not by the RBBI rule parser.
1113 //---------------------------------------------------------------------------------
1114 void RBBIRuleScanner::scanSet() {
1120 if (U_FAILURE(*fRB
->fStatus
)) {
1124 pos
.setIndex(fScanIndex
);
1125 startPos
= fScanIndex
;
1126 UErrorCode localStatus
= U_ZERO_ERROR
;
1127 uset
= new UnicodeSet(fRB
->fRules
, pos
, USET_IGNORE_SPACE
,
1130 if (U_FAILURE(localStatus
)) {
1131 // TODO: Get more accurate position of the error from UnicodeSet's return info.
1132 // UnicodeSet appears to not be reporting correctly at this time.
1133 RBBIDebugPrintf("UnicodeSet parse postion.ErrorIndex = %d\n", pos
.getIndex());
1139 // Verify that the set contains at least one code point.
1141 if (uset
->charAt(0) == -1) {
1142 // This set is empty.
1143 // Make it an error, because it almost certainly is not what the user wanted.
1144 // Also, avoids having to think about corner cases in the tree manipulation code
1145 // that occurs later on.
1146 error(U_BRK_RULE_EMPTY_SET
);
1152 // Advance the RBBI parse postion over the UnicodeSet pattern.
1153 // Don't just set fScanIndex because the line/char positions maintained
1154 // for error reporting would be thrown off.
1157 if (fNextIndex
>= i
) {
1163 if (U_SUCCESS(*fRB
->fStatus
)) {
1166 n
= pushNewNode(RBBINode::setRef
);
1167 n
->fFirstPos
= startPos
;
1168 n
->fLastPos
= fNextIndex
;
1169 fRB
->fRules
.extractBetween(n
->fFirstPos
, n
->fLastPos
, n
->fText
);
1170 // findSetFor() serves several purposes here:
1171 // - Adopts storage for the UnicodeSet, will be responsible for deleting.
1172 // - Mantains collection of all sets in use, needed later for establishing
1173 // character categories for run time engine.
1174 // - Eliminates mulitiple instances of the same set.
1175 // - Creates a new uset node if necessary (if this isn't a duplicate.)
1176 findSetFor(n
->fText
, n
, uset
);
1183 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */