]> git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/rbt_pars.cpp
ICU-6.2.22.tar.gz
[apple/icu.git] / icuSources / i18n / rbt_pars.cpp
1 /*
2 **********************************************************************
3 * Copyright (C) 1999-2004, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Date Name Description
7 * 11/17/99 aliu Creation.
8 **********************************************************************
9 */
10
11 #include "unicode/utypes.h"
12
13 #if !UCONFIG_NO_TRANSLITERATION
14
15 #include "unicode/uobject.h"
16 #include "unicode/parseerr.h"
17 #include "unicode/parsepos.h"
18 #include "unicode/putil.h"
19 #include "unicode/uchar.h"
20 #include "unicode/ustring.h"
21 #include "unicode/uniset.h"
22 #include "cstring.h"
23 #include "funcrepl.h"
24 #include "hash.h"
25 #include "quant.h"
26 #include "rbt.h"
27 #include "rbt_data.h"
28 #include "rbt_pars.h"
29 #include "rbt_rule.h"
30 #include "strmatch.h"
31 #include "strrepl.h"
32 #include "unicode/symtable.h"
33 #include "tridpars.h"
34 #include "uvector.h"
35 #include "util.h"
36 #include "cmemory.h"
37 #include "uprops.h"
38 #include "putilimp.h"
39
40 // Operators
41 #define VARIABLE_DEF_OP ((UChar)0x003D) /*=*/
42 #define FORWARD_RULE_OP ((UChar)0x003E) /*>*/
43 #define REVERSE_RULE_OP ((UChar)0x003C) /*<*/
44 #define FWDREV_RULE_OP ((UChar)0x007E) /*~*/ // internal rep of <> op
45
46 // Other special characters
47 #define QUOTE ((UChar)0x0027) /*'*/
48 #define ESCAPE ((UChar)0x005C) /*\*/
49 #define END_OF_RULE ((UChar)0x003B) /*;*/
50 #define RULE_COMMENT_CHAR ((UChar)0x0023) /*#*/
51
52 #define SEGMENT_OPEN ((UChar)0x0028) /*(*/
53 #define SEGMENT_CLOSE ((UChar)0x0029) /*)*/
54 #define CONTEXT_ANTE ((UChar)0x007B) /*{*/
55 #define CONTEXT_POST ((UChar)0x007D) /*}*/
56 #define CURSOR_POS ((UChar)0x007C) /*|*/
57 #define CURSOR_OFFSET ((UChar)0x0040) /*@*/
58 #define ANCHOR_START ((UChar)0x005E) /*^*/
59 #define KLEENE_STAR ((UChar)0x002A) /***/
60 #define ONE_OR_MORE ((UChar)0x002B) /*+*/
61 #define ZERO_OR_ONE ((UChar)0x003F) /*?*/
62
63 #define DOT ((UChar)46) /*.*/
64
65 static const UChar DOT_SET[] = { // "[^[:Zp:][:Zl:]\r\n$]";
66 91, 94, 91, 58, 90, 112, 58, 93, 91, 58, 90,
67 108, 58, 93, 92, 114, 92, 110, 36, 93, 0
68 };
69
70 // A function is denoted &Source-Target/Variant(text)
71 #define FUNCTION ((UChar)38) /*&*/
72
73 // Aliases for some of the syntax characters. These are provided so
74 // transliteration rules can be expressed in XML without clashing with
75 // XML syntax characters '<', '>', and '&'.
76 #define ALT_REVERSE_RULE_OP ((UChar)0x2190) // Left Arrow
77 #define ALT_FORWARD_RULE_OP ((UChar)0x2192) // Right Arrow
78 #define ALT_FWDREV_RULE_OP ((UChar)0x2194) // Left Right Arrow
79 #define ALT_FUNCTION ((UChar)0x2206) // Increment (~Greek Capital Delta)
80
81 // Special characters disallowed at the top level
82 static const UChar ILLEGAL_TOP[] = {41,0}; // ")"
83
84 // Special characters disallowed within a segment
85 static const UChar ILLEGAL_SEG[] = {123,125,124,64,0}; // "{}|@"
86
87 // Special characters disallowed within a function argument
88 static const UChar ILLEGAL_FUNC[] = {94,40,46,42,43,63,123,125,124,64,0}; // "^(.*+?{}|@"
89
90 // By definition, the ANCHOR_END special character is a
91 // trailing SymbolTable.SYMBOL_REF character.
92 // private static final char ANCHOR_END = '$';
93
94 static const UChar gOPERATORS[] = { // "=><"
95 VARIABLE_DEF_OP, FORWARD_RULE_OP, REVERSE_RULE_OP,
96 ALT_FORWARD_RULE_OP, ALT_REVERSE_RULE_OP, ALT_FWDREV_RULE_OP,
97 0
98 };
99
100 static const UChar HALF_ENDERS[] = { // "=><;"
101 VARIABLE_DEF_OP, FORWARD_RULE_OP, REVERSE_RULE_OP,
102 ALT_FORWARD_RULE_OP, ALT_REVERSE_RULE_OP, ALT_FWDREV_RULE_OP,
103 END_OF_RULE,
104 0
105 };
106
107 // These are also used in Transliterator::toRules()
108 static const int32_t ID_TOKEN_LEN = 2;
109 static const UChar ID_TOKEN[] = { 0x3A, 0x3A }; // ':', ':'
110
111 U_NAMESPACE_BEGIN
112
113 //----------------------------------------------------------------------
114 // BEGIN ParseData
115 //----------------------------------------------------------------------
116
117 /**
118 * This class implements the SymbolTable interface. It is used
119 * during parsing to give UnicodeSet access to variables that
120 * have been defined so far. Note that it uses variablesVector,
121 * _not_ data.setVariables.
122 */
123 class ParseData : public UMemory, public SymbolTable {
124 public:
125 const TransliterationRuleData* data; // alias
126
127 const UVector* variablesVector; // alias
128
129 ParseData(const TransliterationRuleData* data = 0,
130 const UVector* variablesVector = 0);
131
132 virtual const UnicodeString* lookup(const UnicodeString& s) const;
133
134 virtual const UnicodeFunctor* lookupMatcher(UChar32 ch) const;
135
136 virtual UnicodeString parseReference(const UnicodeString& text,
137 ParsePosition& pos, int32_t limit) const;
138 /**
139 * Return true if the given character is a matcher standin or a plain
140 * character (non standin).
141 */
142 UBool isMatcher(UChar32 ch);
143
144 /**
145 * Return true if the given character is a replacer standin or a plain
146 * character (non standin).
147 */
148 UBool isReplacer(UChar32 ch);
149
150 private:
151 ParseData(const ParseData &other); // forbid copying of this class
152 ParseData &operator=(const ParseData &other); // forbid copying of this class
153 };
154
155 ParseData::ParseData(const TransliterationRuleData* d,
156 const UVector* sets) :
157 data(d), variablesVector(sets) {}
158
159 /**
160 * Implement SymbolTable API.
161 */
162 const UnicodeString* ParseData::lookup(const UnicodeString& name) const {
163 return (const UnicodeString*) data->variableNames->get(name);
164 }
165
166 /**
167 * Implement SymbolTable API.
168 */
169 const UnicodeFunctor* ParseData::lookupMatcher(UChar32 ch) const {
170 // Note that we cannot use data.lookupSet() because the
171 // set array has not been constructed yet.
172 const UnicodeFunctor* set = NULL;
173 int32_t i = ch - data->variablesBase;
174 if (i >= 0 && i < variablesVector->size()) {
175 int32_t i = ch - data->variablesBase;
176 set = (i < variablesVector->size()) ?
177 (UnicodeFunctor*) variablesVector->elementAt(i) : 0;
178 }
179 return set;
180 }
181
182 /**
183 * Implement SymbolTable API. Parse out a symbol reference
184 * name.
185 */
186 UnicodeString ParseData::parseReference(const UnicodeString& text,
187 ParsePosition& pos, int32_t limit) const {
188 int32_t start = pos.getIndex();
189 int32_t i = start;
190 UnicodeString result;
191 while (i < limit) {
192 UChar c = text.charAt(i);
193 if ((i==start && !u_isIDStart(c)) || !u_isIDPart(c)) {
194 break;
195 }
196 ++i;
197 }
198 if (i == start) { // No valid name chars
199 return result; // Indicate failure with empty string
200 }
201 pos.setIndex(i);
202 text.extractBetween(start, i, result);
203 return result;
204 }
205
206 UBool ParseData::isMatcher(UChar32 ch) {
207 // Note that we cannot use data.lookup() because the
208 // set array has not been constructed yet.
209 int32_t i = ch - data->variablesBase;
210 if (i >= 0 && i < variablesVector->size()) {
211 UnicodeFunctor *f = (UnicodeFunctor*) variablesVector->elementAt(i);
212 return f != NULL && f->toMatcher() != NULL;
213 }
214 return TRUE;
215 }
216
217 /**
218 * Return true if the given character is a replacer standin or a plain
219 * character (non standin).
220 */
221 UBool ParseData::isReplacer(UChar32 ch) {
222 // Note that we cannot use data.lookup() because the
223 // set array has not been constructed yet.
224 int i = ch - data->variablesBase;
225 if (i >= 0 && i < variablesVector->size()) {
226 UnicodeFunctor *f = (UnicodeFunctor*) variablesVector->elementAt(i);
227 return f != NULL && f->toReplacer() != NULL;
228 }
229 return TRUE;
230 }
231
232 //----------------------------------------------------------------------
233 // BEGIN RuleHalf
234 //----------------------------------------------------------------------
235
236 /**
237 * A class representing one side of a rule. This class knows how to
238 * parse half of a rule. It is tightly coupled to the method
239 * RuleBasedTransliterator.Parser.parseRule().
240 */
241 class RuleHalf : public UMemory {
242
243 public:
244
245 UnicodeString text;
246
247 int32_t cursor; // position of cursor in text
248 int32_t ante; // position of ante context marker '{' in text
249 int32_t post; // position of post context marker '}' in text
250
251 // Record the offset to the cursor either to the left or to the
252 // right of the key. This is indicated by characters on the output
253 // side that allow the cursor to be positioned arbitrarily within
254 // the matching text. For example, abc{def} > | @@@ xyz; changes
255 // def to xyz and moves the cursor to before abc. Offset characters
256 // must be at the start or end, and they cannot move the cursor past
257 // the ante- or postcontext text. Placeholders are only valid in
258 // output text. The length of the ante and post context is
259 // determined at runtime, because of supplementals and quantifiers.
260 int32_t cursorOffset; // only nonzero on output side
261
262 // Position of first CURSOR_OFFSET on _right_. This will be -1
263 // for |@, -2 for |@@, etc., and 1 for @|, 2 for @@|, etc.
264 int32_t cursorOffsetPos;
265
266 UBool anchorStart;
267 UBool anchorEnd;
268
269 UErrorCode ec;
270
271 /**
272 * The segment number from 1..n of the next '(' we see
273 * during parsing; 1-based.
274 */
275 int32_t nextSegmentNumber;
276
277 TransliteratorParser& parser;
278
279 //--------------------------------------------------
280 // Methods
281
282 RuleHalf(TransliteratorParser& parser);
283 ~RuleHalf();
284
285 int32_t parse(const UnicodeString& rule, int32_t pos, int32_t limit);
286
287 int32_t parseSection(const UnicodeString& rule, int32_t pos, int32_t limit,
288 UnicodeString& buf,
289 const UnicodeString& illegal,
290 UBool isSegment);
291
292 /**
293 * Remove context.
294 */
295 void removeContext();
296
297 /**
298 * Return true if this half looks like valid output, that is, does not
299 * contain quantifiers or other special input-only elements.
300 */
301 UBool isValidOutput(TransliteratorParser& parser);
302
303 /**
304 * Return true if this half looks like valid input, that is, does not
305 * contain functions or other special output-only elements.
306 */
307 UBool isValidInput(TransliteratorParser& parser);
308
309 int syntaxError(UErrorCode code,
310 const UnicodeString& rule,
311 int32_t start) {
312 return parser.syntaxError(code, rule, start);
313 }
314
315 private:
316 // Disallowed methods; no impl.
317 RuleHalf(const RuleHalf&);
318 RuleHalf& operator=(const RuleHalf&);
319 };
320
321 RuleHalf::RuleHalf(TransliteratorParser& p) :
322 ec(U_ZERO_ERROR),
323 parser(p)
324 {
325 cursor = -1;
326 ante = -1;
327 post = -1;
328 cursorOffset = 0;
329 cursorOffsetPos = 0;
330 anchorStart = anchorEnd = FALSE;
331 nextSegmentNumber = 1;
332 }
333
334 RuleHalf::~RuleHalf() {
335 }
336
337 /**
338 * Parse one side of a rule, stopping at either the limit,
339 * the END_OF_RULE character, or an operator.
340 * @return the index after the terminating character, or
341 * if limit was reached, limit
342 */
343 int32_t RuleHalf::parse(const UnicodeString& rule, int32_t pos, int32_t limit) {
344 int32_t start = pos;
345 text.truncate(0);
346 pos = parseSection(rule, pos, limit, text, ILLEGAL_TOP, FALSE);
347
348 if (cursorOffset > 0 && cursor != cursorOffsetPos) {
349 return syntaxError(U_MISPLACED_CURSOR_OFFSET, rule, start);
350 }
351
352 return pos;
353 }
354
355 /**
356 * Parse a section of one side of a rule, stopping at either
357 * the limit, the END_OF_RULE character, an operator, or a
358 * segment close character. This method parses both a
359 * top-level rule half and a segment within such a rule half.
360 * It calls itself recursively to parse segments and nested
361 * segments.
362 * @param buf buffer into which to accumulate the rule pattern
363 * characters, either literal characters from the rule or
364 * standins for UnicodeMatcher objects including segments.
365 * @param illegal the set of special characters that is illegal during
366 * this parse.
367 * @param isSegment if true, then we've already seen a '(' and
368 * pos on entry points right after it. Accumulate everything
369 * up to the closing ')', put it in a segment matcher object,
370 * generate a standin for it, and add the standin to buf. As
371 * a side effect, update the segments vector with a reference
372 * to the segment matcher. This works recursively for nested
373 * segments. If isSegment is false, just accumulate
374 * characters into buf.
375 * @return the index after the terminating character, or
376 * if limit was reached, limit
377 */
378 int32_t RuleHalf::parseSection(const UnicodeString& rule, int32_t pos, int32_t limit,
379 UnicodeString& buf,
380 const UnicodeString& illegal,
381 UBool isSegment) {
382 int32_t start = pos;
383 ParsePosition pp;
384 UnicodeString scratch;
385 UBool done = FALSE;
386 int32_t quoteStart = -1; // Most recent 'single quoted string'
387 int32_t quoteLimit = -1;
388 int32_t varStart = -1; // Most recent $variableReference
389 int32_t varLimit = -1;
390 int32_t bufStart = buf.length();
391
392 while (pos < limit && !done) {
393 // Since all syntax characters are in the BMP, fetching
394 // 16-bit code units suffices here.
395 UChar c = rule.charAt(pos++);
396 if (uprv_isRuleWhiteSpace(c)) {
397 // Ignore whitespace. Note that this is not Unicode
398 // spaces, but Java spaces -- a subset, representing
399 // whitespace likely to be seen in code.
400 continue;
401 }
402 if (u_strchr(HALF_ENDERS, c) != NULL) {
403 if (isSegment) {
404 // Unclosed segment
405 return syntaxError(U_UNCLOSED_SEGMENT, rule, start);
406 }
407 break;
408 }
409 if (anchorEnd) {
410 // Text after a presumed end anchor is a syntax err
411 return syntaxError(U_MALFORMED_VARIABLE_REFERENCE, rule, start);
412 }
413 if (UnicodeSet::resemblesPattern(rule, pos-1)) {
414 pp.setIndex(pos-1); // Backup to opening '['
415 buf.append(parser.parseSet(rule, pp));
416 if (U_FAILURE(parser.status)) {
417 return syntaxError(U_MALFORMED_SET, rule, start);
418 }
419 pos = pp.getIndex();
420 continue;
421 }
422 // Handle escapes
423 if (c == ESCAPE) {
424 if (pos == limit) {
425 return syntaxError(U_TRAILING_BACKSLASH, rule, start);
426 }
427 UChar32 escaped = rule.unescapeAt(pos); // pos is already past '\\'
428 if (escaped == (UChar32) -1) {
429 return syntaxError(U_MALFORMED_UNICODE_ESCAPE, rule, start);
430 }
431 if (!parser.checkVariableRange(escaped)) {
432 return syntaxError(U_VARIABLE_RANGE_OVERLAP, rule, start);
433 }
434 buf.append(escaped);
435 continue;
436 }
437 // Handle quoted matter
438 if (c == QUOTE) {
439 int32_t iq = rule.indexOf(QUOTE, pos);
440 if (iq == pos) {
441 buf.append(c); // Parse [''] outside quotes as [']
442 ++pos;
443 } else {
444 /* This loop picks up a run of quoted text of the
445 * form 'aaaa' each time through. If this run
446 * hasn't really ended ('aaaa''bbbb') then it keeps
447 * looping, each time adding on a new run. When it
448 * reaches the final quote it breaks.
449 */
450 quoteStart = buf.length();
451 for (;;) {
452 if (iq < 0) {
453 return syntaxError(U_UNTERMINATED_QUOTE, rule, start);
454 }
455 scratch.truncate(0);
456 rule.extractBetween(pos, iq, scratch);
457 buf.append(scratch);
458 pos = iq+1;
459 if (pos < limit && rule.charAt(pos) == QUOTE) {
460 // Parse [''] inside quotes as [']
461 iq = rule.indexOf(QUOTE, pos+1);
462 // Continue looping
463 } else {
464 break;
465 }
466 }
467 quoteLimit = buf.length();
468
469 for (iq=quoteStart; iq<quoteLimit; ++iq) {
470 if (!parser.checkVariableRange(buf.charAt(iq))) {
471 return syntaxError(U_VARIABLE_RANGE_OVERLAP, rule, start);
472 }
473 }
474 }
475 continue;
476 }
477
478 if (!parser.checkVariableRange(c)) {
479 return syntaxError(U_VARIABLE_RANGE_OVERLAP, rule, start);
480 }
481
482 if (illegal.indexOf(c) >= 0) {
483 syntaxError(U_ILLEGAL_CHARACTER, rule, start);
484 }
485
486 switch (c) {
487
488 //------------------------------------------------------
489 // Elements allowed within and out of segments
490 //------------------------------------------------------
491 case ANCHOR_START:
492 if (buf.length() == 0 && !anchorStart) {
493 anchorStart = TRUE;
494 } else {
495 return syntaxError(U_MISPLACED_ANCHOR_START,
496 rule, start);
497 }
498 break;
499 case SEGMENT_OPEN:
500 {
501 // bufSegStart is the offset in buf to the first
502 // character of the segment we are parsing.
503 int32_t bufSegStart = buf.length();
504
505 // Record segment number now, since nextSegmentNumber
506 // will be incremented during the call to parseSection
507 // if there are nested segments.
508 int32_t segmentNumber = nextSegmentNumber++; // 1-based
509
510 // Parse the segment
511 pos = parseSection(rule, pos, limit, buf, ILLEGAL_SEG, TRUE);
512
513 // After parsing a segment, the relevant characters are
514 // in buf, starting at offset bufSegStart. Extract them
515 // into a string matcher, and replace them with a
516 // standin for that matcher.
517 StringMatcher* m =
518 new StringMatcher(buf, bufSegStart, buf.length(),
519 segmentNumber, *parser.data);
520
521 // Record and associate object and segment number
522 parser.setSegmentObject(segmentNumber, m);
523 buf.truncate(bufSegStart);
524 buf.append(parser.getSegmentStandin(segmentNumber));
525 }
526 break;
527 case FUNCTION:
528 case ALT_FUNCTION:
529 {
530 int32_t iref = pos;
531 TransliteratorIDParser::SingleID* single =
532 TransliteratorIDParser::parseFilterID(rule, iref);
533 // The next character MUST be a segment open
534 if (single == NULL ||
535 !ICU_Utility::parseChar(rule, iref, SEGMENT_OPEN)) {
536 return syntaxError(U_INVALID_FUNCTION, rule, start);
537 }
538
539 Transliterator *t = single->createInstance();
540 delete single;
541 if (t == NULL) {
542 return syntaxError(U_INVALID_FUNCTION, rule, start);
543 }
544
545 // bufSegStart is the offset in buf to the first
546 // character of the segment we are parsing.
547 int32_t bufSegStart = buf.length();
548
549 // Parse the segment
550 pos = parseSection(rule, iref, limit, buf, ILLEGAL_FUNC, TRUE);
551
552 // After parsing a segment, the relevant characters are
553 // in buf, starting at offset bufSegStart.
554 UnicodeString output;
555 buf.extractBetween(bufSegStart, buf.length(), output);
556 FunctionReplacer *r =
557 new FunctionReplacer(t, new StringReplacer(output, parser.data));
558
559 // Replace the buffer contents with a stand-in
560 buf.truncate(bufSegStart);
561 buf.append(parser.generateStandInFor(r));
562 }
563 break;
564 case SymbolTable::SYMBOL_REF:
565 // Handle variable references and segment references "$1" .. "$9"
566 {
567 // A variable reference must be followed immediately
568 // by a Unicode identifier start and zero or more
569 // Unicode identifier part characters, or by a digit
570 // 1..9 if it is a segment reference.
571 if (pos == limit) {
572 // A variable ref character at the end acts as
573 // an anchor to the context limit, as in perl.
574 anchorEnd = TRUE;
575 break;
576 }
577 // Parse "$1" "$2" .. "$9" .. (no upper limit)
578 c = rule.charAt(pos);
579 int32_t r = u_digit(c, 10);
580 if (r >= 1 && r <= 9) {
581 r = ICU_Utility::parseNumber(rule, pos, 10);
582 if (r < 0) {
583 return syntaxError(U_UNDEFINED_SEGMENT_REFERENCE,
584 rule, start);
585 }
586 buf.append(parser.getSegmentStandin(r));
587 } else {
588 pp.setIndex(pos);
589 UnicodeString name = parser.parseData->
590 parseReference(rule, pp, limit);
591 if (name.length() == 0) {
592 // This means the '$' was not followed by a
593 // valid name. Try to interpret it as an
594 // end anchor then. If this also doesn't work
595 // (if we see a following character) then signal
596 // an error.
597 anchorEnd = TRUE;
598 break;
599 }
600 pos = pp.getIndex();
601 // If this is a variable definition statement,
602 // then the LHS variable will be undefined. In
603 // that case appendVariableDef() will append the
604 // special placeholder char variableLimit-1.
605 varStart = buf.length();
606 parser.appendVariableDef(name, buf);
607 varLimit = buf.length();
608 }
609 }
610 break;
611 case DOT:
612 buf.append(parser.getDotStandIn());
613 break;
614 case KLEENE_STAR:
615 case ONE_OR_MORE:
616 case ZERO_OR_ONE:
617 // Quantifiers. We handle single characters, quoted strings,
618 // variable references, and segments.
619 // a+ matches aaa
620 // 'foo'+ matches foofoofoo
621 // $v+ matches xyxyxy if $v == xy
622 // (seg)+ matches segsegseg
623 {
624 if (isSegment && buf.length() == bufStart) {
625 // The */+ immediately follows '('
626 return syntaxError(U_MISPLACED_QUANTIFIER, rule, start);
627 }
628
629 int32_t qstart, qlimit;
630 // The */+ follows an isolated character or quote
631 // or variable reference
632 if (buf.length() == quoteLimit) {
633 // The */+ follows a 'quoted string'
634 qstart = quoteStart;
635 qlimit = quoteLimit;
636 } else if (buf.length() == varLimit) {
637 // The */+ follows a $variableReference
638 qstart = varStart;
639 qlimit = varLimit;
640 } else {
641 // The */+ follows a single character, possibly
642 // a segment standin
643 qstart = buf.length() - 1;
644 qlimit = qstart + 1;
645 }
646
647 UnicodeFunctor *m =
648 new StringMatcher(buf, qstart, qlimit, 0, *parser.data);
649 int32_t min = 0;
650 int32_t max = Quantifier::MAX;
651 switch (c) {
652 case ONE_OR_MORE:
653 min = 1;
654 break;
655 case ZERO_OR_ONE:
656 min = 0;
657 max = 1;
658 break;
659 // case KLEENE_STAR:
660 // do nothing -- min, max already set
661 }
662 m = new Quantifier(m, min, max);
663 buf.truncate(qstart);
664 buf.append(parser.generateStandInFor(m));
665 }
666 break;
667
668 //------------------------------------------------------
669 // Elements allowed ONLY WITHIN segments
670 //------------------------------------------------------
671 case SEGMENT_CLOSE:
672 // assert(isSegment);
673 // We're done parsing a segment.
674 done = TRUE;
675 break;
676
677 //------------------------------------------------------
678 // Elements allowed ONLY OUTSIDE segments
679 //------------------------------------------------------
680 case CONTEXT_ANTE:
681 if (ante >= 0) {
682 return syntaxError(U_MULTIPLE_ANTE_CONTEXTS, rule, start);
683 }
684 ante = buf.length();
685 break;
686 case CONTEXT_POST:
687 if (post >= 0) {
688 return syntaxError(U_MULTIPLE_POST_CONTEXTS, rule, start);
689 }
690 post = buf.length();
691 break;
692 case CURSOR_POS:
693 if (cursor >= 0) {
694 return syntaxError(U_MULTIPLE_CURSORS, rule, start);
695 }
696 cursor = buf.length();
697 break;
698 case CURSOR_OFFSET:
699 if (cursorOffset < 0) {
700 if (buf.length() > 0) {
701 return syntaxError(U_MISPLACED_CURSOR_OFFSET, rule, start);
702 }
703 --cursorOffset;
704 } else if (cursorOffset > 0) {
705 if (buf.length() != cursorOffsetPos || cursor >= 0) {
706 return syntaxError(U_MISPLACED_CURSOR_OFFSET, rule, start);
707 }
708 ++cursorOffset;
709 } else {
710 if (cursor == 0 && buf.length() == 0) {
711 cursorOffset = -1;
712 } else if (cursor < 0) {
713 cursorOffsetPos = buf.length();
714 cursorOffset = 1;
715 } else {
716 return syntaxError(U_MISPLACED_CURSOR_OFFSET, rule, start);
717 }
718 }
719 break;
720
721
722 //------------------------------------------------------
723 // Non-special characters
724 //------------------------------------------------------
725 default:
726 // Disallow unquoted characters other than [0-9A-Za-z]
727 // in the printable ASCII range. These characters are
728 // reserved for possible future use.
729 if (c >= 0x0021 && c <= 0x007E &&
730 !((c >= 0x0030/*'0'*/ && c <= 0x0039/*'9'*/) ||
731 (c >= 0x0041/*'A'*/ && c <= 0x005A/*'Z'*/) ||
732 (c >= 0x0061/*'a'*/ && c <= 0x007A/*'z'*/))) {
733 return syntaxError(U_UNQUOTED_SPECIAL, rule, start);
734 }
735 buf.append(c);
736 break;
737 }
738 }
739
740 return pos;
741 }
742
743 /**
744 * Remove context.
745 */
746 void RuleHalf::removeContext() {
747 //text = text.substring(ante < 0 ? 0 : ante,
748 // post < 0 ? text.length() : post);
749 if (post >= 0) {
750 text.remove(post);
751 }
752 if (ante >= 0) {
753 text.removeBetween(0, ante);
754 }
755 ante = post = -1;
756 anchorStart = anchorEnd = FALSE;
757 }
758
759 /**
760 * Return true if this half looks like valid output, that is, does not
761 * contain quantifiers or other special input-only elements.
762 */
763 UBool RuleHalf::isValidOutput(TransliteratorParser& transParser) {
764 for (int32_t i=0; i<text.length(); ) {
765 UChar32 c = text.char32At(i);
766 i += UTF_CHAR_LENGTH(c);
767 if (!transParser.parseData->isReplacer(c)) {
768 return FALSE;
769 }
770 }
771 return TRUE;
772 }
773
774 /**
775 * Return true if this half looks like valid input, that is, does not
776 * contain functions or other special output-only elements.
777 */
778 UBool RuleHalf::isValidInput(TransliteratorParser& transParser) {
779 for (int32_t i=0; i<text.length(); ) {
780 UChar32 c = text.char32At(i);
781 i += UTF_CHAR_LENGTH(c);
782 if (!transParser.parseData->isMatcher(c)) {
783 return FALSE;
784 }
785 }
786 return TRUE;
787 }
788
789 //----------------------------------------------------------------------
790 // PUBLIC API
791 //----------------------------------------------------------------------
792
793 /**
794 * Constructor.
795 */
796 TransliteratorParser::TransliteratorParser() {
797 data = NULL;
798 compoundFilter = NULL;
799 parseData = NULL;
800 variablesVector = NULL;
801 segmentObjects = NULL;
802 }
803
804 /**
805 * Destructor.
806 */
807 TransliteratorParser::~TransliteratorParser() {
808 delete data;
809 delete compoundFilter;
810 delete parseData;
811 delete variablesVector;
812 delete segmentObjects;
813 }
814
815 void
816 TransliteratorParser::parse(const UnicodeString& rules,
817 UTransDirection transDirection,
818 UParseError& pe,
819 UErrorCode& ec) {
820 if (U_SUCCESS(ec)) {
821 parseRules(rules, transDirection);
822 pe = parseError;
823 ec = status;
824 }
825 }
826
827 /**
828 * Return the compound filter parsed by parse(). Caller owns result.
829 */
830 UnicodeSet* TransliteratorParser::orphanCompoundFilter() {
831 UnicodeSet* f = compoundFilter;
832 compoundFilter = NULL;
833 return f;
834 }
835
836 /**
837 * Return the data object parsed by parse(). Caller owns result.
838 */
839 TransliterationRuleData* TransliteratorParser::orphanData() {
840 TransliterationRuleData* d = data;
841 data = NULL;
842 return d;
843 }
844
845 //----------------------------------------------------------------------
846 // Private implementation
847 //----------------------------------------------------------------------
848
849 /**
850 * Parse the given string as a sequence of rules, separated by newline
851 * characters ('\n'), and cause this object to implement those rules. Any
852 * previous rules are discarded. Typically this method is called exactly
853 * once, during construction.
854 * @exception IllegalArgumentException if there is a syntax error in the
855 * rules
856 */
857 void TransliteratorParser::parseRules(const UnicodeString& rule,
858 UTransDirection theDirection) {
859 // Clear error struct
860 parseError.line = parseError.offset = -1;
861 parseError.preContext[0] = parseError.postContext[0] = (UChar)0;
862 status = U_ZERO_ERROR;
863
864 delete data;
865 data = new TransliterationRuleData(status);
866 if (U_FAILURE(status)) {
867 return;
868 }
869
870 direction = theDirection;
871 ruleCount = 0;
872
873 delete compoundFilter;
874 compoundFilter = NULL;
875
876 if (variablesVector == NULL) {
877 variablesVector = new UVector(status);
878 } else {
879 variablesVector->removeAllElements();
880 }
881 parseData = new ParseData(0, variablesVector);
882 if (parseData == NULL) {
883 status = U_MEMORY_ALLOCATION_ERROR;
884 return;
885 }
886 parseData->data = data;
887
888 // By default, rules use part of the private use area
889 // E000..F8FF for variables and other stand-ins. Currently
890 // the range F000..F8FF is typically sufficient. The 'use
891 // variable range' pragma allows rule sets to modify this.
892 setVariableRange(0xF000, 0xF8FF);
893
894 dotStandIn = (UChar) -1;
895
896 UnicodeString str; // scratch
897 idBlock.truncate(0);
898 idSplitPoint = -1;
899 int32_t pos = 0;
900 int32_t limit = rule.length();
901 // The mode marks whether we are in the header ::id block, the
902 // rule block, or the footer ::id block.
903 // mode == 0: start: rule->1, ::id->0
904 // mode == 1: in rules: rule->1, ::id->2
905 // mode == 2: in footer rule block: rule->ERROR, ::id->2
906 int32_t mode = 0;
907
908 // The compound filter offset is an index into idBlockResult.
909 // If it is 0, then the compound filter occurred at the start,
910 // and it is the offset to the _start_ of the compound filter
911 // pattern. Otherwise it is the offset to the _limit_ of the
912 // compound filter pattern within idBlockResult.
913 compoundFilter = NULL;
914 int32_t compoundFilterOffset = -1;
915
916 // The number of ::ID block entries we have parsed
917 int32_t idBlockCount = 0;
918
919 while (pos < limit && U_SUCCESS(status)) {
920 UChar c = rule.charAt(pos++);
921 if (uprv_isRuleWhiteSpace(c)) {
922 // Ignore leading whitespace.
923 continue;
924 }
925 // Skip lines starting with the comment character
926 if (c == RULE_COMMENT_CHAR) {
927 pos = rule.indexOf((UChar)0x000A /*\n*/, pos) + 1;
928 if (pos == 0) {
929 break; // No "\n" found; rest of rule is a commnet
930 }
931 continue; // Either fall out or restart with next line
932 }
933 // We've found the start of a rule or ID. c is its first
934 // character, and pos points past c.
935 --pos;
936 // Look for an ID token. Must have at least ID_TOKEN_LEN + 1
937 // chars left.
938 if ((pos + ID_TOKEN_LEN + 1) <= limit &&
939 rule.compare(pos, ID_TOKEN_LEN, ID_TOKEN) == 0) {
940 pos += ID_TOKEN_LEN;
941 c = rule.charAt(pos);
942 while (uprv_isRuleWhiteSpace(c) && pos < limit) {
943 ++pos;
944 c = rule.charAt(pos);
945 }
946
947 if (mode == 1) {
948 // We have just entered the footer ::ID block
949 mode = 2;
950 // In the forward direction add elements at the end.
951 // In the reverse direction add elements at the start.
952 idSplitPoint = idBlockCount;
953 }
954 int32_t p = pos;
955
956 TransliteratorIDParser::SingleID* id =
957 TransliteratorIDParser::parseSingleID(rule, p, direction, status);
958 if (p != pos && ICU_Utility::parseChar(rule, p, END_OF_RULE)) {
959 // Successful ::ID parse.
960
961 if (direction == UTRANS_FORWARD) {
962 idBlock.append(id->canonID).append(END_OF_RULE);
963 } else {
964 idBlock.insert(0, END_OF_RULE);
965 idBlock.insert(0, id->canonID);
966 }
967
968 ++idBlockCount;
969
970 } else {
971 // Couldn't parse an ID. Try to parse a global filter
972 int32_t withParens = -1;
973 UnicodeSet* f = TransliteratorIDParser::parseGlobalFilter(rule, p, direction, withParens, &idBlock);
974 if (f != NULL) {
975 if (ICU_Utility::parseChar(rule, p, END_OF_RULE)
976 && (direction == UTRANS_FORWARD) == (withParens == 0))
977 {
978 if (compoundFilter != NULL) {
979 // Multiple compound filters
980 syntaxError(U_MULTIPLE_COMPOUND_FILTERS, rule, pos);
981 delete f;
982 } else {
983 compoundFilter = f;
984 compoundFilterOffset = idBlockCount;
985 }
986 } else {
987 delete f;
988 }
989 } else {
990 // Invalid ::id
991 // Can be parsed as neither an ID nor a global filter
992 syntaxError(U_INVALID_ID, rule, pos);
993 }
994 }
995 delete id;
996
997 pos = p;
998 } else if (resemblesPragma(rule, pos, limit)) {
999 int32_t ppp = parsePragma(rule, pos, limit);
1000 if (ppp < 0) {
1001 syntaxError(U_MALFORMED_PRAGMA, rule, pos);
1002 }
1003 pos = ppp;
1004 } else {
1005 // Parse a rule
1006 pos = parseRule(rule, pos, limit);
1007 if (U_SUCCESS(status)) {
1008 ++ruleCount;
1009 if (mode == 2) {
1010 // ::id in illegal position (because a rule
1011 // occurred after the ::id footer block)
1012 syntaxError(U_ILLEGAL_ARGUMENT_ERROR,rule,pos);
1013 }
1014 }else{
1015 syntaxError(status,rule,pos);
1016 }
1017 mode = 1;
1018 }
1019 }
1020
1021 if (idSplitPoint < 0) {
1022 idSplitPoint = idBlockCount;
1023 }
1024
1025 if (direction == UTRANS_REVERSE) {
1026 idSplitPoint = idBlockCount - idSplitPoint;
1027 }
1028
1029 // Convert the set vector to an array
1030 data->variablesLength = variablesVector->size();
1031 if(data->variablesLength == 0) {
1032 data->variables = 0;
1033 } else {
1034 data->variables = (UnicodeFunctor **)uprv_malloc(data->variablesLength * sizeof(UnicodeFunctor *));
1035 }
1036
1037 // orphanElement removes the given element and shifts all other
1038 // elements down. For performance (and code clarity) we work from
1039 // the end back to index 0.
1040 int32_t i;
1041 for (i=data->variablesLength; i>0; ) {
1042 --i;
1043 data->variables[i] =
1044 (UnicodeSet*) variablesVector->orphanElementAt(i);
1045 }
1046
1047 // Index the rules
1048 if (U_SUCCESS(status)) {
1049 if (compoundFilter != NULL) {
1050 if ((direction == UTRANS_FORWARD &&
1051 compoundFilterOffset != 0) ||
1052 (direction == UTRANS_REVERSE &&
1053 compoundFilterOffset != idBlockCount)) {
1054 status = U_MISPLACED_COMPOUND_FILTER;
1055 }
1056 }
1057
1058 data->ruleSet.freeze(parseError,status);
1059
1060 if (idSplitPoint < 0) {
1061 idSplitPoint = idBlock.length();
1062 }
1063
1064 if (ruleCount == 0) {
1065 delete data;
1066 data = NULL;
1067 }
1068 }
1069 }
1070
1071 /**
1072 * Set the variable range to [start, end] (inclusive).
1073 */
1074 void TransliteratorParser::setVariableRange(int32_t start, int32_t end) {
1075 if (start > end || start < 0 || end > 0xFFFF) {
1076 status = U_MALFORMED_PRAGMA;
1077 return;
1078 }
1079
1080 data->variablesBase = variableNext = (UChar) start; // first private use
1081 variableLimit = (UChar) (end + 1);
1082 }
1083
1084 /**
1085 * Assert that the given character is NOT within the variable range.
1086 * If it is, return FALSE. This is neccesary to ensure that the
1087 * variable range does not overlap characters used in a rule.
1088 */
1089 UBool TransliteratorParser::checkVariableRange(UChar32 ch) const {
1090 return !(ch >= data->variablesBase && ch < variableLimit);
1091 }
1092
1093 /**
1094 * Set the maximum backup to 'backup', in response to a pragma
1095 * statement.
1096 */
1097 void TransliteratorParser::pragmaMaximumBackup(int32_t /*backup*/) {
1098 //TODO Finish
1099 }
1100
1101 /**
1102 * Begin normalizing all rules using the given mode, in response
1103 * to a pragma statement.
1104 */
1105 void TransliteratorParser::pragmaNormalizeRules(UNormalizationMode /*mode*/) {
1106 //TODO Finish
1107 }
1108
1109 static const UChar PRAGMA_USE[] = {0x75,0x73,0x65,0x20,0}; // "use "
1110
1111 static const UChar PRAGMA_VARIABLE_RANGE[] = {0x7E,0x76,0x61,0x72,0x69,0x61,0x62,0x6C,0x65,0x20,0x72,0x61,0x6E,0x67,0x65,0x20,0x23,0x20,0x23,0x7E,0x3B,0}; // "~variable range # #~;"
1112
1113 static const UChar PRAGMA_MAXIMUM_BACKUP[] = {0x7E,0x6D,0x61,0x78,0x69,0x6D,0x75,0x6D,0x20,0x62,0x61,0x63,0x6B,0x75,0x70,0x20,0x23,0x7E,0x3B,0}; // "~maximum backup #~;"
1114
1115 static const UChar PRAGMA_NFD_RULES[] = {0x7E,0x6E,0x66,0x64,0x20,0x72,0x75,0x6C,0x65,0x73,0x7E,0x3B,0}; // "~nfd rules~;"
1116
1117 static const UChar PRAGMA_NFC_RULES[] = {0x7E,0x6E,0x66,0x63,0x20,0x72,0x75,0x6C,0x65,0x73,0x7E,0x3B,0}; // "~nfc rules~;"
1118
1119 /**
1120 * Return true if the given rule looks like a pragma.
1121 * @param pos offset to the first non-whitespace character
1122 * of the rule.
1123 * @param limit pointer past the last character of the rule.
1124 */
1125 UBool TransliteratorParser::resemblesPragma(const UnicodeString& rule, int32_t pos, int32_t limit) {
1126 // Must start with /use\s/i
1127 return ICU_Utility::parsePattern(rule, pos, limit, PRAGMA_USE, NULL) >= 0;
1128 }
1129
1130 /**
1131 * Parse a pragma. This method assumes resemblesPragma() has
1132 * already returned true.
1133 * @param pos offset to the first non-whitespace character
1134 * of the rule.
1135 * @param limit pointer past the last character of the rule.
1136 * @return the position index after the final ';' of the pragma,
1137 * or -1 on failure.
1138 */
1139 int32_t TransliteratorParser::parsePragma(const UnicodeString& rule, int32_t pos, int32_t limit) {
1140 int32_t array[2];
1141
1142 // resemblesPragma() has already returned true, so we
1143 // know that pos points to /use\s/i; we can skip 4 characters
1144 // immediately
1145 pos += 4;
1146
1147 // Here are the pragmas we recognize:
1148 // use variable range 0xE000 0xEFFF;
1149 // use maximum backup 16;
1150 // use nfd rules;
1151 // use nfc rules;
1152 int p = ICU_Utility::parsePattern(rule, pos, limit, PRAGMA_VARIABLE_RANGE, array);
1153 if (p >= 0) {
1154 setVariableRange(array[0], array[1]);
1155 return p;
1156 }
1157
1158 p = ICU_Utility::parsePattern(rule, pos, limit, PRAGMA_MAXIMUM_BACKUP, array);
1159 if (p >= 0) {
1160 pragmaMaximumBackup(array[0]);
1161 return p;
1162 }
1163
1164 p = ICU_Utility::parsePattern(rule, pos, limit, PRAGMA_NFD_RULES, NULL);
1165 if (p >= 0) {
1166 pragmaNormalizeRules(UNORM_NFD);
1167 return p;
1168 }
1169
1170 p = ICU_Utility::parsePattern(rule, pos, limit, PRAGMA_NFC_RULES, NULL);
1171 if (p >= 0) {
1172 pragmaNormalizeRules(UNORM_NFC);
1173 return p;
1174 }
1175
1176 // Syntax error: unable to parse pragma
1177 return -1;
1178 }
1179
1180 /**
1181 * MAIN PARSER. Parse the next rule in the given rule string, starting
1182 * at pos. Return the index after the last character parsed. Do not
1183 * parse characters at or after limit.
1184 *
1185 * Important: The character at pos must be a non-whitespace character
1186 * that is not the comment character.
1187 *
1188 * This method handles quoting, escaping, and whitespace removal. It
1189 * parses the end-of-rule character. It recognizes context and cursor
1190 * indicators. Once it does a lexical breakdown of the rule at pos, it
1191 * creates a rule object and adds it to our rule list.
1192 */
1193 int32_t TransliteratorParser::parseRule(const UnicodeString& rule, int32_t pos, int32_t limit) {
1194 // Locate the left side, operator, and right side
1195 int32_t start = pos;
1196 UChar op = 0;
1197 int32_t i;
1198
1199 // Set up segments data
1200 segmentStandins.truncate(0);
1201 if (segmentObjects == NULL) {
1202 segmentObjects = new UVector(status);
1203 } else {
1204 segmentObjects->removeAllElements();
1205 }
1206
1207 // Use pointers to automatics to make swapping possible.
1208 RuleHalf _left(*this), _right(*this);
1209 RuleHalf* left = &_left;
1210 RuleHalf* right = &_right;
1211
1212 undefinedVariableName.remove();
1213 pos = left->parse(rule, pos, limit);
1214 if (U_FAILURE(status)) {
1215 return start;
1216 }
1217
1218 if (pos == limit || u_strchr(gOPERATORS, (op = rule.charAt(--pos))) == NULL) {
1219 return syntaxError(U_MISSING_OPERATOR, rule, start);
1220 }
1221 ++pos;
1222
1223 // Found an operator char. Check for forward-reverse operator.
1224 if (op == REVERSE_RULE_OP &&
1225 (pos < limit && rule.charAt(pos) == FORWARD_RULE_OP)) {
1226 ++pos;
1227 op = FWDREV_RULE_OP;
1228 }
1229
1230 // Translate alternate op characters.
1231 switch (op) {
1232 case ALT_FORWARD_RULE_OP:
1233 op = FORWARD_RULE_OP;
1234 break;
1235 case ALT_REVERSE_RULE_OP:
1236 op = REVERSE_RULE_OP;
1237 break;
1238 case ALT_FWDREV_RULE_OP:
1239 op = FWDREV_RULE_OP;
1240 break;
1241 }
1242
1243 pos = right->parse(rule, pos, limit);
1244 if (U_FAILURE(status)) {
1245 return start;
1246 }
1247
1248 if (pos < limit) {
1249 if (rule.charAt(--pos) == END_OF_RULE) {
1250 ++pos;
1251 } else {
1252 // RuleHalf parser must have terminated at an operator
1253 return syntaxError(U_UNQUOTED_SPECIAL, rule, start);
1254 }
1255 }
1256
1257 if (op == VARIABLE_DEF_OP) {
1258 // LHS is the name. RHS is a single character, either a literal
1259 // or a set (already parsed). If RHS is longer than one
1260 // character, it is either a multi-character string, or multiple
1261 // sets, or a mixture of chars and sets -- syntax error.
1262
1263 // We expect to see a single undefined variable (the one being
1264 // defined).
1265 if (undefinedVariableName.length() == 0) {
1266 // "Missing '$' or duplicate definition"
1267 return syntaxError(U_BAD_VARIABLE_DEFINITION, rule, start);
1268 }
1269 if (left->text.length() != 1 || left->text.charAt(0) != variableLimit) {
1270 // "Malformed LHS"
1271 return syntaxError(U_MALFORMED_VARIABLE_DEFINITION, rule, start);
1272 }
1273 if (left->anchorStart || left->anchorEnd ||
1274 right->anchorStart || right->anchorEnd) {
1275 return syntaxError(U_MALFORMED_VARIABLE_DEFINITION, rule, start);
1276 }
1277 // We allow anything on the right, including an empty string.
1278 UnicodeString* value = new UnicodeString(right->text);
1279 data->variableNames->put(undefinedVariableName, value, status);
1280 ++variableLimit;
1281 return pos;
1282 }
1283
1284 // If this is not a variable definition rule, we shouldn't have
1285 // any undefined variable names.
1286 if (undefinedVariableName.length() != 0) {
1287 return syntaxError(// "Undefined variable $" + undefinedVariableName,
1288 U_UNDEFINED_VARIABLE,
1289 rule, start);
1290 }
1291
1292 // Verify segments
1293 if (segmentStandins.length() > segmentObjects->size()) {
1294 syntaxError(U_UNDEFINED_SEGMENT_REFERENCE, rule, start);
1295 }
1296 for (i=0; i<segmentStandins.length(); ++i) {
1297 if (segmentStandins.charAt(i) == 0) {
1298 syntaxError(U_INTERNAL_TRANSLITERATOR_ERROR, rule, start); // will never happen
1299 }
1300 }
1301 for (i=0; i<segmentObjects->size(); ++i) {
1302 if (segmentObjects->elementAt(i) == NULL) {
1303 syntaxError(U_INTERNAL_TRANSLITERATOR_ERROR, rule, start); // will never happen
1304 }
1305 }
1306
1307 // If the direction we want doesn't match the rule
1308 // direction, do nothing.
1309 if (op != FWDREV_RULE_OP &&
1310 ((direction == UTRANS_FORWARD) != (op == FORWARD_RULE_OP))) {
1311 return pos;
1312 }
1313
1314 // Transform the rule into a forward rule by swapping the
1315 // sides if necessary.
1316 if (direction == UTRANS_REVERSE) {
1317 left = &_right;
1318 right = &_left;
1319 }
1320
1321 // Remove non-applicable elements in forward-reverse
1322 // rules. Bidirectional rules ignore elements that do not
1323 // apply.
1324 if (op == FWDREV_RULE_OP) {
1325 right->removeContext();
1326 left->cursor = -1;
1327 left->cursorOffset = 0;
1328 }
1329
1330 // Normalize context
1331 if (left->ante < 0) {
1332 left->ante = 0;
1333 }
1334 if (left->post < 0) {
1335 left->post = left->text.length();
1336 }
1337
1338 // Context is only allowed on the input side. Cursors are only
1339 // allowed on the output side. Segment delimiters can only appear
1340 // on the left, and references on the right. Cursor offset
1341 // cannot appear without an explicit cursor. Cursor offset
1342 // cannot place the cursor outside the limits of the context.
1343 // Anchors are only allowed on the input side.
1344 if (right->ante >= 0 || right->post >= 0 || left->cursor >= 0 ||
1345 (right->cursorOffset != 0 && right->cursor < 0) ||
1346 // - The following two checks were used to ensure that the
1347 // - the cursor offset stayed within the ante- or postcontext.
1348 // - However, with the addition of quantifiers, we have to
1349 // - allow arbitrary cursor offsets and do runtime checking.
1350 //(right->cursorOffset > (left->text.length() - left->post)) ||
1351 //(-right->cursorOffset > left->ante) ||
1352 right->anchorStart || right->anchorEnd ||
1353 !left->isValidInput(*this) || !right->isValidOutput(*this) ||
1354 left->ante > left->post) {
1355
1356 return syntaxError(U_MALFORMED_RULE, rule, start);
1357 }
1358
1359 // Flatten segment objects vector to an array
1360 UnicodeFunctor** segmentsArray = NULL;
1361 if (segmentObjects->size() > 0) {
1362 segmentsArray = (UnicodeFunctor **)uprv_malloc(segmentObjects->size() * sizeof(UnicodeFunctor *));
1363 segmentObjects->toArray((void**) segmentsArray);
1364 }
1365
1366 data->ruleSet.addRule(new TransliterationRule(
1367 left->text, left->ante, left->post,
1368 right->text, right->cursor, right->cursorOffset,
1369 segmentsArray,
1370 segmentObjects->size(),
1371 left->anchorStart, left->anchorEnd,
1372 data,
1373 status), status);
1374
1375 return pos;
1376 }
1377
1378 /**
1379 * Called by main parser upon syntax error. Search the rule string
1380 * for the probable end of the rule. Of course, if the error is that
1381 * the end of rule marker is missing, then the rule end will not be found.
1382 * In any case the rule start will be correctly reported.
1383 * @param msg error description
1384 * @param rule pattern string
1385 * @param start position of first character of current rule
1386 */
1387 int32_t TransliteratorParser::syntaxError(UErrorCode parseErrorCode,
1388 const UnicodeString& rule,
1389 int32_t pos) {
1390 parseError.offset = pos;
1391 parseError.line = 0 ; /* we are not using line numbers */
1392
1393 // for pre-context
1394 const int32_t LEN = U_PARSE_CONTEXT_LEN - 1;
1395 int32_t start = uprv_max(pos - LEN, 0);
1396 int32_t stop = pos;
1397
1398 rule.extract(start,stop-start,parseError.preContext);
1399 //null terminate the buffer
1400 parseError.preContext[stop-start] = 0;
1401
1402 //for post-context
1403 start = pos;
1404 stop = uprv_min(pos + LEN, rule.length());
1405
1406 rule.extract(start,stop-start,parseError.postContext);
1407 //null terminate the buffer
1408 parseError.postContext[stop-start]= 0;
1409
1410 status = (UErrorCode)parseErrorCode;
1411 return pos;
1412
1413 }
1414
1415 /**
1416 * Parse a UnicodeSet out, store it, and return the stand-in character
1417 * used to represent it.
1418 */
1419 UChar TransliteratorParser::parseSet(const UnicodeString& rule,
1420 ParsePosition& pos) {
1421 UnicodeSet* set = new UnicodeSet(rule, pos, USET_IGNORE_SPACE, parseData, status);
1422 set->compact();
1423 return generateStandInFor(set);
1424 }
1425
1426 /**
1427 * Generate and return a stand-in for a new UnicodeFunctor. Store
1428 * the matcher (adopt it).
1429 */
1430 UChar TransliteratorParser::generateStandInFor(UnicodeFunctor* adopted) {
1431 // assert(obj != null);
1432
1433 // Look up previous stand-in, if any. This is a short list
1434 // (typical n is 0, 1, or 2); linear search is optimal.
1435 for (int32_t i=0; i<variablesVector->size(); ++i) {
1436 if (variablesVector->elementAt(i) == adopted) { // [sic] pointer comparison
1437 return (UChar) (data->variablesBase + i);
1438 }
1439 }
1440
1441 if (variableNext >= variableLimit) {
1442 delete adopted;
1443 status = U_VARIABLE_RANGE_EXHAUSTED;
1444 return 0;
1445 }
1446 variablesVector->addElement(adopted, status);
1447 return variableNext++;
1448 }
1449
1450 /**
1451 * Return the standin for segment seg (1-based).
1452 */
1453 UChar TransliteratorParser::getSegmentStandin(int32_t seg) {
1454 // Special character used to indicate an empty spot
1455 UChar empty = data->variablesBase - 1;
1456 while (segmentStandins.length() < seg) {
1457 segmentStandins.append(empty);
1458 }
1459 UChar c = segmentStandins.charAt(seg-1);
1460 if (c == empty) {
1461 if (variableNext >= variableLimit) {
1462 status = U_VARIABLE_RANGE_EXHAUSTED;
1463 return 0;
1464 }
1465 c = variableNext++;
1466 // Set a placeholder in the master variables vector that will be
1467 // filled in later by setSegmentObject(). We know that we will get
1468 // called first because setSegmentObject() will call us.
1469 variablesVector->addElement((void*) NULL, status);
1470 segmentStandins.setCharAt(seg-1, c);
1471 }
1472 return c;
1473 }
1474
1475 /**
1476 * Set the object for segment seg (1-based).
1477 */
1478 void TransliteratorParser::setSegmentObject(int32_t seg, StringMatcher* adopted) {
1479 // Since we call parseSection() recursively, nested
1480 // segments will result in segment i+1 getting parsed
1481 // and stored before segment i; be careful with the
1482 // vector handling here.
1483 if (segmentObjects->size() < seg) {
1484 segmentObjects->setSize(seg);
1485 }
1486 int32_t index = getSegmentStandin(seg) - data->variablesBase;
1487 if (segmentObjects->elementAt(seg-1) != NULL ||
1488 variablesVector->elementAt(index) != NULL) {
1489 // should never happen
1490 status = U_INTERNAL_TRANSLITERATOR_ERROR;
1491 return;
1492 }
1493 segmentObjects->setElementAt(adopted, seg-1);
1494 variablesVector->setElementAt(adopted, index);
1495 }
1496
1497 /**
1498 * Return the stand-in for the dot set. It is allocated the first
1499 * time and reused thereafter.
1500 */
1501 UChar TransliteratorParser::getDotStandIn() {
1502 if (dotStandIn == (UChar) -1) {
1503 dotStandIn = generateStandInFor(new UnicodeSet(DOT_SET, status));
1504 }
1505 return dotStandIn;
1506 }
1507
1508 /**
1509 * Append the value of the given variable name to the given
1510 * UnicodeString.
1511 */
1512 void TransliteratorParser::appendVariableDef(const UnicodeString& name,
1513 UnicodeString& buf) {
1514 const UnicodeString* s = (const UnicodeString*) data->variableNames->get(name);
1515 if (s == NULL) {
1516 // We allow one undefined variable so that variable definition
1517 // statements work. For the first undefined variable we return
1518 // the special placeholder variableLimit-1, and save the variable
1519 // name.
1520 if (undefinedVariableName.length() == 0) {
1521 undefinedVariableName = name;
1522 if (variableNext >= variableLimit) {
1523 // throw new RuntimeException("Private use variables exhausted");
1524 status = U_ILLEGAL_ARGUMENT_ERROR;
1525 return;
1526 }
1527 buf.append((UChar) --variableLimit);
1528 } else {
1529 //throw new IllegalArgumentException("Undefined variable $"
1530 // + name);
1531 status = U_ILLEGAL_ARGUMENT_ERROR;
1532 return;
1533 }
1534 } else {
1535 buf.append(*s);
1536 }
1537 }
1538
1539 /**
1540 * Glue method to get around access restrictions in C++.
1541 */
1542 Transliterator* TransliteratorParser::createBasicInstance(const UnicodeString& id, const UnicodeString* canonID) {
1543 return Transliterator::createBasicInstance(id, canonID);
1544 }
1545
1546 U_NAMESPACE_END
1547
1548 #endif /* #if !UCONFIG_NO_TRANSLITERATION */