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