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