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