]> git.saurik.com Git - apple/icu.git/blob - icuSources/common/rbbiscan57.cpp
ICU-66108.tar.gz
[apple/icu.git] / icuSources / common / rbbiscan57.cpp
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 //
4 // Copyright (C) 2002-2016, International Business Machines Corporation and others.
5 // All Rights Reserved.
6 //
7 // This file contains the Rule Based Break Iterator Rule Builder functions for
8 // scanning the rules and assembling a parse tree. This is the first phase
9 // of compiling the rules.
10 //
11 // The overall of the rules is managed by class RBBIRuleBuilder, which will
12 // create and use an instance of this class as part of the process.
13 //
14
15 #include "unicode/utypes.h"
16
17 #if !UCONFIG_NO_BREAK_ITERATION
18
19 #include "unicode/unistr.h"
20 #include "unicode/uniset.h"
21 #include "unicode/uchar.h"
22 #include "unicode/uchriter.h"
23 #include "unicode/parsepos.h"
24 #include "unicode/parseerr.h"
25 #include "cmemory.h"
26 #include "cstring.h"
27
28 #include "rbbirpt.h" // Contains state table for the rbbi rules parser.
29 // generated by a Perl script.
30 #include "rbbirb57.h"
31 #include "rbbinode.h"
32 #include "rbbiscan57.h"
33 #include "rbbitblb57.h"
34
35 #include "uassert.h"
36
37 //------------------------------------------------------------------------------
38 //
39 // Unicode Set init strings for each of the character classes needed for parsing a rule file.
40 // (Initialized with hex values for portability to EBCDIC based machines.
41 // Really ugly, but there's no good way to avoid it.)
42 //
43 // The sets are referred to by name in the rbbirpt.txt, which is the
44 // source form of the state transition table for the RBBI rule parser.
45 //
46 //------------------------------------------------------------------------------
47 static const UChar gRuleSet_rule_char_pattern[] = {
48 // [ ^ [ \ p { Z } \ u 0 0 2 0
49 0x5b, 0x5e, 0x5b, 0x5c, 0x70, 0x7b, 0x5a, 0x7d, 0x5c, 0x75, 0x30, 0x30, 0x32, 0x30,
50 // - \ u 0 0 7 f ] - [ \ p
51 0x2d, 0x5c, 0x75, 0x30, 0x30, 0x37, 0x66, 0x5d, 0x2d, 0x5b, 0x5c, 0x70,
52 // { L } ] - [ \ p { N } ] ]
53 0x7b, 0x4c, 0x7d, 0x5d, 0x2d, 0x5b, 0x5c, 0x70, 0x7b, 0x4e, 0x7d, 0x5d, 0x5d, 0};
54
55 static const UChar gRuleSet_name_char_pattern[] = {
56 // [ _ \ p { L } \ p { N } ]
57 0x5b, 0x5f, 0x5c, 0x70, 0x7b, 0x4c, 0x7d, 0x5c, 0x70, 0x7b, 0x4e, 0x7d, 0x5d, 0};
58
59 static const UChar gRuleSet_digit_char_pattern[] = {
60 // [ 0 - 9 ]
61 0x5b, 0x30, 0x2d, 0x39, 0x5d, 0};
62
63 static const UChar gRuleSet_name_start_char_pattern[] = {
64 // [ _ \ p { L } ]
65 0x5b, 0x5f, 0x5c, 0x70, 0x7b, 0x4c, 0x7d, 0x5d, 0 };
66
67 static const UChar kAny[] = {0x61, 0x6e, 0x79, 0x00}; // "any"
68
69
70 U_CDECL_BEGIN
71 static void U_CALLCONV RBBISetTable_deleter(void *p) {
72 icu::RBBISetTableEl *px = (icu::RBBISetTableEl *)p;
73 delete px->key;
74 // Note: px->val is owned by the linked list "fSetsListHead" in scanner.
75 // Don't delete the value nodes here.
76 uprv_free(px);
77 }
78 U_CDECL_END
79
80 U_NAMESPACE_BEGIN
81
82 //------------------------------------------------------------------------------
83 //
84 // Constructor.
85 //
86 //------------------------------------------------------------------------------
87 RBBIRuleScanner57::RBBIRuleScanner57(RBBIRuleBuilder57 *rb)
88 {
89 fRB = rb;
90 fScanIndex = 0;
91 fNextIndex = 0;
92 fQuoteMode = FALSE;
93 fLineNum = 1;
94 fCharNum = 0;
95 fLastChar = 0;
96
97 fStateTable = NULL;
98 fStack[0] = 0;
99 fStackPtr = 0;
100 fNodeStack[0] = NULL;
101 fNodeStackPtr = 0;
102
103 fReverseRule = FALSE;
104 fLookAheadRule = FALSE;
105 fNoChainInRule = FALSE;
106
107 fSymbolTable = NULL;
108 fSetTable = NULL;
109 fRuleNum = 0;
110 fOptionStart = 0;
111
112 // Do not check status until after all critical fields are sufficiently initialized
113 // that the destructor can run cleanly.
114 if (U_FAILURE(*rb->fStatus)) {
115 return;
116 }
117
118 //
119 // Set up the constant Unicode Sets.
120 // Note: These could be made static, lazily initialized, and shared among
121 // all instances of RBBIRuleScanners. BUT this is quite a bit simpler,
122 // and the time to build these few sets should be small compared to a
123 // full break iterator build.
124 fRuleSets[kRuleSet_rule_char-128]
125 = UnicodeSet(UnicodeString(gRuleSet_rule_char_pattern), *rb->fStatus);
126 // fRuleSets[kRuleSet_white_space-128] = [:Pattern_White_Space:]
127 fRuleSets[kRuleSet_white_space-128].
128 add(9, 0xd).add(0x20).add(0x85).add(0x200e, 0x200f).add(0x2028, 0x2029);
129 fRuleSets[kRuleSet_name_char-128]
130 = UnicodeSet(UnicodeString(gRuleSet_name_char_pattern), *rb->fStatus);
131 fRuleSets[kRuleSet_name_start_char-128]
132 = UnicodeSet(UnicodeString(gRuleSet_name_start_char_pattern), *rb->fStatus);
133 fRuleSets[kRuleSet_digit_char-128]
134 = UnicodeSet(UnicodeString(gRuleSet_digit_char_pattern), *rb->fStatus);
135 if (*rb->fStatus == U_ILLEGAL_ARGUMENT_ERROR) {
136 // This case happens if ICU's data is missing. UnicodeSet tries to look up property
137 // names from the init string, can't find them, and claims an illegal argument.
138 // Change the error so that the actual problem will be clearer to users.
139 *rb->fStatus = U_BRK_INIT_ERROR;
140 }
141 if (U_FAILURE(*rb->fStatus)) {
142 return;
143 }
144
145 fSymbolTable = new RBBISymbolTable57(this, rb->fRules, *rb->fStatus);
146 if (fSymbolTable == NULL) {
147 *rb->fStatus = U_MEMORY_ALLOCATION_ERROR;
148 return;
149 }
150 fSetTable = uhash_open(uhash_hashUnicodeString, uhash_compareUnicodeString, NULL, rb->fStatus);
151 if (U_FAILURE(*rb->fStatus)) {
152 return;
153 }
154 uhash_setValueDeleter(fSetTable, RBBISetTable_deleter);
155 }
156
157
158
159 //------------------------------------------------------------------------------
160 //
161 // Destructor
162 //
163 //------------------------------------------------------------------------------
164 RBBIRuleScanner57::~RBBIRuleScanner57() {
165 delete fSymbolTable;
166 if (fSetTable != NULL) {
167 uhash_close(fSetTable);
168 fSetTable = NULL;
169
170 }
171
172
173 // Node Stack.
174 // Normally has one entry, which is the entire parse tree for the rules.
175 // If errors occured, there may be additional subtrees left on the stack.
176 while (fNodeStackPtr > 0) {
177 delete fNodeStack[fNodeStackPtr];
178 fNodeStackPtr--;
179 }
180
181 }
182
183 //------------------------------------------------------------------------------
184 //
185 // doParseAction Do some action during rule parsing.
186 // Called by the parse state machine.
187 // Actions build the parse tree and Unicode Sets,
188 // and maintain the parse stack for nested expressions.
189 //
190 // TODO: unify EParseAction and RBBI_RuleParseAction enum types.
191 // They represent exactly the same thing. They're separate
192 // only to work around enum forward declaration restrictions
193 // in some compilers, while at the same time avoiding multiple
194 // definitions problems. I'm sure that there's a better way.
195 //
196 //------------------------------------------------------------------------------
197 UBool RBBIRuleScanner57::doParseActions(int32_t action)
198 {
199 RBBINode *n = NULL;
200
201 UBool returnVal = TRUE;
202
203 switch (action) {
204
205 case doExprStart:
206 pushNewNode(RBBINode::opStart);
207 fRuleNum++;
208 break;
209
210
211 case doNoChain:
212 // Scanned a '^' while on the rule start state.
213 fNoChainInRule = TRUE;
214 break;
215
216
217 case doExprOrOperator:
218 {
219 fixOpStack(RBBINode::precOpCat);
220 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
221 RBBINode *orNode = pushNewNode(RBBINode::opOr);
222 if (U_FAILURE(*fRB->fStatus)) {
223 break;
224 }
225 orNode->fLeftChild = operandNode;
226 operandNode->fParent = orNode;
227 }
228 break;
229
230 case doExprCatOperator:
231 // concatenation operator.
232 // For the implicit concatenation of adjacent terms in an expression that are
233 // not separated by any other operator. Action is invoked between the
234 // actions for the two terms.
235 {
236 fixOpStack(RBBINode::precOpCat);
237 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
238 RBBINode *catNode = pushNewNode(RBBINode::opCat);
239 if (U_FAILURE(*fRB->fStatus)) {
240 break;
241 }
242 catNode->fLeftChild = operandNode;
243 operandNode->fParent = catNode;
244 }
245 break;
246
247 case doLParen:
248 // Open Paren.
249 // The openParen node is a dummy operation type with a low precedence,
250 // which has the affect of ensuring that any real binary op that
251 // follows within the parens binds more tightly to the operands than
252 // stuff outside of the parens.
253 pushNewNode(RBBINode::opLParen);
254 break;
255
256 case doExprRParen:
257 fixOpStack(RBBINode::precLParen);
258 break;
259
260 case doNOP:
261 break;
262
263 case doStartAssign:
264 // We've just scanned "$variable = "
265 // The top of the node stack has the $variable ref node.
266
267 // Save the start position of the RHS text in the StartExpression node
268 // that precedes the $variableReference node on the stack.
269 // This will eventually be used when saving the full $variable replacement
270 // text as a string.
271 n = fNodeStack[fNodeStackPtr-1];
272 n->fFirstPos = fNextIndex; // move past the '='
273
274 // Push a new start-of-expression node; needed to keep parse of the
275 // RHS expression happy.
276 pushNewNode(RBBINode::opStart);
277 break;
278
279
280
281
282 case doEndAssign:
283 {
284 // We have reached the end of an assignement statement.
285 // Current scan char is the ';' that terminates the assignment.
286
287 // Terminate expression, leaves expression parse tree rooted in TOS node.
288 fixOpStack(RBBINode::precStart);
289
290 RBBINode *startExprNode = fNodeStack[fNodeStackPtr-2];
291 RBBINode *varRefNode = fNodeStack[fNodeStackPtr-1];
292 RBBINode *RHSExprNode = fNodeStack[fNodeStackPtr];
293
294 // Save original text of right side of assignment, excluding the terminating ';'
295 // in the root of the node for the right-hand-side expression.
296 RHSExprNode->fFirstPos = startExprNode->fFirstPos;
297 RHSExprNode->fLastPos = fScanIndex;
298 fRB->fRules.extractBetween(RHSExprNode->fFirstPos, RHSExprNode->fLastPos, RHSExprNode->fText);
299
300 // Expression parse tree becomes l. child of the $variable reference node.
301 varRefNode->fLeftChild = RHSExprNode;
302 RHSExprNode->fParent = varRefNode;
303
304 // Make a symbol table entry for the $variableRef node.
305 fSymbolTable->addEntry(varRefNode->fText, varRefNode, *fRB->fStatus);
306 if (U_FAILURE(*fRB->fStatus)) {
307 // This is a round-about way to get the parse position set
308 // so that duplicate symbols error messages include a line number.
309 UErrorCode t = *fRB->fStatus;
310 *fRB->fStatus = U_ZERO_ERROR;
311 error(t);
312 }
313
314 // Clean up the stack.
315 delete startExprNode;
316 fNodeStackPtr-=3;
317 break;
318 }
319
320 case doEndOfRule:
321 {
322 fixOpStack(RBBINode::precStart); // Terminate expression, leaves expression
323 if (U_FAILURE(*fRB->fStatus)) { // parse tree rooted in TOS node.
324 break;
325 }
326 #ifdef RBBI_DEBUG
327 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "rtree")) {printNodeStack("end of rule");}
328 #endif
329 U_ASSERT(fNodeStackPtr == 1);
330 RBBINode *thisRule = fNodeStack[fNodeStackPtr];
331
332 // If this rule includes a look-ahead '/', add a endMark node to the
333 // expression tree.
334 if (fLookAheadRule) {
335 RBBINode *endNode = pushNewNode(RBBINode::endMark);
336 RBBINode *catNode = pushNewNode(RBBINode::opCat);
337 if (U_FAILURE(*fRB->fStatus)) {
338 break;
339 }
340 fNodeStackPtr -= 2;
341 catNode->fLeftChild = thisRule;
342 catNode->fRightChild = endNode;
343 fNodeStack[fNodeStackPtr] = catNode;
344 endNode->fVal = fRuleNum;
345 endNode->fLookAheadEnd = TRUE;
346 thisRule = catNode;
347
348 // TODO: Disable chaining out of look-ahead (hard break) rules.
349 // The break on rule match is forced, so there is no point in building up
350 // the state table to chain into another rule for a longer match.
351 }
352
353 // Mark this node as being the root of a rule.
354 thisRule->fRuleRoot = TRUE;
355
356 // Flag if chaining into this rule is wanted.
357 //
358 if (fRB->fChainRules && // If rule chaining is enabled globally via !!chain
359 !fNoChainInRule) { // and no '^' chain-in inhibit was on this rule
360 thisRule->fChainIn = TRUE;
361 }
362
363
364 // All rule expressions are ORed together.
365 // The ';' that terminates an expression really just functions as a '|' with
366 // a low operator prededence.
367 //
368 // Each of the four sets of rules are collected separately.
369 // (forward, reverse, safe_forward, safe_reverse)
370 // OR this rule into the appropriate group of them.
371 //
372 RBBINode **destRules = (fReverseRule? &fRB->fReverseTree : fRB->fDefaultTree);
373
374 if (*destRules != NULL) {
375 // This is not the first rule encounted.
376 // OR previous stuff (from *destRules)
377 // with the current rule expression (on the Node Stack)
378 // with the resulting OR expression going to *destRules
379 //
380 RBBINode *thisRule = fNodeStack[fNodeStackPtr];
381 RBBINode *prevRules = *destRules;
382 RBBINode *orNode = pushNewNode(RBBINode::opOr);
383 if (U_FAILURE(*fRB->fStatus)) {
384 break;
385 }
386 orNode->fLeftChild = prevRules;
387 prevRules->fParent = orNode;
388 orNode->fRightChild = thisRule;
389 thisRule->fParent = orNode;
390 *destRules = orNode;
391 }
392 else
393 {
394 // This is the first rule encountered (for this direction).
395 // Just move its parse tree from the stack to *destRules.
396 *destRules = fNodeStack[fNodeStackPtr];
397 }
398 fReverseRule = FALSE; // in preparation for the next rule.
399 fLookAheadRule = FALSE;
400 fNoChainInRule = FALSE;
401 fNodeStackPtr = 0;
402 }
403 break;
404
405
406 case doRuleError:
407 error(U_BRK_RULE_SYNTAX);
408 returnVal = FALSE;
409 break;
410
411
412 case doVariableNameExpectedErr:
413 error(U_BRK_RULE_SYNTAX);
414 break;
415
416
417 //
418 // Unary operands + ? *
419 // These all appear after the operand to which they apply.
420 // When we hit one, the operand (may be a whole sub expression)
421 // will be on the top of the stack.
422 // Unary Operator becomes TOS, with the old TOS as its one child.
423 case doUnaryOpPlus:
424 {
425 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
426 RBBINode *plusNode = pushNewNode(RBBINode::opPlus);
427 if (U_FAILURE(*fRB->fStatus)) {
428 break;
429 }
430 plusNode->fLeftChild = operandNode;
431 operandNode->fParent = plusNode;
432 }
433 break;
434
435 case doUnaryOpQuestion:
436 {
437 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
438 RBBINode *qNode = pushNewNode(RBBINode::opQuestion);
439 if (U_FAILURE(*fRB->fStatus)) {
440 break;
441 }
442 qNode->fLeftChild = operandNode;
443 operandNode->fParent = qNode;
444 }
445 break;
446
447 case doUnaryOpStar:
448 {
449 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
450 RBBINode *starNode = pushNewNode(RBBINode::opStar);
451 if (U_FAILURE(*fRB->fStatus)) {
452 break;
453 }
454 starNode->fLeftChild = operandNode;
455 operandNode->fParent = starNode;
456 }
457 break;
458
459 case doRuleChar:
460 // A "Rule Character" is any single character that is a literal part
461 // of the regular expression. Like a, b and c in the expression "(abc*) | [:L:]"
462 // These are pretty uncommon in break rules; the terms are more commonly
463 // sets. To keep things uniform, treat these characters like as
464 // sets that just happen to contain only one character.
465 {
466 n = pushNewNode(RBBINode::setRef);
467 if (U_FAILURE(*fRB->fStatus)) {
468 break;
469 }
470 findSetFor(UnicodeString(fC.fChar), n);
471 n->fFirstPos = fScanIndex;
472 n->fLastPos = fNextIndex;
473 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
474 break;
475 }
476
477 case doDotAny:
478 // scanned a ".", meaning match any single character.
479 {
480 n = pushNewNode(RBBINode::setRef);
481 if (U_FAILURE(*fRB->fStatus)) {
482 break;
483 }
484 findSetFor(UnicodeString(TRUE, kAny, 3), n);
485 n->fFirstPos = fScanIndex;
486 n->fLastPos = fNextIndex;
487 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
488 break;
489 }
490
491 case doSlash:
492 // Scanned a '/', which identifies a look-ahead break position in a rule.
493 n = pushNewNode(RBBINode::lookAhead);
494 if (U_FAILURE(*fRB->fStatus)) {
495 break;
496 }
497 n->fVal = fRuleNum;
498 n->fFirstPos = fScanIndex;
499 n->fLastPos = fNextIndex;
500 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
501 fLookAheadRule = TRUE;
502 break;
503
504
505 case doStartTagValue:
506 // Scanned a '{', the opening delimiter for a tag value within a rule.
507 n = pushNewNode(RBBINode::tag);
508 if (U_FAILURE(*fRB->fStatus)) {
509 break;
510 }
511 n->fVal = 0;
512 n->fFirstPos = fScanIndex;
513 n->fLastPos = fNextIndex;
514 break;
515
516 case doTagDigit:
517 // Just scanned a decimal digit that's part of a tag value
518 {
519 n = fNodeStack[fNodeStackPtr];
520 uint32_t v = u_charDigitValue(fC.fChar);
521 U_ASSERT(v < 10);
522 n->fVal = n->fVal*10 + v;
523 break;
524 }
525
526 case doTagValue:
527 n = fNodeStack[fNodeStackPtr];
528 n->fLastPos = fNextIndex;
529 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
530 break;
531
532 case doTagExpectedError:
533 error(U_BRK_MALFORMED_RULE_TAG);
534 returnVal = FALSE;
535 break;
536
537 case doOptionStart:
538 // Scanning a !!option. At the start of string.
539 fOptionStart = fScanIndex;
540 break;
541
542 case doOptionEnd:
543 {
544 UnicodeString opt(fRB->fRules, fOptionStart, fScanIndex-fOptionStart);
545 if (opt == UNICODE_STRING("chain", 5)) {
546 fRB->fChainRules = TRUE;
547 } else if (opt == UNICODE_STRING("LBCMNoChain", 11)) {
548 fRB->fLBCMNoChain = TRUE;
549 } else if (opt == UNICODE_STRING("RINoChain", 9)) {
550 fRB->fRINoChain = TRUE;
551 } else if (opt == UNICODE_STRING("forward", 7)) {
552 fRB->fDefaultTree = &fRB->fForwardTree;
553 } else if (opt == UNICODE_STRING("reverse", 7)) {
554 fRB->fDefaultTree = &fRB->fReverseTree;
555 } else if (opt == UNICODE_STRING("safe_forward", 12)) {
556 fRB->fDefaultTree = &fRB->fSafeFwdTree;
557 } else if (opt == UNICODE_STRING("safe_reverse", 12)) {
558 fRB->fDefaultTree = &fRB->fSafeRevTree;
559 } else if (opt == UNICODE_STRING("lookAheadHardBreak", 18)) {
560 fRB->fLookAheadHardBreak = TRUE;
561 } else {
562 error(U_BRK_UNRECOGNIZED_OPTION);
563 }
564 }
565 break;
566
567 case doReverseDir:
568 fReverseRule = TRUE;
569 break;
570
571 case doStartVariableName:
572 n = pushNewNode(RBBINode::varRef);
573 if (U_FAILURE(*fRB->fStatus)) {
574 break;
575 }
576 n->fFirstPos = fScanIndex;
577 break;
578
579 case doEndVariableName:
580 n = fNodeStack[fNodeStackPtr];
581 if (n==NULL || n->fType != RBBINode::varRef) {
582 error(U_BRK_INTERNAL_ERROR);
583 break;
584 }
585 n->fLastPos = fScanIndex;
586 fRB->fRules.extractBetween(n->fFirstPos+1, n->fLastPos, n->fText);
587 // Look the newly scanned name up in the symbol table
588 // If there's an entry, set the l. child of the var ref to the replacement expression.
589 // (We also pass through here when scanning assignments, but no harm is done, other
590 // than a slight wasted effort that seems hard to avoid. Lookup will be null)
591 n->fLeftChild = fSymbolTable->lookupNode(n->fText);
592 break;
593
594 case doCheckVarDef:
595 n = fNodeStack[fNodeStackPtr];
596 if (n->fLeftChild == NULL) {
597 error(U_BRK_UNDEFINED_VARIABLE);
598 returnVal = FALSE;
599 }
600 break;
601
602 case doExprFinished:
603 break;
604
605 case doRuleErrorAssignExpr:
606 error(U_BRK_ASSIGN_ERROR);
607 returnVal = FALSE;
608 break;
609
610 case doExit:
611 returnVal = FALSE;
612 break;
613
614 case doScanUnicodeSet:
615 scanSet();
616 break;
617
618 default:
619 error(U_BRK_INTERNAL_ERROR);
620 returnVal = FALSE;
621 break;
622 }
623 return returnVal && U_SUCCESS(*fRB->fStatus);
624 }
625
626
627
628
629 //------------------------------------------------------------------------------
630 //
631 // Error Report a rule parse error.
632 // Only report it if no previous error has been recorded.
633 //
634 //------------------------------------------------------------------------------
635 void RBBIRuleScanner57::error(UErrorCode e) {
636 if (U_SUCCESS(*fRB->fStatus)) {
637 *fRB->fStatus = e;
638 if (fRB->fParseError) {
639 fRB->fParseError->line = fLineNum;
640 fRB->fParseError->offset = fCharNum;
641 fRB->fParseError->preContext[0] = 0;
642 fRB->fParseError->postContext[0] = 0;
643 }
644 }
645 }
646
647
648
649
650 //------------------------------------------------------------------------------
651 //
652 // fixOpStack The parse stack holds partially assembled chunks of the parse tree.
653 // An entry on the stack may be as small as a single setRef node,
654 // or as large as the parse tree
655 // for an entire expression (this will be the one item left on the stack
656 // when the parsing of an RBBI rule completes.
657 //
658 // This function is called when a binary operator is encountered.
659 // It looks back up the stack for operators that are not yet associated
660 // with a right operand, and if the precedence of the stacked operator >=
661 // the precedence of the current operator, binds the operand left,
662 // to the previously encountered operator.
663 //
664 //------------------------------------------------------------------------------
665 void RBBIRuleScanner57::fixOpStack(RBBINode::OpPrecedence p) {
666 RBBINode *n;
667 // printNodeStack("entering fixOpStack()");
668 for (;;) {
669 n = fNodeStack[fNodeStackPtr-1]; // an operator node
670 if (n->fPrecedence == 0) {
671 RBBIDebugPuts("RBBIRuleScanner57::fixOpStack, bad operator node");
672 error(U_BRK_INTERNAL_ERROR);
673 return;
674 }
675
676 if (n->fPrecedence < p || n->fPrecedence <= RBBINode::precLParen) {
677 // The most recent operand goes with the current operator,
678 // not with the previously stacked one.
679 break;
680 }
681 // Stack operator is a binary op ( '|' or concatenation)
682 // TOS operand becomes right child of this operator.
683 // Resulting subexpression becomes the TOS operand.
684 n->fRightChild = fNodeStack[fNodeStackPtr];
685 fNodeStack[fNodeStackPtr]->fParent = n;
686 fNodeStackPtr--;
687 // printNodeStack("looping in fixOpStack() ");
688 }
689
690 if (p <= RBBINode::precLParen) {
691 // Scan is at a right paren or end of expression.
692 // The scanned item must match the stack, or else there was an error.
693 // Discard the left paren (or start expr) node from the stack,
694 // leaving the completed (sub)expression as TOS.
695 if (n->fPrecedence != p) {
696 // Right paren encountered matched start of expression node, or
697 // end of expression matched with a left paren node.
698 error(U_BRK_MISMATCHED_PAREN);
699 }
700 fNodeStack[fNodeStackPtr-1] = fNodeStack[fNodeStackPtr];
701 fNodeStackPtr--;
702 // Delete the now-discarded LParen or Start node.
703 delete n;
704 }
705 // printNodeStack("leaving fixOpStack()");
706 }
707
708
709
710
711 //------------------------------------------------------------------------------
712 //
713 // findSetFor given a UnicodeString,
714 // - find the corresponding Unicode Set (uset node)
715 // (create one if necessary)
716 // - Set fLeftChild of the caller's node (should be a setRef node)
717 // to the uset node
718 // Maintain a hash table of uset nodes, so the same one is always used
719 // for the same string.
720 // If a "to adopt" set is provided and we haven't seen this key before,
721 // add the provided set to the hash table.
722 // If the string is one (32 bit) char in length, the set contains
723 // just one element which is the char in question.
724 // If the string is "any", return a set containing all chars.
725 //
726 //------------------------------------------------------------------------------
727 void RBBIRuleScanner57::findSetFor(const UnicodeString &s, RBBINode *node, UnicodeSet *setToAdopt) {
728
729 RBBISetTableEl *el;
730
731 // First check whether we've already cached a set for this string.
732 // If so, just use the cached set in the new node.
733 // delete any set provided by the caller, since we own it.
734 el = (RBBISetTableEl *)uhash_get(fSetTable, &s);
735 if (el != NULL) {
736 delete setToAdopt;
737 node->fLeftChild = el->val;
738 U_ASSERT(node->fLeftChild->fType == RBBINode::uset);
739 return;
740 }
741
742 // Haven't seen this set before.
743 // If the caller didn't provide us with a prebuilt set,
744 // create a new UnicodeSet now.
745 if (setToAdopt == NULL) {
746 if (s.compare(kAny, -1) == 0) {
747 setToAdopt = new UnicodeSet(0x000000, 0x10ffff);
748 } else {
749 UChar32 c;
750 c = s.char32At(0);
751 setToAdopt = new UnicodeSet(c, c);
752 }
753 }
754
755 //
756 // Make a new uset node to refer to this UnicodeSet
757 // This new uset node becomes the child of the caller's setReference node.
758 //
759 RBBINode *usetNode = new RBBINode(RBBINode::uset);
760 if (usetNode == NULL) {
761 error(U_MEMORY_ALLOCATION_ERROR);
762 return;
763 }
764 usetNode->fInputSet = setToAdopt;
765 usetNode->fParent = node;
766 node->fLeftChild = usetNode;
767 usetNode->fText = s;
768
769
770 //
771 // Add the new uset node to the list of all uset nodes.
772 //
773 fRB->fUSetNodes->addElement(usetNode, *fRB->fStatus);
774
775
776 //
777 // Add the new set to the set hash table.
778 //
779 el = (RBBISetTableEl *)uprv_malloc(sizeof(RBBISetTableEl));
780 UnicodeString *tkey = new UnicodeString(s);
781 if (tkey == NULL || el == NULL || setToAdopt == NULL) {
782 // Delete to avoid memory leak
783 delete tkey;
784 tkey = NULL;
785 uprv_free(el);
786 el = NULL;
787 delete setToAdopt;
788 setToAdopt = NULL;
789
790 error(U_MEMORY_ALLOCATION_ERROR);
791 return;
792 }
793 el->key = tkey;
794 el->val = usetNode;
795 uhash_put(fSetTable, el->key, el, fRB->fStatus);
796
797 return;
798 }
799
800
801
802 //
803 // Assorted Unicode character constants.
804 // Numeric because there is no portable way to enter them as literals.
805 // (Think EBCDIC).
806 //
807 static const UChar chCR = 0x0d; // New lines, for terminating comments.
808 static const UChar chLF = 0x0a;
809 static const UChar chNEL = 0x85; // NEL newline variant
810 static const UChar chLS = 0x2028; // Unicode Line Separator
811 static const UChar chApos = 0x27; // single quote, for quoted chars.
812 static const UChar chPound = 0x23; // '#', introduces a comment.
813 static const UChar chBackSlash = 0x5c; // '\' introduces a char escape
814 static const UChar chLParen = 0x28;
815 static const UChar chRParen = 0x29;
816
817
818 //------------------------------------------------------------------------------
819 //
820 // stripRules Return a rules string without unnecessary
821 // characters.
822 //
823 //------------------------------------------------------------------------------
824 UnicodeString RBBIRuleScanner57::stripRules(const UnicodeString &rules) {
825 UnicodeString strippedRules;
826 int rulesLength = rules.length();
827 for (int idx = 0; idx < rulesLength; ) {
828 UChar ch = rules[idx++];
829 if (ch == chPound) {
830 while (idx < rulesLength
831 && ch != chCR && ch != chLF && ch != chNEL)
832 {
833 ch = rules[idx++];
834 }
835 }
836 if (!u_isISOControl(ch)) {
837 strippedRules.append(ch);
838 }
839 }
840 // strippedRules = strippedRules.unescape();
841 return strippedRules;
842 }
843
844
845 //------------------------------------------------------------------------------
846 //
847 // nextCharLL Low Level Next Char from rule input source.
848 // Get a char from the input character iterator,
849 // keep track of input position for error reporting.
850 //
851 //------------------------------------------------------------------------------
852 UChar32 RBBIRuleScanner57::nextCharLL() {
853 UChar32 ch;
854
855 if (fNextIndex >= fRB->fRules.length()) {
856 return (UChar32)-1;
857 }
858 ch = fRB->fRules.char32At(fNextIndex);
859 fNextIndex = fRB->fRules.moveIndex32(fNextIndex, 1);
860
861 if (ch == chCR ||
862 ch == chNEL ||
863 ch == chLS ||
864 (ch == chLF && fLastChar != chCR)) {
865 // Character is starting a new line. Bump up the line number, and
866 // reset the column to 0.
867 fLineNum++;
868 fCharNum=0;
869 if (fQuoteMode) {
870 error(U_BRK_NEW_LINE_IN_QUOTED_STRING);
871 fQuoteMode = FALSE;
872 }
873 }
874 else {
875 // Character is not starting a new line. Except in the case of a
876 // LF following a CR, increment the column position.
877 if (ch != chLF) {
878 fCharNum++;
879 }
880 }
881 fLastChar = ch;
882 return ch;
883 }
884
885
886 //------------------------------------------------------------------------------
887 //
888 // nextChar for rules scanning. At this level, we handle stripping
889 // out comments and processing backslash character escapes.
890 // The rest of the rules grammar is handled at the next level up.
891 //
892 //------------------------------------------------------------------------------
893 void RBBIRuleScanner57::nextChar(RBBIRuleChar &c) {
894
895 // Unicode Character constants needed for the processing done by nextChar(),
896 // in hex because literals wont work on EBCDIC machines.
897
898 fScanIndex = fNextIndex;
899 c.fChar = nextCharLL();
900 c.fEscaped = FALSE;
901
902 //
903 // check for '' sequence.
904 // These are recognized in all contexts, whether in quoted text or not.
905 //
906 if (c.fChar == chApos) {
907 if (fRB->fRules.char32At(fNextIndex) == chApos) {
908 c.fChar = nextCharLL(); // get nextChar officially so character counts
909 c.fEscaped = TRUE; // stay correct.
910 }
911 else
912 {
913 // Single quote, by itself.
914 // Toggle quoting mode.
915 // Return either '(' or ')', because quotes cause a grouping of the quoted text.
916 fQuoteMode = !fQuoteMode;
917 if (fQuoteMode == TRUE) {
918 c.fChar = chLParen;
919 } else {
920 c.fChar = chRParen;
921 }
922 c.fEscaped = FALSE; // The paren that we return is not escaped.
923 return;
924 }
925 }
926
927 if (fQuoteMode) {
928 c.fEscaped = TRUE;
929 }
930 else
931 {
932 // We are not in a 'quoted region' of the source.
933 //
934 if (c.fChar == chPound) {
935 // Start of a comment. Consume the rest of it.
936 // The new-line char that terminates the comment is always returned.
937 // It will be treated as white-space, and serves to break up anything
938 // that might otherwise incorrectly clump together with a comment in
939 // the middle (a variable name, for example.)
940 for (;;) {
941 c.fChar = nextCharLL();
942 if (c.fChar == (UChar32)-1 || // EOF
943 c.fChar == chCR ||
944 c.fChar == chLF ||
945 c.fChar == chNEL ||
946 c.fChar == chLS) {break;}
947 }
948 }
949 if (c.fChar == (UChar32)-1) {
950 return;
951 }
952
953 //
954 // check for backslash escaped characters.
955 // Use UnicodeString::unescapeAt() to handle them.
956 //
957 if (c.fChar == chBackSlash) {
958 c.fEscaped = TRUE;
959 int32_t startX = fNextIndex;
960 c.fChar = fRB->fRules.unescapeAt(fNextIndex);
961 if (fNextIndex == startX) {
962 error(U_BRK_HEX_DIGITS_EXPECTED);
963 }
964 fCharNum += fNextIndex-startX;
965 }
966 }
967 // putc(c.fChar, stdout);
968 }
969
970 //------------------------------------------------------------------------------
971 //
972 // Parse RBBI rules. The state machine for rules parsing is here.
973 // The state tables are hand-written in the file rbbirpt.txt,
974 // and converted to the form used here by a perl
975 // script rbbicst.pl
976 //
977 //------------------------------------------------------------------------------
978 void RBBIRuleScanner57::parse() {
979 uint16_t state;
980 const RBBIRuleTableEl *tableEl;
981
982 if (U_FAILURE(*fRB->fStatus)) {
983 return;
984 }
985
986 state = 1;
987 nextChar(fC);
988 //
989 // Main loop for the rule parsing state machine.
990 // Runs once per state transition.
991 // Each time through optionally performs, depending on the state table,
992 // - an advance to the the next input char
993 // - an action to be performed.
994 // - pushing or popping a state to/from the local state return stack.
995 //
996 for (;;) {
997 // Bail out if anything has gone wrong.
998 // RBBI rule file parsing stops on the first error encountered.
999 if (U_FAILURE(*fRB->fStatus)) {
1000 break;
1001 }
1002
1003 // Quit if state == 0. This is the normal way to exit the state machine.
1004 //
1005 if (state == 0) {
1006 break;
1007 }
1008
1009 // Find the state table element that matches the input char from the rule, or the
1010 // class of the input character. Start with the first table row for this
1011 // state, then linearly scan forward until we find a row that matches the
1012 // character. The last row for each state always matches all characters, so
1013 // the search will stop there, if not before.
1014 //
1015 tableEl = &gRuleParseStateTable[state];
1016 #ifdef RBBI_DEBUG
1017 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "scan")) {
1018 RBBIDebugPrintf("char, line, col = (\'%c\', %d, %d) state=%s ",
1019 fC.fChar, fLineNum, fCharNum, RBBIRuleStateNames[state]);
1020 }
1021 #endif
1022
1023 for (;;) {
1024 #ifdef RBBI_DEBUG
1025 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "scan")) { RBBIDebugPrintf("."); fflush(stdout);}
1026 #endif
1027 if (tableEl->fCharClass < 127 && fC.fEscaped == FALSE && tableEl->fCharClass == fC.fChar) {
1028 // Table row specified an individual character, not a set, and
1029 // the input character is not escaped, and
1030 // the input character matched it.
1031 break;
1032 }
1033 if (tableEl->fCharClass == 255) {
1034 // Table row specified default, match anything character class.
1035 break;
1036 }
1037 if (tableEl->fCharClass == 254 && fC.fEscaped) {
1038 // Table row specified "escaped" and the char was escaped.
1039 break;
1040 }
1041 if (tableEl->fCharClass == 253 && fC.fEscaped &&
1042 (fC.fChar == 0x50 || fC.fChar == 0x70 )) {
1043 // Table row specified "escaped P" and the char is either 'p' or 'P'.
1044 break;
1045 }
1046 if (tableEl->fCharClass == 252 && fC.fChar == (UChar32)-1) {
1047 // Table row specified eof and we hit eof on the input.
1048 break;
1049 }
1050
1051 if (tableEl->fCharClass >= 128 && tableEl->fCharClass < 240 && // Table specs a char class &&
1052 fC.fEscaped == FALSE && // char is not escaped &&
1053 fC.fChar != (UChar32)-1) { // char is not EOF
1054 U_ASSERT((tableEl->fCharClass-128) < UPRV_LENGTHOF(fRuleSets));
1055 if (fRuleSets[tableEl->fCharClass-128].contains(fC.fChar)) {
1056 // Table row specified a character class, or set of characters,
1057 // and the current char matches it.
1058 break;
1059 }
1060 }
1061
1062 // No match on this row, advance to the next row for this state,
1063 tableEl++;
1064 }
1065 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "scan")) { RBBIDebugPuts("");}
1066
1067 //
1068 // We've found the row of the state table that matches the current input
1069 // character from the rules string.
1070 // Perform any action specified by this row in the state table.
1071 if (doParseActions((int32_t)tableEl->fAction) == FALSE) {
1072 // Break out of the state machine loop if the
1073 // the action signalled some kind of error, or
1074 // the action was to exit, occurs on normal end-of-rules-input.
1075 break;
1076 }
1077
1078 if (tableEl->fPushState != 0) {
1079 fStackPtr++;
1080 if (fStackPtr >= kStackSize) {
1081 error(U_BRK_INTERNAL_ERROR);
1082 RBBIDebugPuts("RBBIRuleScanner57::parse() - state stack overflow.");
1083 fStackPtr--;
1084 }
1085 fStack[fStackPtr] = tableEl->fPushState;
1086 }
1087
1088 if (tableEl->fNextChar) {
1089 nextChar(fC);
1090 }
1091
1092 // Get the next state from the table entry, or from the
1093 // state stack if the next state was specified as "pop".
1094 if (tableEl->fNextState != 255) {
1095 state = tableEl->fNextState;
1096 } else {
1097 state = fStack[fStackPtr];
1098 fStackPtr--;
1099 if (fStackPtr < 0) {
1100 error(U_BRK_INTERNAL_ERROR);
1101 RBBIDebugPuts("RBBIRuleScanner57::parse() - state stack underflow.");
1102 fStackPtr++;
1103 }
1104 }
1105
1106 }
1107
1108 //
1109 // If there were NO user specified reverse rules, set up the equivalent of ".*;"
1110 //
1111 if (fRB->fReverseTree == NULL) {
1112 fRB->fReverseTree = pushNewNode(RBBINode::opStar);
1113 RBBINode *operand = pushNewNode(RBBINode::setRef);
1114 if (U_FAILURE(*fRB->fStatus)) {
1115 return;
1116 }
1117 findSetFor(UnicodeString(TRUE, kAny, 3), operand);
1118 fRB->fReverseTree->fLeftChild = operand;
1119 operand->fParent = fRB->fReverseTree;
1120 fNodeStackPtr -= 2;
1121 }
1122
1123
1124 //
1125 // Parsing of the input RBBI rules is complete.
1126 // We now have a parse tree for the rule expressions
1127 // and a list of all UnicodeSets that are referenced.
1128 //
1129 #ifdef RBBI_DEBUG
1130 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "symbols")) {fSymbolTable->rbbiSymtablePrint();}
1131 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "ptree"))
1132 {
1133 RBBIDebugPrintf("Completed Forward Rules Parse Tree...\n");
1134 fRB->fForwardTree->printTree(TRUE);
1135 RBBIDebugPrintf("\nCompleted Reverse Rules Parse Tree...\n");
1136 fRB->fReverseTree->printTree(TRUE);
1137 RBBIDebugPrintf("\nCompleted Safe Point Forward Rules Parse Tree...\n");
1138 fRB->fSafeFwdTree->printTree(TRUE);
1139 RBBIDebugPrintf("\nCompleted Safe Point Reverse Rules Parse Tree...\n");
1140 fRB->fSafeRevTree->printTree(TRUE);
1141 }
1142 #endif
1143 }
1144
1145
1146 //------------------------------------------------------------------------------
1147 //
1148 // printNodeStack for debugging...
1149 //
1150 //------------------------------------------------------------------------------
1151 #ifdef RBBI_DEBUG
1152 void RBBIRuleScanner57::printNodeStack(const char *title) {
1153 int i;
1154 RBBIDebugPrintf("%s. Dumping node stack...\n", title);
1155 for (i=fNodeStackPtr; i>0; i--) {fNodeStack[i]->printTree(TRUE);}
1156 }
1157 #endif
1158
1159
1160
1161
1162 //------------------------------------------------------------------------------
1163 //
1164 // pushNewNode create a new RBBINode of the specified type and push it
1165 // onto the stack of nodes.
1166 //
1167 //------------------------------------------------------------------------------
1168 RBBINode *RBBIRuleScanner57::pushNewNode(RBBINode::NodeType t) {
1169 if (U_FAILURE(*fRB->fStatus)) {
1170 return NULL;
1171 }
1172 fNodeStackPtr++;
1173 if (fNodeStackPtr >= kStackSize) {
1174 error(U_BRK_INTERNAL_ERROR);
1175 RBBIDebugPuts("RBBIRuleScanner57::pushNewNode - stack overflow.");
1176 *fRB->fStatus = U_BRK_INTERNAL_ERROR;
1177 return NULL;
1178 }
1179 fNodeStack[fNodeStackPtr] = new RBBINode(t);
1180 if (fNodeStack[fNodeStackPtr] == NULL) {
1181 *fRB->fStatus = U_MEMORY_ALLOCATION_ERROR;
1182 }
1183 return fNodeStack[fNodeStackPtr];
1184 }
1185
1186
1187
1188 //------------------------------------------------------------------------------
1189 //
1190 // scanSet Construct a UnicodeSet from the text at the current scan
1191 // position. Advance the scan position to the first character
1192 // after the set.
1193 //
1194 // A new RBBI setref node referring to the set is pushed onto the node
1195 // stack.
1196 //
1197 // The scan position is normally under the control of the state machine
1198 // that controls rule parsing. UnicodeSets, however, are parsed by
1199 // the UnicodeSet constructor, not by the RBBI rule parser.
1200 //
1201 //------------------------------------------------------------------------------
1202 void RBBIRuleScanner57::scanSet() {
1203 UnicodeSet *uset;
1204 ParsePosition pos;
1205 int startPos;
1206 int i;
1207
1208 if (U_FAILURE(*fRB->fStatus)) {
1209 return;
1210 }
1211
1212 pos.setIndex(fScanIndex);
1213 startPos = fScanIndex;
1214 UErrorCode localStatus = U_ZERO_ERROR;
1215 uset = new UnicodeSet();
1216 if (uset == NULL) {
1217 localStatus = U_MEMORY_ALLOCATION_ERROR;
1218 } else {
1219 uset->applyPatternIgnoreSpace(fRB->fRules, pos, fSymbolTable, localStatus);
1220 }
1221 if (U_FAILURE(localStatus)) {
1222 // TODO: Get more accurate position of the error from UnicodeSet's return info.
1223 // UnicodeSet appears to not be reporting correctly at this time.
1224 #ifdef RBBI_DEBUG
1225 RBBIDebugPrintf("UnicodeSet parse postion.ErrorIndex = %d\n", pos.getIndex());
1226 #endif
1227 error(localStatus);
1228 delete uset;
1229 return;
1230 }
1231
1232 // Verify that the set contains at least one code point.
1233 //
1234 U_ASSERT(uset!=NULL);
1235 if (uset->isEmpty()) {
1236 // This set is empty.
1237 // Make it an error, because it almost certainly is not what the user wanted.
1238 // Also, avoids having to think about corner cases in the tree manipulation code
1239 // that occurs later on.
1240 error(U_BRK_RULE_EMPTY_SET);
1241 delete uset;
1242 return;
1243 }
1244
1245
1246 // Advance the RBBI parse postion over the UnicodeSet pattern.
1247 // Don't just set fScanIndex because the line/char positions maintained
1248 // for error reporting would be thrown off.
1249 i = pos.getIndex();
1250 for (;;) {
1251 if (fNextIndex >= i) {
1252 break;
1253 }
1254 nextCharLL();
1255 }
1256
1257 if (U_SUCCESS(*fRB->fStatus)) {
1258 RBBINode *n;
1259
1260 n = pushNewNode(RBBINode::setRef);
1261 if (U_FAILURE(*fRB->fStatus)) {
1262 return;
1263 }
1264 n->fFirstPos = startPos;
1265 n->fLastPos = fNextIndex;
1266 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
1267 // findSetFor() serves several purposes here:
1268 // - Adopts storage for the UnicodeSet, will be responsible for deleting.
1269 // - Mantains collection of all sets in use, needed later for establishing
1270 // character categories for run time engine.
1271 // - Eliminates mulitiple instances of the same set.
1272 // - Creates a new uset node if necessary (if this isn't a duplicate.)
1273 findSetFor(n->fText, n, uset);
1274 }
1275
1276 }
1277
1278 U_NAMESPACE_END
1279
1280 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */