Coverage Report

Created: 2025-06-24 06:43

/src/icu/source/i18n/numparse_decimal.cpp
Line
Count
Source (jump to first uncovered line)
1
// © 2018 and later: Unicode, Inc. and others.
2
// License & terms of use: http://www.unicode.org/copyright.html
3
4
#include "unicode/utypes.h"
5
6
#if !UCONFIG_NO_FORMATTING
7
8
// Allow implicit conversion from char16_t* to UnicodeString for this file:
9
// Helpful in toString methods and elsewhere.
10
#define UNISTR_FROM_STRING_EXPLICIT
11
12
#include "numparse_types.h"
13
#include "numparse_decimal.h"
14
#include "static_unicode_sets.h"
15
#include "numparse_utils.h"
16
#include "unicode/uchar.h"
17
#include "putilimp.h"
18
#include "number_decimalquantity.h"
19
#include "string_segment.h"
20
21
using namespace icu;
22
using namespace icu::numparse;
23
using namespace icu::numparse::impl;
24
25
26
DecimalMatcher::DecimalMatcher(const DecimalFormatSymbols& symbols, const Grouper& grouper,
27
0
                               parse_flags_t parseFlags) {
28
0
    if (0 != (parseFlags & PARSE_FLAG_MONETARY_SEPARATORS)) {
29
0
        groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol);
30
0
        decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
31
0
    } else {
32
0
        groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
33
0
        decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
34
0
    }
35
0
    bool strictSeparators = 0 != (parseFlags & PARSE_FLAG_STRICT_SEPARATORS);
36
0
    unisets::Key groupingKey = strictSeparators ? unisets::STRICT_ALL_SEPARATORS
37
0
                                                : unisets::ALL_SEPARATORS;
38
39
    // Attempt to find separators in the static cache
40
41
0
    groupingUniSet = unisets::get(groupingKey);
42
0
    unisets::Key decimalKey = unisets::chooseFrom(
43
0
            decimalSeparator,
44
0
            strictSeparators ? unisets::STRICT_COMMA : unisets::COMMA,
45
0
            strictSeparators ? unisets::STRICT_PERIOD : unisets::PERIOD);
46
0
    if (decimalKey >= 0) {
47
0
        decimalUniSet = unisets::get(decimalKey);
48
0
    } else if (!decimalSeparator.isEmpty()) {
49
0
        auto* set = new UnicodeSet();
50
0
        set->add(decimalSeparator.char32At(0));
51
0
        set->freeze();
52
0
        decimalUniSet = set;
53
0
        fLocalDecimalUniSet.adoptInstead(set);
54
0
    } else {
55
0
        decimalUniSet = unisets::get(unisets::EMPTY);
56
0
    }
57
58
0
    if (groupingKey >= 0 && decimalKey >= 0) {
59
        // Everything is available in the static cache
60
0
        separatorSet = groupingUniSet;
61
0
        leadSet = unisets::get(
62
0
                strictSeparators ? unisets::DIGITS_OR_ALL_SEPARATORS
63
0
                                 : unisets::DIGITS_OR_STRICT_ALL_SEPARATORS);
64
0
    } else {
65
0
        auto* set = new UnicodeSet();
66
0
        set->addAll(*groupingUniSet);
67
0
        set->addAll(*decimalUniSet);
68
0
        set->freeze();
69
0
        separatorSet = set;
70
0
        fLocalSeparatorSet.adoptInstead(set);
71
0
        leadSet = nullptr;
72
0
    }
73
74
0
    UChar32 cpZero = symbols.getCodePointZero();
75
0
    if (cpZero == -1 || !u_isdigit(cpZero) || u_digit(cpZero, 10) != 0) {
76
        // Uncommon case: okay to allocate.
77
0
        auto digitStrings = new UnicodeString[10];
78
0
        fLocalDigitStrings.adoptInstead(digitStrings);
79
0
        for (int32_t i = 0; i <= 9; i++) {
80
0
            digitStrings[i] = symbols.getConstDigitSymbol(i);
81
0
        }
82
0
    }
83
84
0
    requireGroupingMatch = 0 != (parseFlags & PARSE_FLAG_STRICT_GROUPING_SIZE);
85
0
    groupingDisabled = 0 != (parseFlags & PARSE_FLAG_GROUPING_DISABLED);
86
0
    integerOnly = 0 != (parseFlags & PARSE_FLAG_INTEGER_ONLY);
87
0
    grouping1 = grouper.getPrimary();
88
0
    grouping2 = grouper.getSecondary();
89
90
    // Fraction grouping parsing is disabled for now but could be enabled later.
91
    // See http://bugs.icu-project.org/trac/ticket/10794
92
    // fractionGrouping = 0 != (parseFlags & PARSE_FLAG_FRACTION_GROUPING_ENABLED);
93
0
}
94
95
0
bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode& status) const {
96
0
    return match(segment, result, 0, status);
97
0
}
98
99
bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, int8_t exponentSign,
100
0
                           UErrorCode&) const {
101
0
    if (result.seenNumber() && exponentSign == 0) {
102
        // A number has already been consumed.
103
0
        return false;
104
0
    } else if (exponentSign != 0) {
105
        // scientific notation always comes after the number
106
0
        U_ASSERT(!result.quantity.bogus);
107
0
    }
108
109
    // Initial offset before any character consumption.
110
0
    int32_t initialOffset = segment.getOffset();
111
112
    // Return value: whether to ask for more characters.
113
0
    bool maybeMore = false;
114
115
    // All digits consumed so far.
116
0
    number::impl::DecimalQuantity digitsConsumed;
117
0
    digitsConsumed.bogus = true;
118
119
    // The total number of digits after the decimal place, used for scaling the result.
120
0
    int32_t digitsAfterDecimalPlace = 0;
121
122
    // The actual grouping and decimal separators used in the string.
123
    // If non-null, we have seen that token.
124
0
    UnicodeString actualGroupingString;
125
0
    UnicodeString actualDecimalString;
126
0
    actualGroupingString.setToBogus();
127
0
    actualDecimalString.setToBogus();
128
129
    // Information for two groups: the previous group and the current group.
130
    //
131
    // Each group has three pieces of information:
132
    //
133
    // Offset: the string position of the beginning of the group, including a leading separator
134
    // if there was a leading separator. This is needed in case we need to rewind the parse to
135
    // that position.
136
    //
137
    // Separator type:
138
    // 0 => beginning of string
139
    // 1 => lead separator is a grouping separator
140
    // 2 => lead separator is a decimal separator
141
    //
142
    // Count: the number of digits in the group. If -1, the group has been validated.
143
0
    int32_t currGroupOffset = 0;
144
0
    int32_t currGroupSepType = 0;
145
0
    int32_t currGroupCount = 0;
146
0
    int32_t prevGroupOffset = -1;
147
0
    int32_t prevGroupSepType = -1;
148
0
    int32_t prevGroupCount = -1;
149
150
0
    while (segment.length() > 0) {
151
0
        maybeMore = false;
152
153
        // Attempt to match a digit.
154
0
        int8_t digit = -1;
155
156
        // Try by code point digit value.
157
0
        UChar32 cp = segment.getCodePoint();
158
0
        if (u_isdigit(cp)) {
159
0
            segment.adjustOffset(U16_LENGTH(cp));
160
0
            digit = static_cast<int8_t>(u_digit(cp, 10));
161
0
        }
162
163
        // Try by digit string.
164
0
        if (digit == -1 && !fLocalDigitStrings.isNull()) {
165
0
            for (int32_t i = 0; i < 10; i++) {
166
0
                const UnicodeString& str = fLocalDigitStrings[i];
167
0
                if (str.isEmpty()) {
168
0
                    continue;
169
0
                }
170
0
                int32_t overlap = segment.getCommonPrefixLength(str);
171
0
                if (overlap == str.length()) {
172
0
                    segment.adjustOffset(overlap);
173
0
                    digit = static_cast<int8_t>(i);
174
0
                    break;
175
0
                }
176
0
                maybeMore = maybeMore || (overlap == segment.length());
177
0
            }
178
0
        }
179
180
0
        if (digit >= 0) {
181
            // Digit was found.
182
0
            if (digitsConsumed.bogus) {
183
0
                digitsConsumed.bogus = false;
184
0
                digitsConsumed.clear();
185
0
            }
186
0
            digitsConsumed.appendDigit(digit, 0, true);
187
0
            currGroupCount++;
188
0
            if (!actualDecimalString.isBogus()) {
189
0
                digitsAfterDecimalPlace++;
190
0
            }
191
0
            continue;
192
0
        }
193
194
        // Attempt to match a literal grouping or decimal separator.
195
0
        bool isDecimal = false;
196
0
        bool isGrouping = false;
197
198
        // 1) Attempt the decimal separator string literal.
199
        // if (we have not seen a decimal separator yet) { ... }
200
0
        if (actualDecimalString.isBogus() && !decimalSeparator.isEmpty()) {
201
0
            int32_t overlap = segment.getCommonPrefixLength(decimalSeparator);
202
0
            maybeMore = maybeMore || (overlap == segment.length());
203
0
            if (overlap == decimalSeparator.length()) {
204
0
                isDecimal = true;
205
0
                actualDecimalString = decimalSeparator;
206
0
            }
207
0
        }
208
209
        // 2) Attempt to match the actual grouping string literal.
210
0
        if (!actualGroupingString.isBogus()) {
211
0
            int32_t overlap = segment.getCommonPrefixLength(actualGroupingString);
212
0
            maybeMore = maybeMore || (overlap == segment.length());
213
0
            if (overlap == actualGroupingString.length()) {
214
0
                isGrouping = true;
215
0
            }
216
0
        }
217
218
        // 2.5) Attempt to match a new the grouping separator string literal.
219
        // if (we have not seen a grouping or decimal separator yet) { ... }
220
0
        if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus() &&
221
0
            !groupingSeparator.isEmpty()) {
222
0
            int32_t overlap = segment.getCommonPrefixLength(groupingSeparator);
223
0
            maybeMore = maybeMore || (overlap == segment.length());
224
0
            if (overlap == groupingSeparator.length()) {
225
0
                isGrouping = true;
226
0
                actualGroupingString = groupingSeparator;
227
0
            }
228
0
        }
229
230
        // 3) Attempt to match a decimal separator from the equivalence set.
231
        // if (we have not seen a decimal separator yet) { ... }
232
        // The !isGrouping is to confirm that we haven't yet matched the current character.
233
0
        if (!isGrouping && actualDecimalString.isBogus()) {
234
0
            if (decimalUniSet->contains(cp)) {
235
0
                isDecimal = true;
236
0
                actualDecimalString = UnicodeString(cp);
237
0
            }
238
0
        }
239
240
        // 4) Attempt to match a grouping separator from the equivalence set.
241
        // if (we have not seen a grouping or decimal separator yet) { ... }
242
0
        if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus()) {
243
0
            if (groupingUniSet->contains(cp)) {
244
0
                isGrouping = true;
245
0
                actualGroupingString = UnicodeString(cp);
246
0
            }
247
0
        }
248
249
        // Leave if we failed to match this as a separator.
250
0
        if (!isDecimal && !isGrouping) {
251
0
            break;
252
0
        }
253
254
        // Check for conditions when we don't want to accept the separator.
255
0
        if (isDecimal && integerOnly) {
256
0
            break;
257
0
        } else if (currGroupSepType == 2 && isGrouping) {
258
            // Fraction grouping
259
0
            break;
260
0
        }
261
262
        // Validate intermediate grouping sizes.
263
0
        bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false);
264
0
        bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true);
265
0
        if (!prevValidSecondary || (isDecimal && !currValidPrimary)) {
266
            // Invalid grouping sizes.
267
0
            if (isGrouping && currGroupCount == 0) {
268
                // Trailing grouping separators: these are taken care of below
269
0
                U_ASSERT(currGroupSepType == 1);
270
0
            } else if (requireGroupingMatch) {
271
                // Strict mode: reject the parse
272
0
                digitsConsumed.clear();
273
0
                digitsConsumed.bogus = true;
274
0
            }
275
0
            break;
276
0
        } else if (requireGroupingMatch && currGroupCount == 0 && currGroupSepType == 1) {
277
0
            break;
278
0
        } else {
279
            // Grouping sizes OK so far.
280
0
            prevGroupOffset = currGroupOffset;
281
0
            prevGroupCount = currGroupCount;
282
0
            if (isDecimal) {
283
                // Do not validate this group any more.
284
0
                prevGroupSepType = -1;
285
0
            } else {
286
0
                prevGroupSepType = currGroupSepType;
287
0
            }
288
0
        }
289
290
        // OK to accept the separator.
291
        // Special case: don't update currGroup if it is empty; this allows two grouping
292
        // separators in a row in lenient mode.
293
0
        if (currGroupCount != 0) {
294
0
            currGroupOffset = segment.getOffset();
295
0
        }
296
0
        currGroupSepType = isGrouping ? 1 : 2;
297
0
        currGroupCount = 0;
298
0
        if (isGrouping) {
299
0
            segment.adjustOffset(actualGroupingString.length());
300
0
        } else {
301
0
            segment.adjustOffset(actualDecimalString.length());
302
0
        }
303
0
    }
304
305
    // End of main loop.
306
    // Back up if there was a trailing grouping separator.
307
    // Shift prev -> curr so we can check it as a final group.
308
0
    if (currGroupSepType != 2 && currGroupCount == 0) {
309
0
        maybeMore = true;
310
0
        segment.setOffset(currGroupOffset);
311
0
        currGroupOffset = prevGroupOffset;
312
0
        currGroupSepType = prevGroupSepType;
313
0
        currGroupCount = prevGroupCount;
314
0
        prevGroupOffset = -1;
315
0
        prevGroupSepType = 0;
316
0
        prevGroupCount = 1;
317
0
    }
318
319
    // Validate final grouping sizes.
320
0
    bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false);
321
0
    bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true);
322
0
    if (!requireGroupingMatch) {
323
        // The cases we need to handle here are lone digits.
324
        // Examples: "1,1"  "1,1,"  "1,1,1"  "1,1,1,"  ",1" (all parse as 1)
325
        // See more examples in numberformattestspecification.txt
326
0
        int32_t digitsToRemove = 0;
327
0
        if (!prevValidSecondary) {
328
0
            segment.setOffset(prevGroupOffset);
329
0
            digitsToRemove += prevGroupCount;
330
0
            digitsToRemove += currGroupCount;
331
0
        } else if (!currValidPrimary && (prevGroupSepType != 0 || prevGroupCount != 0)) {
332
0
            maybeMore = true;
333
0
            segment.setOffset(currGroupOffset);
334
0
            digitsToRemove += currGroupCount;
335
0
        }
336
0
        if (digitsToRemove != 0) {
337
0
            digitsConsumed.adjustMagnitude(-digitsToRemove);
338
0
            digitsConsumed.truncate();
339
0
        }
340
0
        prevValidSecondary = true;
341
0
        currValidPrimary = true;
342
0
    }
343
0
    if (currGroupSepType != 2 && (!prevValidSecondary || !currValidPrimary)) {
344
        // Grouping failure.
345
0
        digitsConsumed.bogus = true;
346
0
    }
347
348
    // Strings that start with a separator but have no digits,
349
    // or strings that failed a grouping size check.
350
0
    if (digitsConsumed.bogus) {
351
0
        maybeMore = maybeMore || (segment.length() == 0);
352
0
        segment.setOffset(initialOffset);
353
0
        return maybeMore;
354
0
    }
355
356
    // We passed all inspections. Start post-processing.
357
358
    // Adjust for fraction part.
359
0
    digitsConsumed.adjustMagnitude(-digitsAfterDecimalPlace);
360
361
    // Set the digits, either normal or exponent.
362
0
    if (exponentSign != 0 && segment.getOffset() != initialOffset) {
363
0
        bool overflow = false;
364
0
        if (digitsConsumed.fitsInLong()) {
365
0
            int64_t exponentLong = digitsConsumed.toLong(false);
366
0
            U_ASSERT(exponentLong >= 0);
367
0
            if (exponentLong <= INT32_MAX) {
368
0
                auto exponentInt = static_cast<int32_t>(exponentLong);
369
0
                if (result.quantity.adjustMagnitude(exponentSign * exponentInt)) {
370
0
                    overflow = true;
371
0
                }
372
0
            } else {
373
0
                overflow = true;
374
0
            }
375
0
        } else {
376
0
            overflow = true;
377
0
        }
378
0
        if (overflow) {
379
0
            if (exponentSign == -1) {
380
                // Set to zero
381
0
                result.quantity.clear();
382
0
            } else {
383
                // Set to infinity
384
0
                result.quantity.bogus = true;
385
0
                result.flags |= FLAG_INFINITY;
386
0
            }
387
0
        }
388
0
    } else {
389
0
        result.quantity = digitsConsumed;
390
0
    }
391
392
    // Set other information into the result and return.
393
0
    if (!actualDecimalString.isBogus()) {
394
0
        result.flags |= FLAG_HAS_DECIMAL_SEPARATOR;
395
0
    }
396
0
    result.setCharsConsumed(segment);
397
0
    return segment.length() == 0 || maybeMore;
398
0
}
399
400
0
bool DecimalMatcher::validateGroup(int32_t sepType, int32_t count, bool isPrimary) const {
401
0
    if (requireGroupingMatch) {
402
0
        if (sepType == -1) {
403
            // No such group (prevGroup before first shift).
404
0
            return true;
405
0
        } else if (sepType == 0) {
406
            // First group.
407
0
            if (isPrimary) {
408
                // No grouping separators is OK.
409
0
                return true;
410
0
            } else {
411
0
                return count != 0 && count <= grouping2;
412
0
            }
413
0
        } else if (sepType == 1) {
414
            // Middle group.
415
0
            if (isPrimary) {
416
0
                return count == grouping1;
417
0
            } else {
418
0
                return count == grouping2;
419
0
            }
420
0
        } else {
421
0
            U_ASSERT(sepType == 2);
422
            // After the decimal separator.
423
0
            return true;
424
0
        }
425
0
    } else {
426
0
        if (sepType == 1) {
427
            // #11230: don't accept middle groups with only 1 digit.
428
0
            return count != 1;
429
0
        } else {
430
0
            return true;
431
0
        }
432
0
    }
433
0
}
434
435
0
bool DecimalMatcher::smokeTest(const StringSegment& segment) const {
436
    // The common case uses a static leadSet for efficiency.
437
0
    if (fLocalDigitStrings.isNull() && leadSet != nullptr) {
438
0
        return segment.startsWith(*leadSet);
439
0
    }
440
0
    if (segment.startsWith(*separatorSet) || u_isdigit(segment.getCodePoint())) {
441
0
        return true;
442
0
    }
443
0
    if (fLocalDigitStrings.isNull()) {
444
0
        return false;
445
0
    }
446
0
    for (int32_t i = 0; i < 10; i++) {
447
0
        if (segment.startsWith(fLocalDigitStrings[i])) {
448
0
            return true;
449
0
        }
450
0
    }
451
0
    return false;
452
0
}
453
454
0
UnicodeString DecimalMatcher::toString() const {
455
0
    return u"<Decimal>";
456
0
}
457
458
459
#endif /* #if !UCONFIG_NO_FORMATTING */