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