]> git.saurik.com Git - apple/icu.git/blob - icuSources/common/rbbiscan.cpp
ICU-6.2.22.tar.gz
[apple/icu.git] / icuSources / common / rbbiscan.cpp
1
2 //
3 // file: rbbiscan.cpp
4 //
5 // Copyright (C) 2002-2004, International Business Machines Corporation and others.
6 // All Rights Reserved.
7 //
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.
11 //
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.
14 //
15
16 #include "unicode/utypes.h"
17
18 #if !UCONFIG_NO_BREAK_ITERATION
19
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"
26 #include "uprops.h"
27 #include "cmemory.h"
28 #include "cstring.h"
29
30 #include "rbbirpt.h" // Contains state table for the rbbi rules parser.
31 // generated by a Perl script.
32 #include "rbbirb.h"
33 #include "rbbinode.h"
34 #include "rbbiscan.h"
35 #include "rbbitblb.h"
36
37 #include "uassert.h"
38
39
40 //----------------------------------------------------------------------------------------
41 //
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.)
45 //
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.
48 //
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};
57
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};
61
62 static const UChar gRuleSet_digit_char_pattern[] = {
63 // [ 0 - 9 ]
64 0x5b, 0x30, 0x2d, 0x39, 0x5d, 0};
65
66 static const UChar gRuleSet_name_start_char_pattern[] = {
67 // [ _ \ p { L } ]
68 0x5b, 0x5f, 0x5c, 0x70, 0x7b, 0x4c, 0x7d, 0x5d, 0 };
69
70 static const UChar kAny[] = {0x61, 0x6e, 0x79, 0x00}; // "any"
71
72
73 U_CDECL_BEGIN
74 static void U_EXPORT2 U_CALLCONV RBBISetTable_deleter(void *p) {
75 RBBISetTableEl *px = (RBBISetTableEl *)p;
76 delete px->key;
77 // Note: px->val is owned by the linked list "fSetsListHead" in scanner.
78 // Don't delete the value nodes here.
79 uprv_free(px);
80 }
81 U_CDECL_END
82
83 U_NAMESPACE_BEGIN
84
85 //----------------------------------------------------------------------------------------
86 //
87 // Constructor.
88 //
89 //----------------------------------------------------------------------------------------
90 RBBIRuleScanner::RBBIRuleScanner(RBBIRuleBuilder *rb)
91 {
92 fRB = rb;
93 fStackPtr = 0;
94 fStack[fStackPtr] = 0;
95 fNodeStackPtr = 0;
96 fRuleNum = 0;
97 fNodeStack[0] = NULL;
98
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;
104 fSymbolTable = NULL;
105 fSetTable = NULL;
106
107 fScanIndex = 0;
108 fNextIndex = 0;
109
110 fReverseRule = FALSE;
111 fLookAheadRule = FALSE;
112
113 fLineNum = 1;
114 fCharNum = 0;
115 fQuoteMode = FALSE;
116
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)) {
120 return;
121 }
122
123 //
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;
139 }
140 if (U_FAILURE(*rb->fStatus)) {
141 return;
142 }
143
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);
147 }
148
149
150
151 //----------------------------------------------------------------------------------------
152 //
153 // Destructor
154 //
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];
162
163 delete fSymbolTable;
164 if (fSetTable != NULL) {
165 uhash_close(fSetTable);
166 fSetTable = NULL;
167
168 }
169
170
171 // Node Stack.
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];
176 fNodeStackPtr--;
177 }
178
179 }
180
181 //----------------------------------------------------------------------------------------
182 //
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.
187 //
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.
193 //
194 //----------------------------------------------------------------------------------------
195 UBool RBBIRuleScanner::doParseActions(EParseAction action)
196 {
197 RBBINode *n = NULL;
198
199 UBool returnVal = TRUE;
200
201 switch ((RBBI_RuleParseAction)action) {
202
203 case doExprStart:
204 pushNewNode(RBBINode::opStart);
205 fRuleNum++;
206 break;
207
208
209 case doExprOrOperator:
210 {
211 fixOpStack(RBBINode::precOpCat);
212 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
213 RBBINode *orNode = pushNewNode(RBBINode::opOr);
214 orNode->fLeftChild = operandNode;
215 operandNode->fParent = orNode;
216 }
217 break;
218
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.
224 {
225 fixOpStack(RBBINode::precOpCat);
226 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
227 RBBINode *catNode = pushNewNode(RBBINode::opCat);
228 catNode->fLeftChild = operandNode;
229 operandNode->fParent = catNode;
230 }
231 break;
232
233 case doLParen:
234 // Open Paren.
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);
240 break;
241
242 case doExprRParen:
243 fixOpStack(RBBINode::precLParen);
244 break;
245
246 case doNOP:
247 break;
248
249 case doStartAssign:
250 // We've just scanned "$variable = "
251 // The top of the node stack has the $variable ref node.
252
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
256 // text as a string.
257 n = fNodeStack[fNodeStackPtr-1];
258 n->fFirstPos = fNextIndex; // move past the '='
259
260 // Push a new start-of-expression node; needed to keep parse of the
261 // RHS expression happy.
262 pushNewNode(RBBINode::opStart);
263 break;
264
265
266
267
268 case doEndAssign:
269 {
270 // We have reached the end of an assignement statement.
271 // Current scan char is the ';' that terminates the assignment.
272
273 // Terminate expression, leaves expression parse tree rooted in TOS node.
274 fixOpStack(RBBINode::precStart);
275
276 RBBINode *startExprNode = fNodeStack[fNodeStackPtr-2];
277 RBBINode *varRefNode = fNodeStack[fNodeStackPtr-1];
278 RBBINode *RHSExprNode = fNodeStack[fNodeStackPtr];
279
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);
285
286 // Expression parse tree becomes l. child of the $variable reference node.
287 varRefNode->fLeftChild = RHSExprNode;
288 RHSExprNode->fParent = varRefNode;
289
290 // Make a symbol table entry for the $variableRef node.
291 fSymbolTable->addEntry(varRefNode->fText, varRefNode, *fRB->fStatus);
292
293 // Clean up the stack.
294 delete startExprNode;
295 fNodeStackPtr-=3;
296 break;
297 }
298
299 case doEndOfRule:
300 {
301 fixOpStack(RBBINode::precStart); // Terminate expression, leaves expression
302 if (U_FAILURE(*fRB->fStatus)) { // parse tree rooted in TOS node.
303 break;
304 }
305 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "rtree")) {printNodeStack("end of rule");}
306 U_ASSERT(fNodeStackPtr == 1);
307
308 // If this rule includes a look-ahead '/', add a endMark node to the
309 // expression tree.
310 if (fLookAheadRule) {
311 RBBINode *thisRule = fNodeStack[fNodeStackPtr];
312 RBBINode *endNode = pushNewNode(RBBINode::endMark);
313 RBBINode *catNode = pushNewNode(RBBINode::opCat);
314 fNodeStackPtr -= 2;
315 catNode->fLeftChild = thisRule;
316 catNode->fRightChild = endNode;
317 fNodeStack[fNodeStackPtr] = catNode;
318 endNode->fVal = fRuleNum;
319 endNode->fLookAheadEnd = TRUE;
320 }
321
322 // All rule expressions are ORed together.
323 // The ';' that terminates an expression really just functions as a '|' with
324 // a low operator prededence.
325 //
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.
329 //
330 RBBINode **destRules = (fReverseRule? &fRB->fReverseTree : fRB->fDefaultTree);
331
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
337 //
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;
345 *destRules = orNode;
346 }
347 else
348 {
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];
352 }
353 fReverseRule = FALSE; // in preparation for the next rule.
354 fLookAheadRule = FALSE;
355 fNodeStackPtr = 0;
356 }
357 break;
358
359
360 case doRuleError:
361 error(U_BRK_RULE_SYNTAX);
362 returnVal = FALSE;
363 break;
364
365
366 case doVariableNameExpectedErr:
367 error(U_BRK_RULE_SYNTAX);
368 break;
369
370
371 //
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.
377 case doUnaryOpPlus:
378 {
379 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
380 RBBINode *plusNode = pushNewNode(RBBINode::opPlus);
381 plusNode->fLeftChild = operandNode;
382 operandNode->fParent = plusNode;
383 }
384 break;
385
386 case doUnaryOpQuestion:
387 {
388 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
389 RBBINode *qNode = pushNewNode(RBBINode::opQuestion);
390 qNode->fLeftChild = operandNode;
391 operandNode->fParent = qNode;
392 }
393 break;
394
395 case doUnaryOpStar:
396 {
397 RBBINode *operandNode = fNodeStack[fNodeStackPtr--];
398 RBBINode *starNode = pushNewNode(RBBINode::opStar);
399 starNode->fLeftChild = operandNode;
400 operandNode->fParent = starNode;
401 }
402 break;
403
404 case doRuleChar:
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.
410 {
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);
416 break;
417 }
418
419 case doDotAny:
420 // scanned a ".", meaning match any single character.
421 {
422 n = pushNewNode(RBBINode::setRef);
423 findSetFor(kAny, n);
424 n->fFirstPos = fScanIndex;
425 n->fLastPos = fNextIndex;
426 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
427 break;
428 }
429 break;
430
431 case doSlash:
432 // Scanned a '/', which identifies a look-ahead break position in a rule.
433 n = pushNewNode(RBBINode::lookAhead);
434 n->fVal = fRuleNum;
435 n->fFirstPos = fScanIndex;
436 n->fLastPos = fNextIndex;
437 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
438 fLookAheadRule = TRUE;
439 break;
440
441
442 case doStartTagValue:
443 // Scanned a '{', the opening delimiter for a tag value within a rule.
444 n = pushNewNode(RBBINode::tag);
445 n->fVal = 0;
446 n->fFirstPos = fScanIndex;
447 n->fLastPos = fNextIndex;
448 break;
449
450 case doTagDigit:
451 // Just scanned a decimal digit that's part of a tag value
452 {
453 n = fNodeStack[fNodeStackPtr];
454 uint32_t v = u_charDigitValue(fC.fChar);
455 U_ASSERT(v < 10);
456 n->fVal = n->fVal*10 + v;
457 break;
458 }
459
460 case doTagValue:
461 n = fNodeStack[fNodeStackPtr];
462 n->fLastPos = fNextIndex;
463 fRB->fRules.extractBetween(n->fFirstPos, n->fLastPos, n->fText);
464 break;
465
466 case doTagExpectedError:
467 error(U_BRK_MALFORMED_RULE_TAG);
468 returnVal = FALSE;
469 break;
470
471 case doOptionStart:
472 // Scanning a !!option. At the start of string.
473 fOptionStart = fScanIndex;
474 break;
475
476 case doOptionEnd:
477 {
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;
493 } else {
494 error(U_BRK_UNRECOGNIZED_OPTION);
495 }
496 }
497 break;
498
499 case doReverseDir:
500 fReverseRule = TRUE;
501 break;
502
503 case doStartVariableName:
504 n = pushNewNode(RBBINode::varRef);
505 if (U_FAILURE(*fRB->fStatus)) {
506 break;
507 }
508 n->fFirstPos = fScanIndex;
509 break;
510
511 case doEndVariableName:
512 n = fNodeStack[fNodeStackPtr];
513 if (n==NULL || n->fType != RBBINode::varRef) {
514 error(U_BRK_INTERNAL_ERROR);
515 break;
516 }
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);
524 break;
525
526 case doCheckVarDef:
527 n = fNodeStack[fNodeStackPtr];
528 if (n->fLeftChild == NULL) {
529 error(U_BRK_UNDEFINED_VARIABLE);
530 returnVal = FALSE;
531 }
532 break;
533
534 case doExprFinished:
535 break;
536
537 case doRuleErrorAssignExpr:
538 error(U_BRK_ASSIGN_ERROR);
539 returnVal = FALSE;
540 break;
541
542 case doExit:
543 returnVal = FALSE;
544 break;
545
546 case doScanUnicodeSet:
547 scanSet();
548 break;
549
550 default:
551 error(U_BRK_INTERNAL_ERROR);
552 returnVal = FALSE;
553 break;
554 }
555 return returnVal;
556 }
557
558
559
560
561 //----------------------------------------------------------------------------------------
562 //
563 // Error Report a rule parse error.
564 // Only report it if no previous error has been recorded.
565 //
566 //----------------------------------------------------------------------------------------
567 void RBBIRuleScanner::error(UErrorCode e) {
568 if (U_SUCCESS(*fRB->fStatus)) {
569 *fRB->fStatus = e;
570 fRB->fParseError->line = fLineNum;
571 fRB->fParseError->offset = fCharNum;
572 fRB->fParseError->preContext[0] = 0;
573 fRB->fParseError->preContext[0] = 0;
574 }
575 }
576
577
578
579
580 //----------------------------------------------------------------------------------------
581 //
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.
587 //
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.
593 //
594 //----------------------------------------------------------------------------------------
595 void RBBIRuleScanner::fixOpStack(RBBINode::OpPrecedence p) {
596 RBBINode *n;
597 // printNodeStack("entering fixOpStack()");
598 for (;;) {
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);
603 return;
604 }
605
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.
609 break;
610 }
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;
616 fNodeStackPtr--;
617 // printNodeStack("looping in fixOpStack() ");
618 }
619
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);
629 }
630 fNodeStack[fNodeStackPtr-1] = fNodeStack[fNodeStackPtr];
631 fNodeStackPtr--;
632 // Delete the now-discarded LParen or Start node.
633 delete n;
634 }
635 // printNodeStack("leaving fixOpStack()");
636 }
637
638
639
640
641 //----------------------------------------------------------------------------------------
642 //
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)
647 // to the uset 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.
655 //
656 //----------------------------------------------------------------------------------------
657 void RBBIRuleScanner::findSetFor(const UnicodeString &s, RBBINode *node, UnicodeSet *setToAdopt) {
658
659 RBBISetTableEl *el;
660
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);
665 if (el != NULL) {
666 delete setToAdopt;
667 node->fLeftChild = el->val;
668 U_ASSERT(node->fLeftChild->fType == RBBINode::uset);
669 return;
670 }
671
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);
678 } else {
679 UChar32 c;
680 c = s.char32At(0);
681 setToAdopt = new UnicodeSet(c, c);
682 }
683 }
684
685 //
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.
688 //
689 RBBINode *usetNode = new RBBINode(RBBINode::uset);
690 usetNode->fInputSet = setToAdopt;
691 usetNode->fParent = node;
692 node->fLeftChild = usetNode;
693 usetNode->fText = s;
694
695
696 //
697 // Add the new uset node to the list of all uset nodes.
698 //
699 fRB->fUSetNodes->addElement(usetNode, *fRB->fStatus);
700
701
702 //
703 // Add the new set to the set hash table.
704 //
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);
709 return;
710 }
711 el->key = tkey;
712 el->val = usetNode;
713 uhash_put(fSetTable, el->key, el, fRB->fStatus);
714
715 return;
716 }
717
718
719
720 //
721 // Assorted Unicode character constants.
722 // Numeric because there is no portable way to enter them as literals.
723 // (Think EBCDIC).
724 //
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;
734
735
736 //----------------------------------------------------------------------------------------
737 //
738 // stripRules Return a rules string without unnecessary
739 // characters.
740 //
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++];
747 if (ch == chPound) {
748 while (idx < rulesLength
749 && ch != chCR && ch != chLF && ch != chNEL)
750 {
751 ch = rules[idx++];
752 }
753 }
754 if (!u_isISOControl(ch)) {
755 strippedRules.append(ch);
756 }
757 }
758 // strippedRules = strippedRules.unescape();
759 return strippedRules;
760 }
761
762
763 //----------------------------------------------------------------------------------------
764 //
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.
768 //
769 //----------------------------------------------------------------------------------------
770 UChar32 RBBIRuleScanner::nextCharLL() {
771 UChar32 ch;
772
773 if (fNextIndex >= fRB->fRules.length()) {
774 return (UChar32)-1;
775 }
776 ch = fRB->fRules.char32At(fNextIndex);
777 fNextIndex = fRB->fRules.moveIndex32(fNextIndex, 1);
778
779 if (ch == chCR ||
780 ch == chNEL ||
781 ch == chLS ||
782 ch == chLF && fLastChar != chCR) {
783 // Character is starting a new line. Bump up the line number, and
784 // reset the column to 0.
785 fLineNum++;
786 fCharNum=0;
787 if (fQuoteMode) {
788 error(U_BRK_NEW_LINE_IN_QUOTED_STRING);
789 fQuoteMode = FALSE;
790 }
791 }
792 else {
793 // Character is not starting a new line. Except in the case of a
794 // LF following a CR, increment the column position.
795 if (ch != chLF) {
796 fCharNum++;
797 }
798 }
799 fLastChar = ch;
800 return ch;
801 }
802
803
804 //---------------------------------------------------------------------------------
805 //
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.
809 //
810 //---------------------------------------------------------------------------------
811 void RBBIRuleScanner::nextChar(RBBIRuleChar &c) {
812
813 // Unicode Character constants needed for the processing done by nextChar(),
814 // in hex because literals wont work on EBCDIC machines.
815
816 fScanIndex = fNextIndex;
817 c.fChar = nextCharLL();
818 c.fEscaped = FALSE;
819
820 //
821 // check for '' sequence.
822 // These are recognized in all contexts, whether in quoted text or not.
823 //
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.
828 }
829 else
830 {
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) {
836 c.fChar = chLParen;
837 } else {
838 c.fChar = chRParen;
839 }
840 c.fEscaped = FALSE; // The paren that we return is not escaped.
841 return;
842 }
843 }
844
845 if (fQuoteMode) {
846 c.fEscaped = TRUE;
847 }
848 else
849 {
850 // We are not in a 'quoted region' of the source.
851 //
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.)
858 for (;;) {
859 c.fChar = nextCharLL();
860 if (c.fChar == (UChar32)-1 || // EOF
861 c.fChar == chCR ||
862 c.fChar == chLF ||
863 c.fChar == chNEL ||
864 c.fChar == chLS) {break;}
865 }
866 }
867 if (c.fChar == (UChar32)-1) {
868 return;
869 }
870
871 //
872 // check for backslash escaped characters.
873 // Use UnicodeString::unescapeAt() to handle them.
874 //
875 if (c.fChar == chBackSlash) {
876 c.fEscaped = TRUE;
877 int32_t startX = fNextIndex;
878 c.fChar = fRB->fRules.unescapeAt(fNextIndex);
879 if (fNextIndex == startX) {
880 error(U_BRK_HEX_DIGITS_EXPECTED);
881 }
882 fCharNum += fNextIndex-startX;
883 }
884 }
885 // putc(c.fChar, stdout);
886 }
887
888 //---------------------------------------------------------------------------------
889 //
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
893 // script rbbicst.pl
894 //
895 //---------------------------------------------------------------------------------
896 void RBBIRuleScanner::parse() {
897 uint16_t state;
898 const RBBIRuleTableEl *tableEl;
899
900 if (U_FAILURE(*fRB->fStatus)) {
901 return;
902 }
903
904 state = 1;
905 nextChar(fC);
906 //
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.
913 //
914 for (;;) {
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)) {
918 break;
919 }
920
921 // Quit if state == 0. This is the normal way to exit the state machine.
922 //
923 if (state == 0) {
924 break;
925 }
926
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.
932 //
933 tableEl = &gRuleParseStateTable[state];
934 #ifdef RBBI_DEBUG
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]);
938 }
939 #endif
940
941 for (;;) {
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.
947 break;
948 }
949 if (tableEl->fCharClass == 255) {
950 // Table row specified default, match anything character class.
951 break;
952 }
953 if (tableEl->fCharClass == 254 && fC.fEscaped) {
954 // Table row specified "escaped" and the char was escaped.
955 break;
956 }
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'.
960 break;
961 }
962 if (tableEl->fCharClass == 252 && fC.fChar == (UChar32)-1) {
963 // Table row specified eof and we hit eof on the input.
964 break;
965 }
966
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.
974 break;
975 }
976 }
977
978 // No match on this row, advance to the next row for this state,
979 tableEl++;
980 }
981 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "scan")) { RBBIDebugPrintf("\n");}
982
983 //
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.
991 break;
992 }
993
994 if (tableEl->fPushState != 0) {
995 fStackPtr++;
996 if (fStackPtr >= kStackSize) {
997 error(U_BRK_INTERNAL_ERROR);
998 RBBIDebugPuts("RBBIRuleScanner::parse() - state stack overflow.");
999 fStackPtr--;
1000 }
1001 fStack[fStackPtr] = tableEl->fPushState;
1002 }
1003
1004 if (tableEl->fNextChar) {
1005 nextChar(fC);
1006 }
1007
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;
1012 } else {
1013 state = fStack[fStackPtr];
1014 fStackPtr--;
1015 if (fStackPtr < 0) {
1016 error(U_BRK_INTERNAL_ERROR);
1017 RBBIDebugPuts("RBBIRuleScanner::parse() - state stack underflow.");
1018 fStackPtr++;
1019 }
1020 }
1021
1022 }
1023
1024 //
1025 // If there were NO user specified reverse rules, set up the equivalent of ".*;"
1026 //
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;
1033 fNodeStackPtr -= 2;
1034 }
1035
1036
1037 //
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.
1041 //
1042 #ifdef RBBI_DEBUG
1043 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "symbols")) {fSymbolTable->rbbiSymtablePrint();}
1044 if (fRB->fDebugEnv && uprv_strstr(fRB->fDebugEnv, "ptree"))
1045 {
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);
1054 }
1055 #endif
1056 }
1057
1058
1059 //---------------------------------------------------------------------------------
1060 //
1061 // printNodeStack for debugging...
1062 //
1063 //---------------------------------------------------------------------------------
1064 #ifdef RBBI_DEBUG
1065 void RBBIRuleScanner::printNodeStack(const char *) {}
1066 #else
1067 void RBBIRuleScanner::printNodeStack(const char *title) {
1068 int i;
1069 RBBIDebugPrintf("%s. Dumping node stack...\n", title);
1070 for (i=fNodeStackPtr; i>0; i--) {fNodeStack[i]->printTree(TRUE);}
1071 }
1072 #endif
1073
1074
1075
1076
1077 //---------------------------------------------------------------------------------
1078 //
1079 // pushNewNode create a new RBBINode of the specified type and push it
1080 // onto the stack of nodes.
1081 //
1082 //---------------------------------------------------------------------------------
1083 RBBINode *RBBIRuleScanner::pushNewNode(RBBINode::NodeType t) {
1084 fNodeStackPtr++;
1085 if (fNodeStackPtr >= kStackSize) {
1086 error(U_BRK_INTERNAL_ERROR);
1087 RBBIDebugPuts("RBBIRuleScanner::pushNewNode - stack overflow.");
1088 *fRB->fStatus = U_BRK_INTERNAL_ERROR;
1089 return NULL;
1090 }
1091 fNodeStack[fNodeStackPtr] = new RBBINode(t);
1092 if (fNodeStack[fNodeStackPtr] == NULL) {
1093 *fRB->fStatus = U_MEMORY_ALLOCATION_ERROR;
1094 }
1095 return fNodeStack[fNodeStackPtr];
1096 }
1097
1098
1099
1100 //---------------------------------------------------------------------------------
1101 //
1102 // scanSet Construct a UnicodeSet from the text at the current scan
1103 // position. Advance the scan position to the first character
1104 // after the set.
1105 //
1106 // A new RBBI setref node referring to the set is pushed onto the node
1107 // stack.
1108 //
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.
1112 //
1113 //---------------------------------------------------------------------------------
1114 void RBBIRuleScanner::scanSet() {
1115 UnicodeSet *uset;
1116 ParsePosition pos;
1117 int startPos;
1118 int i;
1119
1120 if (U_FAILURE(*fRB->fStatus)) {
1121 return;
1122 }
1123
1124 pos.setIndex(fScanIndex);
1125 startPos = fScanIndex;
1126 UErrorCode localStatus = U_ZERO_ERROR;
1127 uset = new UnicodeSet(fRB->fRules, pos, USET_IGNORE_SPACE,
1128 fSymbolTable,
1129 localStatus);
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());
1134 error(localStatus);
1135 delete uset;
1136 return;
1137 }
1138
1139 // Verify that the set contains at least one code point.
1140 //
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);
1147 delete uset;
1148 return;
1149 }
1150
1151
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.
1155 i = pos.getIndex();
1156 for (;;) {
1157 if (fNextIndex >= i) {
1158 break;
1159 }
1160 nextCharLL();
1161 }
1162
1163 if (U_SUCCESS(*fRB->fStatus)) {
1164 RBBINode *n;
1165
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);
1177 }
1178
1179 }
1180
1181 U_NAMESPACE_END
1182
1183 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */