2 **********************************************************************
3 * Copyright (C) 1999-2004, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Date Name Description
7 * 11/17/99 aliu Creation.
8 **********************************************************************
11 #include "unicode/utypes.h"
13 #if !UCONFIG_NO_TRANSLITERATION
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"
32 #include "unicode/symtable.h"
41 #define VARIABLE_DEF_OP ((UChar)0x003D) /*=*/
42 #define FORWARD_RULE_OP ((UChar)0x003E) /*>*/
43 #define REVERSE_RULE_OP ((UChar)0x003C) /*<*/
44 #define FWDREV_RULE_OP ((UChar)0x007E) /*~*/ // internal rep of <> op
46 // Other special characters
47 #define QUOTE ((UChar)0x0027) /*'*/
48 #define ESCAPE ((UChar)0x005C) /*\*/
49 #define END_OF_RULE ((UChar)0x003B) /*;*/
50 #define RULE_COMMENT_CHAR ((UChar)0x0023) /*#*/
52 #define SEGMENT_OPEN ((UChar)0x0028) /*(*/
53 #define SEGMENT_CLOSE ((UChar)0x0029) /*)*/
54 #define CONTEXT_ANTE ((UChar)0x007B) /*{*/
55 #define CONTEXT_POST ((UChar)0x007D) /*}*/
56 #define CURSOR_POS ((UChar)0x007C) /*|*/
57 #define CURSOR_OFFSET ((UChar)0x0040) /*@*/
58 #define ANCHOR_START ((UChar)0x005E) /*^*/
59 #define KLEENE_STAR ((UChar)0x002A) /***/
60 #define ONE_OR_MORE ((UChar)0x002B) /*+*/
61 #define ZERO_OR_ONE ((UChar)0x003F) /*?*/
63 #define DOT ((UChar)46) /*.*/
65 static const UChar DOT_SET
[] = { // "[^[:Zp:][:Zl:]\r\n$]";
66 91, 94, 91, 58, 90, 112, 58, 93, 91, 58, 90,
67 108, 58, 93, 92, 114, 92, 110, 36, 93, 0
70 // A function is denoted &Source-Target/Variant(text)
71 #define FUNCTION ((UChar)38) /*&*/
73 // Aliases for some of the syntax characters. These are provided so
74 // transliteration rules can be expressed in XML without clashing with
75 // XML syntax characters '<', '>', and '&'.
76 #define ALT_REVERSE_RULE_OP ((UChar)0x2190) // Left Arrow
77 #define ALT_FORWARD_RULE_OP ((UChar)0x2192) // Right Arrow
78 #define ALT_FWDREV_RULE_OP ((UChar)0x2194) // Left Right Arrow
79 #define ALT_FUNCTION ((UChar)0x2206) // Increment (~Greek Capital Delta)
81 // Special characters disallowed at the top level
82 static const UChar ILLEGAL_TOP
[] = {41,0}; // ")"
84 // Special characters disallowed within a segment
85 static const UChar ILLEGAL_SEG
[] = {123,125,124,64,0}; // "{}|@"
87 // Special characters disallowed within a function argument
88 static const UChar ILLEGAL_FUNC
[] = {94,40,46,42,43,63,123,125,124,64,0}; // "^(.*+?{}|@"
90 // By definition, the ANCHOR_END special character is a
91 // trailing SymbolTable.SYMBOL_REF character.
92 // private static final char ANCHOR_END = '$';
94 static const UChar gOPERATORS
[] = { // "=><"
95 VARIABLE_DEF_OP
, FORWARD_RULE_OP
, REVERSE_RULE_OP
,
96 ALT_FORWARD_RULE_OP
, ALT_REVERSE_RULE_OP
, ALT_FWDREV_RULE_OP
,
100 static const UChar HALF_ENDERS
[] = { // "=><;"
101 VARIABLE_DEF_OP
, FORWARD_RULE_OP
, REVERSE_RULE_OP
,
102 ALT_FORWARD_RULE_OP
, ALT_REVERSE_RULE_OP
, ALT_FWDREV_RULE_OP
,
107 // These are also used in Transliterator::toRules()
108 static const int32_t ID_TOKEN_LEN
= 2;
109 static const UChar ID_TOKEN
[] = { 0x3A, 0x3A }; // ':', ':'
113 //----------------------------------------------------------------------
115 //----------------------------------------------------------------------
118 * This class implements the SymbolTable interface. It is used
119 * during parsing to give UnicodeSet access to variables that
120 * have been defined so far. Note that it uses variablesVector,
121 * _not_ data.setVariables.
123 class ParseData
: public UMemory
, public SymbolTable
{
125 const TransliterationRuleData
* data
; // alias
127 const UVector
* variablesVector
; // alias
129 ParseData(const TransliterationRuleData
* data
= 0,
130 const UVector
* variablesVector
= 0);
132 virtual const UnicodeString
* lookup(const UnicodeString
& s
) const;
134 virtual const UnicodeFunctor
* lookupMatcher(UChar32 ch
) const;
136 virtual UnicodeString
parseReference(const UnicodeString
& text
,
137 ParsePosition
& pos
, int32_t limit
) const;
139 * Return true if the given character is a matcher standin or a plain
140 * character (non standin).
142 UBool
isMatcher(UChar32 ch
);
145 * Return true if the given character is a replacer standin or a plain
146 * character (non standin).
148 UBool
isReplacer(UChar32 ch
);
151 ParseData(const ParseData
&other
); // forbid copying of this class
152 ParseData
&operator=(const ParseData
&other
); // forbid copying of this class
155 ParseData::ParseData(const TransliterationRuleData
* d
,
156 const UVector
* sets
) :
157 data(d
), variablesVector(sets
) {}
160 * Implement SymbolTable API.
162 const UnicodeString
* ParseData::lookup(const UnicodeString
& name
) const {
163 return (const UnicodeString
*) data
->variableNames
->get(name
);
167 * Implement SymbolTable API.
169 const UnicodeFunctor
* ParseData::lookupMatcher(UChar32 ch
) const {
170 // Note that we cannot use data.lookupSet() because the
171 // set array has not been constructed yet.
172 const UnicodeFunctor
* set
= NULL
;
173 int32_t i
= ch
- data
->variablesBase
;
174 if (i
>= 0 && i
< variablesVector
->size()) {
175 int32_t i
= ch
- data
->variablesBase
;
176 set
= (i
< variablesVector
->size()) ?
177 (UnicodeFunctor
*) variablesVector
->elementAt(i
) : 0;
183 * Implement SymbolTable API. Parse out a symbol reference
186 UnicodeString
ParseData::parseReference(const UnicodeString
& text
,
187 ParsePosition
& pos
, int32_t limit
) const {
188 int32_t start
= pos
.getIndex();
190 UnicodeString result
;
192 UChar c
= text
.charAt(i
);
193 if ((i
==start
&& !u_isIDStart(c
)) || !u_isIDPart(c
)) {
198 if (i
== start
) { // No valid name chars
199 return result
; // Indicate failure with empty string
202 text
.extractBetween(start
, i
, result
);
206 UBool
ParseData::isMatcher(UChar32 ch
) {
207 // Note that we cannot use data.lookup() because the
208 // set array has not been constructed yet.
209 int32_t i
= ch
- data
->variablesBase
;
210 if (i
>= 0 && i
< variablesVector
->size()) {
211 UnicodeFunctor
*f
= (UnicodeFunctor
*) variablesVector
->elementAt(i
);
212 return f
!= NULL
&& f
->toMatcher() != NULL
;
218 * Return true if the given character is a replacer standin or a plain
219 * character (non standin).
221 UBool
ParseData::isReplacer(UChar32 ch
) {
222 // Note that we cannot use data.lookup() because the
223 // set array has not been constructed yet.
224 int i
= ch
- data
->variablesBase
;
225 if (i
>= 0 && i
< variablesVector
->size()) {
226 UnicodeFunctor
*f
= (UnicodeFunctor
*) variablesVector
->elementAt(i
);
227 return f
!= NULL
&& f
->toReplacer() != NULL
;
232 //----------------------------------------------------------------------
234 //----------------------------------------------------------------------
237 * A class representing one side of a rule. This class knows how to
238 * parse half of a rule. It is tightly coupled to the method
239 * RuleBasedTransliterator.Parser.parseRule().
241 class RuleHalf
: public UMemory
{
247 int32_t cursor
; // position of cursor in text
248 int32_t ante
; // position of ante context marker '{' in text
249 int32_t post
; // position of post context marker '}' in text
251 // Record the offset to the cursor either to the left or to the
252 // right of the key. This is indicated by characters on the output
253 // side that allow the cursor to be positioned arbitrarily within
254 // the matching text. For example, abc{def} > | @@@ xyz; changes
255 // def to xyz and moves the cursor to before abc. Offset characters
256 // must be at the start or end, and they cannot move the cursor past
257 // the ante- or postcontext text. Placeholders are only valid in
258 // output text. The length of the ante and post context is
259 // determined at runtime, because of supplementals and quantifiers.
260 int32_t cursorOffset
; // only nonzero on output side
262 // Position of first CURSOR_OFFSET on _right_. This will be -1
263 // for |@, -2 for |@@, etc., and 1 for @|, 2 for @@|, etc.
264 int32_t cursorOffsetPos
;
272 * The segment number from 1..n of the next '(' we see
273 * during parsing; 1-based.
275 int32_t nextSegmentNumber
;
277 TransliteratorParser
& parser
;
279 //--------------------------------------------------
282 RuleHalf(TransliteratorParser
& parser
);
285 int32_t parse(const UnicodeString
& rule
, int32_t pos
, int32_t limit
);
287 int32_t parseSection(const UnicodeString
& rule
, int32_t pos
, int32_t limit
,
289 const UnicodeString
& illegal
,
295 void removeContext();
298 * Return true if this half looks like valid output, that is, does not
299 * contain quantifiers or other special input-only elements.
301 UBool
isValidOutput(TransliteratorParser
& parser
);
304 * Return true if this half looks like valid input, that is, does not
305 * contain functions or other special output-only elements.
307 UBool
isValidInput(TransliteratorParser
& parser
);
309 int syntaxError(UErrorCode code
,
310 const UnicodeString
& rule
,
312 return parser
.syntaxError(code
, rule
, start
);
316 // Disallowed methods; no impl.
317 RuleHalf(const RuleHalf
&);
318 RuleHalf
& operator=(const RuleHalf
&);
321 RuleHalf::RuleHalf(TransliteratorParser
& p
) :
330 anchorStart
= anchorEnd
= FALSE
;
331 nextSegmentNumber
= 1;
334 RuleHalf::~RuleHalf() {
338 * Parse one side of a rule, stopping at either the limit,
339 * the END_OF_RULE character, or an operator.
340 * @return the index after the terminating character, or
341 * if limit was reached, limit
343 int32_t RuleHalf::parse(const UnicodeString
& rule
, int32_t pos
, int32_t limit
) {
346 pos
= parseSection(rule
, pos
, limit
, text
, ILLEGAL_TOP
, FALSE
);
348 if (cursorOffset
> 0 && cursor
!= cursorOffsetPos
) {
349 return syntaxError(U_MISPLACED_CURSOR_OFFSET
, rule
, start
);
356 * Parse a section of one side of a rule, stopping at either
357 * the limit, the END_OF_RULE character, an operator, or a
358 * segment close character. This method parses both a
359 * top-level rule half and a segment within such a rule half.
360 * It calls itself recursively to parse segments and nested
362 * @param buf buffer into which to accumulate the rule pattern
363 * characters, either literal characters from the rule or
364 * standins for UnicodeMatcher objects including segments.
365 * @param illegal the set of special characters that is illegal during
367 * @param isSegment if true, then we've already seen a '(' and
368 * pos on entry points right after it. Accumulate everything
369 * up to the closing ')', put it in a segment matcher object,
370 * generate a standin for it, and add the standin to buf. As
371 * a side effect, update the segments vector with a reference
372 * to the segment matcher. This works recursively for nested
373 * segments. If isSegment is false, just accumulate
374 * characters into buf.
375 * @return the index after the terminating character, or
376 * if limit was reached, limit
378 int32_t RuleHalf::parseSection(const UnicodeString
& rule
, int32_t pos
, int32_t limit
,
380 const UnicodeString
& illegal
,
384 UnicodeString scratch
;
386 int32_t quoteStart
= -1; // Most recent 'single quoted string'
387 int32_t quoteLimit
= -1;
388 int32_t varStart
= -1; // Most recent $variableReference
389 int32_t varLimit
= -1;
390 int32_t bufStart
= buf
.length();
392 while (pos
< limit
&& !done
) {
393 // Since all syntax characters are in the BMP, fetching
394 // 16-bit code units suffices here.
395 UChar c
= rule
.charAt(pos
++);
396 if (uprv_isRuleWhiteSpace(c
)) {
397 // Ignore whitespace. Note that this is not Unicode
398 // spaces, but Java spaces -- a subset, representing
399 // whitespace likely to be seen in code.
402 if (u_strchr(HALF_ENDERS
, c
) != NULL
) {
405 return syntaxError(U_UNCLOSED_SEGMENT
, rule
, start
);
410 // Text after a presumed end anchor is a syntax err
411 return syntaxError(U_MALFORMED_VARIABLE_REFERENCE
, rule
, start
);
413 if (UnicodeSet::resemblesPattern(rule
, pos
-1)) {
414 pp
.setIndex(pos
-1); // Backup to opening '['
415 buf
.append(parser
.parseSet(rule
, pp
));
416 if (U_FAILURE(parser
.status
)) {
417 return syntaxError(U_MALFORMED_SET
, rule
, start
);
425 return syntaxError(U_TRAILING_BACKSLASH
, rule
, start
);
427 UChar32 escaped
= rule
.unescapeAt(pos
); // pos is already past '\\'
428 if (escaped
== (UChar32
) -1) {
429 return syntaxError(U_MALFORMED_UNICODE_ESCAPE
, rule
, start
);
431 if (!parser
.checkVariableRange(escaped
)) {
432 return syntaxError(U_VARIABLE_RANGE_OVERLAP
, rule
, start
);
437 // Handle quoted matter
439 int32_t iq
= rule
.indexOf(QUOTE
, pos
);
441 buf
.append(c
); // Parse [''] outside quotes as [']
444 /* This loop picks up a run of quoted text of the
445 * form 'aaaa' each time through. If this run
446 * hasn't really ended ('aaaa''bbbb') then it keeps
447 * looping, each time adding on a new run. When it
448 * reaches the final quote it breaks.
450 quoteStart
= buf
.length();
453 return syntaxError(U_UNTERMINATED_QUOTE
, rule
, start
);
456 rule
.extractBetween(pos
, iq
, scratch
);
459 if (pos
< limit
&& rule
.charAt(pos
) == QUOTE
) {
460 // Parse [''] inside quotes as [']
461 iq
= rule
.indexOf(QUOTE
, pos
+1);
467 quoteLimit
= buf
.length();
469 for (iq
=quoteStart
; iq
<quoteLimit
; ++iq
) {
470 if (!parser
.checkVariableRange(buf
.charAt(iq
))) {
471 return syntaxError(U_VARIABLE_RANGE_OVERLAP
, rule
, start
);
478 if (!parser
.checkVariableRange(c
)) {
479 return syntaxError(U_VARIABLE_RANGE_OVERLAP
, rule
, start
);
482 if (illegal
.indexOf(c
) >= 0) {
483 syntaxError(U_ILLEGAL_CHARACTER
, rule
, start
);
488 //------------------------------------------------------
489 // Elements allowed within and out of segments
490 //------------------------------------------------------
492 if (buf
.length() == 0 && !anchorStart
) {
495 return syntaxError(U_MISPLACED_ANCHOR_START
,
501 // bufSegStart is the offset in buf to the first
502 // character of the segment we are parsing.
503 int32_t bufSegStart
= buf
.length();
505 // Record segment number now, since nextSegmentNumber
506 // will be incremented during the call to parseSection
507 // if there are nested segments.
508 int32_t segmentNumber
= nextSegmentNumber
++; // 1-based
511 pos
= parseSection(rule
, pos
, limit
, buf
, ILLEGAL_SEG
, TRUE
);
513 // After parsing a segment, the relevant characters are
514 // in buf, starting at offset bufSegStart. Extract them
515 // into a string matcher, and replace them with a
516 // standin for that matcher.
518 new StringMatcher(buf
, bufSegStart
, buf
.length(),
519 segmentNumber
, *parser
.data
);
521 // Record and associate object and segment number
522 parser
.setSegmentObject(segmentNumber
, m
);
523 buf
.truncate(bufSegStart
);
524 buf
.append(parser
.getSegmentStandin(segmentNumber
));
531 TransliteratorIDParser::SingleID
* single
=
532 TransliteratorIDParser::parseFilterID(rule
, iref
);
533 // The next character MUST be a segment open
534 if (single
== NULL
||
535 !ICU_Utility::parseChar(rule
, iref
, SEGMENT_OPEN
)) {
536 return syntaxError(U_INVALID_FUNCTION
, rule
, start
);
539 Transliterator
*t
= single
->createInstance();
542 return syntaxError(U_INVALID_FUNCTION
, rule
, start
);
545 // bufSegStart is the offset in buf to the first
546 // character of the segment we are parsing.
547 int32_t bufSegStart
= buf
.length();
550 pos
= parseSection(rule
, iref
, limit
, buf
, ILLEGAL_FUNC
, TRUE
);
552 // After parsing a segment, the relevant characters are
553 // in buf, starting at offset bufSegStart.
554 UnicodeString output
;
555 buf
.extractBetween(bufSegStart
, buf
.length(), output
);
556 FunctionReplacer
*r
=
557 new FunctionReplacer(t
, new StringReplacer(output
, parser
.data
));
559 // Replace the buffer contents with a stand-in
560 buf
.truncate(bufSegStart
);
561 buf
.append(parser
.generateStandInFor(r
));
564 case SymbolTable::SYMBOL_REF
:
565 // Handle variable references and segment references "$1" .. "$9"
567 // A variable reference must be followed immediately
568 // by a Unicode identifier start and zero or more
569 // Unicode identifier part characters, or by a digit
570 // 1..9 if it is a segment reference.
572 // A variable ref character at the end acts as
573 // an anchor to the context limit, as in perl.
577 // Parse "$1" "$2" .. "$9" .. (no upper limit)
578 c
= rule
.charAt(pos
);
579 int32_t r
= u_digit(c
, 10);
580 if (r
>= 1 && r
<= 9) {
581 r
= ICU_Utility::parseNumber(rule
, pos
, 10);
583 return syntaxError(U_UNDEFINED_SEGMENT_REFERENCE
,
586 buf
.append(parser
.getSegmentStandin(r
));
589 UnicodeString name
= parser
.parseData
->
590 parseReference(rule
, pp
, limit
);
591 if (name
.length() == 0) {
592 // This means the '$' was not followed by a
593 // valid name. Try to interpret it as an
594 // end anchor then. If this also doesn't work
595 // (if we see a following character) then signal
601 // If this is a variable definition statement,
602 // then the LHS variable will be undefined. In
603 // that case appendVariableDef() will append the
604 // special placeholder char variableLimit-1.
605 varStart
= buf
.length();
606 parser
.appendVariableDef(name
, buf
);
607 varLimit
= buf
.length();
612 buf
.append(parser
.getDotStandIn());
617 // Quantifiers. We handle single characters, quoted strings,
618 // variable references, and segments.
620 // 'foo'+ matches foofoofoo
621 // $v+ matches xyxyxy if $v == xy
622 // (seg)+ matches segsegseg
624 if (isSegment
&& buf
.length() == bufStart
) {
625 // The */+ immediately follows '('
626 return syntaxError(U_MISPLACED_QUANTIFIER
, rule
, start
);
629 int32_t qstart
, qlimit
;
630 // The */+ follows an isolated character or quote
631 // or variable reference
632 if (buf
.length() == quoteLimit
) {
633 // The */+ follows a 'quoted string'
636 } else if (buf
.length() == varLimit
) {
637 // The */+ follows a $variableReference
641 // The */+ follows a single character, possibly
643 qstart
= buf
.length() - 1;
648 new StringMatcher(buf
, qstart
, qlimit
, 0, *parser
.data
);
650 int32_t max
= Quantifier::MAX
;
660 // do nothing -- min, max already set
662 m
= new Quantifier(m
, min
, max
);
663 buf
.truncate(qstart
);
664 buf
.append(parser
.generateStandInFor(m
));
668 //------------------------------------------------------
669 // Elements allowed ONLY WITHIN segments
670 //------------------------------------------------------
672 // assert(isSegment);
673 // We're done parsing a segment.
677 //------------------------------------------------------
678 // Elements allowed ONLY OUTSIDE segments
679 //------------------------------------------------------
682 return syntaxError(U_MULTIPLE_ANTE_CONTEXTS
, rule
, start
);
688 return syntaxError(U_MULTIPLE_POST_CONTEXTS
, rule
, start
);
694 return syntaxError(U_MULTIPLE_CURSORS
, rule
, start
);
696 cursor
= buf
.length();
699 if (cursorOffset
< 0) {
700 if (buf
.length() > 0) {
701 return syntaxError(U_MISPLACED_CURSOR_OFFSET
, rule
, start
);
704 } else if (cursorOffset
> 0) {
705 if (buf
.length() != cursorOffsetPos
|| cursor
>= 0) {
706 return syntaxError(U_MISPLACED_CURSOR_OFFSET
, rule
, start
);
710 if (cursor
== 0 && buf
.length() == 0) {
712 } else if (cursor
< 0) {
713 cursorOffsetPos
= buf
.length();
716 return syntaxError(U_MISPLACED_CURSOR_OFFSET
, rule
, start
);
722 //------------------------------------------------------
723 // Non-special characters
724 //------------------------------------------------------
726 // Disallow unquoted characters other than [0-9A-Za-z]
727 // in the printable ASCII range. These characters are
728 // reserved for possible future use.
729 if (c
>= 0x0021 && c
<= 0x007E &&
730 !((c
>= 0x0030/*'0'*/ && c
<= 0x0039/*'9'*/) ||
731 (c
>= 0x0041/*'A'*/ && c
<= 0x005A/*'Z'*/) ||
732 (c
>= 0x0061/*'a'*/ && c
<= 0x007A/*'z'*/))) {
733 return syntaxError(U_UNQUOTED_SPECIAL
, rule
, start
);
746 void RuleHalf::removeContext() {
747 //text = text.substring(ante < 0 ? 0 : ante,
748 // post < 0 ? text.length() : post);
753 text
.removeBetween(0, ante
);
756 anchorStart
= anchorEnd
= FALSE
;
760 * Return true if this half looks like valid output, that is, does not
761 * contain quantifiers or other special input-only elements.
763 UBool
RuleHalf::isValidOutput(TransliteratorParser
& transParser
) {
764 for (int32_t i
=0; i
<text
.length(); ) {
765 UChar32 c
= text
.char32At(i
);
766 i
+= UTF_CHAR_LENGTH(c
);
767 if (!transParser
.parseData
->isReplacer(c
)) {
775 * Return true if this half looks like valid input, that is, does not
776 * contain functions or other special output-only elements.
778 UBool
RuleHalf::isValidInput(TransliteratorParser
& transParser
) {
779 for (int32_t i
=0; i
<text
.length(); ) {
780 UChar32 c
= text
.char32At(i
);
781 i
+= UTF_CHAR_LENGTH(c
);
782 if (!transParser
.parseData
->isMatcher(c
)) {
789 //----------------------------------------------------------------------
791 //----------------------------------------------------------------------
796 TransliteratorParser::TransliteratorParser() {
798 compoundFilter
= NULL
;
800 variablesVector
= NULL
;
801 segmentObjects
= NULL
;
807 TransliteratorParser::~TransliteratorParser() {
809 delete compoundFilter
;
811 delete variablesVector
;
812 delete segmentObjects
;
816 TransliteratorParser::parse(const UnicodeString
& rules
,
817 UTransDirection transDirection
,
821 parseRules(rules
, transDirection
);
828 * Return the compound filter parsed by parse(). Caller owns result.
830 UnicodeSet
* TransliteratorParser::orphanCompoundFilter() {
831 UnicodeSet
* f
= compoundFilter
;
832 compoundFilter
= NULL
;
837 * Return the data object parsed by parse(). Caller owns result.
839 TransliterationRuleData
* TransliteratorParser::orphanData() {
840 TransliterationRuleData
* d
= data
;
845 //----------------------------------------------------------------------
846 // Private implementation
847 //----------------------------------------------------------------------
850 * Parse the given string as a sequence of rules, separated by newline
851 * characters ('\n'), and cause this object to implement those rules. Any
852 * previous rules are discarded. Typically this method is called exactly
853 * once, during construction.
854 * @exception IllegalArgumentException if there is a syntax error in the
857 void TransliteratorParser::parseRules(const UnicodeString
& rule
,
858 UTransDirection theDirection
) {
859 // Clear error struct
860 parseError
.line
= parseError
.offset
= -1;
861 parseError
.preContext
[0] = parseError
.postContext
[0] = (UChar
)0;
862 status
= U_ZERO_ERROR
;
865 data
= new TransliterationRuleData(status
);
866 if (U_FAILURE(status
)) {
870 direction
= theDirection
;
873 delete compoundFilter
;
874 compoundFilter
= NULL
;
876 if (variablesVector
== NULL
) {
877 variablesVector
= new UVector(status
);
879 variablesVector
->removeAllElements();
881 parseData
= new ParseData(0, variablesVector
);
882 if (parseData
== NULL
) {
883 status
= U_MEMORY_ALLOCATION_ERROR
;
886 parseData
->data
= data
;
888 // By default, rules use part of the private use area
889 // E000..F8FF for variables and other stand-ins. Currently
890 // the range F000..F8FF is typically sufficient. The 'use
891 // variable range' pragma allows rule sets to modify this.
892 setVariableRange(0xF000, 0xF8FF);
894 dotStandIn
= (UChar
) -1;
896 UnicodeString str
; // scratch
900 int32_t limit
= rule
.length();
901 // The mode marks whether we are in the header ::id block, the
902 // rule block, or the footer ::id block.
903 // mode == 0: start: rule->1, ::id->0
904 // mode == 1: in rules: rule->1, ::id->2
905 // mode == 2: in footer rule block: rule->ERROR, ::id->2
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;
916 // The number of ::ID block entries we have parsed
917 int32_t idBlockCount
= 0;
919 while (pos
< limit
&& U_SUCCESS(status
)) {
920 UChar c
= rule
.charAt(pos
++);
921 if (uprv_isRuleWhiteSpace(c
)) {
922 // Ignore leading whitespace.
925 // Skip lines starting with the comment character
926 if (c
== RULE_COMMENT_CHAR
) {
927 pos
= rule
.indexOf((UChar
)0x000A /*\n*/, pos
) + 1;
929 break; // No "\n" found; rest of rule is a commnet
931 continue; // Either fall out or restart with next line
933 // We've found the start of a rule or ID. c is its first
934 // character, and pos points past c.
936 // Look for an ID token. Must have at least ID_TOKEN_LEN + 1
938 if ((pos
+ ID_TOKEN_LEN
+ 1) <= limit
&&
939 rule
.compare(pos
, ID_TOKEN_LEN
, ID_TOKEN
) == 0) {
941 c
= rule
.charAt(pos
);
942 while (uprv_isRuleWhiteSpace(c
) && pos
< limit
) {
944 c
= rule
.charAt(pos
);
948 // We have just entered the footer ::ID block
950 // In the forward direction add elements at the end.
951 // In the reverse direction add elements at the start.
952 idSplitPoint
= idBlockCount
;
956 TransliteratorIDParser::SingleID
* id
=
957 TransliteratorIDParser::parseSingleID(rule
, p
, direction
, status
);
958 if (p
!= pos
&& ICU_Utility::parseChar(rule
, p
, END_OF_RULE
)) {
959 // Successful ::ID parse.
961 if (direction
== UTRANS_FORWARD
) {
962 idBlock
.append(id
->canonID
).append(END_OF_RULE
);
964 idBlock
.insert(0, END_OF_RULE
);
965 idBlock
.insert(0, id
->canonID
);
971 // Couldn't parse an ID. Try to parse a global filter
972 int32_t withParens
= -1;
973 UnicodeSet
* f
= TransliteratorIDParser::parseGlobalFilter(rule
, p
, direction
, withParens
, &idBlock
);
975 if (ICU_Utility::parseChar(rule
, p
, END_OF_RULE
)
976 && (direction
== UTRANS_FORWARD
) == (withParens
== 0))
978 if (compoundFilter
!= NULL
) {
979 // Multiple compound filters
980 syntaxError(U_MULTIPLE_COMPOUND_FILTERS
, rule
, pos
);
984 compoundFilterOffset
= idBlockCount
;
991 // Can be parsed as neither an ID nor a global filter
992 syntaxError(U_INVALID_ID
, rule
, pos
);
998 } else if (resemblesPragma(rule
, pos
, limit
)) {
999 int32_t ppp
= parsePragma(rule
, pos
, limit
);
1001 syntaxError(U_MALFORMED_PRAGMA
, rule
, pos
);
1006 pos
= parseRule(rule
, pos
, limit
);
1007 if (U_SUCCESS(status
)) {
1010 // ::id in illegal position (because a rule
1011 // occurred after the ::id footer block)
1012 syntaxError(U_ILLEGAL_ARGUMENT_ERROR
,rule
,pos
);
1015 syntaxError(status
,rule
,pos
);
1021 if (idSplitPoint
< 0) {
1022 idSplitPoint
= idBlockCount
;
1025 if (direction
== UTRANS_REVERSE
) {
1026 idSplitPoint
= idBlockCount
- idSplitPoint
;
1029 // Convert the set vector to an array
1030 data
->variablesLength
= variablesVector
->size();
1031 if(data
->variablesLength
== 0) {
1032 data
->variables
= 0;
1034 data
->variables
= (UnicodeFunctor
**)uprv_malloc(data
->variablesLength
* sizeof(UnicodeFunctor
*));
1037 // orphanElement removes the given element and shifts all other
1038 // elements down. For performance (and code clarity) we work from
1039 // the end back to index 0.
1041 for (i
=data
->variablesLength
; i
>0; ) {
1043 data
->variables
[i
] =
1044 (UnicodeSet
*) variablesVector
->orphanElementAt(i
);
1048 if (U_SUCCESS(status
)) {
1049 if (compoundFilter
!= NULL
) {
1050 if ((direction
== UTRANS_FORWARD
&&
1051 compoundFilterOffset
!= 0) ||
1052 (direction
== UTRANS_REVERSE
&&
1053 compoundFilterOffset
!= idBlockCount
)) {
1054 status
= U_MISPLACED_COMPOUND_FILTER
;
1058 data
->ruleSet
.freeze(parseError
,status
);
1060 if (idSplitPoint
< 0) {
1061 idSplitPoint
= idBlock
.length();
1064 if (ruleCount
== 0) {
1072 * Set the variable range to [start, end] (inclusive).
1074 void TransliteratorParser::setVariableRange(int32_t start
, int32_t end
) {
1075 if (start
> end
|| start
< 0 || end
> 0xFFFF) {
1076 status
= U_MALFORMED_PRAGMA
;
1080 data
->variablesBase
= variableNext
= (UChar
) start
; // first private use
1081 variableLimit
= (UChar
) (end
+ 1);
1085 * Assert that the given character is NOT within the variable range.
1086 * If it is, return FALSE. This is neccesary to ensure that the
1087 * variable range does not overlap characters used in a rule.
1089 UBool
TransliteratorParser::checkVariableRange(UChar32 ch
) const {
1090 return !(ch
>= data
->variablesBase
&& ch
< variableLimit
);
1094 * Set the maximum backup to 'backup', in response to a pragma
1097 void TransliteratorParser::pragmaMaximumBackup(int32_t /*backup*/) {
1102 * Begin normalizing all rules using the given mode, in response
1103 * to a pragma statement.
1105 void TransliteratorParser::pragmaNormalizeRules(UNormalizationMode
/*mode*/) {
1109 static const UChar PRAGMA_USE
[] = {0x75,0x73,0x65,0x20,0}; // "use "
1111 static const UChar PRAGMA_VARIABLE_RANGE
[] = {0x7E,0x76,0x61,0x72,0x69,0x61,0x62,0x6C,0x65,0x20,0x72,0x61,0x6E,0x67,0x65,0x20,0x23,0x20,0x23,0x7E,0x3B,0}; // "~variable range # #~;"
1113 static const UChar PRAGMA_MAXIMUM_BACKUP
[] = {0x7E,0x6D,0x61,0x78,0x69,0x6D,0x75,0x6D,0x20,0x62,0x61,0x63,0x6B,0x75,0x70,0x20,0x23,0x7E,0x3B,0}; // "~maximum backup #~;"
1115 static const UChar PRAGMA_NFD_RULES
[] = {0x7E,0x6E,0x66,0x64,0x20,0x72,0x75,0x6C,0x65,0x73,0x7E,0x3B,0}; // "~nfd rules~;"
1117 static const UChar PRAGMA_NFC_RULES
[] = {0x7E,0x6E,0x66,0x63,0x20,0x72,0x75,0x6C,0x65,0x73,0x7E,0x3B,0}; // "~nfc rules~;"
1120 * Return true if the given rule looks like a pragma.
1121 * @param pos offset to the first non-whitespace character
1123 * @param limit pointer past the last character of the rule.
1125 UBool
TransliteratorParser::resemblesPragma(const UnicodeString
& rule
, int32_t pos
, int32_t limit
) {
1126 // Must start with /use\s/i
1127 return ICU_Utility::parsePattern(rule
, pos
, limit
, PRAGMA_USE
, NULL
) >= 0;
1131 * Parse a pragma. This method assumes resemblesPragma() has
1132 * already returned true.
1133 * @param pos offset to the first non-whitespace character
1135 * @param limit pointer past the last character of the rule.
1136 * @return the position index after the final ';' of the pragma,
1139 int32_t TransliteratorParser::parsePragma(const UnicodeString
& rule
, int32_t pos
, int32_t limit
) {
1142 // resemblesPragma() has already returned true, so we
1143 // know that pos points to /use\s/i; we can skip 4 characters
1147 // Here are the pragmas we recognize:
1148 // use variable range 0xE000 0xEFFF;
1149 // use maximum backup 16;
1152 int p
= ICU_Utility::parsePattern(rule
, pos
, limit
, PRAGMA_VARIABLE_RANGE
, array
);
1154 setVariableRange(array
[0], array
[1]);
1158 p
= ICU_Utility::parsePattern(rule
, pos
, limit
, PRAGMA_MAXIMUM_BACKUP
, array
);
1160 pragmaMaximumBackup(array
[0]);
1164 p
= ICU_Utility::parsePattern(rule
, pos
, limit
, PRAGMA_NFD_RULES
, NULL
);
1166 pragmaNormalizeRules(UNORM_NFD
);
1170 p
= ICU_Utility::parsePattern(rule
, pos
, limit
, PRAGMA_NFC_RULES
, NULL
);
1172 pragmaNormalizeRules(UNORM_NFC
);
1176 // Syntax error: unable to parse pragma
1181 * MAIN PARSER. Parse the next rule in the given rule string, starting
1182 * at pos. Return the index after the last character parsed. Do not
1183 * parse characters at or after limit.
1185 * Important: The character at pos must be a non-whitespace character
1186 * that is not the comment character.
1188 * This method handles quoting, escaping, and whitespace removal. It
1189 * parses the end-of-rule character. It recognizes context and cursor
1190 * indicators. Once it does a lexical breakdown of the rule at pos, it
1191 * creates a rule object and adds it to our rule list.
1193 int32_t TransliteratorParser::parseRule(const UnicodeString
& rule
, int32_t pos
, int32_t limit
) {
1194 // Locate the left side, operator, and right side
1195 int32_t start
= pos
;
1199 // Set up segments data
1200 segmentStandins
.truncate(0);
1201 if (segmentObjects
== NULL
) {
1202 segmentObjects
= new UVector(status
);
1204 segmentObjects
->removeAllElements();
1207 // Use pointers to automatics to make swapping possible.
1208 RuleHalf
_left(*this), _right(*this);
1209 RuleHalf
* left
= &_left
;
1210 RuleHalf
* right
= &_right
;
1212 undefinedVariableName
.remove();
1213 pos
= left
->parse(rule
, pos
, limit
);
1214 if (U_FAILURE(status
)) {
1218 if (pos
== limit
|| u_strchr(gOPERATORS
, (op
= rule
.charAt(--pos
))) == NULL
) {
1219 return syntaxError(U_MISSING_OPERATOR
, rule
, start
);
1223 // Found an operator char. Check for forward-reverse operator.
1224 if (op
== REVERSE_RULE_OP
&&
1225 (pos
< limit
&& rule
.charAt(pos
) == FORWARD_RULE_OP
)) {
1227 op
= FWDREV_RULE_OP
;
1230 // Translate alternate op characters.
1232 case ALT_FORWARD_RULE_OP
:
1233 op
= FORWARD_RULE_OP
;
1235 case ALT_REVERSE_RULE_OP
:
1236 op
= REVERSE_RULE_OP
;
1238 case ALT_FWDREV_RULE_OP
:
1239 op
= FWDREV_RULE_OP
;
1243 pos
= right
->parse(rule
, pos
, limit
);
1244 if (U_FAILURE(status
)) {
1249 if (rule
.charAt(--pos
) == END_OF_RULE
) {
1252 // RuleHalf parser must have terminated at an operator
1253 return syntaxError(U_UNQUOTED_SPECIAL
, rule
, start
);
1257 if (op
== VARIABLE_DEF_OP
) {
1258 // LHS is the name. RHS is a single character, either a literal
1259 // or a set (already parsed). If RHS is longer than one
1260 // character, it is either a multi-character string, or multiple
1261 // sets, or a mixture of chars and sets -- syntax error.
1263 // We expect to see a single undefined variable (the one being
1265 if (undefinedVariableName
.length() == 0) {
1266 // "Missing '$' or duplicate definition"
1267 return syntaxError(U_BAD_VARIABLE_DEFINITION
, rule
, start
);
1269 if (left
->text
.length() != 1 || left
->text
.charAt(0) != variableLimit
) {
1271 return syntaxError(U_MALFORMED_VARIABLE_DEFINITION
, rule
, start
);
1273 if (left
->anchorStart
|| left
->anchorEnd
||
1274 right
->anchorStart
|| right
->anchorEnd
) {
1275 return syntaxError(U_MALFORMED_VARIABLE_DEFINITION
, rule
, start
);
1277 // We allow anything on the right, including an empty string.
1278 UnicodeString
* value
= new UnicodeString(right
->text
);
1279 data
->variableNames
->put(undefinedVariableName
, value
, status
);
1284 // If this is not a variable definition rule, we shouldn't have
1285 // any undefined variable names.
1286 if (undefinedVariableName
.length() != 0) {
1287 return syntaxError(// "Undefined variable $" + undefinedVariableName,
1288 U_UNDEFINED_VARIABLE
,
1293 if (segmentStandins
.length() > segmentObjects
->size()) {
1294 syntaxError(U_UNDEFINED_SEGMENT_REFERENCE
, rule
, start
);
1296 for (i
=0; i
<segmentStandins
.length(); ++i
) {
1297 if (segmentStandins
.charAt(i
) == 0) {
1298 syntaxError(U_INTERNAL_TRANSLITERATOR_ERROR
, rule
, start
); // will never happen
1301 for (i
=0; i
<segmentObjects
->size(); ++i
) {
1302 if (segmentObjects
->elementAt(i
) == NULL
) {
1303 syntaxError(U_INTERNAL_TRANSLITERATOR_ERROR
, rule
, start
); // will never happen
1307 // If the direction we want doesn't match the rule
1308 // direction, do nothing.
1309 if (op
!= FWDREV_RULE_OP
&&
1310 ((direction
== UTRANS_FORWARD
) != (op
== FORWARD_RULE_OP
))) {
1314 // Transform the rule into a forward rule by swapping the
1315 // sides if necessary.
1316 if (direction
== UTRANS_REVERSE
) {
1321 // Remove non-applicable elements in forward-reverse
1322 // rules. Bidirectional rules ignore elements that do not
1324 if (op
== FWDREV_RULE_OP
) {
1325 right
->removeContext();
1327 left
->cursorOffset
= 0;
1330 // Normalize context
1331 if (left
->ante
< 0) {
1334 if (left
->post
< 0) {
1335 left
->post
= left
->text
.length();
1338 // Context is only allowed on the input side. Cursors are only
1339 // allowed on the output side. Segment delimiters can only appear
1340 // on the left, and references on the right. Cursor offset
1341 // cannot appear without an explicit cursor. Cursor offset
1342 // cannot place the cursor outside the limits of the context.
1343 // Anchors are only allowed on the input side.
1344 if (right
->ante
>= 0 || right
->post
>= 0 || left
->cursor
>= 0 ||
1345 (right
->cursorOffset
!= 0 && right
->cursor
< 0) ||
1346 // - The following two checks were used to ensure that the
1347 // - the cursor offset stayed within the ante- or postcontext.
1348 // - However, with the addition of quantifiers, we have to
1349 // - allow arbitrary cursor offsets and do runtime checking.
1350 //(right->cursorOffset > (left->text.length() - left->post)) ||
1351 //(-right->cursorOffset > left->ante) ||
1352 right
->anchorStart
|| right
->anchorEnd
||
1353 !left
->isValidInput(*this) || !right
->isValidOutput(*this) ||
1354 left
->ante
> left
->post
) {
1356 return syntaxError(U_MALFORMED_RULE
, rule
, start
);
1359 // Flatten segment objects vector to an array
1360 UnicodeFunctor
** segmentsArray
= NULL
;
1361 if (segmentObjects
->size() > 0) {
1362 segmentsArray
= (UnicodeFunctor
**)uprv_malloc(segmentObjects
->size() * sizeof(UnicodeFunctor
*));
1363 segmentObjects
->toArray((void**) segmentsArray
);
1366 data
->ruleSet
.addRule(new TransliterationRule(
1367 left
->text
, left
->ante
, left
->post
,
1368 right
->text
, right
->cursor
, right
->cursorOffset
,
1370 segmentObjects
->size(),
1371 left
->anchorStart
, left
->anchorEnd
,
1379 * Called by main parser upon syntax error. Search the rule string
1380 * for the probable end of the rule. Of course, if the error is that
1381 * the end of rule marker is missing, then the rule end will not be found.
1382 * In any case the rule start will be correctly reported.
1383 * @param msg error description
1384 * @param rule pattern string
1385 * @param start position of first character of current rule
1387 int32_t TransliteratorParser::syntaxError(UErrorCode parseErrorCode
,
1388 const UnicodeString
& rule
,
1390 parseError
.offset
= pos
;
1391 parseError
.line
= 0 ; /* we are not using line numbers */
1394 const int32_t LEN
= U_PARSE_CONTEXT_LEN
- 1;
1395 int32_t start
= uprv_max(pos
- LEN
, 0);
1398 rule
.extract(start
,stop
-start
,parseError
.preContext
);
1399 //null terminate the buffer
1400 parseError
.preContext
[stop
-start
] = 0;
1404 stop
= uprv_min(pos
+ LEN
, rule
.length());
1406 rule
.extract(start
,stop
-start
,parseError
.postContext
);
1407 //null terminate the buffer
1408 parseError
.postContext
[stop
-start
]= 0;
1410 status
= (UErrorCode
)parseErrorCode
;
1416 * Parse a UnicodeSet out, store it, and return the stand-in character
1417 * used to represent it.
1419 UChar
TransliteratorParser::parseSet(const UnicodeString
& rule
,
1420 ParsePosition
& pos
) {
1421 UnicodeSet
* set
= new UnicodeSet(rule
, pos
, USET_IGNORE_SPACE
, parseData
, status
);
1423 return generateStandInFor(set
);
1427 * Generate and return a stand-in for a new UnicodeFunctor. Store
1428 * the matcher (adopt it).
1430 UChar
TransliteratorParser::generateStandInFor(UnicodeFunctor
* adopted
) {
1431 // assert(obj != null);
1433 // Look up previous stand-in, if any. This is a short list
1434 // (typical n is 0, 1, or 2); linear search is optimal.
1435 for (int32_t i
=0; i
<variablesVector
->size(); ++i
) {
1436 if (variablesVector
->elementAt(i
) == adopted
) { // [sic] pointer comparison
1437 return (UChar
) (data
->variablesBase
+ i
);
1441 if (variableNext
>= variableLimit
) {
1443 status
= U_VARIABLE_RANGE_EXHAUSTED
;
1446 variablesVector
->addElement(adopted
, status
);
1447 return variableNext
++;
1451 * Return the standin for segment seg (1-based).
1453 UChar
TransliteratorParser::getSegmentStandin(int32_t seg
) {
1454 // Special character used to indicate an empty spot
1455 UChar empty
= data
->variablesBase
- 1;
1456 while (segmentStandins
.length() < seg
) {
1457 segmentStandins
.append(empty
);
1459 UChar c
= segmentStandins
.charAt(seg
-1);
1461 if (variableNext
>= variableLimit
) {
1462 status
= U_VARIABLE_RANGE_EXHAUSTED
;
1466 // Set a placeholder in the master variables vector that will be
1467 // filled in later by setSegmentObject(). We know that we will get
1468 // called first because setSegmentObject() will call us.
1469 variablesVector
->addElement((void*) NULL
, status
);
1470 segmentStandins
.setCharAt(seg
-1, c
);
1476 * Set the object for segment seg (1-based).
1478 void TransliteratorParser::setSegmentObject(int32_t seg
, StringMatcher
* adopted
) {
1479 // Since we call parseSection() recursively, nested
1480 // segments will result in segment i+1 getting parsed
1481 // and stored before segment i; be careful with the
1482 // vector handling here.
1483 if (segmentObjects
->size() < seg
) {
1484 segmentObjects
->setSize(seg
);
1486 int32_t index
= getSegmentStandin(seg
) - data
->variablesBase
;
1487 if (segmentObjects
->elementAt(seg
-1) != NULL
||
1488 variablesVector
->elementAt(index
) != NULL
) {
1489 // should never happen
1490 status
= U_INTERNAL_TRANSLITERATOR_ERROR
;
1493 segmentObjects
->setElementAt(adopted
, seg
-1);
1494 variablesVector
->setElementAt(adopted
, index
);
1498 * Return the stand-in for the dot set. It is allocated the first
1499 * time and reused thereafter.
1501 UChar
TransliteratorParser::getDotStandIn() {
1502 if (dotStandIn
== (UChar
) -1) {
1503 dotStandIn
= generateStandInFor(new UnicodeSet(DOT_SET
, status
));
1509 * Append the value of the given variable name to the given
1512 void TransliteratorParser::appendVariableDef(const UnicodeString
& name
,
1513 UnicodeString
& buf
) {
1514 const UnicodeString
* s
= (const UnicodeString
*) data
->variableNames
->get(name
);
1516 // We allow one undefined variable so that variable definition
1517 // statements work. For the first undefined variable we return
1518 // the special placeholder variableLimit-1, and save the variable
1520 if (undefinedVariableName
.length() == 0) {
1521 undefinedVariableName
= name
;
1522 if (variableNext
>= variableLimit
) {
1523 // throw new RuntimeException("Private use variables exhausted");
1524 status
= U_ILLEGAL_ARGUMENT_ERROR
;
1527 buf
.append((UChar
) --variableLimit
);
1529 //throw new IllegalArgumentException("Undefined variable $"
1531 status
= U_ILLEGAL_ARGUMENT_ERROR
;
1540 * Glue method to get around access restrictions in C++.
1542 Transliterator
* TransliteratorParser::createBasicInstance(const UnicodeString
& id
, const UnicodeString
* canonID
) {
1543 return Transliterator::createBasicInstance(id
, canonID
);
1548 #endif /* #if !UCONFIG_NO_TRANSLITERATION */