Debian Codegraph @

intl/components/src/NumberFormatFields.cpp

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 #include "ICU4CGlue.h"
5 #include "NumberFormatFields.h"
6 #include "ScopedICUObject.h"
7
8 #include "mozilla/FloatingPoint.h"
9 #include "unicode/uformattedvalue.h"
10 #include "unicode/unum.h"
11 #include "unicode/unumberformatter.h"
12
13 namespace mozilla::intl {
14
15 bool NumberFormatFields::append(NumberPartType type, int32_t begin,
16 int32_t end) {
17 MOZ_ASSERT(begin >= 0);
18 MOZ_ASSERT(end >= 0);
19 MOZ_ASSERT(begin < end, "erm, aren't fields always non-empty?");
20
21 return fields_.emplaceBack(uint32_t(begin), uint32_t(end), type);
22 }
23
24 bool NumberFormatFields::toPartsVector(size_t overallLength,
25 const NumberPartSourceMap& sourceMap,
26 NumberPartVector& parts) {
27 std::sort(fields_.begin(), fields_.end(),
28 [](const NumberFormatField& left, const NumberFormatField& right) {
29 // Sort first by begin index, then to place
30 // enclosing fields before nested fields.
31 return left.begin < right.begin ||
32 (left.begin == right.begin && left.end > right.end);
33 });
34
35 // Then iterate over the sorted field list to generate a sequence of parts
36 // (what ECMA-402 actually exposes). A part is a maximal character sequence
37 // entirely within no field or a single most-nested field.
38 //
39 // Diagrams may be helpful to illustrate how fields map to parts. Consider
40 // formatting -19,766,580,028,249.41, the US national surplus (negative
41 // because it's actually a debt) on October 18, 2016.
42 //
43 // var options =
44 // { style: "currency", currency: "USD", currencyDisplay: "name" };
45 // var usdFormatter = new Intl.NumberFormat("en-US", options);
46 // usdFormatter.format(-19766580028249.41);
47 //
48 // The formatted result is "-19,766,580,028,249.41 US dollars". ICU
49 // identifies these fields in the string:
50 //
51 // UNUM_GROUPING_SEPARATOR_FIELD
52 // |
53 // UNUM_SIGN_FIELD | UNUM_DECIMAL_SEPARATOR_FIELD
54 // | __________/| |
55 // | / | | | |
56 // "-19,766,580,028,249.41 US dollars"
57 // \________________/ |/ \_______/
58 // | | |
59 // UNUM_INTEGER_FIELD | UNUM_CURRENCY_FIELD
60 // |
61 // UNUM_FRACTION_FIELD
62 //
63 // These fields map to parts as follows:
64 //
65 // integer decimal
66 // _____|________ |
67 // / /| |\ |\ |\ | literal
68 // /| / | | \ | \ | \| |
69 // "-19,766,580,028,249.41 US dollars"
70 // | \___|___|___/ |/ \________/
71 // | | | |
72 // | group | currency
73 // | |
74 // minusSign fraction
75 //
76 // The sign is a part. Each comma is a part, splitting the integer field
77 // into parts for trillions/billions/&c. digits. The decimal point is a
78 // part. Cents are a part. The space between cents and currency is a part
79 // (outside any field). Last, the currency field is a part.
80
81 class PartGenerator {
82 // The fields in order from start to end, then least to most nested.
83 const FieldsVector& fields;
84
85 // Index of the current field, in |fields|, being considered to
86 // determine part boundaries. |lastEnd <= fields[index].begin| is an
87 // invariant.
88 size_t index = 0;
89
90 // The end index of the last part produced, always less than or equal
91 // to |limit|, strictly increasing.
92 uint32_t lastEnd = 0;
93
94 // The length of the overall formatted string.
95 const uint32_t limit = 0;
96
97 NumberPartSourceMap sourceMap;
98
99 Vector<size_t, 4> enclosingFields;
100
101 void popEnclosingFieldsEndingAt(uint32_t end) {
102 MOZ_ASSERT_IF(enclosingFields.length() > 0,
103 fields[enclosingFields.back()].end >= end);
104
105 while (enclosingFields.length() > 0 &&
106 fields[enclosingFields.back()].end == end) {
107 enclosingFields.popBack();
108 }
109 }
110
111 bool nextPartInternal(NumberPart* part) {
112 size_t len = fields.length();
113 MOZ_ASSERT(index <= len);
114
115 // If we're out of fields, all that remains are part(s) consisting
116 // of trailing portions of enclosing fields, and maybe a final
117 // literal part.
118 if (index == len) {
119 if (enclosingFields.length() > 0) {
120 const auto& enclosing = fields[enclosingFields.popCopy()];
121 *part = {enclosing.type, sourceMap.source(enclosing), enclosing.end};
122
123 // If additional enclosing fields end where this part ends,
124 // pop them as well.
125 popEnclosingFieldsEndingAt(part->endIndex);
126 } else {
127 *part = {NumberPartType::Literal, sourceMap.source(limit), limit};
128 }
129
130 return true;
131 }
132
133 // Otherwise we still have a field to process.
134 const NumberFormatField* current = &fields[index];
135 MOZ_ASSERT(lastEnd <= current->begin);
136 MOZ_ASSERT(current->begin < current->end);
137
138 // But first, deal with inter-field space.
139 if (lastEnd < current->begin) {
140 if (enclosingFields.length() > 0) {
141 // Space between fields, within an enclosing field, is part
142 // of that enclosing field, until the start of the current
143 // field or the end of the enclosing field, whichever is
144 // earlier.
145 const auto& enclosing = fields[enclosingFields.back()];
146 *part = {enclosing.type, sourceMap.source(enclosing),
147 std::min(enclosing.end, current->begin)};
148 popEnclosingFieldsEndingAt(part->endIndex);
149 } else {
150 // If there's no enclosing field, the space is a literal.
151 *part = {NumberPartType::Literal, sourceMap.source(current->begin),
152 current->begin};
153 }
154
155 return true;
156 }
157
158 // Otherwise, the part spans a prefix of the current field. Find
159 // the most-nested field containing that prefix.
160 const NumberFormatField* next;
161 do {
162 current = &fields[index];
163
164 // If the current field is last, the part extends to its end.
165 if (++index == len) {
166 *part = {current->type, sourceMap.source(*current), current->end};
167 return true;
168 }
169
170 next = &fields[index];
171 MOZ_ASSERT(current->begin <= next->begin);
172 MOZ_ASSERT(current->begin < next->end);
173
174 // If the next field nests within the current field, push an
175 // enclosing field. (If there are no nested fields, don't
176 // bother pushing a field that'd be immediately popped.)
177 if (current->end > next->begin) {
178 if (!enclosingFields.append(index - 1)) {
179 return false;
180 }
181 }
182
183 // Do so until the next field begins after this one.
184 } while (current->begin == next->begin);
185
186 if (current->end <= next->begin) {
187 // The next field begins after the current field ends. Therefore
188 // the current part ends at the end of the current field.
189 *part = {current->type, sourceMap.source(*current), current->end};
190 popEnclosingFieldsEndingAt(part->endIndex);
191 } else {
192 // The current field encloses the next one. The current part
193 // ends where the next field/part will start.
194 *part = {current->type, sourceMap.source(*current), next->begin};
195 }
196
197 return true;
198 }
199
200 public:
201 PartGenerator(const FieldsVector& vec, uint32_t limit,
202 const NumberPartSourceMap& sourceMap)
203 : fields(vec), limit(limit), sourceMap(sourceMap) {}
204
205 bool nextPart(bool* hasPart, NumberPart* part) {
206 // There are no parts left if we've partitioned the entire string.
207 if (lastEnd == limit) {
208 MOZ_ASSERT(enclosingFields.length() == 0);
209 *hasPart = false;
210 return true;
211 }
212
213 if (!nextPartInternal(part)) {
214 return false;
215 }
216
217 *hasPart = true;
218 lastEnd = part->endIndex;
219 return true;
220 }
221 };
222
223 // Finally, generate the result array.
224 size_t lastEndIndex = 0;
225
226 PartGenerator gen(fields_, overallLength, sourceMap);
227 do {
228 bool hasPart;
229 NumberPart part;
230 if (!gen.nextPart(&hasPart, &part)) {
231 return false;
232 }
233
234 if (!hasPart) {
235 break;
236 }
237
238 MOZ_ASSERT(lastEndIndex < part.endIndex);
239
240 if (!parts.append(part)) {
241 return false;
242 }
243
244 lastEndIndex = part.endIndex;
245 } while (true);
246
247 MOZ_ASSERT(lastEndIndex == overallLength,
248 "result array must partition the entire string");
249
250 return lastEndIndex == overallLength;
251 }
252
253 Result<std::u16string_view, ICUError> FormatResultToParts(
254 const UFormattedNumber* value, Maybe<double> number, bool isNegative,
255 bool formatForUnit, NumberPartVector& parts) {
256 UErrorCode status = U_ZERO_ERROR;
257
258 const UFormattedValue* formattedValue = unumf_resultAsValue(value, &status);
259 if (U_FAILURE(status)) {
260 return Err(ToICUError(status));
261 }
262
263 return FormatResultToParts(formattedValue, number, isNegative, formatForUnit,
264 parts);
265 }
266
267 Result<std::u16string_view, ICUError> FormatResultToParts(
268 const UFormattedValue* value, Maybe<double> number, bool isNegative,
269 bool formatForUnit, NumberPartVector& parts) {
270 UErrorCode status = U_ZERO_ERROR;
271
272 int32_t utf16Length;
273 const char16_t* utf16Str = ufmtval_getString(value, &utf16Length, &status);
274 if (U_FAILURE(status)) {
275 return Err(ToICUError(status));
276 }
277
278 UConstrainedFieldPosition* fpos = ucfpos_open(&status);
279 if (U_FAILURE(status)) {
280 return Err(ToICUError(status));
281 }
282 ScopedICUObject<UConstrainedFieldPosition, ucfpos_close> toCloseFpos(fpos);
283
284 // We're only interested in UFIELD_CATEGORY_NUMBER fields.
285 ucfpos_constrainCategory(fpos, UFIELD_CATEGORY_NUMBER, &status);
286 if (U_FAILURE(status)) {
287 return Err(ToICUError(status));
288 }
289
290 // Vacuum up fields in the overall formatted string.
291 NumberFormatFields fields;
292
293 while (true) {
294 bool hasMore = ufmtval_nextPosition(value, fpos, &status);
295 if (U_FAILURE(status)) {
296 return Err(ToICUError(status));
297 }
298 if (!hasMore) {
299 break;
300 }
301
302 int32_t fieldName = ucfpos_getField(fpos, &status);
303 if (U_FAILURE(status)) {
304 return Err(ToICUError(status));
305 }
306
307 int32_t beginIndex, endIndex;
308 ucfpos_getIndexes(fpos, &beginIndex, &endIndex, &status);
309 if (U_FAILURE(status)) {
310 return Err(ToICUError(status));
311 }
312
313 Maybe<NumberPartType> partType = GetPartTypeForNumberField(
314 UNumberFormatFields(fieldName), number, isNegative, formatForUnit);
315 if (!partType || !fields.append(*partType, beginIndex, endIndex)) {
316 return Err(ICUError::InternalError);
317 }
318 }
319
320 if (!fields.toPartsVector(utf16Length, parts)) {
321 return Err(ICUError::InternalError);
322 }
323
324 return std::u16string_view(utf16Str, static_cast<size_t>(utf16Length));
325 }
326
327 // See intl/icu/source/i18n/unicode/unum.h for a detailed field list. This
328 // list is deliberately exhaustive: cases might have to be added/removed if
329 // this code is compiled with a different ICU with more UNumberFormatFields
330 // enum initializers. Please guard such cases with appropriate ICU
331 // version-testing #ifdefs, should cross-version divergence occur.
332 Maybe<NumberPartType> GetPartTypeForNumberField(UNumberFormatFields fieldName,
333 Maybe<double> number,
334 bool isNegative,
335 bool formatForUnit) {
336 switch (fieldName) {
337 case UNUM_INTEGER_FIELD:
338 if (number.isSome()) {
339 if (std::isnan(*number)) {
340 return Some(NumberPartType::Nan);
341 }
342 if (!std::isfinite(*number)) {
343 return Some(NumberPartType::Infinity);
344 }
345 }
346 return Some(NumberPartType::Integer);
347 case UNUM_FRACTION_FIELD:
348 return Some(NumberPartType::Fraction);
349 case UNUM_DECIMAL_SEPARATOR_FIELD:
350 return Some(NumberPartType::Decimal);
351 case UNUM_EXPONENT_SYMBOL_FIELD:
352 return Some(NumberPartType::ExponentSeparator);
353 case UNUM_EXPONENT_SIGN_FIELD:
354 return Some(NumberPartType::ExponentMinusSign);
355 case UNUM_EXPONENT_FIELD:
356 return Some(NumberPartType::ExponentInteger);
357 case UNUM_GROUPING_SEPARATOR_FIELD:
358 return Some(NumberPartType::Group);
359 case UNUM_CURRENCY_FIELD:
360 return Some(NumberPartType::Currency);
361 case UNUM_PERCENT_FIELD:
362 if (formatForUnit) {
363 return Some(NumberPartType::Unit);
364 }
365 return Some(NumberPartType::Percent);
366 case UNUM_PERMILL_FIELD:
367 MOZ_ASSERT_UNREACHABLE(
368 "unexpected permill field found, even though "
369 "we don't use any user-defined patterns that "
370 "would require a permill field");
371 break;
372 case UNUM_SIGN_FIELD:
373 if (isNegative) {
374 return Some(NumberPartType::MinusSign);
375 }
376 return Some(NumberPartType::PlusSign);
377 case UNUM_MEASURE_UNIT_FIELD:
378 return Some(NumberPartType::Unit);
379 case UNUM_COMPACT_FIELD:
380 return Some(NumberPartType::Compact);
381 case UNUM_APPROXIMATELY_SIGN_FIELD:
382 return Some(NumberPartType::ApproximatelySign);
383 #ifndef U_HIDE_DEPRECATED_API
384 case UNUM_FIELD_COUNT:
385 MOZ_ASSERT_UNREACHABLE(
386 "format field sentinel value returned by iterator!");
387 break;
388 #endif
389 }
390
391 MOZ_ASSERT_UNREACHABLE(
392 "unenumerated, undocumented format field returned by iterator");
393 return Nothing();
394 }
395
396 } // namespace mozilla::intl