• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2017 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 #include "cstring.h"
9 #include "number_patternmodifier.h"
10 #include "unicode/dcfmtsym.h"
11 #include "unicode/ucurr.h"
12 #include "unicode/unistr.h"
13 #include "number_microprops.h"
14 
15 using namespace icu;
16 using namespace icu::number;
17 using namespace icu::number::impl;
18 
19 
20 AffixPatternProvider::~AffixPatternProvider() = default;
21 
22 
MutablePatternModifier(bool isStrong)23 MutablePatternModifier::MutablePatternModifier(bool isStrong)
24         : fStrong(isStrong) {}
25 
setPatternInfo(const AffixPatternProvider * patternInfo)26 void MutablePatternModifier::setPatternInfo(const AffixPatternProvider* patternInfo) {
27     fPatternInfo = patternInfo;
28 }
29 
setPatternAttributes(UNumberSignDisplay signDisplay,bool perMille)30 void MutablePatternModifier::setPatternAttributes(UNumberSignDisplay signDisplay, bool perMille) {
31     fSignDisplay = signDisplay;
32     this->perMilleReplacesPercent = perMille;
33 }
34 
setSymbols(const DecimalFormatSymbols * symbols,const CurrencySymbols * currencySymbols,const UNumberUnitWidth unitWidth,const PluralRules * rules)35 void MutablePatternModifier::setSymbols(const DecimalFormatSymbols* symbols,
36                                         const CurrencySymbols* currencySymbols,
37                                         const UNumberUnitWidth unitWidth, const PluralRules* rules) {
38     U_ASSERT((rules != nullptr) == needsPlurals());
39     fSymbols = symbols;
40     fCurrencySymbols = currencySymbols;
41     fUnitWidth = unitWidth;
42     fRules = rules;
43 }
44 
setNumberProperties(int8_t signum,StandardPlural::Form plural)45 void MutablePatternModifier::setNumberProperties(int8_t signum, StandardPlural::Form plural) {
46     fSignum = signum;
47     fPlural = plural;
48 }
49 
needsPlurals() const50 bool MutablePatternModifier::needsPlurals() const {
51     UErrorCode statusLocal = U_ZERO_ERROR;
52     return fPatternInfo->containsSymbolType(AffixPatternType::TYPE_CURRENCY_TRIPLE, statusLocal);
53     // Silently ignore any error codes.
54 }
55 
createImmutable(UErrorCode & status)56 ImmutablePatternModifier* MutablePatternModifier::createImmutable(UErrorCode& status) {
57     return createImmutableAndChain(nullptr, status);
58 }
59 
60 ImmutablePatternModifier*
createImmutableAndChain(const MicroPropsGenerator * parent,UErrorCode & status)61 MutablePatternModifier::createImmutableAndChain(const MicroPropsGenerator* parent, UErrorCode& status) {
62 
63     // TODO: Move StandardPlural VALUES to standardplural.h
64     static const StandardPlural::Form STANDARD_PLURAL_VALUES[] = {
65             StandardPlural::Form::ZERO,
66             StandardPlural::Form::ONE,
67             StandardPlural::Form::TWO,
68             StandardPlural::Form::FEW,
69             StandardPlural::Form::MANY,
70             StandardPlural::Form::OTHER};
71 
72     auto pm = new AdoptingModifierStore();
73     if (pm == nullptr) {
74         status = U_MEMORY_ALLOCATION_ERROR;
75         return nullptr;
76     }
77 
78     if (needsPlurals()) {
79         // Slower path when we require the plural keyword.
80         for (StandardPlural::Form plural : STANDARD_PLURAL_VALUES) {
81             setNumberProperties(1, plural);
82             pm->adoptModifier(1, plural, createConstantModifier(status));
83             setNumberProperties(0, plural);
84             pm->adoptModifier(0, plural, createConstantModifier(status));
85             setNumberProperties(-1, plural);
86             pm->adoptModifier(-1, plural, createConstantModifier(status));
87         }
88         if (U_FAILURE(status)) {
89             delete pm;
90             return nullptr;
91         }
92         return new ImmutablePatternModifier(pm, fRules, parent);  // adopts pm
93     } else {
94         // Faster path when plural keyword is not needed.
95         setNumberProperties(1, StandardPlural::Form::COUNT);
96         pm->adoptModifierWithoutPlural(1, createConstantModifier(status));
97         setNumberProperties(0, StandardPlural::Form::COUNT);
98         pm->adoptModifierWithoutPlural(0, createConstantModifier(status));
99         setNumberProperties(-1, StandardPlural::Form::COUNT);
100         pm->adoptModifierWithoutPlural(-1, createConstantModifier(status));
101         if (U_FAILURE(status)) {
102             delete pm;
103             return nullptr;
104         }
105         return new ImmutablePatternModifier(pm, nullptr, parent);  // adopts pm
106     }
107 }
108 
createConstantModifier(UErrorCode & status)109 ConstantMultiFieldModifier* MutablePatternModifier::createConstantModifier(UErrorCode& status) {
110     NumberStringBuilder a;
111     NumberStringBuilder b;
112     insertPrefix(a, 0, status);
113     insertSuffix(b, 0, status);
114     if (fPatternInfo->hasCurrencySign()) {
115         return new CurrencySpacingEnabledModifier(
116                 a, b, !fPatternInfo->hasBody(), fStrong, *fSymbols, status);
117     } else {
118         return new ConstantMultiFieldModifier(a, b, !fPatternInfo->hasBody(), fStrong);
119     }
120 }
121 
ImmutablePatternModifier(AdoptingModifierStore * pm,const PluralRules * rules,const MicroPropsGenerator * parent)122 ImmutablePatternModifier::ImmutablePatternModifier(AdoptingModifierStore* pm, const PluralRules* rules,
123                                                    const MicroPropsGenerator* parent)
124         : pm(pm), rules(rules), parent(parent) {}
125 
processQuantity(DecimalQuantity & quantity,MicroProps & micros,UErrorCode & status) const126 void ImmutablePatternModifier::processQuantity(DecimalQuantity& quantity, MicroProps& micros,
127                                                UErrorCode& status) const {
128     parent->processQuantity(quantity, micros, status);
129     applyToMicros(micros, quantity);
130 }
131 
applyToMicros(MicroProps & micros,DecimalQuantity & quantity) const132 void ImmutablePatternModifier::applyToMicros(MicroProps& micros, DecimalQuantity& quantity) const {
133     if (rules == nullptr) {
134         micros.modMiddle = pm->getModifierWithoutPlural(quantity.signum());
135     } else {
136         // TODO: Fix this. Avoid the copy.
137         DecimalQuantity copy(quantity);
138         copy.roundToInfinity();
139         StandardPlural::Form plural = utils::getStandardPlural(rules, copy);
140         micros.modMiddle = pm->getModifier(quantity.signum(), plural);
141     }
142 }
143 
getModifier(int8_t signum,StandardPlural::Form plural) const144 const Modifier* ImmutablePatternModifier::getModifier(int8_t signum, StandardPlural::Form plural) const {
145     if (rules == nullptr) {
146         return pm->getModifierWithoutPlural(signum);
147     } else {
148         return pm->getModifier(signum, plural);
149     }
150 }
151 
152 
153 /** Used by the unsafe code path. */
addToChain(const MicroPropsGenerator * parent)154 MicroPropsGenerator& MutablePatternModifier::addToChain(const MicroPropsGenerator* parent) {
155     fParent = parent;
156     return *this;
157 }
158 
processQuantity(DecimalQuantity & fq,MicroProps & micros,UErrorCode & status) const159 void MutablePatternModifier::processQuantity(DecimalQuantity& fq, MicroProps& micros,
160                                              UErrorCode& status) const {
161     fParent->processQuantity(fq, micros, status);
162     // The unsafe code path performs self-mutation, so we need a const_cast.
163     // This method needs to be const because it overrides a const method in the parent class.
164     auto nonConstThis = const_cast<MutablePatternModifier*>(this);
165     if (needsPlurals()) {
166         // TODO: Fix this. Avoid the copy.
167         DecimalQuantity copy(fq);
168         micros.rounder.apply(copy, status);
169         nonConstThis->setNumberProperties(fq.signum(), utils::getStandardPlural(fRules, copy));
170     } else {
171         nonConstThis->setNumberProperties(fq.signum(), StandardPlural::Form::COUNT);
172     }
173     micros.modMiddle = this;
174 }
175 
apply(NumberStringBuilder & output,int32_t leftIndex,int32_t rightIndex,UErrorCode & status) const176 int32_t MutablePatternModifier::apply(NumberStringBuilder& output, int32_t leftIndex, int32_t rightIndex,
177                                       UErrorCode& status) const {
178     // The unsafe code path performs self-mutation, so we need a const_cast.
179     // This method needs to be const because it overrides a const method in the parent class.
180     auto nonConstThis = const_cast<MutablePatternModifier*>(this);
181     int32_t prefixLen = nonConstThis->insertPrefix(output, leftIndex, status);
182     int32_t suffixLen = nonConstThis->insertSuffix(output, rightIndex + prefixLen, status);
183     // If the pattern had no decimal stem body (like #,##0.00), overwrite the value.
184     int32_t overwriteLen = 0;
185     if (!fPatternInfo->hasBody()) {
186         overwriteLen = output.splice(
187                 leftIndex + prefixLen,
188                 rightIndex + prefixLen,
189                 UnicodeString(),
190                 0,
191                 0,
192                 UNUM_FIELD_COUNT,
193                 status);
194     }
195     CurrencySpacingEnabledModifier::applyCurrencySpacing(
196             output,
197             leftIndex,
198             prefixLen,
199             rightIndex + overwriteLen + prefixLen,
200             suffixLen,
201             *fSymbols,
202             status);
203     return prefixLen + overwriteLen + suffixLen;
204 }
205 
getPrefixLength() const206 int32_t MutablePatternModifier::getPrefixLength() const {
207     // The unsafe code path performs self-mutation, so we need a const_cast.
208     // This method needs to be const because it overrides a const method in the parent class.
209     auto nonConstThis = const_cast<MutablePatternModifier*>(this);
210 
211     // Enter and exit CharSequence Mode to get the length.
212     UErrorCode status = U_ZERO_ERROR; // status fails only with an iilegal argument exception
213     nonConstThis->prepareAffix(true);
214     int result = AffixUtils::unescapedCodePointCount(currentAffix, *this, status);  // prefix length
215     return result;
216 }
217 
getCodePointCount() const218 int32_t MutablePatternModifier::getCodePointCount() const {
219     // The unsafe code path performs self-mutation, so we need a const_cast.
220     // This method needs to be const because it overrides a const method in the parent class.
221     auto nonConstThis = const_cast<MutablePatternModifier*>(this);
222 
223     // Render the affixes to get the length
224     UErrorCode status = U_ZERO_ERROR; // status fails only with an iilegal argument exception
225     nonConstThis->prepareAffix(true);
226     int result = AffixUtils::unescapedCodePointCount(currentAffix, *this, status);  // prefix length
227     nonConstThis->prepareAffix(false);
228     result += AffixUtils::unescapedCodePointCount(currentAffix, *this, status);  // suffix length
229     return result;
230 }
231 
isStrong() const232 bool MutablePatternModifier::isStrong() const {
233     return fStrong;
234 }
235 
containsField(UNumberFormatFields field) const236 bool MutablePatternModifier::containsField(UNumberFormatFields field) const {
237     (void)field;
238     // This method is not currently used.
239     U_ASSERT(false);
240     return false;
241 }
242 
getParameters(Parameters & output) const243 void MutablePatternModifier::getParameters(Parameters& output) const {
244     (void)output;
245     // This method is not currently used.
246     U_ASSERT(false);
247 }
248 
semanticallyEquivalent(const Modifier & other) const249 bool MutablePatternModifier::semanticallyEquivalent(const Modifier& other) const {
250     (void)other;
251     // This method is not currently used.
252     U_ASSERT(false);
253     return false;
254 }
255 
insertPrefix(NumberStringBuilder & sb,int position,UErrorCode & status)256 int32_t MutablePatternModifier::insertPrefix(NumberStringBuilder& sb, int position, UErrorCode& status) {
257     prepareAffix(true);
258     int length = AffixUtils::unescape(currentAffix, sb, position, *this, status);
259     return length;
260 }
261 
insertSuffix(NumberStringBuilder & sb,int position,UErrorCode & status)262 int32_t MutablePatternModifier::insertSuffix(NumberStringBuilder& sb, int position, UErrorCode& status) {
263     prepareAffix(false);
264     int length = AffixUtils::unescape(currentAffix, sb, position, *this, status);
265     return length;
266 }
267 
268 /** This method contains the heart of the logic for rendering LDML affix strings. */
prepareAffix(bool isPrefix)269 void MutablePatternModifier::prepareAffix(bool isPrefix) {
270     PatternStringUtils::patternInfoToStringBuilder(
271             *fPatternInfo, isPrefix, fSignum, fSignDisplay, fPlural, perMilleReplacesPercent, currentAffix);
272 }
273 
getSymbol(AffixPatternType type) const274 UnicodeString MutablePatternModifier::getSymbol(AffixPatternType type) const {
275     UErrorCode localStatus = U_ZERO_ERROR;
276     switch (type) {
277         case AffixPatternType::TYPE_MINUS_SIGN:
278             return fSymbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kMinusSignSymbol);
279         case AffixPatternType::TYPE_PLUS_SIGN:
280             return fSymbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPlusSignSymbol);
281         case AffixPatternType::TYPE_PERCENT:
282             return fSymbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPercentSymbol);
283         case AffixPatternType::TYPE_PERMILLE:
284             return fSymbols->getSymbol(DecimalFormatSymbols::ENumberFormatSymbol::kPerMillSymbol);
285         case AffixPatternType::TYPE_CURRENCY_SINGLE: {
286             // UnitWidth ISO and HIDDEN overrides the singular currency symbol.
287             if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_ISO_CODE) {
288                 return fCurrencySymbols->getIntlCurrencySymbol(localStatus);
289             } else if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_HIDDEN) {
290                 return UnicodeString();
291             } else if (fUnitWidth == UNumberUnitWidth::UNUM_UNIT_WIDTH_NARROW) {
292                 return fCurrencySymbols->getNarrowCurrencySymbol(localStatus);
293             } else {
294                 return fCurrencySymbols->getCurrencySymbol(localStatus);
295             }
296         }
297         case AffixPatternType::TYPE_CURRENCY_DOUBLE:
298             return fCurrencySymbols->getIntlCurrencySymbol(localStatus);
299         case AffixPatternType::TYPE_CURRENCY_TRIPLE:
300             // NOTE: This is the code path only for patterns containing "¤¤¤".
301             // Plural currencies set via the API are formatted in LongNameHandler.
302             // This code path is used by DecimalFormat via CurrencyPluralInfo.
303             U_ASSERT(fPlural != StandardPlural::Form::COUNT);
304             return fCurrencySymbols->getPluralName(fPlural, localStatus);
305         case AffixPatternType::TYPE_CURRENCY_QUAD:
306             return UnicodeString(u"\uFFFD");
307         case AffixPatternType::TYPE_CURRENCY_QUINT:
308             return UnicodeString(u"\uFFFD");
309         default:
310             U_ASSERT(false);
311             return UnicodeString();
312     }
313 }
314 
toUnicodeString() const315 UnicodeString MutablePatternModifier::toUnicodeString() const {
316     // Never called by AffixUtils
317     U_ASSERT(false);
318     return UnicodeString();
319 }
320 
321 #endif /* #if !UCONFIG_NO_FORMATTING */
322