File: IntlNumberFormatInlines.h

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (353 lines) | stat: -rw-r--r-- 16,957 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
 * Copyright (C) 2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include "BuiltinNames.h"
#include "IntlNumberFormat.h"
#include "IntlObjectInlines.h"
#include "JSGlobalObject.h"
#include "JSGlobalObjectFunctions.h"

WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN

namespace JSC  {

template<typename IntlType>
void setNumberFormatDigitOptions(JSGlobalObject* globalObject, IntlType* intlInstance, JSObject* options, unsigned minimumFractionDigitsDefault, unsigned maximumFractionDigitsDefault, IntlNotation notation)
{
    VM& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    unsigned minimumIntegerDigits = intlNumberOption(globalObject, options, vm.propertyNames->minimumIntegerDigits, 1, 21, 1);
    RETURN_IF_EXCEPTION(scope, void());

    JSValue minimumFractionDigitsValue = jsUndefined();
    JSValue maximumFractionDigitsValue = jsUndefined();
    JSValue minimumSignificantDigitsValue = jsUndefined();
    JSValue maximumSignificantDigitsValue = jsUndefined();
    if (options) {
        minimumFractionDigitsValue = options->get(globalObject, vm.propertyNames->minimumFractionDigits);
        RETURN_IF_EXCEPTION(scope, void());

        maximumFractionDigitsValue = options->get(globalObject, vm.propertyNames->maximumFractionDigits);
        RETURN_IF_EXCEPTION(scope, void());

        minimumSignificantDigitsValue = options->get(globalObject, vm.propertyNames->minimumSignificantDigits);
        RETURN_IF_EXCEPTION(scope, void());

        maximumSignificantDigitsValue = options->get(globalObject, vm.propertyNames->maximumSignificantDigits);
        RETURN_IF_EXCEPTION(scope, void());
    }

    intlInstance->m_minimumIntegerDigits = minimumIntegerDigits;

    unsigned roundingIncrement = intlNumberOption(globalObject, options, vm.propertyNames->roundingIncrement, 1, 5000, 1);
    RETURN_IF_EXCEPTION(scope, void());
    static constexpr const unsigned roundingIncrementCandidates[] = {
        1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000
    };
    if (std::none_of(roundingIncrementCandidates, roundingIncrementCandidates + std::size(roundingIncrementCandidates),
        [&](unsigned candidate) {
            return candidate == roundingIncrement;
        })) {
        throwRangeError(globalObject, scope, "roundingIncrement must be one of 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000"_s);
        return;
    }

    RoundingMode roundingMode = intlOption<RoundingMode>(globalObject, options, vm.propertyNames->roundingMode, {
            { "ceil"_s, RoundingMode::Ceil },
            { "floor"_s, RoundingMode::Floor },
            { "expand"_s, RoundingMode::Expand },
            { "trunc"_s, RoundingMode::Trunc },
            { "halfCeil"_s, RoundingMode::HalfCeil },
            { "halfFloor"_s, RoundingMode::HalfFloor },
            { "halfExpand"_s, RoundingMode::HalfExpand },
            { "halfTrunc"_s, RoundingMode::HalfTrunc },
            { "halfEven"_s, RoundingMode::HalfEven }
        }, "roundingMode must be either \"ceil\", \"floor\", \"expand\", \"trunc\", \"halfCeil\", \"halfFloor\", \"halfExpand\", \"halfTrunc\", or \"halfEven\""_s, RoundingMode::HalfExpand);
    RETURN_IF_EXCEPTION(scope, void());

    IntlRoundingPriority roundingPriority = intlOption<IntlRoundingPriority>(globalObject, options, vm.propertyNames->roundingPriority, { { "auto"_s, IntlRoundingPriority::Auto }, { "morePrecision"_s, IntlRoundingPriority::MorePrecision }, { "lessPrecision"_s, IntlRoundingPriority::LessPrecision } }, "roundingPriority must be either \"auto\", \"morePrecision\", or \"lessPrecision\""_s, IntlRoundingPriority::Auto);
    RETURN_IF_EXCEPTION(scope, void());

    IntlTrailingZeroDisplay trailingZeroDisplay = intlOption<IntlTrailingZeroDisplay>(globalObject, options, vm.propertyNames->trailingZeroDisplay, { { "auto"_s, IntlTrailingZeroDisplay::Auto }, { "stripIfInteger"_s, IntlTrailingZeroDisplay::StripIfInteger } }, "trailingZeroDisplay must be either \"auto\" or \"stripIfInteger\""_s, IntlTrailingZeroDisplay::Auto);
    RETURN_IF_EXCEPTION(scope, void());

    if (roundingIncrement != 1)
        maximumFractionDigitsDefault = minimumFractionDigitsDefault;

    intlInstance->m_roundingIncrement = roundingIncrement;
    intlInstance->m_roundingMode = roundingMode;
    intlInstance->m_trailingZeroDisplay = trailingZeroDisplay;

    bool hasSd = !minimumSignificantDigitsValue.isUndefined() || !maximumSignificantDigitsValue.isUndefined();
    bool hasFd = !minimumFractionDigitsValue.isUndefined() || !maximumFractionDigitsValue.isUndefined();

    bool needSd = true;
    bool needFd = true;

    if (roundingPriority == IntlRoundingPriority::Auto) {
        needSd = hasSd;
        if (hasSd || (!hasFd && notation == IntlNotation::Compact))
            needFd = false;
    }

    if (needSd) {
        if (hasSd) {
            unsigned minimumSignificantDigits = intlDefaultNumberOption(globalObject, minimumSignificantDigitsValue, vm.propertyNames->minimumSignificantDigits, 1, 21, 1);
            RETURN_IF_EXCEPTION(scope, void());
            unsigned maximumSignificantDigits = intlDefaultNumberOption(globalObject, maximumSignificantDigitsValue, vm.propertyNames->maximumSignificantDigits, minimumSignificantDigits, 21, 21);
            RETURN_IF_EXCEPTION(scope, void());
            intlInstance->m_minimumSignificantDigits = minimumSignificantDigits;
            intlInstance->m_maximumSignificantDigits = maximumSignificantDigits;
        } else {
            intlInstance->m_minimumSignificantDigits = 1;
            intlInstance->m_maximumSignificantDigits = 21;
        }
    }

    if (needFd) {
        if (hasFd) {
            constexpr unsigned undefinedValue = UINT32_MAX;
            unsigned minimumFractionDigits = intlDefaultNumberOption(globalObject, minimumFractionDigitsValue, vm.propertyNames->minimumFractionDigits, 0, 100, undefinedValue);
            RETURN_IF_EXCEPTION(scope, void());
            unsigned maximumFractionDigits = intlDefaultNumberOption(globalObject, maximumFractionDigitsValue, vm.propertyNames->maximumFractionDigits, 0, 100, undefinedValue);
            RETURN_IF_EXCEPTION(scope, void());

            if (minimumFractionDigits == undefinedValue)
                minimumFractionDigits = std::min(minimumFractionDigitsDefault, maximumFractionDigits);
            else if (maximumFractionDigits == undefinedValue)
                maximumFractionDigits = std::max(maximumFractionDigitsDefault, minimumFractionDigits);
            else if (minimumFractionDigits > maximumFractionDigits) {
                throwRangeError(globalObject, scope, "Computed minimumFractionDigits is larger than maximumFractionDigits"_s);
                return;
            }

            intlInstance->m_minimumFractionDigits = minimumFractionDigits;
            intlInstance->m_maximumFractionDigits = maximumFractionDigits;
        } else {
            intlInstance->m_minimumFractionDigits = minimumFractionDigitsDefault;
            intlInstance->m_maximumFractionDigits = maximumFractionDigitsDefault;
        }
    }

    if (needSd || needFd) {
        if (roundingPriority == IntlRoundingPriority::MorePrecision)
            intlInstance->m_roundingType = IntlRoundingType::MorePrecision;
        else if (roundingPriority == IntlRoundingPriority::LessPrecision)
            intlInstance->m_roundingType = IntlRoundingType::LessPrecision;
        else if (hasSd)
            intlInstance->m_roundingType = IntlRoundingType::SignificantDigits;
        else
            intlInstance->m_roundingType = IntlRoundingType::FractionDigits;
    } else {
        intlInstance->m_roundingType = IntlRoundingType::MorePrecision;
        intlInstance->m_minimumFractionDigits = 0;
        intlInstance->m_maximumFractionDigits = 0;
        intlInstance->m_minimumSignificantDigits = 1;
        intlInstance->m_maximumSignificantDigits = 2;
    }

    if (roundingIncrement != 1) {
        if (intlInstance->m_roundingType != IntlRoundingType::FractionDigits) {
            throwTypeError(globalObject, scope, "rounding type is not fraction-digits while roundingIncrement is specified"_s);
            return;
        }
        if (intlInstance->m_maximumFractionDigits != intlInstance->m_minimumFractionDigits) {
            throwRangeError(globalObject, scope, "maximumFractionDigits and minimumFractionDigits are different while roundingIncrement is specified"_s);
            return;
        }
    }
}

template<typename IntlType>
void appendNumberFormatDigitOptionsToSkeleton(IntlType* intlInstance, StringBuilder& skeletonBuilder)
{
    switch (intlInstance->m_roundingMode) {
    case RoundingMode::Ceil:
        skeletonBuilder.append(" rounding-mode-ceiling"_s);
        break;
    case RoundingMode::Floor:
        skeletonBuilder.append(" rounding-mode-floor"_s);
        break;
    case RoundingMode::Expand:
        skeletonBuilder.append(" rounding-mode-up"_s);
        break;
    case RoundingMode::Trunc:
        skeletonBuilder.append(" rounding-mode-down"_s);
        break;
    case RoundingMode::HalfCeil:
        skeletonBuilder.append(" rounding-mode-half-ceiling"_s);
        break;
    case RoundingMode::HalfFloor:
        skeletonBuilder.append(" rounding-mode-half-floor"_s);
        break;
    case RoundingMode::HalfExpand:
        skeletonBuilder.append(" rounding-mode-half-up"_s);
        break;
    case RoundingMode::HalfTrunc:
        skeletonBuilder.append(" rounding-mode-half-down"_s);
        break;
    case RoundingMode::HalfEven:
        skeletonBuilder.append(" rounding-mode-half-even"_s);
        break;
    }

    // https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#integer-width
    skeletonBuilder.append(" integer-width/*"_s);
    for (unsigned i = 0; i < intlInstance->m_minimumIntegerDigits; ++i)
        skeletonBuilder.append('0');

    if (intlInstance->m_roundingIncrement != 1) {
        skeletonBuilder.append(" precision-increment/"_s);
        auto string = numberToStringUnsigned<Vector<LChar, 10>>(intlInstance->m_roundingIncrement);
        if (intlInstance->m_maximumFractionDigits >= string.size()) {
            skeletonBuilder.append("0."_s);
            for (unsigned i = 0; i < (intlInstance->m_maximumFractionDigits - string.size()); ++i)
                skeletonBuilder.append('0');
            skeletonBuilder.append(string);
        } else {
            unsigned nonFraction = string.size() - intlInstance->m_maximumFractionDigits;
            skeletonBuilder.append(std::span(string.data(), nonFraction), '.', std::span(string.data() + nonFraction, intlInstance->m_maximumFractionDigits));
        }
    } else {
        switch (intlInstance->m_roundingType) {
        case IntlRoundingType::FractionDigits: {
            // https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#fraction-precision
            skeletonBuilder.append(" ."_s);
            for (unsigned i = 0; i < intlInstance->m_minimumFractionDigits; ++i)
                skeletonBuilder.append('0');
            for (unsigned i = 0; i < intlInstance->m_maximumFractionDigits - intlInstance->m_minimumFractionDigits; ++i)
                skeletonBuilder.append('#');
            break;
        }
        case IntlRoundingType::SignificantDigits: {
            // https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#significant-digits-precision
            skeletonBuilder.append(' ');
            for (unsigned i = 0; i < intlInstance->m_minimumSignificantDigits; ++i)
                skeletonBuilder.append('@');
            for (unsigned i = 0; i < intlInstance->m_maximumSignificantDigits - intlInstance->m_minimumSignificantDigits; ++i)
                skeletonBuilder.append('#');
            break;
        }
        case IntlRoundingType::MorePrecision:
        case IntlRoundingType::LessPrecision:
            // https://github.com/unicode-org/icu/commit/d7db6c1f8655bb53153695b09a50029fd04a8364
            // https://github.com/unicode-org/icu/blob/main/docs/userguide/format_parse/numbers/skeletons.md#precision
            skeletonBuilder.append(" ."_s);
            for (unsigned i = 0; i < intlInstance->m_minimumFractionDigits; ++i)
                skeletonBuilder.append('0');
            for (unsigned i = 0; i < intlInstance->m_maximumFractionDigits - intlInstance->m_minimumFractionDigits; ++i)
                skeletonBuilder.append('#');
            skeletonBuilder.append('/');
            for (unsigned i = 0; i < intlInstance->m_minimumSignificantDigits; ++i)
                skeletonBuilder.append('@');
            for (unsigned i = 0; i < intlInstance->m_maximumSignificantDigits - intlInstance->m_minimumSignificantDigits; ++i)
                skeletonBuilder.append('#');
            skeletonBuilder.append(intlInstance->m_roundingType == IntlRoundingType::MorePrecision ? 'r' : 's');
            break;
        }
    }

    // Configure this just after precision.
    // https://github.com/unicode-org/icu/blob/main/docs/userguide/format_parse/numbers/skeletons.md#trailing-zero-display
    switch (intlInstance->m_trailingZeroDisplay) {
    case IntlTrailingZeroDisplay::Auto:
        break;
    case IntlTrailingZeroDisplay::StripIfInteger:
        skeletonBuilder.append("/w"_s);
        break;
    }
}

class IntlFieldIterator {
public:
    WTF_MAKE_NONCOPYABLE(IntlFieldIterator);

    explicit IntlFieldIterator(UFieldPositionIterator& iterator)
        : m_iterator(iterator)
    {
    }

    int32_t next(int32_t& beginIndex, int32_t& endIndex, UErrorCode&)
    {
        return ufieldpositer_next(&m_iterator, &beginIndex, &endIndex);
    }

private:
    UFieldPositionIterator& m_iterator;
};

// https://tc39.es/ecma402/#sec-unwrapnumberformat
inline IntlNumberFormat* IntlNumberFormat::unwrapForOldFunctions(JSGlobalObject* globalObject, JSValue thisValue)
{
    return unwrapForLegacyIntlConstructor<IntlNumberFormat>(globalObject, thisValue, globalObject->numberFormatConstructor());
}

// https://tc39.es/ecma402/#sec-tointlmathematicalvalue
inline IntlMathematicalValue toIntlMathematicalValue(JSGlobalObject* globalObject, JSValue value)
{
    VM& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (auto number = JSBigInt::tryExtractDouble(value))
        return IntlMathematicalValue { number.value() };

    JSValue primitive = value.toPrimitive(globalObject, PreferredPrimitiveType::PreferNumber);
    RETURN_IF_EXCEPTION(scope, { });

    auto bigIntToIntlMathematicalValue = [](JSGlobalObject* globalObject, JSValue value) -> IntlMathematicalValue {
        VM& vm = globalObject->vm();
        auto scope = DECLARE_THROW_SCOPE(vm);

        if (auto number = JSBigInt::tryExtractDouble(value))
            return IntlMathematicalValue { number.value() };

        auto* bigInt = value.asHeapBigInt();
        auto string = bigInt->toString(globalObject, 10);
        RETURN_IF_EXCEPTION(scope, { });
        return IntlMathematicalValue {
            IntlMathematicalValue::NumberType::Integer,
            bigInt->sign(),
            string.ascii(),
        };
    };

    if (primitive.isBigInt())
        RELEASE_AND_RETURN(scope, bigIntToIntlMathematicalValue(globalObject, primitive));

    if (!primitive.isString())
        RELEASE_AND_RETURN(scope, IntlMathematicalValue { primitive.toNumber(globalObject) });

    auto string = asString(primitive)->value(globalObject);
    RETURN_IF_EXCEPTION(scope, { });

    RELEASE_AND_RETURN(scope, IntlMathematicalValue::parseString(globalObject, WTFMove(string)));
}

} // namespace JSC

WTF_ALLOW_UNSAFE_BUFFER_USAGE_END