Bug Summary

File:root/firefox-clang/intl/icu/source/i18n/nfrule.cpp
Warning:line 1252, column 33
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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