2 ******************************************************************************
3 * Copyright (C) 1997-2004, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 ******************************************************************************
6 * file name: nfrule.cpp
8 * tab size: 8 (not used)
11 * Modification history
13 * 10/11/2001 Doug Ported from ICU4J
20 #include "unicode/rbnf.h"
21 #include "unicode/tblcoll.h"
22 #include "unicode/coleitr.h"
23 #include "unicode/uchar.h"
32 extern const UChar
* CSleftBracket
;
33 extern const UChar
* CSrightBracket
;
35 NFRule::NFRule(const RuleBasedNumberFormat
* _rbnf
)
36 : baseValue((int32_t)0)
52 static const UChar gLeftBracket
= 0x005b;
53 static const UChar gRightBracket
= 0x005d;
54 static const UChar gColon
= 0x003a;
55 static const UChar gZero
= 0x0030;
56 static const UChar gNine
= 0x0039;
57 static const UChar gSpace
= 0x0020;
58 static const UChar gSlash
= 0x002f;
59 static const UChar gGreaterThan
= 0x003e;
60 static const UChar gComma
= 0x002c;
61 static const UChar gDot
= 0x002e;
62 static const UChar gTick
= 0x0027;
63 static const UChar gMinus
= 0x002d;
64 static const UChar gSemicolon
= 0x003b;
66 static const UChar gMinusX
[] = {0x2D, 0x78, 0}; /* "-x" */
67 static const UChar gXDotX
[] = {0x78, 0x2E, 0x78, 0}; /* "x.x" */
68 static const UChar gXDotZero
[] = {0x78, 0x2E, 0x30, 0}; /* "x.0" */
69 static const UChar gZeroDotX
[] = {0x30, 0x2E, 0x78, 0}; /* "0.x" */
71 static const UChar gLessLess
[] = {0x3C, 0x3C, 0}; /* "<<" */
72 static const UChar gLessPercent
[] = {0x3C, 0x25, 0}; /* "<%" */
73 static const UChar gLessHash
[] = {0x3C, 0x23, 0}; /* "<#" */
74 static const UChar gLessZero
[] = {0x3C, 0x30, 0}; /* "<0" */
75 static const UChar gGreaterGreater
[] = {0x3E, 0x3E, 0}; /* ">>" */
76 static const UChar gGreaterPercent
[] = {0x3E, 0x25, 0}; /* ">%" */
77 static const UChar gGreaterHash
[] = {0x3E, 0x23, 0}; /* ">#" */
78 static const UChar gGreaterZero
[] = {0x3E, 0x30, 0}; /* ">0" */
79 static const UChar gEqualPercent
[] = {0x3D, 0x25, 0}; /* "=%" */
80 static const UChar gEqualHash
[] = {0x3D, 0x23, 0}; /* "=#" */
81 static const UChar gEqualZero
[] = {0x3D, 0x30, 0}; /* "=0" */
82 static const UChar gEmptyString
[] = {0}; /* "" */
83 static const UChar gGreaterGreaterGreater
[] = {0x3E, 0x3E, 0x3E, 0}; /* ">>>" */
85 static const UChar
* const tokenStrings
[] = {
86 gLessLess
, gLessPercent
, gLessHash
, gLessZero
,
87 gGreaterGreater
, gGreaterPercent
,gGreaterHash
, gGreaterZero
,
88 gEqualPercent
, gEqualHash
, gEqualZero
, NULL
92 NFRule::makeRules(UnicodeString
& description
,
93 const NFRuleSet
*ruleSet
,
94 const NFRule
*predecessor
,
95 const RuleBasedNumberFormat
*rbnf
,
99 // we know we're making at least one rule, so go ahead and
100 // new it up and initialize its basevalue and divisor
101 // (this also strips the rule descriptor, if any, off the
102 // descripton string)
103 NFRule
* rule1
= new NFRule(rbnf
);
106 status
= U_MEMORY_ALLOCATION_ERROR
;
109 rule1
->parseRuleDescriptor(description
, status
);
111 // check the description to see whether there's text enclosed
113 int32_t brack1
= description
.indexOf(gLeftBracket
);
114 int32_t brack2
= description
.indexOf(gRightBracket
);
116 // if the description doesn't contain a matched pair of brackets,
117 // or if it's of a type that doesn't recognize bracketed text,
118 // then leave the description alone, initialize the rule's
119 // rule text and substitutions, and return that rule
120 if (brack1
== -1 || brack2
== -1 || brack1
> brack2
121 || rule1
->getType() == kProperFractionRule
122 || rule1
->getType() == kNegativeNumberRule
) {
123 rule1
->ruleText
= description
;
124 rule1
->extractSubstitutions(ruleSet
, predecessor
, rbnf
, status
);
127 // if the description does contain a matched pair of brackets,
128 // then it's really shorthand for two rules (with one exception)
129 NFRule
* rule2
= NULL
;
132 // we'll actually only split the rule into two rules if its
133 // base value is an even multiple of its divisor (or it's one
134 // of the special rules)
135 if ((rule1
->baseValue
> 0
136 && (rule1
->baseValue
% util64_pow(rule1
->radix
, rule1
->exponent
)) == 0)
137 || rule1
->getType() == kImproperFractionRule
138 || rule1
->getType() == kMasterRule
) {
140 // if it passes that test, new up the second rule. If the
141 // rule set both rules will belong to is a fraction rule
142 // set, they both have the same base value; otherwise,
143 // increment the original rule's base value ("rule1" actually
144 // goes SECOND in the rule set's rule list)
145 rule2
= new NFRule(rbnf
);
148 status
= U_MEMORY_ALLOCATION_ERROR
;
151 if (rule1
->baseValue
>= 0) {
152 rule2
->baseValue
= rule1
->baseValue
;
153 if (!ruleSet
->isFractionRuleSet()) {
158 // if the description began with "x.x" and contains bracketed
159 // text, it describes both the improper fraction rule and
160 // the proper fraction rule
161 else if (rule1
->getType() == kImproperFractionRule
) {
162 rule2
->setType(kProperFractionRule
);
165 // if the description began with "x.0" and contains bracketed
166 // text, it describes both the master rule and the
167 // improper fraction rule
168 else if (rule1
->getType() == kMasterRule
) {
169 rule2
->baseValue
= rule1
->baseValue
;
170 rule1
->setType(kImproperFractionRule
);
173 // both rules have the same radix and exponent (i.e., the
175 rule2
->radix
= rule1
->radix
;
176 rule2
->exponent
= rule1
->exponent
;
178 // rule2's rule text omits the stuff in brackets: initalize
179 // its rule text and substitutions accordingly
180 sbuf
.append(description
, 0, brack1
);
181 if (brack2
+ 1 < description
.length()) {
182 sbuf
.append(description
, brack2
+ 1, description
.length() - brack2
- 1);
184 rule2
->ruleText
.setTo(sbuf
);
185 rule2
->extractSubstitutions(ruleSet
, predecessor
, rbnf
, status
);
188 // rule1's text includes the text in the brackets but omits
189 // the brackets themselves: initialize _its_ rule text and
190 // substitutions accordingly
191 sbuf
.setTo(description
, 0, brack1
);
192 sbuf
.append(description
, brack1
+ 1, brack2
- brack1
- 1);
193 if (brack2
+ 1 < description
.length()) {
194 sbuf
.append(description
, brack2
+ 1, description
.length() - brack2
- 1);
196 rule1
->ruleText
.setTo(sbuf
);
197 rule1
->extractSubstitutions(ruleSet
, predecessor
, rbnf
, status
);
199 // if we only have one rule, return it; if we have two, return
200 // a two-element array containing them (notice that rule2 goes
201 // BEFORE rule1 in the list: in all cases, rule2 OMITS the
202 // material in the brackets and rule1 INCLUDES the material
212 * This function parses the rule's rule descriptor (i.e., the base
213 * value and/or other tokens that precede the rule's rule text
214 * in the description) and sets the rule's base value, radix, and
215 * exponent according to the descriptor. (If the description doesn't
216 * include a rule descriptor, then this function sets everything to
217 * default values and the rule set sets the rule's real base value).
218 * @param description The rule's description
219 * @return If "description" included a rule descriptor, this is
220 * "description" with the descriptor and any trailing whitespace
221 * stripped off. Otherwise; it's "descriptor" unchangd.
224 NFRule::parseRuleDescriptor(UnicodeString
& description
, UErrorCode
& status
)
226 // the description consists of a rule descriptor and a rule body,
227 // separated by a colon. The rule descriptor is optional. If
228 // it's omitted, just set the base value to 0.
229 int32_t p
= description
.indexOf(gColon
);
231 setBaseValue((int32_t)0, status
);
233 // copy the descriptor out into its own string and strip it,
234 // along with any trailing whitespace, out of the original
236 UnicodeString descriptor
;
237 descriptor
.setTo(description
, 0, p
);
240 while (p
< description
.length() && uprv_isRuleWhiteSpace(description
.charAt(p
))) {
243 description
.removeBetween(0, p
);
245 // check first to see if the rule descriptor matches the token
246 // for one of the special rules. If it does, set the base
247 // value to the correct identfier value
248 if (descriptor
== gMinusX
) {
249 setType(kNegativeNumberRule
);
251 else if (descriptor
== gXDotX
) {
252 setType(kImproperFractionRule
);
254 else if (descriptor
== gZeroDotX
) {
255 setType(kProperFractionRule
);
257 else if (descriptor
== gXDotZero
) {
258 setType(kMasterRule
);
261 // if the rule descriptor begins with a digit, it's a descriptor
263 // since we don't have Long.parseLong, and this isn't much work anyway,
264 // just build up the value as we encounter the digits.
265 else if (descriptor
.charAt(0) >= gZero
&& descriptor
.charAt(0) <= gNine
) {
270 // begin parsing the descriptor: copy digits
271 // into "tempValue", skip periods, commas, and spaces,
272 // stop on a slash or > sign (or at the end of the string),
273 // and throw an exception on any other character
275 while (p
< descriptor
.length()) {
276 c
= descriptor
.charAt(p
);
277 if (c
>= gZero
&& c
<= gNine
) {
278 val
= val
* ll_10
+ (int32_t)(c
- gZero
);
280 else if (c
== gSlash
|| c
== gGreaterThan
) {
283 else if (uprv_isRuleWhiteSpace(c
) || c
== gComma
|| c
== gDot
) {
286 // throw new IllegalArgumentException("Illegal character in rule descriptor");
287 status
= U_PARSE_ERROR
;
293 // we have the base value, so set it
294 setBaseValue(val
, status
);
296 // if we stopped the previous loop on a slash, we're
297 // now parsing the rule's radix. Again, accumulate digits
298 // in tempValue, skip punctuation, stop on a > mark, and
299 // throw an exception on anything else
304 while (p
< descriptor
.length()) {
305 c
= descriptor
.charAt(p
);
306 if (c
>= gZero
&& c
<= gNine
) {
307 val
= val
* ll_10
+ (int32_t)(c
- gZero
);
309 else if (c
== gGreaterThan
) {
312 else if (uprv_isRuleWhiteSpace(c
) || c
== gComma
|| c
== gDot
) {
315 // throw new IllegalArgumentException("Illegal character is rule descriptor");
316 status
= U_PARSE_ERROR
;
322 // tempValue now contain's the rule's radix. Set it
323 // accordingly, and recalculate the rule's exponent
324 radix
= (int32_t)val
;
326 // throw new IllegalArgumentException("Rule can't have radix of 0");
327 status
= U_PARSE_ERROR
;
330 exponent
= expectedExponent();
333 // if we stopped the previous loop on a > sign, then continue
334 // for as long as we still see > signs. For each one,
335 // decrement the exponent (unless the exponent is already 0).
336 // If we see another character before reaching the end of
337 // the descriptor, that's also a syntax error.
338 if (c
== gGreaterThan
) {
339 while (p
< descriptor
.length()) {
340 c
= descriptor
.charAt(p
);
341 if (c
== gGreaterThan
&& exponent
> 0) {
344 // throw new IllegalArgumentException("Illegal character in rule descriptor");
345 status
= U_PARSE_ERROR
;
354 // finally, if the rule body begins with an apostrophe, strip it off
355 // (this is generally used to put whitespace at the beginning of
356 // a rule's rule text)
357 if (description
.length() > 0 && description
.charAt(0) == gTick
) {
358 description
.removeBetween(0, 1);
361 // return the description with all the stuff we've just waded through
362 // stripped off the front. It now contains just the rule body.
363 // return description;
367 * Searches the rule's rule text for the substitution tokens,
368 * creates the substitutions, and removes the substitution tokens
369 * from the rule's rule text.
370 * @param owner The rule set containing this rule
371 * @param predecessor The rule preseding this one in "owners" rule list
372 * @param ownersOwner The RuleBasedFormat that owns this rule
375 NFRule::extractSubstitutions(const NFRuleSet
* ruleSet
,
376 const NFRule
* predecessor
,
377 const RuleBasedNumberFormat
* rbnf
,
380 if (U_SUCCESS(status
)) {
381 sub1
= extractSubstitution(ruleSet
, predecessor
, rbnf
, status
);
382 sub2
= extractSubstitution(ruleSet
, predecessor
, rbnf
, status
);
387 * Searches the rule's rule text for the first substitution token,
388 * creates a substitution based on it, and removes the token from
389 * the rule's rule text.
390 * @param owner The rule set containing this rule
391 * @param predecessor The rule preceding this one in the rule set's
393 * @param ownersOwner The RuleBasedNumberFormat that owns this rule
394 * @return The newly-created substitution. This is never null; if
395 * the rule text doesn't contain any substitution tokens, this will
396 * be a NullSubstitution.
399 NFRule::extractSubstitution(const NFRuleSet
* ruleSet
,
400 const NFRule
* predecessor
,
401 const RuleBasedNumberFormat
* rbnf
,
404 NFSubstitution
* result
= NULL
;
406 // search the rule's rule text for the first two characters of
407 // a substitution token
408 int32_t subStart
= indexOfAny(tokenStrings
);
409 int32_t subEnd
= subStart
;
411 // if we didn't find one, create a null substitution positioned
412 // at the end of the rule text
413 if (subStart
== -1) {
414 return NFSubstitution::makeSubstitution(ruleText
.length(), this, predecessor
,
415 ruleSet
, rbnf
, gEmptyString
, status
);
418 // special-case the ">>>" token, since searching for the > at the
419 // end will actually find the > in the middle
420 if (ruleText
.indexOf(gGreaterGreaterGreater
) == subStart
) {
421 subEnd
= subStart
+ 2;
423 // otherwise the substitution token ends with the same character
426 subEnd
= ruleText
.indexOf(ruleText
.charAt(subStart
), subStart
+ 1);
429 // if we don't find the end of the token (i.e., if we're on a single,
430 // unmatched token character), create a null substitution positioned
431 // at the end of the rule
433 return NFSubstitution::makeSubstitution(ruleText
.length(), this, predecessor
,
434 ruleSet
, rbnf
, gEmptyString
, status
);
437 // if we get here, we have a real substitution token (or at least
438 // some text bounded by substitution token characters). Use
439 // makeSubstitution() to create the right kind of substitution
440 UnicodeString subToken
;
441 subToken
.setTo(ruleText
, subStart
, subEnd
+ 1 - subStart
);
442 result
= NFSubstitution::makeSubstitution(subStart
, this, predecessor
, ruleSet
,
443 rbnf
, subToken
, status
);
445 // remove the substitution from the rule text
446 ruleText
.removeBetween(subStart
, subEnd
+1);
452 * Sets the rule's base value, and causes the radix and exponent
453 * to be recalculated. This is used during construction when we
454 * don't know the rule's base value until after it's been
455 * constructed. It should be used at any other time.
456 * @param The new base value for the rule.
459 NFRule::setBaseValue(int64_t newBaseValue
, UErrorCode
& status
)
461 // set the base value
462 baseValue
= newBaseValue
;
464 // if this isn't a special rule, recalculate the radix and exponent
465 // (the radix always defaults to 10; if it's supposed to be something
466 // else, it's cleaned up by the caller and the exponent is
467 // recalculated again-- the only function that does this is
468 // NFRule.parseRuleDescriptor() )
469 if (baseValue
>= 1) {
471 exponent
= expectedExponent();
473 // this function gets called on a fully-constructed rule whose
474 // description didn't specify a base value. This means it
475 // has substitutions, and some substitutions hold on to copies
476 // of the rule's divisor. Fix their copies of the divisor.
478 sub1
->setDivisor(radix
, exponent
, status
);
481 sub2
->setDivisor(radix
, exponent
, status
);
484 // if this is a special rule, its radix and exponent are basically
485 // ignored. Set them to "safe" default values
493 * This calculates the rule's exponent based on its radix and base
494 * value. This will be the highest power the radix can be raised to
495 * and still produce a result less than or equal to the base value.
498 NFRule::expectedExponent() const
500 // since the log of 0, or the log base 0 of something, causes an
501 // error, declare the exponent in these cases to be 0 (we also
502 // deal with the special-rule identifiers here)
503 if (radix
== 0 || baseValue
< 1) {
507 // we get rounding error in some cases-- for example, log 1000 / log 10
508 // gives us 1.9999999996 instead of 2. The extra logic here is to take
510 int16_t tempResult
= (int16_t)(uprv_log((double)baseValue
) / uprv_log((double)radix
));
511 int64_t temp
= util64_pow(radix
, tempResult
+ 1);
512 if (temp
<= baseValue
) {
519 * Searches the rule's rule text for any of the specified strings.
520 * @param strings An array of strings to search the rule's rule
522 * @return The index of the first match in the rule's rule text
523 * (i.e., the first substring in the rule's rule text that matches
524 * _any_ of the strings in "strings"). If none of the strings in
525 * "strings" is found in the rule's rule text, returns -1.
528 NFRule::indexOfAny(const UChar
* const strings
[]) const
531 for (int i
= 0; strings
[i
]; i
++) {
532 int32_t pos
= ruleText
.indexOf(*strings
[i
]);
533 if (pos
!= -1 && (result
== -1 || pos
< result
)) {
540 //-----------------------------------------------------------------------
542 //-----------------------------------------------------------------------
545 * Tests two rules for equality.
546 * @param that The rule to compare this one against
547 * @return True is the two rules are functionally equivalent
550 NFRule::operator==(const NFRule
& rhs
) const
552 return baseValue
== rhs
.baseValue
553 && radix
== rhs
.radix
554 && exponent
== rhs
.exponent
555 && ruleText
== rhs
.ruleText
556 && *sub1
== *rhs
.sub1
557 && *sub2
== *rhs
.sub2
;
561 * Returns a textual representation of the rule. This won't
562 * necessarily be the same as the description that this rule
563 * was created with, but it will produce the same result.
564 * @return A textual description of the rule
566 static void util_append64(UnicodeString
& result
, int64_t n
)
569 int32_t len
= util64_tou(n
, buffer
, sizeof(buffer
));
570 UnicodeString
temp(buffer
, len
);
575 NFRule::appendRuleText(UnicodeString
& result
) const
578 case kNegativeNumberRule
: result
.append(gMinusX
); break;
579 case kImproperFractionRule
: result
.append(gXDotX
); break;
580 case kProperFractionRule
: result
.append(gZeroDotX
); break;
581 case kMasterRule
: result
.append(gXDotZero
); break;
583 // for a normal rule, write out its base value, and if the radix is
584 // something other than 10, write out the radix (with the preceding
585 // slash, of course). Then calculate the expected exponent and if
586 // if isn't the same as the actual exponent, write an appropriate
587 // number of > signs. Finally, terminate the whole thing with
589 util_append64(result
, baseValue
);
591 result
.append(gSlash
);
592 util_append64(result
, radix
);
594 int numCarets
= expectedExponent() - exponent
;
595 for (int i
= 0; i
< numCarets
; i
++) {
596 result
.append(gGreaterThan
);
600 result
.append(gColon
);
601 result
.append(gSpace
);
603 // if the rule text begins with a space, write an apostrophe
604 // (whitespace after the rule descriptor is ignored; the
605 // apostrophe is used to make the whitespace significant)
606 if (ruleText
.startsWith(gSpace
) && sub1
->getPos() != 0) {
607 result
.append(gTick
);
610 // now, write the rule's rule text, inserting appropriate
611 // substitution tokens in the appropriate places
612 UnicodeString ruleTextCopy
;
613 ruleTextCopy
.setTo(ruleText
);
616 sub2
->toString(temp
);
617 ruleTextCopy
.insert(sub2
->getPos(), temp
);
618 sub1
->toString(temp
);
619 ruleTextCopy
.insert(sub1
->getPos(), temp
);
621 result
.append(ruleTextCopy
);
623 // and finally, top the whole thing off with a semicolon and
625 result
.append(gSemicolon
);
628 //-----------------------------------------------------------------------
630 //-----------------------------------------------------------------------
633 * Formats the number, and inserts the resulting text into
635 * @param number The number being formatted
636 * @param toInsertInto The string where the resultant text should
638 * @param pos The position in toInsertInto where the resultant text
642 NFRule::doFormat(int64_t number
, UnicodeString
& toInsertInto
, int32_t pos
) const
644 // first, insert the rule's rule text into toInsertInto at the
645 // specified position, then insert the results of the substitutions
646 // into the right places in toInsertInto (notice we do the
647 // substitutions in reverse order so that the offsets don't get
649 toInsertInto
.insert(pos
, ruleText
);
650 sub2
->doSubstitution(number
, toInsertInto
, pos
);
651 sub1
->doSubstitution(number
, toInsertInto
, pos
);
655 * Formats the number, and inserts the resulting text into
657 * @param number The number being formatted
658 * @param toInsertInto The string where the resultant text should
660 * @param pos The position in toInsertInto where the resultant text
664 NFRule::doFormat(double number
, UnicodeString
& toInsertInto
, int32_t pos
) const
666 // first, insert the rule's rule text into toInsertInto at the
667 // specified position, then insert the results of the substitutions
668 // into the right places in toInsertInto
669 // [again, we have two copies of this routine that do the same thing
670 // so that we don't sacrifice precision in a long by casting it
672 toInsertInto
.insert(pos
, ruleText
);
673 sub2
->doSubstitution(number
, toInsertInto
, pos
);
674 sub1
->doSubstitution(number
, toInsertInto
, pos
);
678 * Used by the owning rule set to determine whether to invoke the
679 * rollback rule (i.e., whether this rule or the one that precedes
680 * it in the rule set's list should be used to format the number)
681 * @param The number being formatted
682 * @return True if the rule set should use the rule that precedes
683 * this one in its list; false if it should use this rule
686 NFRule::shouldRollBack(double number
) const
688 // we roll back if the rule contains a modulus substitution,
689 // the number being formatted is an even multiple of the rule's
690 // divisor, and the rule's base value is NOT an even multiple
692 // In other words, if the original description had
693 // 100: << hundred[ >>];
696 // 101: << hundred >>;
697 // internally. But when we're formatting 200, if we use the rule
698 // at 101, which would normally apply, we get "two hundred zero".
699 // To prevent this, we roll back and use the rule at 100 instead.
700 // This is the logic that makes this happen: the rule at 101 has
701 // a modulus substitution, its base value isn't an even multiple
702 // of 100, and the value we're trying to format _is_ an even
703 // multiple of 100. This is called the "rollback rule."
704 if ((sub1
->isModulusSubstitution()) || (sub2
->isModulusSubstitution())) {
705 int64_t re
= util64_pow(radix
, exponent
);
706 return uprv_fmod(number
, (double)re
) == 0 && (baseValue
% re
) != 0;
711 //-----------------------------------------------------------------------
713 //-----------------------------------------------------------------------
716 * Attempts to parse the string with this rule.
717 * @param text The string being parsed
718 * @param parsePosition On entry, the value is ignored and assumed to
719 * be 0. On exit, this has been updated with the position of the first
720 * character not consumed by matching the text against this rule
721 * (if this rule doesn't match the text at all, the parse position
722 * if left unchanged (presumably at 0) and the function returns
724 * @param isFractionRule True if this rule is contained within a
725 * fraction rule set. This is only used if the rule has no
727 * @return If this rule matched the text, this is the rule's base value
728 * combined appropriately with the results of parsing the substitutions.
729 * If nothing matched, this is new Long(0) and the parse position is
730 * left unchanged. The result will be an instance of Long if the
731 * result is an integer and Double otherwise. The result is never null.
736 static void dumpUS(FILE* f
, const UnicodeString
& us
) {
737 int len
= us
.length();
738 char* buf
= (char *)uprv_malloc((len
+1)*sizeof(char)); //new char[len+1];
739 us
.extract(0, len
, buf
);
741 fprintf(f
, "%s", buf
);
742 uprv_free(buf
); //delete[] buf;
747 NFRule::doParse(const UnicodeString
& text
,
748 ParsePosition
& parsePosition
,
749 UBool isFractionRule
,
751 Formattable
& resVal
) const
753 // internally we operate on a copy of the string being parsed
754 // (because we're going to change it) and use our own ParsePosition
756 UnicodeString
workText(text
);
758 // check to see whether the text before the first substitution
759 // matches the text at the beginning of the string being
760 // parsed. If it does, strip that off the front of workText;
761 // otherwise, dump out with a mismatch
762 UnicodeString prefix
;
763 prefix
.setTo(ruleText
, 0, sub1
->getPos());
766 fprintf(stderr
, "doParse %x ", this);
773 fprintf(stderr
, " text: '", this);
774 dumpUS(stderr
, text
);
775 fprintf(stderr
, "' prefix: '");
776 dumpUS(stderr
, prefix
);
778 stripPrefix(workText
, prefix
, pp
);
779 int32_t prefixLength
= text
.length() - workText
.length();
782 fprintf(stderr
, "' pl: %d ppi: %d s1p: %d\n", prefixLength
, pp
.getIndex(), sub1
->getPos());
785 if (pp
.getIndex() == 0 && sub1
->getPos() != 0) {
786 // commented out because ParsePosition doesn't have error index in 1.1.x
787 // restored for ICU4C port
788 parsePosition
.setErrorIndex(pp
.getErrorIndex());
793 // this is the fun part. The basic guts of the rule-matching
794 // logic is matchToDelimiter(), which is called twice. The first
795 // time it searches the input string for the rule text BETWEEN
796 // the substitutions and tries to match the intervening text
797 // in the input string with the first substitution. If that
798 // succeeds, it then calls it again, this time to look for the
799 // rule text after the second substitution and to match the
800 // intervening input text against the second substitution.
802 // For example, say we have a rule that looks like this:
803 // first << middle >> last;
804 // and input text that looks like this:
805 // first one middle two last
806 // First we use stripPrefix() to match "first " in both places and
807 // strip it off the front, leaving
808 // one middle two last
809 // Then we use matchToDelimiter() to match " middle " and try to
810 // match "one" against a substitution. If it's successful, we now
813 // We use matchToDelimiter() a second time to match " last" and
814 // try to match "two" against a substitution. If "two" matches
815 // the substitution, we have a successful parse.
817 // Since it's possible in many cases to find multiple instances
818 // of each of these pieces of rule text in the input string,
819 // we need to try all the possible combinations of these
820 // locations. This prevents us from prematurely declaring a mismatch,
821 // and makes sure we match as much input text as we can.
822 int highWaterMark
= 0;
825 double tempBaseValue
= (double)(baseValue
<= 0 ? 0 : baseValue
);
829 // our partial parse result starts out as this rule's base
830 // value. If it finds a successful match, matchToDelimiter()
831 // will compose this in some way with what it gets back from
832 // the substitution, giving us a new partial parse result
835 temp
.setTo(ruleText
, sub1
->getPos(), sub2
->getPos() - sub1
->getPos());
836 double partialResult
= matchToDelimiter(workText
, start
, tempBaseValue
,
840 // if we got a successful match (or were trying to match a
841 // null substitution), pp is now pointing at the first unmatched
842 // character. Take note of that, and try matchToDelimiter()
843 // on the input text again
844 if (pp
.getIndex() != 0 || sub1
->isNullSubstitution()) {
845 start
= pp
.getIndex();
847 UnicodeString workText2
;
848 workText2
.setTo(workText
, pp
.getIndex(), workText
.length() - pp
.getIndex());
851 // the second matchToDelimiter() will compose our previous
852 // partial result with whatever it gets back from its
853 // substitution if there's a successful match, giving us
855 temp
.setTo(ruleText
, sub2
->getPos(), ruleText
.length() - sub2
->getPos());
856 partialResult
= matchToDelimiter(workText2
, 0, partialResult
,
860 // if we got a successful match on this second
861 // matchToDelimiter() call, update the high-water mark
862 // and result (if necessary)
863 if (pp2
.getIndex() != 0 || sub2
->isNullSubstitution()) {
864 if (prefixLength
+ pp
.getIndex() + pp2
.getIndex() > highWaterMark
) {
865 highWaterMark
= prefixLength
+ pp
.getIndex() + pp2
.getIndex();
866 result
= partialResult
;
869 // commented out because ParsePosition doesn't have error index in 1.1.x
870 // restored for ICU4C port
872 int32_t temp
= pp2
.getErrorIndex() + sub1
->getPos() + pp
.getIndex();
873 if (temp
> parsePosition
.getErrorIndex()) {
874 parsePosition
.setErrorIndex(temp
);
878 // commented out because ParsePosition doesn't have error index in 1.1.x
879 // restored for ICU4C port
881 int32_t temp
= sub1
->getPos() + pp
.getErrorIndex();
882 if (temp
> parsePosition
.getErrorIndex()) {
883 parsePosition
.setErrorIndex(temp
);
886 // keep trying to match things until the outer matchToDelimiter()
887 // call fails to make a match (each time, it picks up where it
888 // left off the previous time)
889 } while (sub1
->getPos() != sub2
->getPos()
891 && pp
.getIndex() < workText
.length()
892 && pp
.getIndex() != start
);
894 // update the caller's ParsePosition with our high-water mark
895 // (i.e., it now points at the first character this function
896 // didn't match-- the ParsePosition is therefore unchanged if
897 // we didn't match anything)
898 parsePosition
.setIndex(highWaterMark
);
899 // commented out because ParsePosition doesn't have error index in 1.1.x
900 // restored for ICU4C port
901 if (highWaterMark
> 0) {
902 parsePosition
.setErrorIndex(0);
905 // this is a hack for one unusual condition: Normally, whether this
906 // rule belong to a fraction rule set or not is handled by its
907 // substitutions. But if that rule HAS NO substitutions, then
908 // we have to account for it here. By definition, if the matching
909 // rule in a fraction rule set has no substitutions, its numerator
910 // is 1, and so the result is the reciprocal of its base value.
911 if (isFractionRule
&&
913 sub1
->isNullSubstitution()) {
917 resVal
.setDouble(result
);
918 return TRUE
; // ??? do we need to worry if it is a long or a double?
922 * This function is used by parse() to match the text being parsed
923 * against a possible prefix string. This function
924 * matches characters from the beginning of the string being parsed
925 * to characters from the prospective prefix. If they match, pp is
926 * updated to the first character not matched, and the result is
927 * the unparsed part of the string. If they don't match, the whole
928 * string is returned, and pp is left unchanged.
929 * @param text The string being parsed
930 * @param prefix The text to match against
931 * @param pp On entry, ignored and assumed to be 0. On exit, points
932 * to the first unmatched character (assuming the whole prefix matched),
933 * or is unchanged (if the whole prefix didn't match).
934 * @return If things match, this is the unparsed part of "text";
935 * if they didn't match, this is "text".
938 NFRule::stripPrefix(UnicodeString
& text
, const UnicodeString
& prefix
, ParsePosition
& pp
) const
940 // if the prefix text is empty, dump out without doing anything
941 if (prefix
.length() != 0) {
942 // use prefixLength() to match the beginning of
943 // "text" against "prefix". This function returns the
944 // number of characters from "text" that matched (or 0 if
945 // we didn't match the whole prefix)
946 int32_t pfl
= prefixLength(text
, prefix
);
948 // if we got a successful match, update the parse position
949 // and strip the prefix off of "text"
950 pp
.setIndex(pp
.getIndex() + pfl
);
957 * Used by parse() to match a substitution and any following text.
958 * "text" is searched for instances of "delimiter". For each instance
959 * of delimiter, the intervening text is tested to see whether it
960 * matches the substitution. The longest match wins.
961 * @param text The string being parsed
962 * @param startPos The position in "text" where we should start looking
964 * @param baseValue A partial parse result (often the rule's base value),
965 * which is combined with the result from matching the substitution
966 * @param delimiter The string to search "text" for.
967 * @param pp Ignored and presumed to be 0 on entry. If there's a match,
968 * on exit this will point to the first unmatched character.
969 * @param sub If we find "delimiter" in "text", this substitution is used
970 * to match the text between the beginning of the string and the
971 * position of "delimiter." (If "delimiter" is the empty string, then
972 * this function just matches against this substitution and updates
973 * everything accordingly.)
974 * @param upperBound When matching the substitution, it will only
975 * consider rules with base values lower than this value.
976 * @return If there's a match, this is the result of composing
977 * baseValue with the result of matching the substitution. Otherwise,
978 * this is new Long(0). It's never null. If the result is an integer,
979 * this will be an instance of Long; otherwise, it's an instance of
982 * !!! note {dlf} in point of fact, in the java code the caller always converts
983 * the result to a double, so we might as well return one.
986 NFRule::matchToDelimiter(const UnicodeString
& text
,
989 const UnicodeString
& delimiter
,
991 const NFSubstitution
* sub
,
992 double upperBound
) const
994 // if "delimiter" contains real (i.e., non-ignorable) text, search
995 // it for "delimiter" beginning at "start". If that succeeds, then
996 // use "sub"'s doParse() method to match the text before the
997 // instance of "delimiter" we just found.
998 if (!allIgnorable(delimiter
)) {
999 ParsePosition tempPP
;
1002 // use findText() to search for "delimiter". It returns a two-
1003 // element array: element 0 is the position of the match, and
1004 // element 1 is the number of characters that matched
1007 int32_t dPos
= findText(text
, delimiter
, startPos
, &dLen
);
1009 // if findText() succeeded, isolate the text preceding the
1010 // match, and use "sub" to match that text
1012 UnicodeString subText
;
1013 subText
.setTo(text
, 0, dPos
);
1014 if (subText
.length() > 0) {
1015 UBool success
= sub
->doParse(subText
, tempPP
, _baseValue
, upperBound
,
1016 #if UCONFIG_NO_COLLATION
1019 formatter
->isLenient(),
1023 // if the substitution could match all the text up to
1024 // where we found "delimiter", then this function has
1025 // a successful match. Bump the caller's parse position
1026 // to point to the first character after the text
1027 // that matches "delimiter", and return the result
1028 // we got from parsing the substitution.
1029 if (success
&& tempPP
.getIndex() == dPos
) {
1030 pp
.setIndex(dPos
+ dLen
);
1031 return result
.getDouble();
1033 // commented out because ParsePosition doesn't have error index in 1.1.x
1034 // restored for ICU4C port
1036 if (tempPP
.getErrorIndex() > 0) {
1037 pp
.setErrorIndex(tempPP
.getErrorIndex());
1039 pp
.setErrorIndex(tempPP
.getIndex());
1044 // if we didn't match the substitution, search for another
1045 // copy of "delimiter" in "text" and repeat the loop if
1048 dPos
= findText(text
, delimiter
, dPos
+ dLen
, &dLen
);
1050 // if we make it here, this was an unsuccessful match, and we
1051 // leave pp unchanged and return 0
1055 // if "delimiter" is empty, or consists only of ignorable characters
1056 // (i.e., is semantically empty), thwe we obviously can't search
1057 // for "delimiter". Instead, just use "sub" to parse as much of
1058 // "text" as possible.
1060 ParsePosition tempPP
;
1063 // try to match the whole string against the substitution
1064 UBool success
= sub
->doParse(text
, tempPP
, _baseValue
, upperBound
,
1065 #if UCONFIG_NO_COLLATION
1068 formatter
->isLenient(),
1071 if (success
&& (tempPP
.getIndex() != 0 || sub
->isNullSubstitution())) {
1072 // if there's a successful match (or it's a null
1073 // substitution), update pp to point to the first
1074 // character we didn't match, and pass the result from
1075 // sub.doParse() on through to the caller
1076 pp
.setIndex(tempPP
.getIndex());
1077 return result
.getDouble();
1079 // commented out because ParsePosition doesn't have error index in 1.1.x
1080 // restored for ICU4C port
1082 pp
.setErrorIndex(tempPP
.getErrorIndex());
1085 // and if we get to here, then nothing matched, so we return
1086 // 0 and leave pp alone
1092 * Used by stripPrefix() to match characters. If lenient parse mode
1093 * is off, this just calls startsWith(). If lenient parse mode is on,
1094 * this function uses CollationElementIterators to match characters in
1095 * the strings (only primary-order differences are significant in
1096 * determining whether there's a match).
1097 * @param str The string being tested
1098 * @param prefix The text we're hoping to see at the beginning
1100 * @return If "prefix" is found at the beginning of "str", this
1101 * is the number of characters in "str" that were matched (this
1102 * isn't necessarily the same as the length of "prefix" when matching
1103 * text with a collator). If there's no match, this is 0.
1106 NFRule::prefixLength(const UnicodeString
& str
, const UnicodeString
& prefix
) const
1108 // if we're looking for an empty prefix, it obviously matches
1109 // zero characters. Just go ahead and return 0.
1110 if (prefix
.length() == 0) {
1114 #if !UCONFIG_NO_COLLATION
1115 // go through all this grief if we're in lenient-parse mode
1116 if (formatter
->isLenient()) {
1117 // get the formatter's collator and use it to create two
1118 // collation element iterators, one over the target string
1119 // and another over the prefix (right now, we'll throw an
1120 // exception if the collator we get back from the formatter
1121 // isn't a RuleBasedCollator, because RuleBasedCollator defines
1122 // the CollationElementIterator protocol. Hopefully, this
1123 // will change someday.)
1124 RuleBasedCollator
* collator
= (RuleBasedCollator
*)formatter
->getCollator();
1125 CollationElementIterator
* strIter
= collator
->createCollationElementIterator(str
);
1126 CollationElementIterator
* prefixIter
= collator
->createCollationElementIterator(prefix
);
1128 UErrorCode err
= U_ZERO_ERROR
;
1130 // The original code was problematic. Consider this match:
1131 // prefix = "fifty-"
1132 // string = " fifty-7"
1133 // The intent is to match string up to the '7', by matching 'fifty-' at position 1
1134 // in the string. Unfortunately, we were getting a match, and then computing where
1135 // the match terminated by rematching the string. The rematch code was using as an
1136 // initial guess the substring of string between 0 and prefix.length. Because of
1137 // the leading space and trailing hyphen (both ignorable) this was succeeding, leaving
1138 // the position before the hyphen in the string. Recursing down, we then parsed the
1139 // remaining string '-7' as numeric. The resulting number turned out as 43 (50 - 7).
1140 // This was not pretty, especially since the string "fifty-7" parsed just fine.
1142 // We have newer APIs now, so we can use calls on the iterator to determine what we
1143 // matched up to. If we terminate because we hit the last element in the string,
1144 // our match terminates at this length. If we terminate because we hit the last element
1145 // in the target, our match terminates at one before the element iterator position.
1147 // match collation elements between the strings
1148 int32_t oStr
= strIter
->next(err
);
1149 int32_t oPrefix
= prefixIter
->next(err
);
1151 while (oPrefix
!= CollationElementIterator::NULLORDER
) {
1152 // skip over ignorable characters in the target string
1153 while (CollationElementIterator::primaryOrder(oStr
) == 0
1154 && oStr
!= CollationElementIterator::NULLORDER
) {
1155 oStr
= strIter
->next(err
);
1158 // skip over ignorable characters in the prefix
1159 while (CollationElementIterator::primaryOrder(oPrefix
) == 0
1160 && oPrefix
!= CollationElementIterator::NULLORDER
) {
1161 oPrefix
= prefixIter
->next(err
);
1164 // dlf: move this above following test, if we consume the
1165 // entire target, aren't we ok even if the source was also
1166 // entirely consumed?
1168 // if skipping over ignorables brought to the end of
1169 // the prefix, we DID match: drop out of the loop
1170 if (oPrefix
== CollationElementIterator::NULLORDER
) {
1174 // if skipping over ignorables brought us to the end
1175 // of the target string, we didn't match and return 0
1176 if (oStr
== CollationElementIterator::NULLORDER
) {
1182 // match collation elements from the two strings
1183 // (considering only primary differences). If we
1184 // get a mismatch, dump out and return 0
1185 if (CollationElementIterator::primaryOrder(oStr
)
1186 != CollationElementIterator::primaryOrder(oPrefix
)) {
1191 // otherwise, advance to the next character in each string
1192 // and loop (we drop out of the loop when we exhaust
1193 // collation elements in the prefix)
1195 oStr
= strIter
->next(err
);
1196 oPrefix
= prefixIter
->next(err
);
1200 int32_t result
= strIter
->getOffset();
1201 if (oStr
!= CollationElementIterator::NULLORDER
) {
1202 --result
; // back over character that we don't want to consume;
1206 fprintf(stderr
, "prefix length: %d\n", result
);
1213 //----------------------------------------------------------------
1214 // JDK 1.2-specific API call
1215 // return strIter.getOffset();
1216 //----------------------------------------------------------------
1217 // JDK 1.1 HACK (take out for 1.2-specific code)
1219 // if we make it to here, we have a successful match. Now we
1220 // have to find out HOW MANY characters from the target string
1221 // matched the prefix (there isn't necessarily a one-to-one
1222 // mapping between collation elements and characters).
1223 // In JDK 1.2, there's a simple getOffset() call we can use.
1224 // In JDK 1.1, on the other hand, we have to go through some
1225 // ugly contortions. First, use the collator to compare the
1226 // same number of characters from the prefix and target string.
1227 // If they're equal, we're done.
1228 collator
->setStrength(Collator::PRIMARY
);
1229 if (str
.length() >= prefix
.length()) {
1231 temp
.setTo(str
, 0, prefix
.length());
1232 if (collator
->equals(temp
, prefix
)) {
1234 fprintf(stderr
, "returning: %d\n", prefix
.length());
1236 return prefix
.length();
1240 // if they're not equal, then we have to compare successively
1241 // larger and larger substrings of the target string until we
1242 // get to one that matches the prefix. At that point, we know
1243 // how many characters matched the prefix, and we can return.
1245 while (p
<= str
.length()) {
1247 temp
.setTo(str
, 0, p
);
1248 if (collator
->equals(temp
, prefix
)) {
1255 // SHOULD NEVER GET HERE!!!
1257 //----------------------------------------------------------------
1260 // If lenient parsing is turned off, forget all that crap above.
1261 // Just use String.startsWith() and be done with it.
1265 if (str
.startsWith(prefix
)) {
1266 return prefix
.length();
1274 * Searches a string for another string. If lenient parsing is off,
1275 * this just calls indexOf(). If lenient parsing is on, this function
1276 * uses CollationElementIterator to match characters, and only
1277 * primary-order differences are significant in determining whether
1279 * @param str The string to search
1280 * @param key The string to search "str" for
1281 * @param startingAt The index into "str" where the search is to
1283 * @return A two-element array of ints. Element 0 is the position
1284 * of the match, or -1 if there was no match. Element 1 is the
1285 * number of characters in "str" that matched (which isn't necessarily
1286 * the same as the length of "key")
1289 NFRule::findText(const UnicodeString
& str
,
1290 const UnicodeString
& key
,
1292 int32_t* length
) const
1294 #if !UCONFIG_NO_COLLATION
1295 // if lenient parsing is turned off, this is easy: just call
1296 // String.indexOf() and we're done
1297 if (!formatter
->isLenient()) {
1298 *length
= key
.length();
1299 return str
.indexOf(key
, startingAt
);
1301 // but if lenient parsing is turned ON, we've got some work
1306 //----------------------------------------------------------------
1307 // JDK 1.1 HACK (take out of 1.2-specific code)
1309 // in JDK 1.2, CollationElementIterator provides us with an
1310 // API to map between character offsets and collation elements
1311 // and we can do this by marching through the string comparing
1312 // collation elements. We can't do that in JDK 1.1. Insted,
1313 // we have to go through this horrible slow mess:
1314 int32_t p
= startingAt
;
1317 // basically just isolate smaller and smaller substrings of
1318 // the target string (each running to the end of the string,
1319 // and with the first one running from startingAt to the end)
1320 // and then use prefixLength() to see if the search key is at
1321 // the beginning of each substring. This is excruciatingly
1322 // slow, but it will locate the key and tell use how long the
1323 // matching text was.
1325 while (p
< str
.length() && keyLen
== 0) {
1326 temp
.setTo(str
, p
, str
.length() - p
);
1327 keyLen
= prefixLength(temp
, key
);
1334 // if we make it to here, we didn't find it. Return -1 for the
1335 // location. The length should be ignored, but set it to 0,
1336 // which should be "safe"
1340 //----------------------------------------------------------------
1341 // JDK 1.2 version of this routine
1342 //RuleBasedCollator collator = (RuleBasedCollator)formatter.getCollator();
1344 //CollationElementIterator strIter = collator.getCollationElementIterator(str);
1345 //CollationElementIterator keyIter = collator.getCollationElementIterator(key);
1347 //int keyStart = -1;
1349 //str.setOffset(startingAt);
1351 //int oStr = strIter.next();
1352 //int oKey = keyIter.next();
1353 //while (oKey != CollationElementIterator.NULLORDER) {
1354 // while (oStr != CollationElementIterator.NULLORDER &&
1355 // CollationElementIterator.primaryOrder(oStr) == 0)
1356 // oStr = strIter.next();
1358 // while (oKey != CollationElementIterator.NULLORDER &&
1359 // CollationElementIterator.primaryOrder(oKey) == 0)
1360 // oKey = keyIter.next();
1362 // if (oStr == CollationElementIterator.NULLORDER) {
1363 // return new int[] { -1, 0 };
1366 // if (oKey == CollationElementIterator.NULLORDER) {
1370 // if (CollationElementIterator.primaryOrder(oStr) ==
1371 // CollationElementIterator.primaryOrder(oKey)) {
1372 // keyStart = strIter.getOffset();
1373 // oStr = strIter.next();
1374 // oKey = keyIter.next();
1376 // if (keyStart != -1) {
1380 // oStr = strIter.next();
1385 //if (oKey == CollationElementIterator.NULLORDER) {
1386 // return new int[] { keyStart, strIter.getOffset() - keyStart };
1388 // return new int[] { -1, 0 };
1394 * Checks to see whether a string consists entirely of ignorable
1396 * @param str The string to test.
1397 * @return true if the string is empty of consists entirely of
1398 * characters that the number formatter's collator says are
1399 * ignorable at the primary-order level. false otherwise.
1402 NFRule::allIgnorable(const UnicodeString
& str
) const
1404 // if the string is empty, we can just return true
1405 if (str
.length() == 0) {
1409 #if !UCONFIG_NO_COLLATION
1410 // if lenient parsing is turned on, walk through the string with
1411 // a collation element iterator and make sure each collation
1412 // element is 0 (ignorable) at the primary level
1413 if (formatter
->isLenient()) {
1414 RuleBasedCollator
* collator
= (RuleBasedCollator
*)(formatter
->getCollator());
1415 CollationElementIterator
* iter
= collator
->createCollationElementIterator(str
);
1417 UErrorCode err
= U_ZERO_ERROR
;
1418 int32_t o
= iter
->next(err
);
1419 while (o
!= CollationElementIterator::NULLORDER
1420 && CollationElementIterator::primaryOrder(o
) == 0) {
1421 o
= iter
->next(err
);
1425 return o
== CollationElementIterator::NULLORDER
;
1429 // if lenient parsing is turned off, there is no such thing as
1430 // an ignorable character: return true only if the string is empty