• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_affixes.h"
14 #include "numparse_utils.h"
15 #include "number_utils.h"
16 #include "string_segment.h"
17 
18 using namespace icu;
19 using namespace icu::numparse;
20 using namespace icu::numparse::impl;
21 using namespace icu::number;
22 using namespace icu::number::impl;
23 
24 
25 namespace {
26 
27 /**
28  * Helper method to return whether the given AffixPatternMatcher equals the given pattern string.
29  * Either both arguments must be null or the pattern string inside the AffixPatternMatcher must equal
30  * the given pattern string.
31  */
matched(const AffixPatternMatcher * affix,const UnicodeString & patternString)32 static bool matched(const AffixPatternMatcher* affix, const UnicodeString& patternString) {
33     return (affix == nullptr && patternString.isBogus()) ||
34            (affix != nullptr && affix->getPattern() == patternString);
35 }
36 
37 /**
38  * Helper method to return the length of the given AffixPatternMatcher. Returns 0 for null.
39  */
length(const AffixPatternMatcher * matcher)40 static int32_t length(const AffixPatternMatcher* matcher) {
41     return matcher == nullptr ? 0 : matcher->getPattern().length();
42 }
43 
44 /**
45  * Helper method to return whether (1) both lhs and rhs are null/invalid, or (2) if they are both
46  * valid, whether they are equal according to operator==.  Similar to Java Objects.equals()
47  */
equals(const AffixPatternMatcher * lhs,const AffixPatternMatcher * rhs)48 static bool equals(const AffixPatternMatcher* lhs, const AffixPatternMatcher* rhs) {
49     if (lhs == nullptr && rhs == nullptr) {
50         return true;
51     }
52     if (lhs == nullptr || rhs == nullptr) {
53         return false;
54     }
55     return *lhs == *rhs;
56 }
57 
58 }
59 
60 
AffixPatternMatcherBuilder(const UnicodeString & pattern,AffixTokenMatcherWarehouse & warehouse,IgnorablesMatcher * ignorables)61 AffixPatternMatcherBuilder::AffixPatternMatcherBuilder(const UnicodeString& pattern,
62                                                        AffixTokenMatcherWarehouse& warehouse,
63                                                        IgnorablesMatcher* ignorables)
64         : fMatchersLen(0),
65           fLastTypeOrCp(0),
66           fPattern(pattern),
67           fWarehouse(warehouse),
68           fIgnorables(ignorables) {}
69 
consumeToken(AffixPatternType type,UChar32 cp,UErrorCode & status)70 void AffixPatternMatcherBuilder::consumeToken(AffixPatternType type, UChar32 cp, UErrorCode& status) {
71     // This is called by AffixUtils.iterateWithConsumer() for each token.
72 
73     // Add an ignorables matcher between tokens except between two literals, and don't put two
74     // ignorables matchers in a row.
75     if (fIgnorables != nullptr && fMatchersLen > 0 &&
76         (fLastTypeOrCp < 0 || !fIgnorables->getSet()->contains(fLastTypeOrCp))) {
77         addMatcher(*fIgnorables);
78     }
79 
80     if (type != TYPE_CODEPOINT) {
81         // Case 1: the token is a symbol.
82         switch (type) {
83             case TYPE_MINUS_SIGN:
84                 addMatcher(fWarehouse.minusSign());
85                 break;
86             case TYPE_PLUS_SIGN:
87                 addMatcher(fWarehouse.plusSign());
88                 break;
89             case TYPE_PERCENT:
90                 addMatcher(fWarehouse.percent());
91                 break;
92             case TYPE_PERMILLE:
93                 addMatcher(fWarehouse.permille());
94                 break;
95             case TYPE_CURRENCY_SINGLE:
96             case TYPE_CURRENCY_DOUBLE:
97             case TYPE_CURRENCY_TRIPLE:
98             case TYPE_CURRENCY_QUAD:
99             case TYPE_CURRENCY_QUINT:
100                 // All currency symbols use the same matcher
101                 addMatcher(fWarehouse.currency(status));
102                 break;
103             default:
104                 UPRV_UNREACHABLE;
105         }
106 
107     } else if (fIgnorables != nullptr && fIgnorables->getSet()->contains(cp)) {
108         // Case 2: the token is an ignorable literal.
109         // No action necessary: the ignorables matcher has already been added.
110 
111     } else {
112         // Case 3: the token is a non-ignorable literal.
113         if (auto* ptr = fWarehouse.nextCodePointMatcher(cp, status)) {
114             addMatcher(*ptr);
115         } else {
116             // OOM; unwind the stack
117             return;
118         }
119     }
120     fLastTypeOrCp = type != TYPE_CODEPOINT ? type : cp;
121 }
122 
addMatcher(NumberParseMatcher & matcher)123 void AffixPatternMatcherBuilder::addMatcher(NumberParseMatcher& matcher) {
124     if (fMatchersLen >= fMatchers.getCapacity()) {
125         fMatchers.resize(fMatchersLen * 2, fMatchersLen);
126     }
127     fMatchers[fMatchersLen++] = &matcher;
128 }
129 
build(UErrorCode & status)130 AffixPatternMatcher AffixPatternMatcherBuilder::build(UErrorCode& status) {
131     return AffixPatternMatcher(fMatchers, fMatchersLen, fPattern, status);
132 }
133 
AffixTokenMatcherWarehouse(const AffixTokenMatcherSetupData * setupData)134 AffixTokenMatcherWarehouse::AffixTokenMatcherWarehouse(const AffixTokenMatcherSetupData* setupData)
135         : fSetupData(setupData) {}
136 
minusSign()137 NumberParseMatcher& AffixTokenMatcherWarehouse::minusSign() {
138     return fMinusSign = {fSetupData->dfs, true};
139 }
140 
plusSign()141 NumberParseMatcher& AffixTokenMatcherWarehouse::plusSign() {
142     return fPlusSign = {fSetupData->dfs, true};
143 }
144 
percent()145 NumberParseMatcher& AffixTokenMatcherWarehouse::percent() {
146     return fPercent = {fSetupData->dfs};
147 }
148 
permille()149 NumberParseMatcher& AffixTokenMatcherWarehouse::permille() {
150     return fPermille = {fSetupData->dfs};
151 }
152 
currency(UErrorCode & status)153 NumberParseMatcher& AffixTokenMatcherWarehouse::currency(UErrorCode& status) {
154     return fCurrency = {fSetupData->currencySymbols, fSetupData->dfs, fSetupData->parseFlags, status};
155 }
156 
ignorables()157 IgnorablesMatcher& AffixTokenMatcherWarehouse::ignorables() {
158     return fSetupData->ignorables;
159 }
160 
nextCodePointMatcher(UChar32 cp,UErrorCode & status)161 NumberParseMatcher* AffixTokenMatcherWarehouse::nextCodePointMatcher(UChar32 cp, UErrorCode& status) {
162     if (U_FAILURE(status)) {
163         return nullptr;
164     }
165     auto* result = fCodePoints.create(cp);
166     if (result == nullptr) {
167         status = U_MEMORY_ALLOCATION_ERROR;
168     }
169     return result;
170 }
171 
172 
CodePointMatcher(UChar32 cp)173 CodePointMatcher::CodePointMatcher(UChar32 cp)
174         : fCp(cp) {}
175 
match(StringSegment & segment,ParsedNumber & result,UErrorCode &) const176 bool CodePointMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode&) const {
177     if (segment.startsWith(fCp)) {
178         segment.adjustOffsetByCodePoint();
179         result.setCharsConsumed(segment);
180     }
181     return false;
182 }
183 
smokeTest(const StringSegment & segment) const184 bool CodePointMatcher::smokeTest(const StringSegment& segment) const {
185     return segment.startsWith(fCp);
186 }
187 
toString() const188 UnicodeString CodePointMatcher::toString() const {
189     return u"<CodePoint>";
190 }
191 
192 
fromAffixPattern(const UnicodeString & affixPattern,AffixTokenMatcherWarehouse & tokenWarehouse,parse_flags_t parseFlags,bool * success,UErrorCode & status)193 AffixPatternMatcher AffixPatternMatcher::fromAffixPattern(const UnicodeString& affixPattern,
194                                                           AffixTokenMatcherWarehouse& tokenWarehouse,
195                                                           parse_flags_t parseFlags, bool* success,
196                                                           UErrorCode& status) {
197     if (affixPattern.isEmpty()) {
198         *success = false;
199         return {};
200     }
201     *success = true;
202 
203     IgnorablesMatcher* ignorables;
204     if (0 != (parseFlags & PARSE_FLAG_EXACT_AFFIX)) {
205         ignorables = nullptr;
206     } else {
207         ignorables = &tokenWarehouse.ignorables();
208     }
209 
210     AffixPatternMatcherBuilder builder(affixPattern, tokenWarehouse, ignorables);
211     AffixUtils::iterateWithConsumer(affixPattern, builder, status);
212     return builder.build(status);
213 }
214 
AffixPatternMatcher(MatcherArray & matchers,int32_t matchersLen,const UnicodeString & pattern,UErrorCode & status)215 AffixPatternMatcher::AffixPatternMatcher(MatcherArray& matchers, int32_t matchersLen,
216                                          const UnicodeString& pattern, UErrorCode& status)
217     : ArraySeriesMatcher(matchers, matchersLen), fPattern(pattern, status) {
218 }
219 
getPattern() const220 UnicodeString AffixPatternMatcher::getPattern() const {
221     return fPattern.toAliasedUnicodeString();
222 }
223 
operator ==(const AffixPatternMatcher & other) const224 bool AffixPatternMatcher::operator==(const AffixPatternMatcher& other) const {
225     return fPattern == other.fPattern;
226 }
227 
228 
AffixMatcherWarehouse(AffixTokenMatcherWarehouse * tokenWarehouse)229 AffixMatcherWarehouse::AffixMatcherWarehouse(AffixTokenMatcherWarehouse* tokenWarehouse)
230         : fTokenWarehouse(tokenWarehouse) {
231 }
232 
isInteresting(const AffixPatternProvider & patternInfo,const IgnorablesMatcher & ignorables,parse_flags_t parseFlags,UErrorCode & status)233 bool AffixMatcherWarehouse::isInteresting(const AffixPatternProvider& patternInfo,
234                                           const IgnorablesMatcher& ignorables, parse_flags_t parseFlags,
235                                           UErrorCode& status) {
236     UnicodeString posPrefixString = patternInfo.getString(AffixPatternProvider::AFFIX_POS_PREFIX);
237     UnicodeString posSuffixString = patternInfo.getString(AffixPatternProvider::AFFIX_POS_SUFFIX);
238     UnicodeString negPrefixString;
239     UnicodeString negSuffixString;
240     if (patternInfo.hasNegativeSubpattern()) {
241         negPrefixString = patternInfo.getString(AffixPatternProvider::AFFIX_NEG_PREFIX);
242         negSuffixString = patternInfo.getString(AffixPatternProvider::AFFIX_NEG_SUFFIX);
243     }
244 
245     if (0 == (parseFlags & PARSE_FLAG_USE_FULL_AFFIXES) &&
246         AffixUtils::containsOnlySymbolsAndIgnorables(posPrefixString, *ignorables.getSet(), status) &&
247         AffixUtils::containsOnlySymbolsAndIgnorables(posSuffixString, *ignorables.getSet(), status) &&
248         AffixUtils::containsOnlySymbolsAndIgnorables(negPrefixString, *ignorables.getSet(), status) &&
249         AffixUtils::containsOnlySymbolsAndIgnorables(negSuffixString, *ignorables.getSet(), status)
250         // HACK: Plus and minus sign are a special case: we accept them trailing only if they are
251         // trailing in the pattern string.
252         && !AffixUtils::containsType(posSuffixString, TYPE_PLUS_SIGN, status) &&
253         !AffixUtils::containsType(posSuffixString, TYPE_MINUS_SIGN, status) &&
254         !AffixUtils::containsType(negSuffixString, TYPE_PLUS_SIGN, status) &&
255         !AffixUtils::containsType(negSuffixString, TYPE_MINUS_SIGN, status)) {
256         // The affixes contain only symbols and ignorables.
257         // No need to generate affix matchers.
258         return false;
259     }
260     return true;
261 }
262 
createAffixMatchers(const AffixPatternProvider & patternInfo,MutableMatcherCollection & output,const IgnorablesMatcher & ignorables,parse_flags_t parseFlags,UErrorCode & status)263 void AffixMatcherWarehouse::createAffixMatchers(const AffixPatternProvider& patternInfo,
264                                                 MutableMatcherCollection& output,
265                                                 const IgnorablesMatcher& ignorables,
266                                                 parse_flags_t parseFlags, UErrorCode& status) {
267     if (!isInteresting(patternInfo, ignorables, parseFlags, status)) {
268         return;
269     }
270 
271     // The affixes have interesting characters, or we are in strict mode.
272     // Use initial capacity of 6, the highest possible number of AffixMatchers.
273     UnicodeString sb;
274     bool includeUnpaired = 0 != (parseFlags & PARSE_FLAG_INCLUDE_UNPAIRED_AFFIXES);
275 
276     int32_t numAffixMatchers = 0;
277     int32_t numAffixPatternMatchers = 0;
278 
279     AffixPatternMatcher* posPrefix = nullptr;
280     AffixPatternMatcher* posSuffix = nullptr;
281 
282     // Pre-process the affix strings to resolve LDML rules like sign display.
283     for (int8_t typeInt = 0; typeInt < PATTERN_SIGN_TYPE_COUNT; typeInt++) {
284         auto type = static_cast<PatternSignType>(typeInt);
285 
286         // Skip affixes in some cases
287         if (type == PATTERN_SIGN_TYPE_POS
288                 && 0 != (parseFlags & PARSE_FLAG_PLUS_SIGN_ALLOWED)) {
289             continue;
290         }
291         if (type == PATTERN_SIGN_TYPE_POS_SIGN
292                 && 0 == (parseFlags & PARSE_FLAG_PLUS_SIGN_ALLOWED)) {
293             continue;
294         }
295 
296         // Generate Prefix
297         bool hasPrefix = false;
298         PatternStringUtils::patternInfoToStringBuilder(
299                 patternInfo, true, type, StandardPlural::OTHER, false, sb);
300         fAffixPatternMatchers[numAffixPatternMatchers] = AffixPatternMatcher::fromAffixPattern(
301                 sb, *fTokenWarehouse, parseFlags, &hasPrefix, status);
302         AffixPatternMatcher* prefix = hasPrefix ? &fAffixPatternMatchers[numAffixPatternMatchers++]
303                                                 : nullptr;
304 
305         // Generate Suffix
306         bool hasSuffix = false;
307         PatternStringUtils::patternInfoToStringBuilder(
308                 patternInfo, false, type, StandardPlural::OTHER, false, sb);
309         fAffixPatternMatchers[numAffixPatternMatchers] = AffixPatternMatcher::fromAffixPattern(
310                 sb, *fTokenWarehouse, parseFlags, &hasSuffix, status);
311         AffixPatternMatcher* suffix = hasSuffix ? &fAffixPatternMatchers[numAffixPatternMatchers++]
312                                                 : nullptr;
313 
314         if (type == PATTERN_SIGN_TYPE_POS) {
315             posPrefix = prefix;
316             posSuffix = suffix;
317         } else if (equals(prefix, posPrefix) && equals(suffix, posSuffix)) {
318             // Skip adding these matchers (we already have equivalents)
319             continue;
320         }
321 
322         // Flags for setting in the ParsedNumber; the token matchers may add more.
323         int flags = (type == PATTERN_SIGN_TYPE_NEG) ? FLAG_NEGATIVE : 0;
324 
325         // Note: it is indeed possible for posPrefix and posSuffix to both be null.
326         // We still need to add that matcher for strict mode to work.
327         fAffixMatchers[numAffixMatchers++] = {prefix, suffix, flags};
328         if (includeUnpaired && prefix != nullptr && suffix != nullptr) {
329             // The following if statements are designed to prevent adding two identical matchers.
330             if (type == PATTERN_SIGN_TYPE_POS || !equals(prefix, posPrefix)) {
331                 fAffixMatchers[numAffixMatchers++] = {prefix, nullptr, flags};
332             }
333             if (type == PATTERN_SIGN_TYPE_POS || !equals(suffix, posSuffix)) {
334                 fAffixMatchers[numAffixMatchers++] = {nullptr, suffix, flags};
335             }
336         }
337     }
338 
339     // Put the AffixMatchers in order, and then add them to the output.
340     // Since there are at most 9 elements, do a simple-to-implement bubble sort.
341     bool madeChanges;
342     do {
343         madeChanges = false;
344         for (int32_t i = 1; i < numAffixMatchers; i++) {
345             if (fAffixMatchers[i - 1].compareTo(fAffixMatchers[i]) > 0) {
346                 madeChanges = true;
347                 AffixMatcher temp = std::move(fAffixMatchers[i - 1]);
348                 fAffixMatchers[i - 1] = std::move(fAffixMatchers[i]);
349                 fAffixMatchers[i] = std::move(temp);
350             }
351         }
352     } while (madeChanges);
353 
354     for (int32_t i = 0; i < numAffixMatchers; i++) {
355         // Enable the following line to debug affixes
356         //std::cout << "Adding affix matcher: " << CStr(fAffixMatchers[i].toString())() << std::endl;
357         output.addMatcher(fAffixMatchers[i]);
358     }
359 }
360 
361 
AffixMatcher(AffixPatternMatcher * prefix,AffixPatternMatcher * suffix,result_flags_t flags)362 AffixMatcher::AffixMatcher(AffixPatternMatcher* prefix, AffixPatternMatcher* suffix, result_flags_t flags)
363         : fPrefix(prefix), fSuffix(suffix), fFlags(flags) {}
364 
match(StringSegment & segment,ParsedNumber & result,UErrorCode & status) const365 bool AffixMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode& status) const {
366     if (!result.seenNumber()) {
367         // Prefix
368         // Do not match if:
369         // 1. We have already seen a prefix (result.prefix != null)
370         // 2. The prefix in this AffixMatcher is empty (prefix == null)
371         if (!result.prefix.isBogus() || fPrefix == nullptr) {
372             return false;
373         }
374 
375         // Attempt to match the prefix.
376         int initialOffset = segment.getOffset();
377         bool maybeMore = fPrefix->match(segment, result, status);
378         if (initialOffset != segment.getOffset()) {
379             result.prefix = fPrefix->getPattern();
380         }
381         return maybeMore;
382 
383     } else {
384         // Suffix
385         // Do not match if:
386         // 1. We have already seen a suffix (result.suffix != null)
387         // 2. The suffix in this AffixMatcher is empty (suffix == null)
388         // 3. The matched prefix does not equal this AffixMatcher's prefix
389         if (!result.suffix.isBogus() || fSuffix == nullptr || !matched(fPrefix, result.prefix)) {
390             return false;
391         }
392 
393         // Attempt to match the suffix.
394         int initialOffset = segment.getOffset();
395         bool maybeMore = fSuffix->match(segment, result, status);
396         if (initialOffset != segment.getOffset()) {
397             result.suffix = fSuffix->getPattern();
398         }
399         return maybeMore;
400     }
401 }
402 
smokeTest(const StringSegment & segment) const403 bool AffixMatcher::smokeTest(const StringSegment& segment) const {
404     return (fPrefix != nullptr && fPrefix->smokeTest(segment)) ||
405            (fSuffix != nullptr && fSuffix->smokeTest(segment));
406 }
407 
postProcess(ParsedNumber & result) const408 void AffixMatcher::postProcess(ParsedNumber& result) const {
409     // Check to see if our affix is the one that was matched. If so, set the flags in the result.
410     if (matched(fPrefix, result.prefix) && matched(fSuffix, result.suffix)) {
411         // Fill in the result prefix and suffix with non-null values (empty string).
412         // Used by strict mode to determine whether an entire affix pair was matched.
413         if (result.prefix.isBogus()) {
414             result.prefix = UnicodeString();
415         }
416         if (result.suffix.isBogus()) {
417             result.suffix = UnicodeString();
418         }
419         result.flags |= fFlags;
420         if (fPrefix != nullptr) {
421             fPrefix->postProcess(result);
422         }
423         if (fSuffix != nullptr) {
424             fSuffix->postProcess(result);
425         }
426     }
427 }
428 
compareTo(const AffixMatcher & rhs) const429 int8_t AffixMatcher::compareTo(const AffixMatcher& rhs) const {
430     const AffixMatcher& lhs = *this;
431     if (length(lhs.fPrefix) != length(rhs.fPrefix)) {
432         return length(lhs.fPrefix) > length(rhs.fPrefix) ? -1 : 1;
433     } else if (length(lhs.fSuffix) != length(rhs.fSuffix)) {
434         return length(lhs.fSuffix) > length(rhs.fSuffix) ? -1 : 1;
435     } else {
436         return 0;
437     }
438 }
439 
toString() const440 UnicodeString AffixMatcher::toString() const {
441     bool isNegative = 0 != (fFlags & FLAG_NEGATIVE);
442     return UnicodeString(u"<Affix") + (isNegative ? u":negative " : u" ") +
443            (fPrefix ? fPrefix->getPattern() : u"null") + u"#" +
444            (fSuffix ? fSuffix->getPattern() : u"null") + u">";
445 
446 }
447 
448 
449 #endif /* #if !UCONFIG_NO_FORMATTING */
450