1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ******************************************************************************
5 * Copyright (C) 1997-2015, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 ******************************************************************************
8 * file name: nfrule.cpp
9 * encoding: UTF-8
10 * tab size: 8 (not used)
11 * indentation:4
12 *
13 * Modification history
14 * Date Name Comments
15 * 10/11/2001 Doug Ported from ICU4J
16 */
17
18 #include "nfrule.h"
19
20 #if U_HAVE_RBNF
21
22 #include "unicode/localpointer.h"
23 #include "unicode/rbnf.h"
24 #include "unicode/tblcoll.h"
25 #include "unicode/plurfmt.h"
26 #include "unicode/upluralrules.h"
27 #include "unicode/coleitr.h"
28 #include "unicode/uchar.h"
29 #include "nfrs.h"
30 #include "nfrlist.h"
31 #include "nfsubs.h"
32 #include "patternprops.h"
33 #include "putilimp.h"
34
35 U_NAMESPACE_BEGIN
36
NFRule(const RuleBasedNumberFormat * _rbnf,const UnicodeString & _ruleText,UErrorCode & status)37 NFRule::NFRule(const RuleBasedNumberFormat* _rbnf, const UnicodeString &_ruleText, UErrorCode &status)
38 : baseValue((int32_t)0)
39 , radix(10)
40 , exponent(0)
41 , decimalPoint(0)
42 , fRuleText(_ruleText)
43 , sub1(nullptr)
44 , sub2(nullptr)
45 , formatter(_rbnf)
46 , rulePatternFormat(nullptr)
47 {
48 if (!fRuleText.isEmpty()) {
49 parseRuleDescriptor(fRuleText, status);
50 }
51 }
52
~NFRule()53 NFRule::~NFRule()
54 {
55 if (sub1 != sub2) {
56 delete sub2;
57 sub2 = nullptr;
58 }
59 delete sub1;
60 sub1 = nullptr;
61 delete rulePatternFormat;
62 rulePatternFormat = nullptr;
63 }
64
65 static const char16_t gLeftBracket = 0x005b;
66 static const char16_t gRightBracket = 0x005d;
67 static const char16_t gColon = 0x003a;
68 static const char16_t gZero = 0x0030;
69 static const char16_t gNine = 0x0039;
70 static const char16_t gSpace = 0x0020;
71 static const char16_t gSlash = 0x002f;
72 static const char16_t gGreaterThan = 0x003e;
73 static const char16_t gLessThan = 0x003c;
74 static const char16_t gComma = 0x002c;
75 static const char16_t gDot = 0x002e;
76 static const char16_t gTick = 0x0027;
77 //static const char16_t gMinus = 0x002d;
78 static const char16_t gSemicolon = 0x003b;
79 static const char16_t gX = 0x0078;
80
81 static const char16_t gMinusX[] = {0x2D, 0x78, 0}; /* "-x" */
82 static const char16_t gInf[] = {0x49, 0x6E, 0x66, 0}; /* "Inf" */
83 static const char16_t gNaN[] = {0x4E, 0x61, 0x4E, 0}; /* "NaN" */
84
85 static const char16_t gDollarOpenParenthesis[] = {0x24, 0x28, 0}; /* "$(" */
86 static const char16_t gClosedParenthesisDollar[] = {0x29, 0x24, 0}; /* ")$" */
87
88 static const char16_t gLessLess[] = {0x3C, 0x3C, 0}; /* "<<" */
89 static const char16_t gLessPercent[] = {0x3C, 0x25, 0}; /* "<%" */
90 static const char16_t gLessHash[] = {0x3C, 0x23, 0}; /* "<#" */
91 static const char16_t gLessZero[] = {0x3C, 0x30, 0}; /* "<0" */
92 static const char16_t gGreaterGreater[] = {0x3E, 0x3E, 0}; /* ">>" */
93 static const char16_t gGreaterPercent[] = {0x3E, 0x25, 0}; /* ">%" */
94 static const char16_t gGreaterHash[] = {0x3E, 0x23, 0}; /* ">#" */
95 static const char16_t gGreaterZero[] = {0x3E, 0x30, 0}; /* ">0" */
96 static const char16_t gEqualPercent[] = {0x3D, 0x25, 0}; /* "=%" */
97 static const char16_t gEqualHash[] = {0x3D, 0x23, 0}; /* "=#" */
98 static const char16_t gEqualZero[] = {0x3D, 0x30, 0}; /* "=0" */
99 static const char16_t gGreaterGreaterGreater[] = {0x3E, 0x3E, 0x3E, 0}; /* ">>>" */
100
101 static const char16_t * const RULE_PREFIXES[] = {
102 gLessLess, gLessPercent, gLessHash, gLessZero,
103 gGreaterGreater, gGreaterPercent,gGreaterHash, gGreaterZero,
104 gEqualPercent, gEqualHash, gEqualZero, nullptr
105 };
106
107 void
makeRules(UnicodeString & description,NFRuleSet * owner,const NFRule * predecessor,const RuleBasedNumberFormat * rbnf,NFRuleList & rules,UErrorCode & status)108 NFRule::makeRules(UnicodeString& description,
109 NFRuleSet *owner,
110 const NFRule *predecessor,
111 const RuleBasedNumberFormat *rbnf,
112 NFRuleList& rules,
113 UErrorCode& status)
114 {
115 // we know we're making at least one rule, so go ahead and
116 // new it up and initialize its basevalue and divisor
117 // (this also strips the rule descriptor, if any, off the
118 // description string)
119 NFRule* rule1 = new NFRule(rbnf, description, status);
120 /* test for nullptr */
121 if (rule1 == nullptr) {
122 status = U_MEMORY_ALLOCATION_ERROR;
123 return;
124 }
125 description = rule1->fRuleText;
126
127 // check the description to see whether there's text enclosed
128 // in brackets
129 int32_t brack1 = description.indexOf(gLeftBracket);
130 int32_t brack2 = brack1 < 0 ? -1 : description.indexOf(gRightBracket);
131
132 // if the description doesn't contain a matched pair of brackets,
133 // or if it's of a type that doesn't recognize bracketed text,
134 // then leave the description alone, initialize the rule's
135 // rule text and substitutions, and return that rule
136 if (brack2 < 0 || brack1 > brack2
137 || rule1->getType() == kProperFractionRule
138 || rule1->getType() == kNegativeNumberRule
139 || rule1->getType() == kInfinityRule
140 || rule1->getType() == kNaNRule)
141 {
142 rule1->extractSubstitutions(owner, description, predecessor, status);
143 }
144 else {
145 // if the description does contain a matched pair of brackets,
146 // then it's really shorthand for two rules (with one exception)
147 NFRule* rule2 = nullptr;
148 UnicodeString sbuf;
149
150 // we'll actually only split the rule into two rules if its
151 // base value is an even multiple of its divisor (or it's one
152 // of the special rules)
153 if ((rule1->baseValue > 0
154 && (rule1->baseValue % util64_pow(rule1->radix, rule1->exponent)) == 0)
155 || rule1->getType() == kImproperFractionRule
156 || rule1->getType() == kDefaultRule) {
157
158 // if it passes that test, new up the second rule. If the
159 // rule set both rules will belong to is a fraction rule
160 // set, they both have the same base value; otherwise,
161 // increment the original rule's base value ("rule1" actually
162 // goes SECOND in the rule set's rule list)
163 rule2 = new NFRule(rbnf, UnicodeString(), status);
164 /* test for nullptr */
165 if (rule2 == nullptr) {
166 status = U_MEMORY_ALLOCATION_ERROR;
167 return;
168 }
169 if (rule1->baseValue >= 0) {
170 rule2->baseValue = rule1->baseValue;
171 if (!owner->isFractionRuleSet()) {
172 ++rule1->baseValue;
173 }
174 }
175
176 // if the description began with "x.x" and contains bracketed
177 // text, it describes both the improper fraction rule and
178 // the proper fraction rule
179 else if (rule1->getType() == kImproperFractionRule) {
180 rule2->setType(kProperFractionRule);
181 }
182
183 // if the description began with "x.0" and contains bracketed
184 // text, it describes both the default rule and the
185 // improper fraction rule
186 else if (rule1->getType() == kDefaultRule) {
187 rule2->baseValue = rule1->baseValue;
188 rule1->setType(kImproperFractionRule);
189 }
190
191 // both rules have the same radix and exponent (i.e., the
192 // same divisor)
193 rule2->radix = rule1->radix;
194 rule2->exponent = rule1->exponent;
195
196 // rule2's rule text omits the stuff in brackets: initialize
197 // its rule text and substitutions accordingly
198 sbuf.append(description, 0, brack1);
199 if (brack2 + 1 < description.length()) {
200 sbuf.append(description, brack2 + 1, description.length() - brack2 - 1);
201 }
202 rule2->extractSubstitutions(owner, sbuf, predecessor, status);
203 }
204
205 // rule1's text includes the text in the brackets but omits
206 // the brackets themselves: initialize _its_ rule text and
207 // substitutions accordingly
208 sbuf.setTo(description, 0, brack1);
209 sbuf.append(description, brack1 + 1, brack2 - brack1 - 1);
210 if (brack2 + 1 < description.length()) {
211 sbuf.append(description, brack2 + 1, description.length() - brack2 - 1);
212 }
213 rule1->extractSubstitutions(owner, sbuf, predecessor, status);
214
215 // if we only have one rule, return it; if we have two, return
216 // a two-element array containing them (notice that rule2 goes
217 // BEFORE rule1 in the list: in all cases, rule2 OMITS the
218 // material in the brackets and rule1 INCLUDES the material
219 // in the brackets)
220 if (rule2 != nullptr) {
221 if (rule2->baseValue >= kNoBase) {
222 rules.add(rule2);
223 }
224 else {
225 owner->setNonNumericalRule(rule2);
226 }
227 }
228 }
229 if (rule1->baseValue >= kNoBase) {
230 rules.add(rule1);
231 }
232 else {
233 owner->setNonNumericalRule(rule1);
234 }
235 }
236
237 /**
238 * This function parses the rule's rule descriptor (i.e., the base
239 * value and/or other tokens that precede the rule's rule text
240 * in the description) and sets the rule's base value, radix, and
241 * exponent according to the descriptor. (If the description doesn't
242 * include a rule descriptor, then this function sets everything to
243 * default values and the rule set sets the rule's real base value).
244 * @param description The rule's description
245 * @return If "description" included a rule descriptor, this is
246 * "description" with the descriptor and any trailing whitespace
247 * stripped off. Otherwise; it's "descriptor" unchangd.
248 */
249 void
parseRuleDescriptor(UnicodeString & description,UErrorCode & status)250 NFRule::parseRuleDescriptor(UnicodeString& description, UErrorCode& status)
251 {
252 // the description consists of a rule descriptor and a rule body,
253 // separated by a colon. The rule descriptor is optional. If
254 // it's omitted, just set the base value to 0.
255 int32_t p = description.indexOf(gColon);
256 if (p != -1) {
257 // copy the descriptor out into its own string and strip it,
258 // along with any trailing whitespace, out of the original
259 // description
260 UnicodeString descriptor;
261 descriptor.setTo(description, 0, p);
262
263 ++p;
264 while (p < description.length() && PatternProps::isWhiteSpace(description.charAt(p))) {
265 ++p;
266 }
267 description.removeBetween(0, p);
268
269 // check first to see if the rule descriptor matches the token
270 // for one of the special rules. If it does, set the base
271 // value to the correct identifier value
272 int descriptorLength = descriptor.length();
273 char16_t firstChar = descriptor.charAt(0);
274 char16_t lastChar = descriptor.charAt(descriptorLength - 1);
275 if (firstChar >= gZero && firstChar <= gNine && lastChar != gX) {
276 // if the rule descriptor begins with a digit, it's a descriptor
277 // for a normal rule
278 // since we don't have Long.parseLong, and this isn't much work anyway,
279 // just build up the value as we encounter the digits.
280 int64_t val = 0;
281 p = 0;
282 char16_t c = gSpace;
283
284 // begin parsing the descriptor: copy digits
285 // into "tempValue", skip periods, commas, and spaces,
286 // stop on a slash or > sign (or at the end of the string),
287 // and throw an exception on any other character
288 int64_t ll_10 = 10;
289 while (p < descriptorLength) {
290 c = descriptor.charAt(p);
291 if (c >= gZero && c <= gNine) {
292 val = val * ll_10 + (int32_t)(c - gZero);
293 }
294 else if (c == gSlash || c == gGreaterThan) {
295 break;
296 }
297 else if (PatternProps::isWhiteSpace(c) || c == gComma || c == gDot) {
298 }
299 else {
300 // throw new IllegalArgumentException("Illegal character in rule descriptor");
301 status = U_PARSE_ERROR;
302 return;
303 }
304 ++p;
305 }
306
307 // we have the base value, so set it
308 setBaseValue(val, status);
309
310 // if we stopped the previous loop on a slash, we're
311 // now parsing the rule's radix. Again, accumulate digits
312 // in tempValue, skip punctuation, stop on a > mark, and
313 // throw an exception on anything else
314 if (c == gSlash) {
315 val = 0;
316 ++p;
317 ll_10 = 10;
318 while (p < descriptorLength) {
319 c = descriptor.charAt(p);
320 if (c >= gZero && c <= gNine) {
321 val = val * ll_10 + (int32_t)(c - gZero);
322 }
323 else if (c == gGreaterThan) {
324 break;
325 }
326 else if (PatternProps::isWhiteSpace(c) || c == gComma || c == gDot) {
327 }
328 else {
329 // throw new IllegalArgumentException("Illegal character is rule descriptor");
330 status = U_PARSE_ERROR;
331 return;
332 }
333 ++p;
334 }
335
336 // tempValue now contain's the rule's radix. Set it
337 // accordingly, and recalculate the rule's exponent
338 radix = (int32_t)val;
339 if (radix == 0) {
340 // throw new IllegalArgumentException("Rule can't have radix of 0");
341 status = U_PARSE_ERROR;
342 }
343
344 exponent = expectedExponent();
345 }
346
347 // if we stopped the previous loop on a > sign, then continue
348 // for as long as we still see > signs. For each one,
349 // decrement the exponent (unless the exponent is already 0).
350 // If we see another character before reaching the end of
351 // the descriptor, that's also a syntax error.
352 if (c == gGreaterThan) {
353 while (p < descriptor.length()) {
354 c = descriptor.charAt(p);
355 if (c == gGreaterThan && exponent > 0) {
356 --exponent;
357 } else {
358 // throw new IllegalArgumentException("Illegal character in rule descriptor");
359 status = U_PARSE_ERROR;
360 return;
361 }
362 ++p;
363 }
364 }
365 }
366 else if (0 == descriptor.compare(gMinusX, 2)) {
367 setType(kNegativeNumberRule);
368 }
369 else if (descriptorLength == 3) {
370 if (firstChar == gZero && lastChar == gX) {
371 setBaseValue(kProperFractionRule, status);
372 decimalPoint = descriptor.charAt(1);
373 }
374 else if (firstChar == gX && lastChar == gX) {
375 setBaseValue(kImproperFractionRule, status);
376 decimalPoint = descriptor.charAt(1);
377 }
378 else if (firstChar == gX && lastChar == gZero) {
379 setBaseValue(kDefaultRule, status);
380 decimalPoint = descriptor.charAt(1);
381 }
382 else if (descriptor.compare(gNaN, 3) == 0) {
383 setBaseValue(kNaNRule, status);
384 }
385 else if (descriptor.compare(gInf, 3) == 0) {
386 setBaseValue(kInfinityRule, status);
387 }
388 }
389 }
390 // else use the default base value for now.
391
392 // finally, if the rule body begins with an apostrophe, strip it off
393 // (this is generally used to put whitespace at the beginning of
394 // a rule's rule text)
395 if (description.length() > 0 && description.charAt(0) == gTick) {
396 description.removeBetween(0, 1);
397 }
398
399 // return the description with all the stuff we've just waded through
400 // stripped off the front. It now contains just the rule body.
401 // return description;
402 }
403
404 /**
405 * Searches the rule's rule text for the substitution tokens,
406 * creates the substitutions, and removes the substitution tokens
407 * from the rule's rule text.
408 * @param owner The rule set containing this rule
409 * @param predecessor The rule preseding this one in "owners" rule list
410 * @param ownersOwner The RuleBasedFormat that owns this rule
411 */
412 void
extractSubstitutions(const NFRuleSet * ruleSet,const UnicodeString & ruleText,const NFRule * predecessor,UErrorCode & status)413 NFRule::extractSubstitutions(const NFRuleSet* ruleSet,
414 const UnicodeString &ruleText,
415 const NFRule* predecessor,
416 UErrorCode& status)
417 {
418 if (U_FAILURE(status)) {
419 return;
420 }
421 fRuleText = ruleText;
422 sub1 = extractSubstitution(ruleSet, predecessor, status);
423 if (sub1 == nullptr) {
424 // Small optimization. There is no need to create a redundant NullSubstitution.
425 sub2 = nullptr;
426 }
427 else {
428 sub2 = extractSubstitution(ruleSet, predecessor, status);
429 }
430 int32_t pluralRuleStart = fRuleText.indexOf(gDollarOpenParenthesis, -1, 0);
431 int32_t pluralRuleEnd = (pluralRuleStart >= 0 ? fRuleText.indexOf(gClosedParenthesisDollar, -1, pluralRuleStart) : -1);
432 if (pluralRuleEnd >= 0) {
433 int32_t endType = fRuleText.indexOf(gComma, pluralRuleStart);
434 if (endType < 0) {
435 status = U_PARSE_ERROR;
436 return;
437 }
438 UnicodeString type(fRuleText.tempSubString(pluralRuleStart + 2, endType - pluralRuleStart - 2));
439 UPluralType pluralType;
440 if (type.startsWith(UNICODE_STRING_SIMPLE("cardinal"))) {
441 pluralType = UPLURAL_TYPE_CARDINAL;
442 }
443 else if (type.startsWith(UNICODE_STRING_SIMPLE("ordinal"))) {
444 pluralType = UPLURAL_TYPE_ORDINAL;
445 }
446 else {
447 status = U_ILLEGAL_ARGUMENT_ERROR;
448 return;
449 }
450 rulePatternFormat = formatter->createPluralFormat(pluralType,
451 fRuleText.tempSubString(endType + 1, pluralRuleEnd - endType - 1), status);
452 }
453 }
454
455 /**
456 * Searches the rule's rule text for the first substitution token,
457 * creates a substitution based on it, and removes the token from
458 * the rule's rule text.
459 * @param owner The rule set containing this rule
460 * @param predecessor The rule preceding this one in the rule set's
461 * rule list
462 * @param ownersOwner The RuleBasedNumberFormat that owns this rule
463 * @return The newly-created substitution. This is never null; if
464 * the rule text doesn't contain any substitution tokens, this will
465 * be a NullSubstitution.
466 */
467 NFSubstitution *
extractSubstitution(const NFRuleSet * ruleSet,const NFRule * predecessor,UErrorCode & status)468 NFRule::extractSubstitution(const NFRuleSet* ruleSet,
469 const NFRule* predecessor,
470 UErrorCode& status)
471 {
472 NFSubstitution* result = nullptr;
473
474 // search the rule's rule text for the first two characters of
475 // a substitution token
476 int32_t subStart = indexOfAnyRulePrefix();
477 int32_t subEnd = subStart;
478
479 // if we didn't find one, create a null substitution positioned
480 // at the end of the rule text
481 if (subStart == -1) {
482 return nullptr;
483 }
484
485 // special-case the ">>>" token, since searching for the > at the
486 // end will actually find the > in the middle
487 if (fRuleText.indexOf(gGreaterGreaterGreater, 3, 0) == subStart) {
488 subEnd = subStart + 2;
489
490 // otherwise the substitution token ends with the same character
491 // it began with
492 } else {
493 char16_t c = fRuleText.charAt(subStart);
494 subEnd = fRuleText.indexOf(c, subStart + 1);
495 // special case for '<%foo<<'
496 if (c == gLessThan && subEnd != -1 && subEnd < fRuleText.length() - 1 && fRuleText.charAt(subEnd+1) == c) {
497 // ordinals use "=#,##0==%abbrev=" as their rule. Notice that the '==' in the middle
498 // occurs because of the juxtaposition of two different rules. The check for '<' is a hack
499 // to get around this. Having the duplicate at the front would cause problems with
500 // rules like "<<%" to format, say, percents...
501 ++subEnd;
502 }
503 }
504
505 // if we don't find the end of the token (i.e., if we're on a single,
506 // unmatched token character), create a null substitution positioned
507 // at the end of the rule
508 if (subEnd == -1) {
509 return nullptr;
510 }
511
512 // if we get here, we have a real substitution token (or at least
513 // some text bounded by substitution token characters). Use
514 // makeSubstitution() to create the right kind of substitution
515 UnicodeString subToken;
516 subToken.setTo(fRuleText, subStart, subEnd + 1 - subStart);
517 result = NFSubstitution::makeSubstitution(subStart, this, predecessor, ruleSet,
518 this->formatter, subToken, status);
519
520 // remove the substitution from the rule text
521 fRuleText.removeBetween(subStart, subEnd+1);
522
523 return result;
524 }
525
526 /**
527 * Sets the rule's base value, and causes the radix and exponent
528 * to be recalculated. This is used during construction when we
529 * don't know the rule's base value until after it's been
530 * constructed. It should be used at any other time.
531 * @param The new base value for the rule.
532 */
533 void
setBaseValue(int64_t newBaseValue,UErrorCode & status)534 NFRule::setBaseValue(int64_t newBaseValue, UErrorCode& status)
535 {
536 // set the base value
537 baseValue = newBaseValue;
538 radix = 10;
539
540 // if this isn't a special rule, recalculate the radix and exponent
541 // (the radix always defaults to 10; if it's supposed to be something
542 // else, it's cleaned up by the caller and the exponent is
543 // recalculated again-- the only function that does this is
544 // NFRule.parseRuleDescriptor() )
545 if (baseValue >= 1) {
546 exponent = expectedExponent();
547
548 // this function gets called on a fully-constructed rule whose
549 // description didn't specify a base value. This means it
550 // has substitutions, and some substitutions hold on to copies
551 // of the rule's divisor. Fix their copies of the divisor.
552 if (sub1 != nullptr) {
553 sub1->setDivisor(radix, exponent, status);
554 }
555 if (sub2 != nullptr) {
556 sub2->setDivisor(radix, exponent, status);
557 }
558
559 // if this is a special rule, its radix and exponent are basically
560 // ignored. Set them to "safe" default values
561 } else {
562 exponent = 0;
563 }
564 }
565
566 /**
567 * This calculates the rule's exponent based on its radix and base
568 * value. This will be the highest power the radix can be raised to
569 * and still produce a result less than or equal to the base value.
570 */
571 int16_t
expectedExponent() const572 NFRule::expectedExponent() const
573 {
574 // since the log of 0, or the log base 0 of something, causes an
575 // error, declare the exponent in these cases to be 0 (we also
576 // deal with the special-rule identifiers here)
577 if (radix == 0 || baseValue < 1) {
578 return 0;
579 }
580
581 // we get rounding error in some cases-- for example, log 1000 / log 10
582 // gives us 1.9999999996 instead of 2. The extra logic here is to take
583 // that into account
584 int16_t tempResult = (int16_t)(uprv_log((double)baseValue) / uprv_log((double)radix));
585 int64_t temp = util64_pow(radix, tempResult + 1);
586 if (temp <= baseValue) {
587 tempResult += 1;
588 }
589 return tempResult;
590 }
591
592 /**
593 * Searches the rule's rule text for any of the specified strings.
594 * @return The index of the first match in the rule's rule text
595 * (i.e., the first substring in the rule's rule text that matches
596 * _any_ of the strings in "strings"). If none of the strings in
597 * "strings" is found in the rule's rule text, returns -1.
598 */
599 int32_t
indexOfAnyRulePrefix() const600 NFRule::indexOfAnyRulePrefix() const
601 {
602 int result = -1;
603 for (int i = 0; RULE_PREFIXES[i]; i++) {
604 int32_t pos = fRuleText.indexOf(*RULE_PREFIXES[i]);
605 if (pos != -1 && (result == -1 || pos < result)) {
606 result = pos;
607 }
608 }
609 return result;
610 }
611
612 //-----------------------------------------------------------------------
613 // boilerplate
614 //-----------------------------------------------------------------------
615
616 static UBool
util_equalSubstitutions(const NFSubstitution * sub1,const NFSubstitution * sub2)617 util_equalSubstitutions(const NFSubstitution* sub1, const NFSubstitution* sub2)
618 {
619 if (sub1) {
620 if (sub2) {
621 return *sub1 == *sub2;
622 }
623 } else if (!sub2) {
624 return true;
625 }
626 return false;
627 }
628
629 /**
630 * Tests two rules for equality.
631 * @param that The rule to compare this one against
632 * @return True is the two rules are functionally equivalent
633 */
634 bool
operator ==(const NFRule & rhs) const635 NFRule::operator==(const NFRule& rhs) const
636 {
637 return baseValue == rhs.baseValue
638 && radix == rhs.radix
639 && exponent == rhs.exponent
640 && fRuleText == rhs.fRuleText
641 && util_equalSubstitutions(sub1, rhs.sub1)
642 && util_equalSubstitutions(sub2, rhs.sub2);
643 }
644
645 /**
646 * Returns a textual representation of the rule. This won't
647 * necessarily be the same as the description that this rule
648 * was created with, but it will produce the same result.
649 * @return A textual description of the rule
650 */
util_append64(UnicodeString & result,int64_t n)651 static void util_append64(UnicodeString& result, int64_t n)
652 {
653 char16_t buffer[256];
654 int32_t len = util64_tou(n, buffer, sizeof(buffer));
655 UnicodeString temp(buffer, len);
656 result.append(temp);
657 }
658
659 void
_appendRuleText(UnicodeString & result) const660 NFRule::_appendRuleText(UnicodeString& result) const
661 {
662 switch (getType()) {
663 case kNegativeNumberRule: result.append(gMinusX, 2); break;
664 case kImproperFractionRule: result.append(gX).append(decimalPoint == 0 ? gDot : decimalPoint).append(gX); break;
665 case kProperFractionRule: result.append(gZero).append(decimalPoint == 0 ? gDot : decimalPoint).append(gX); break;
666 case kDefaultRule: result.append(gX).append(decimalPoint == 0 ? gDot : decimalPoint).append(gZero); break;
667 case kInfinityRule: result.append(gInf, 3); break;
668 case kNaNRule: result.append(gNaN, 3); break;
669 default:
670 // for a normal rule, write out its base value, and if the radix is
671 // something other than 10, write out the radix (with the preceding
672 // slash, of course). Then calculate the expected exponent and if
673 // if isn't the same as the actual exponent, write an appropriate
674 // number of > signs. Finally, terminate the whole thing with
675 // a colon.
676 util_append64(result, baseValue);
677 if (radix != 10) {
678 result.append(gSlash);
679 util_append64(result, radix);
680 }
681 int numCarets = expectedExponent() - exponent;
682 for (int i = 0; i < numCarets; i++) {
683 result.append(gGreaterThan);
684 }
685 break;
686 }
687 result.append(gColon);
688 result.append(gSpace);
689
690 // if the rule text begins with a space, write an apostrophe
691 // (whitespace after the rule descriptor is ignored; the
692 // apostrophe is used to make the whitespace significant)
693 if (fRuleText.charAt(0) == gSpace && (sub1 == nullptr || sub1->getPos() != 0)) {
694 result.append(gTick);
695 }
696
697 // now, write the rule's rule text, inserting appropriate
698 // substitution tokens in the appropriate places
699 UnicodeString ruleTextCopy;
700 ruleTextCopy.setTo(fRuleText);
701
702 UnicodeString temp;
703 if (sub2 != nullptr) {
704 sub2->toString(temp);
705 ruleTextCopy.insert(sub2->getPos(), temp);
706 }
707 if (sub1 != nullptr) {
708 sub1->toString(temp);
709 ruleTextCopy.insert(sub1->getPos(), temp);
710 }
711
712 result.append(ruleTextCopy);
713
714 // and finally, top the whole thing off with a semicolon and
715 // return the result
716 result.append(gSemicolon);
717 }
718
getDivisor() const719 int64_t NFRule::getDivisor() const
720 {
721 return util64_pow(radix, exponent);
722 }
723
724 /**
725 * Internal function to facilitate numerical rounding. See the explanation in MultiplierSubstitution::transformNumber().
726 */
hasModulusSubstitution() const727 bool NFRule::hasModulusSubstitution() const
728 {
729 return (sub1 != nullptr && sub1->isModulusSubstitution()) || (sub2 != nullptr && sub2->isModulusSubstitution());
730 }
731
732
733 //-----------------------------------------------------------------------
734 // formatting
735 //-----------------------------------------------------------------------
736
737 /**
738 * Formats the number, and inserts the resulting text into
739 * toInsertInto.
740 * @param number The number being formatted
741 * @param toInsertInto The string where the resultant text should
742 * be inserted
743 * @param pos The position in toInsertInto where the resultant text
744 * should be inserted
745 */
746 void
doFormat(int64_t number,UnicodeString & toInsertInto,int32_t pos,int32_t recursionCount,UErrorCode & status) const747 NFRule::doFormat(int64_t number, UnicodeString& toInsertInto, int32_t pos, int32_t recursionCount, UErrorCode& status) const
748 {
749 // first, insert the rule's rule text into toInsertInto at the
750 // specified position, then insert the results of the substitutions
751 // into the right places in toInsertInto (notice we do the
752 // substitutions in reverse order so that the offsets don't get
753 // messed up)
754 int32_t pluralRuleStart = fRuleText.length();
755 int32_t lengthOffset = 0;
756 if (!rulePatternFormat) {
757 toInsertInto.insert(pos, fRuleText);
758 }
759 else {
760 pluralRuleStart = fRuleText.indexOf(gDollarOpenParenthesis, -1, 0);
761 int pluralRuleEnd = fRuleText.indexOf(gClosedParenthesisDollar, -1, pluralRuleStart);
762 int initialLength = toInsertInto.length();
763 if (pluralRuleEnd < fRuleText.length() - 1) {
764 toInsertInto.insert(pos, fRuleText.tempSubString(pluralRuleEnd + 2));
765 }
766 toInsertInto.insert(pos,
767 rulePatternFormat->format((int32_t)(number/util64_pow(radix, exponent)), status));
768 if (pluralRuleStart > 0) {
769 toInsertInto.insert(pos, fRuleText.tempSubString(0, pluralRuleStart));
770 }
771 lengthOffset = fRuleText.length() - (toInsertInto.length() - initialLength);
772 }
773
774 if (sub2 != nullptr) {
775 sub2->doSubstitution(number, toInsertInto, pos - (sub2->getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount, status);
776 }
777 if (sub1 != nullptr) {
778 sub1->doSubstitution(number, toInsertInto, pos - (sub1->getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount, status);
779 }
780 }
781
782 /**
783 * Formats the number, and inserts the resulting text into
784 * toInsertInto.
785 * @param number The number being formatted
786 * @param toInsertInto The string where the resultant text should
787 * be inserted
788 * @param pos The position in toInsertInto where the resultant text
789 * should be inserted
790 */
791 void
doFormat(double number,UnicodeString & toInsertInto,int32_t pos,int32_t recursionCount,UErrorCode & status) const792 NFRule::doFormat(double number, UnicodeString& toInsertInto, int32_t pos, int32_t recursionCount, UErrorCode& status) const
793 {
794 // first, insert the rule's rule text into toInsertInto at the
795 // specified position, then insert the results of the substitutions
796 // into the right places in toInsertInto
797 // [again, we have two copies of this routine that do the same thing
798 // so that we don't sacrifice precision in a long by casting it
799 // to a double]
800 int32_t pluralRuleStart = fRuleText.length();
801 int32_t lengthOffset = 0;
802 if (!rulePatternFormat) {
803 toInsertInto.insert(pos, fRuleText);
804 }
805 else {
806 pluralRuleStart = fRuleText.indexOf(gDollarOpenParenthesis, -1, 0);
807 int pluralRuleEnd = fRuleText.indexOf(gClosedParenthesisDollar, -1, pluralRuleStart);
808 int initialLength = toInsertInto.length();
809 if (pluralRuleEnd < fRuleText.length() - 1) {
810 toInsertInto.insert(pos, fRuleText.tempSubString(pluralRuleEnd + 2));
811 }
812 double pluralVal = number;
813 if (0 <= pluralVal && pluralVal < 1) {
814 // We're in a fractional rule, and we have to match the NumeratorSubstitution behavior.
815 // 2.3 can become 0.2999999999999998 for the fraction due to rounding errors.
816 pluralVal = uprv_round(pluralVal * util64_pow(radix, exponent));
817 }
818 else {
819 pluralVal = pluralVal / util64_pow(radix, exponent);
820 }
821 toInsertInto.insert(pos, rulePatternFormat->format((int32_t)(pluralVal), status));
822 if (pluralRuleStart > 0) {
823 toInsertInto.insert(pos, fRuleText.tempSubString(0, pluralRuleStart));
824 }
825 lengthOffset = fRuleText.length() - (toInsertInto.length() - initialLength);
826 }
827
828 if (sub2 != nullptr) {
829 sub2->doSubstitution(number, toInsertInto, pos - (sub2->getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount, status);
830 }
831 if (sub1 != nullptr) {
832 sub1->doSubstitution(number, toInsertInto, pos - (sub1->getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount, status);
833 }
834 }
835
836 /**
837 * Used by the owning rule set to determine whether to invoke the
838 * rollback rule (i.e., whether this rule or the one that precedes
839 * it in the rule set's list should be used to format the number)
840 * @param The number being formatted
841 * @return True if the rule set should use the rule that precedes
842 * this one in its list; false if it should use this rule
843 */
844 UBool
shouldRollBack(int64_t number) const845 NFRule::shouldRollBack(int64_t number) const
846 {
847 // we roll back if the rule contains a modulus substitution,
848 // the number being formatted is an even multiple of the rule's
849 // divisor, and the rule's base value is NOT an even multiple
850 // of its divisor
851 // In other words, if the original description had
852 // 100: << hundred[ >>];
853 // that expands into
854 // 100: << hundred;
855 // 101: << hundred >>;
856 // internally. But when we're formatting 200, if we use the rule
857 // at 101, which would normally apply, we get "two hundred zero".
858 // To prevent this, we roll back and use the rule at 100 instead.
859 // This is the logic that makes this happen: the rule at 101 has
860 // a modulus substitution, its base value isn't an even multiple
861 // of 100, and the value we're trying to format _is_ an even
862 // multiple of 100. This is called the "rollback rule."
863 if ((sub1 != nullptr && sub1->isModulusSubstitution()) || (sub2 != nullptr && sub2->isModulusSubstitution())) {
864 int64_t re = util64_pow(radix, exponent);
865 return (number % re) == 0 && (baseValue % re) != 0;
866 }
867 return false;
868 }
869
870 //-----------------------------------------------------------------------
871 // parsing
872 //-----------------------------------------------------------------------
873
874 /**
875 * Attempts to parse the string with this rule.
876 * @param text The string being parsed
877 * @param parsePosition On entry, the value is ignored and assumed to
878 * be 0. On exit, this has been updated with the position of the first
879 * character not consumed by matching the text against this rule
880 * (if this rule doesn't match the text at all, the parse position
881 * if left unchanged (presumably at 0) and the function returns
882 * new Long(0)).
883 * @param isFractionRule True if this rule is contained within a
884 * fraction rule set. This is only used if the rule has no
885 * substitutions.
886 * @return If this rule matched the text, this is the rule's base value
887 * combined appropriately with the results of parsing the substitutions.
888 * If nothing matched, this is new Long(0) and the parse position is
889 * left unchanged. The result will be an instance of Long if the
890 * result is an integer and Double otherwise. The result is never null.
891 */
892 #ifdef RBNF_DEBUG
893 #include <stdio.h>
894
dumpUS(FILE * f,const UnicodeString & us)895 static void dumpUS(FILE* f, const UnicodeString& us) {
896 int len = us.length();
897 char* buf = (char *)uprv_malloc((len+1)*sizeof(char)); //new char[len+1];
898 if (buf != nullptr) {
899 us.extract(0, len, buf);
900 buf[len] = 0;
901 fprintf(f, "%s", buf);
902 uprv_free(buf); //delete[] buf;
903 }
904 }
905 #endif
906 UBool
doParse(const UnicodeString & text,ParsePosition & parsePosition,UBool isFractionRule,double upperBound,uint32_t nonNumericalExecutedRuleMask,Formattable & resVal) const907 NFRule::doParse(const UnicodeString& text,
908 ParsePosition& parsePosition,
909 UBool isFractionRule,
910 double upperBound,
911 uint32_t nonNumericalExecutedRuleMask,
912 Formattable& resVal) const
913 {
914 // internally we operate on a copy of the string being parsed
915 // (because we're going to change it) and use our own ParsePosition
916 ParsePosition pp;
917 UnicodeString workText(text);
918
919 int32_t sub1Pos = sub1 != nullptr ? sub1->getPos() : fRuleText.length();
920 int32_t sub2Pos = sub2 != nullptr ? sub2->getPos() : fRuleText.length();
921
922 // check to see whether the text before the first substitution
923 // matches the text at the beginning of the string being
924 // parsed. If it does, strip that off the front of workText;
925 // otherwise, dump out with a mismatch
926 UnicodeString prefix;
927 prefix.setTo(fRuleText, 0, sub1Pos);
928
929 #ifdef RBNF_DEBUG
930 fprintf(stderr, "doParse %p ", this);
931 {
932 UnicodeString rt;
933 _appendRuleText(rt);
934 dumpUS(stderr, rt);
935 }
936
937 fprintf(stderr, " text: '");
938 dumpUS(stderr, text);
939 fprintf(stderr, "' prefix: '");
940 dumpUS(stderr, prefix);
941 #endif
942 stripPrefix(workText, prefix, pp);
943 int32_t prefixLength = text.length() - workText.length();
944
945 #ifdef RBNF_DEBUG
946 fprintf(stderr, "' pl: %d ppi: %d s1p: %d\n", prefixLength, pp.getIndex(), sub1Pos);
947 #endif
948
949 if (pp.getIndex() == 0 && sub1Pos != 0) {
950 // commented out because ParsePosition doesn't have error index in 1.1.x
951 // restored for ICU4C port
952 parsePosition.setErrorIndex(pp.getErrorIndex());
953 resVal.setLong(0);
954 return true;
955 }
956 if (baseValue == kInfinityRule) {
957 // If you match this, don't try to perform any calculations on it.
958 parsePosition.setIndex(pp.getIndex());
959 resVal.setDouble(uprv_getInfinity());
960 return true;
961 }
962 if (baseValue == kNaNRule) {
963 // If you match this, don't try to perform any calculations on it.
964 parsePosition.setIndex(pp.getIndex());
965 resVal.setDouble(uprv_getNaN());
966 return true;
967 }
968
969 // this is the fun part. The basic guts of the rule-matching
970 // logic is matchToDelimiter(), which is called twice. The first
971 // time it searches the input string for the rule text BETWEEN
972 // the substitutions and tries to match the intervening text
973 // in the input string with the first substitution. If that
974 // succeeds, it then calls it again, this time to look for the
975 // rule text after the second substitution and to match the
976 // intervening input text against the second substitution.
977 //
978 // For example, say we have a rule that looks like this:
979 // first << middle >> last;
980 // and input text that looks like this:
981 // first one middle two last
982 // First we use stripPrefix() to match "first " in both places and
983 // strip it off the front, leaving
984 // one middle two last
985 // Then we use matchToDelimiter() to match " middle " and try to
986 // match "one" against a substitution. If it's successful, we now
987 // have
988 // two last
989 // We use matchToDelimiter() a second time to match " last" and
990 // try to match "two" against a substitution. If "two" matches
991 // the substitution, we have a successful parse.
992 //
993 // Since it's possible in many cases to find multiple instances
994 // of each of these pieces of rule text in the input string,
995 // we need to try all the possible combinations of these
996 // locations. This prevents us from prematurely declaring a mismatch,
997 // and makes sure we match as much input text as we can.
998 int highWaterMark = 0;
999 double result = 0;
1000 int start = 0;
1001 double tempBaseValue = (double)(baseValue <= 0 ? 0 : baseValue);
1002
1003 UnicodeString temp;
1004 do {
1005 // our partial parse result starts out as this rule's base
1006 // value. If it finds a successful match, matchToDelimiter()
1007 // will compose this in some way with what it gets back from
1008 // the substitution, giving us a new partial parse result
1009 pp.setIndex(0);
1010
1011 temp.setTo(fRuleText, sub1Pos, sub2Pos - sub1Pos);
1012 double partialResult = matchToDelimiter(workText, start, tempBaseValue,
1013 temp, pp, sub1,
1014 nonNumericalExecutedRuleMask,
1015 upperBound);
1016
1017 // if we got a successful match (or were trying to match a
1018 // null substitution), pp is now pointing at the first unmatched
1019 // character. Take note of that, and try matchToDelimiter()
1020 // on the input text again
1021 if (pp.getIndex() != 0 || sub1 == nullptr) {
1022 start = pp.getIndex();
1023
1024 UnicodeString workText2;
1025 workText2.setTo(workText, pp.getIndex(), workText.length() - pp.getIndex());
1026 ParsePosition pp2;
1027
1028 // the second matchToDelimiter() will compose our previous
1029 // partial result with whatever it gets back from its
1030 // substitution if there's a successful match, giving us
1031 // a real result
1032 temp.setTo(fRuleText, sub2Pos, fRuleText.length() - sub2Pos);
1033 partialResult = matchToDelimiter(workText2, 0, partialResult,
1034 temp, pp2, sub2,
1035 nonNumericalExecutedRuleMask,
1036 upperBound);
1037
1038 // if we got a successful match on this second
1039 // matchToDelimiter() call, update the high-water mark
1040 // and result (if necessary)
1041 if (pp2.getIndex() != 0 || sub2 == nullptr) {
1042 if (prefixLength + pp.getIndex() + pp2.getIndex() > highWaterMark) {
1043 highWaterMark = prefixLength + pp.getIndex() + pp2.getIndex();
1044 result = partialResult;
1045 }
1046 }
1047 else {
1048 // commented out because ParsePosition doesn't have error index in 1.1.x
1049 // restored for ICU4C port
1050 int32_t i_temp = pp2.getErrorIndex() + sub1Pos + pp.getIndex();
1051 if (i_temp> parsePosition.getErrorIndex()) {
1052 parsePosition.setErrorIndex(i_temp);
1053 }
1054 }
1055 }
1056 else {
1057 // commented out because ParsePosition doesn't have error index in 1.1.x
1058 // restored for ICU4C port
1059 int32_t i_temp = sub1Pos + pp.getErrorIndex();
1060 if (i_temp > parsePosition.getErrorIndex()) {
1061 parsePosition.setErrorIndex(i_temp);
1062 }
1063 }
1064 // keep trying to match things until the outer matchToDelimiter()
1065 // call fails to make a match (each time, it picks up where it
1066 // left off the previous time)
1067 } while (sub1Pos != sub2Pos
1068 && pp.getIndex() > 0
1069 && pp.getIndex() < workText.length()
1070 && pp.getIndex() != start);
1071
1072 // update the caller's ParsePosition with our high-water mark
1073 // (i.e., it now points at the first character this function
1074 // didn't match-- the ParsePosition is therefore unchanged if
1075 // we didn't match anything)
1076 parsePosition.setIndex(highWaterMark);
1077 // commented out because ParsePosition doesn't have error index in 1.1.x
1078 // restored for ICU4C port
1079 if (highWaterMark > 0) {
1080 parsePosition.setErrorIndex(0);
1081 }
1082
1083 // this is a hack for one unusual condition: Normally, whether this
1084 // rule belong to a fraction rule set or not is handled by its
1085 // substitutions. But if that rule HAS NO substitutions, then
1086 // we have to account for it here. By definition, if the matching
1087 // rule in a fraction rule set has no substitutions, its numerator
1088 // is 1, and so the result is the reciprocal of its base value.
1089 if (isFractionRule && highWaterMark > 0 && sub1 == nullptr) {
1090 result = 1 / result;
1091 }
1092
1093 resVal.setDouble(result);
1094 return true; // ??? do we need to worry if it is a long or a double?
1095 }
1096
1097 /**
1098 * This function is used by parse() to match the text being parsed
1099 * against a possible prefix string. This function
1100 * matches characters from the beginning of the string being parsed
1101 * to characters from the prospective prefix. If they match, pp is
1102 * updated to the first character not matched, and the result is
1103 * the unparsed part of the string. If they don't match, the whole
1104 * string is returned, and pp is left unchanged.
1105 * @param text The string being parsed
1106 * @param prefix The text to match against
1107 * @param pp On entry, ignored and assumed to be 0. On exit, points
1108 * to the first unmatched character (assuming the whole prefix matched),
1109 * or is unchanged (if the whole prefix didn't match).
1110 * @return If things match, this is the unparsed part of "text";
1111 * if they didn't match, this is "text".
1112 */
1113 void
stripPrefix(UnicodeString & text,const UnicodeString & prefix,ParsePosition & pp) const1114 NFRule::stripPrefix(UnicodeString& text, const UnicodeString& prefix, ParsePosition& pp) const
1115 {
1116 // if the prefix text is empty, dump out without doing anything
1117 if (prefix.length() != 0) {
1118 UErrorCode status = U_ZERO_ERROR;
1119 // use prefixLength() to match the beginning of
1120 // "text" against "prefix". This function returns the
1121 // number of characters from "text" that matched (or 0 if
1122 // we didn't match the whole prefix)
1123 int32_t pfl = prefixLength(text, prefix, status);
1124 if (U_FAILURE(status)) { // Memory allocation error.
1125 return;
1126 }
1127 if (pfl != 0) {
1128 // if we got a successful match, update the parse position
1129 // and strip the prefix off of "text"
1130 pp.setIndex(pp.getIndex() + pfl);
1131 text.remove(0, pfl);
1132 }
1133 }
1134 }
1135
1136 /**
1137 * Used by parse() to match a substitution and any following text.
1138 * "text" is searched for instances of "delimiter". For each instance
1139 * of delimiter, the intervening text is tested to see whether it
1140 * matches the substitution. The longest match wins.
1141 * @param text The string being parsed
1142 * @param startPos The position in "text" where we should start looking
1143 * for "delimiter".
1144 * @param baseValue A partial parse result (often the rule's base value),
1145 * which is combined with the result from matching the substitution
1146 * @param delimiter The string to search "text" for.
1147 * @param pp Ignored and presumed to be 0 on entry. If there's a match,
1148 * on exit this will point to the first unmatched character.
1149 * @param sub If we find "delimiter" in "text", this substitution is used
1150 * to match the text between the beginning of the string and the
1151 * position of "delimiter." (If "delimiter" is the empty string, then
1152 * this function just matches against this substitution and updates
1153 * everything accordingly.)
1154 * @param upperBound When matching the substitution, it will only
1155 * consider rules with base values lower than this value.
1156 * @return If there's a match, this is the result of composing
1157 * baseValue with the result of matching the substitution. Otherwise,
1158 * this is new Long(0). It's never null. If the result is an integer,
1159 * this will be an instance of Long; otherwise, it's an instance of
1160 * Double.
1161 *
1162 * !!! note {dlf} in point of fact, in the java code the caller always converts
1163 * the result to a double, so we might as well return one.
1164 */
1165 double
matchToDelimiter(const UnicodeString & text,int32_t startPos,double _baseValue,const UnicodeString & delimiter,ParsePosition & pp,const NFSubstitution * sub,uint32_t nonNumericalExecutedRuleMask,double upperBound) const1166 NFRule::matchToDelimiter(const UnicodeString& text,
1167 int32_t startPos,
1168 double _baseValue,
1169 const UnicodeString& delimiter,
1170 ParsePosition& pp,
1171 const NFSubstitution* sub,
1172 uint32_t nonNumericalExecutedRuleMask,
1173 double upperBound) const
1174 {
1175 UErrorCode status = U_ZERO_ERROR;
1176 // if "delimiter" contains real (i.e., non-ignorable) text, search
1177 // it for "delimiter" beginning at "start". If that succeeds, then
1178 // use "sub"'s doParse() method to match the text before the
1179 // instance of "delimiter" we just found.
1180 if (!allIgnorable(delimiter, status)) {
1181 if (U_FAILURE(status)) { //Memory allocation error.
1182 return 0;
1183 }
1184 ParsePosition tempPP;
1185 Formattable result;
1186
1187 // use findText() to search for "delimiter". It returns a two-
1188 // element array: element 0 is the position of the match, and
1189 // element 1 is the number of characters that matched
1190 // "delimiter".
1191 int32_t dLen;
1192 int32_t dPos = findText(text, delimiter, startPos, &dLen);
1193
1194 // if findText() succeeded, isolate the text preceding the
1195 // match, and use "sub" to match that text
1196 while (dPos >= 0) {
1197 UnicodeString subText;
1198 subText.setTo(text, 0, dPos);
1199 if (subText.length() > 0) {
1200 UBool success = sub->doParse(subText, tempPP, _baseValue, upperBound,
1201 #if UCONFIG_NO_COLLATION
1202 false,
1203 #else
1204 formatter->isLenient(),
1205 #endif
1206 nonNumericalExecutedRuleMask,
1207 result);
1208
1209 // if the substitution could match all the text up to
1210 // where we found "delimiter", then this function has
1211 // a successful match. Bump the caller's parse position
1212 // to point to the first character after the text
1213 // that matches "delimiter", and return the result
1214 // we got from parsing the substitution.
1215 if (success && tempPP.getIndex() == dPos) {
1216 pp.setIndex(dPos + dLen);
1217 return result.getDouble();
1218 }
1219 else {
1220 // commented out because ParsePosition doesn't have error index in 1.1.x
1221 // restored for ICU4C port
1222 if (tempPP.getErrorIndex() > 0) {
1223 pp.setErrorIndex(tempPP.getErrorIndex());
1224 } else {
1225 pp.setErrorIndex(tempPP.getIndex());
1226 }
1227 }
1228 }
1229
1230 // if we didn't match the substitution, search for another
1231 // copy of "delimiter" in "text" and repeat the loop if
1232 // we find it
1233 tempPP.setIndex(0);
1234 dPos = findText(text, delimiter, dPos + dLen, &dLen);
1235 }
1236 // if we make it here, this was an unsuccessful match, and we
1237 // leave pp unchanged and return 0
1238 pp.setIndex(0);
1239 return 0;
1240
1241 // if "delimiter" is empty, or consists only of ignorable characters
1242 // (i.e., is semantically empty), thwe we obviously can't search
1243 // for "delimiter". Instead, just use "sub" to parse as much of
1244 // "text" as possible.
1245 }
1246 else if (sub == nullptr) {
1247 return _baseValue;
1248 }
1249 else {
1250 ParsePosition tempPP;
1251 Formattable result;
1252
1253 // try to match the whole string against the substitution
1254 UBool success = sub->doParse(text, tempPP, _baseValue, upperBound,
1255 #if UCONFIG_NO_COLLATION
1256 false,
1257 #else
1258 formatter->isLenient(),
1259 #endif
1260 nonNumericalExecutedRuleMask,
1261 result);
1262 if (success && (tempPP.getIndex() != 0)) {
1263 // if there's a successful match (or it's a null
1264 // substitution), update pp to point to the first
1265 // character we didn't match, and pass the result from
1266 // sub.doParse() on through to the caller
1267 pp.setIndex(tempPP.getIndex());
1268 return result.getDouble();
1269 }
1270 else {
1271 // commented out because ParsePosition doesn't have error index in 1.1.x
1272 // restored for ICU4C port
1273 pp.setErrorIndex(tempPP.getErrorIndex());
1274 }
1275
1276 // and if we get to here, then nothing matched, so we return
1277 // 0 and leave pp alone
1278 return 0;
1279 }
1280 }
1281
1282 /**
1283 * Used by stripPrefix() to match characters. If lenient parse mode
1284 * is off, this just calls startsWith(). If lenient parse mode is on,
1285 * this function uses CollationElementIterators to match characters in
1286 * the strings (only primary-order differences are significant in
1287 * determining whether there's a match).
1288 * @param str The string being tested
1289 * @param prefix The text we're hoping to see at the beginning
1290 * of "str"
1291 * @return If "prefix" is found at the beginning of "str", this
1292 * is the number of characters in "str" that were matched (this
1293 * isn't necessarily the same as the length of "prefix" when matching
1294 * text with a collator). If there's no match, this is 0.
1295 */
1296 int32_t
prefixLength(const UnicodeString & str,const UnicodeString & prefix,UErrorCode & status) const1297 NFRule::prefixLength(const UnicodeString& str, const UnicodeString& prefix, UErrorCode& status) const
1298 {
1299 // if we're looking for an empty prefix, it obviously matches
1300 // zero characters. Just go ahead and return 0.
1301 if (prefix.length() == 0) {
1302 return 0;
1303 }
1304
1305 #if !UCONFIG_NO_COLLATION
1306 // go through all this grief if we're in lenient-parse mode
1307 if (formatter->isLenient()) {
1308 // Check if non-lenient rule finds the text before call lenient parsing
1309 if (str.startsWith(prefix)) {
1310 return prefix.length();
1311 }
1312 // get the formatter's collator and use it to create two
1313 // collation element iterators, one over the target string
1314 // and another over the prefix (right now, we'll throw an
1315 // exception if the collator we get back from the formatter
1316 // isn't a RuleBasedCollator, because RuleBasedCollator defines
1317 // the CollationElementIterator protocol. Hopefully, this
1318 // will change someday.)
1319 const RuleBasedCollator* collator = formatter->getCollator();
1320 if (collator == nullptr) {
1321 status = U_MEMORY_ALLOCATION_ERROR;
1322 return 0;
1323 }
1324 LocalPointer<CollationElementIterator> strIter(collator->createCollationElementIterator(str));
1325 LocalPointer<CollationElementIterator> prefixIter(collator->createCollationElementIterator(prefix));
1326 // Check for memory allocation error.
1327 if (strIter.isNull() || prefixIter.isNull()) {
1328 status = U_MEMORY_ALLOCATION_ERROR;
1329 return 0;
1330 }
1331
1332 UErrorCode err = U_ZERO_ERROR;
1333
1334 // The original code was problematic. Consider this match:
1335 // prefix = "fifty-"
1336 // string = " fifty-7"
1337 // The intent is to match string up to the '7', by matching 'fifty-' at position 1
1338 // in the string. Unfortunately, we were getting a match, and then computing where
1339 // the match terminated by rematching the string. The rematch code was using as an
1340 // initial guess the substring of string between 0 and prefix.length. Because of
1341 // the leading space and trailing hyphen (both ignorable) this was succeeding, leaving
1342 // the position before the hyphen in the string. Recursing down, we then parsed the
1343 // remaining string '-7' as numeric. The resulting number turned out as 43 (50 - 7).
1344 // This was not pretty, especially since the string "fifty-7" parsed just fine.
1345 //
1346 // We have newer APIs now, so we can use calls on the iterator to determine what we
1347 // matched up to. If we terminate because we hit the last element in the string,
1348 // our match terminates at this length. If we terminate because we hit the last element
1349 // in the target, our match terminates at one before the element iterator position.
1350
1351 // match collation elements between the strings
1352 int32_t oStr = strIter->next(err);
1353 int32_t oPrefix = prefixIter->next(err);
1354
1355 while (oPrefix != CollationElementIterator::NULLORDER) {
1356 // skip over ignorable characters in the target string
1357 while (CollationElementIterator::primaryOrder(oStr) == 0
1358 && oStr != CollationElementIterator::NULLORDER) {
1359 oStr = strIter->next(err);
1360 }
1361
1362 // skip over ignorable characters in the prefix
1363 while (CollationElementIterator::primaryOrder(oPrefix) == 0
1364 && oPrefix != CollationElementIterator::NULLORDER) {
1365 oPrefix = prefixIter->next(err);
1366 }
1367
1368 // dlf: move this above following test, if we consume the
1369 // entire target, aren't we ok even if the source was also
1370 // entirely consumed?
1371
1372 // if skipping over ignorables brought to the end of
1373 // the prefix, we DID match: drop out of the loop
1374 if (oPrefix == CollationElementIterator::NULLORDER) {
1375 break;
1376 }
1377
1378 // if skipping over ignorables brought us to the end
1379 // of the target string, we didn't match and return 0
1380 if (oStr == CollationElementIterator::NULLORDER) {
1381 return 0;
1382 }
1383
1384 // match collation elements from the two strings
1385 // (considering only primary differences). If we
1386 // get a mismatch, dump out and return 0
1387 if (CollationElementIterator::primaryOrder(oStr)
1388 != CollationElementIterator::primaryOrder(oPrefix)) {
1389 return 0;
1390
1391 // otherwise, advance to the next character in each string
1392 // and loop (we drop out of the loop when we exhaust
1393 // collation elements in the prefix)
1394 } else {
1395 oStr = strIter->next(err);
1396 oPrefix = prefixIter->next(err);
1397 }
1398 }
1399
1400 int32_t result = strIter->getOffset();
1401 if (oStr != CollationElementIterator::NULLORDER) {
1402 --result; // back over character that we don't want to consume;
1403 }
1404
1405 #ifdef RBNF_DEBUG
1406 fprintf(stderr, "prefix length: %d\n", result);
1407 #endif
1408 return result;
1409 #if 0
1410 //----------------------------------------------------------------
1411 // JDK 1.2-specific API call
1412 // return strIter.getOffset();
1413 //----------------------------------------------------------------
1414 // JDK 1.1 HACK (take out for 1.2-specific code)
1415
1416 // if we make it to here, we have a successful match. Now we
1417 // have to find out HOW MANY characters from the target string
1418 // matched the prefix (there isn't necessarily a one-to-one
1419 // mapping between collation elements and characters).
1420 // In JDK 1.2, there's a simple getOffset() call we can use.
1421 // In JDK 1.1, on the other hand, we have to go through some
1422 // ugly contortions. First, use the collator to compare the
1423 // same number of characters from the prefix and target string.
1424 // If they're equal, we're done.
1425 collator->setStrength(Collator::PRIMARY);
1426 if (str.length() >= prefix.length()) {
1427 UnicodeString temp;
1428 temp.setTo(str, 0, prefix.length());
1429 if (collator->equals(temp, prefix)) {
1430 #ifdef RBNF_DEBUG
1431 fprintf(stderr, "returning: %d\n", prefix.length());
1432 #endif
1433 return prefix.length();
1434 }
1435 }
1436
1437 // if they're not equal, then we have to compare successively
1438 // larger and larger substrings of the target string until we
1439 // get to one that matches the prefix. At that point, we know
1440 // how many characters matched the prefix, and we can return.
1441 int32_t p = 1;
1442 while (p <= str.length()) {
1443 UnicodeString temp;
1444 temp.setTo(str, 0, p);
1445 if (collator->equals(temp, prefix)) {
1446 return p;
1447 } else {
1448 ++p;
1449 }
1450 }
1451
1452 // SHOULD NEVER GET HERE!!!
1453 return 0;
1454 //----------------------------------------------------------------
1455 #endif
1456
1457 // If lenient parsing is turned off, forget all that crap above.
1458 // Just use String.startsWith() and be done with it.
1459 } else
1460 #endif
1461 {
1462 if (str.startsWith(prefix)) {
1463 return prefix.length();
1464 } else {
1465 return 0;
1466 }
1467 }
1468 }
1469
1470 /**
1471 * Searches a string for another string. If lenient parsing is off,
1472 * this just calls indexOf(). If lenient parsing is on, this function
1473 * uses CollationElementIterator to match characters, and only
1474 * primary-order differences are significant in determining whether
1475 * there's a match.
1476 * @param str The string to search
1477 * @param key The string to search "str" for
1478 * @param startingAt The index into "str" where the search is to
1479 * begin
1480 * @return A two-element array of ints. Element 0 is the position
1481 * of the match, or -1 if there was no match. Element 1 is the
1482 * number of characters in "str" that matched (which isn't necessarily
1483 * the same as the length of "key")
1484 */
1485 int32_t
findText(const UnicodeString & str,const UnicodeString & key,int32_t startingAt,int32_t * length) const1486 NFRule::findText(const UnicodeString& str,
1487 const UnicodeString& key,
1488 int32_t startingAt,
1489 int32_t* length) const
1490 {
1491 if (rulePatternFormat) {
1492 Formattable result;
1493 FieldPosition position(UNUM_INTEGER_FIELD);
1494 position.setBeginIndex(startingAt);
1495 rulePatternFormat->parseType(str, this, result, position);
1496 int start = position.getBeginIndex();
1497 if (start >= 0) {
1498 int32_t pluralRuleStart = fRuleText.indexOf(gDollarOpenParenthesis, -1, 0);
1499 int32_t pluralRuleSuffix = fRuleText.indexOf(gClosedParenthesisDollar, -1, pluralRuleStart) + 2;
1500 int32_t matchLen = position.getEndIndex() - start;
1501 UnicodeString prefix(fRuleText.tempSubString(0, pluralRuleStart));
1502 UnicodeString suffix(fRuleText.tempSubString(pluralRuleSuffix));
1503 if (str.compare(start - prefix.length(), prefix.length(), prefix, 0, prefix.length()) == 0
1504 && str.compare(start + matchLen, suffix.length(), suffix, 0, suffix.length()) == 0)
1505 {
1506 *length = matchLen + prefix.length() + suffix.length();
1507 return start - prefix.length();
1508 }
1509 }
1510 *length = 0;
1511 return -1;
1512 }
1513 if (!formatter->isLenient()) {
1514 // if lenient parsing is turned off, this is easy: just call
1515 // String.indexOf() and we're done
1516 *length = key.length();
1517 return str.indexOf(key, startingAt);
1518 }
1519 else {
1520 // Check if non-lenient rule finds the text before call lenient parsing
1521 *length = key.length();
1522 int32_t pos = str.indexOf(key, startingAt);
1523 if(pos >= 0) {
1524 return pos;
1525 } else {
1526 // but if lenient parsing is turned ON, we've got some work ahead of us
1527 return findTextLenient(str, key, startingAt, length);
1528 }
1529 }
1530 }
1531
1532 int32_t
findTextLenient(const UnicodeString & str,const UnicodeString & key,int32_t startingAt,int32_t * length) const1533 NFRule::findTextLenient(const UnicodeString& str,
1534 const UnicodeString& key,
1535 int32_t startingAt,
1536 int32_t* length) const
1537 {
1538 //----------------------------------------------------------------
1539 // JDK 1.1 HACK (take out of 1.2-specific code)
1540
1541 // in JDK 1.2, CollationElementIterator provides us with an
1542 // API to map between character offsets and collation elements
1543 // and we can do this by marching through the string comparing
1544 // collation elements. We can't do that in JDK 1.1. Instead,
1545 // we have to go through this horrible slow mess:
1546 int32_t p = startingAt;
1547 int32_t keyLen = 0;
1548
1549 // basically just isolate smaller and smaller substrings of
1550 // the target string (each running to the end of the string,
1551 // and with the first one running from startingAt to the end)
1552 // and then use prefixLength() to see if the search key is at
1553 // the beginning of each substring. This is excruciatingly
1554 // slow, but it will locate the key and tell use how long the
1555 // matching text was.
1556 UnicodeString temp;
1557 UErrorCode status = U_ZERO_ERROR;
1558 while (p < str.length() && keyLen == 0) {
1559 temp.setTo(str, p, str.length() - p);
1560 keyLen = prefixLength(temp, key, status);
1561 if (U_FAILURE(status)) {
1562 break;
1563 }
1564 if (keyLen != 0) {
1565 *length = keyLen;
1566 return p;
1567 }
1568 ++p;
1569 }
1570 // if we make it to here, we didn't find it. Return -1 for the
1571 // location. The length should be ignored, but set it to 0,
1572 // which should be "safe"
1573 *length = 0;
1574 return -1;
1575 }
1576
1577 /**
1578 * Checks to see whether a string consists entirely of ignorable
1579 * characters.
1580 * @param str The string to test.
1581 * @return true if the string is empty of consists entirely of
1582 * characters that the number formatter's collator says are
1583 * ignorable at the primary-order level. false otherwise.
1584 */
1585 UBool
allIgnorable(const UnicodeString & str,UErrorCode & status) const1586 NFRule::allIgnorable(const UnicodeString& str, UErrorCode& status) const
1587 {
1588 // if the string is empty, we can just return true
1589 if (str.length() == 0) {
1590 return true;
1591 }
1592
1593 #if !UCONFIG_NO_COLLATION
1594 // if lenient parsing is turned on, walk through the string with
1595 // a collation element iterator and make sure each collation
1596 // element is 0 (ignorable) at the primary level
1597 if (formatter->isLenient()) {
1598 const RuleBasedCollator* collator = formatter->getCollator();
1599 if (collator == nullptr) {
1600 status = U_MEMORY_ALLOCATION_ERROR;
1601 return false;
1602 }
1603 LocalPointer<CollationElementIterator> iter(collator->createCollationElementIterator(str));
1604
1605 // Memory allocation error check.
1606 if (iter.isNull()) {
1607 status = U_MEMORY_ALLOCATION_ERROR;
1608 return false;
1609 }
1610
1611 UErrorCode err = U_ZERO_ERROR;
1612 int32_t o = iter->next(err);
1613 while (o != CollationElementIterator::NULLORDER
1614 && CollationElementIterator::primaryOrder(o) == 0) {
1615 o = iter->next(err);
1616 }
1617
1618 return o == CollationElementIterator::NULLORDER;
1619 }
1620 #endif
1621
1622 // if lenient parsing is turned off, there is no such thing as
1623 // an ignorable character: return true only if the string is empty
1624 return false;
1625 }
1626
1627 void
setDecimalFormatSymbols(const DecimalFormatSymbols & newSymbols,UErrorCode & status)1628 NFRule::setDecimalFormatSymbols(const DecimalFormatSymbols& newSymbols, UErrorCode& status) {
1629 if (sub1 != nullptr) {
1630 sub1->setDecimalFormatSymbols(newSymbols, status);
1631 }
1632 if (sub2 != nullptr) {
1633 sub2->setDecimalFormatSymbols(newSymbols, status);
1634 }
1635 }
1636
1637 U_NAMESPACE_END
1638
1639 /* U_HAVE_RBNF */
1640 #endif
1641