blob: 1311381c45d99d624900335ce05c5241b89fdc8d [file] [log] [blame]
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +00001/*
commit-queue@webkit.orgcc0ef6d2018-05-07 22:44:28 +00002 * Copyright (C) 2015 Andy VanWagoner (andy@vanwagoner.family)
sukolsak@gmail.com92059832016-02-11 21:24:52 +00003 * Copyright (C) 2016 Sukolsak Sakshuwong (sukolsak@gmail.com)
mark.lam@apple.comcce76562017-05-08 16:56:32 +00004 * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +00005 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
19 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
25 * THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "config.h"
29#include "IntlNumberFormat.h"
30
31#if ENABLE(INTL)
32
annulen@yandex.ru6712c2d2017-06-25 17:40:30 +000033#include "CatchScope.h"
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000034#include "Error.h"
35#include "IntlNumberFormatConstructor.h"
36#include "IntlObject.h"
37#include "JSBoundFunction.h"
commit-queue@webkit.org70266c72016-09-02 02:43:52 +000038#include "JSCInlines.h"
sukolsak@gmail.com92059832016-02-11 21:24:52 +000039#include "ObjectConstructor.h"
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000040
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +000041#if HAVE(ICU_FORMAT_DOUBLE_FOR_FIELDS)
42#include <unicode/ufieldpositer.h>
43#endif
44
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000045namespace JSC {
46
utatane.tea@gmail.coma5544f12017-05-19 09:23:20 +000047const ClassInfo IntlNumberFormat::s_info = { "Object", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(IntlNumberFormat) };
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000048
ticaiolima@gmail.com4f3dce42017-12-22 23:33:15 +000049static const char* const relevantNumberExtensionKeys[1] = { "nu" };
sukolsak@gmail.com92059832016-02-11 21:24:52 +000050
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +000051void IntlNumberFormat::UNumberFormatDeleter::operator()(UNumberFormat* numberFormat) const
52{
53 if (numberFormat)
54 unum_close(numberFormat);
55}
56
utatane.tea@gmail.comf77bece2016-05-15 21:11:27 +000057IntlNumberFormat* IntlNumberFormat::create(VM& vm, Structure* structure)
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000058{
utatane.tea@gmail.comf77bece2016-05-15 21:11:27 +000059 IntlNumberFormat* format = new (NotNull, allocateCell<IntlNumberFormat>(vm.heap)) IntlNumberFormat(vm, structure);
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000060 format->finishCreation(vm);
61 return format;
62}
63
64Structure* IntlNumberFormat::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
65{
66 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
67}
68
69IntlNumberFormat::IntlNumberFormat(VM& vm, Structure* structure)
70 : JSDestructibleObject(vm, structure)
71{
72}
73
74void IntlNumberFormat::finishCreation(VM& vm)
75{
76 Base::finishCreation(vm);
keith_miller@apple.com45da7602017-01-27 01:47:52 +000077 ASSERT(inherits(vm, info()));
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000078}
79
80void IntlNumberFormat::destroy(JSCell* cell)
81{
82 static_cast<IntlNumberFormat*>(cell)->IntlNumberFormat::~IntlNumberFormat();
83}
84
85void IntlNumberFormat::visitChildren(JSCell* cell, SlotVisitor& visitor)
86{
87 IntlNumberFormat* thisObject = jsCast<IntlNumberFormat*>(cell);
88 ASSERT_GC_OBJECT_INHERITS(thisObject, info());
89
90 Base::visitChildren(thisObject, visitor);
91
fpizlo@apple.comf7240e02016-12-16 02:16:19 +000092 visitor.append(thisObject->m_boundFormat);
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000093}
94
keith_miller@apple.com504d5852017-09-13 01:31:07 +000095namespace IntlNFInternal {
sukolsak@gmail.com92059832016-02-11 21:24:52 +000096static Vector<String> localeData(const String& locale, size_t keyIndex)
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +000097{
sukolsak@gmail.com92059832016-02-11 21:24:52 +000098 // 9.1 Internal slots of Service Constructors & 11.2.3 Internal slots (ECMA-402 2.0)
99 ASSERT_UNUSED(keyIndex, !keyIndex); // The index of the extension key "nu" in relevantExtensionKeys is 0.
100 return numberingSystemsForLocale(locale);
101}
keith_miller@apple.com504d5852017-09-13 01:31:07 +0000102}
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000103
commit-queue@webkit.orgcfc5f012017-03-15 23:40:24 +0000104static inline unsigned computeCurrencySortKey(const String& currency)
105{
106 ASSERT(currency.length() == 3);
107 ASSERT(currency.isAllSpecialCharacters<isASCIIUpper>());
108 return (currency[0] << 16) + (currency[1] << 8) + currency[2];
109}
110
111static inline unsigned computeCurrencySortKey(const char* currency)
112{
113 ASSERT(strlen(currency) == 3);
114 ASSERT(isAllSpecialCharacters<isASCIIUpper>(currency, 3));
115 return (currency[0] << 16) + (currency[1] << 8) + currency[2];
116}
117
118static unsigned extractCurrencySortKey(std::pair<const char*, unsigned>* currencyMinorUnit)
119{
120 return computeCurrencySortKey(currencyMinorUnit->first);
121}
122
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000123static unsigned computeCurrencyDigits(const String& currency)
124{
125 // 11.1.1 The abstract operation CurrencyDigits (currency)
126 // "If the ISO 4217 currency and funds code list contains currency as an alphabetic code,
127 // then return the minor unit value corresponding to the currency from the list; else return 2.
commit-queue@webkit.orgcfc5f012017-03-15 23:40:24 +0000128 std::pair<const char*, unsigned> currencyMinorUnits[] = {
129 { "BHD", 3 },
130 { "BIF", 0 },
131 { "BYR", 0 },
132 { "CLF", 4 },
133 { "CLP", 0 },
134 { "DJF", 0 },
135 { "GNF", 0 },
136 { "IQD", 3 },
137 { "ISK", 0 },
138 { "JOD", 3 },
139 { "JPY", 0 },
140 { "KMF", 0 },
141 { "KRW", 0 },
142 { "KWD", 3 },
143 { "LYD", 3 },
144 { "OMR", 3 },
145 { "PYG", 0 },
146 { "RWF", 0 },
147 { "TND", 3 },
148 { "UGX", 0 },
149 { "UYI", 0 },
150 { "VND", 0 },
151 { "VUV", 0 },
152 { "XAF", 0 },
153 { "XOF", 0 },
154 { "XPF", 0 }
155 };
156 auto* currencyMinorUnit = tryBinarySearch<std::pair<const char*, unsigned>>(currencyMinorUnits, WTF_ARRAY_LENGTH(currencyMinorUnits), computeCurrencySortKey(currency), extractCurrencySortKey);
157 if (currencyMinorUnit)
158 return currencyMinorUnit->second;
159 return 2;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000160}
161
162void IntlNumberFormat::initializeNumberFormat(ExecState& state, JSValue locales, JSValue optionsValue)
163{
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000164 VM& vm = state.vm();
mark.lam@apple.com284f4562016-08-30 20:54:54 +0000165 auto scope = DECLARE_THROW_SCOPE(vm);
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000166
commit-queue@webkit.org54264682018-05-13 14:28:39 +0000167 // 11.1.2 InitializeNumberFormat (numberFormat, locales, options) (ECMA-402)
168 // https://tc39.github.io/ecma402/#sec-initializenumberformat
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000169
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000170 auto requestedLocales = canonicalizeLocaleList(state, locales);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000171 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000172
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000173 JSObject* options;
commit-queue@webkit.org54264682018-05-13 14:28:39 +0000174 if (optionsValue.isUndefined())
175 options = constructEmptyObject(&state, state.lexicalGlobalObject()->nullPrototypeObjectStructure());
176 else {
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000177 options = optionsValue.toObject(&state);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000178 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000179 }
180
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000181 HashMap<String, String> opt;
182
mark.lam@apple.com284f4562016-08-30 20:54:54 +0000183 String matcher = intlStringOption(state, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit");
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000184 RETURN_IF_EXCEPTION(scope, void());
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000185 opt.add("localeMatcher"_s, matcher);
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000186
utatane.tea@gmail.comb860d692018-05-31 06:19:33 +0000187 auto& availableLocales = state.jsCallee()->globalObject(vm)->intlNumberFormatAvailableLocales();
ticaiolima@gmail.com4f3dce42017-12-22 23:33:15 +0000188 auto result = resolveLocale(state, availableLocales, requestedLocales, opt, relevantNumberExtensionKeys, WTF_ARRAY_LENGTH(relevantNumberExtensionKeys), IntlNFInternal::localeData);
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000189
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000190 m_locale = result.get("locale"_s);
carlosgc@webkit.org4cb0c4f2016-09-23 08:20:06 +0000191 if (m_locale.isEmpty()) {
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000192 throwTypeError(&state, scope, "failed to initialize NumberFormat due to invalid locale"_s);
carlosgc@webkit.org4cb0c4f2016-09-23 08:20:06 +0000193 return;
194 }
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000195
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000196 m_numberingSystem = result.get("nu"_s);
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000197
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000198 String styleString = intlStringOption(state, options, Identifier::fromString(&vm, "style"), { "decimal", "percent", "currency" }, "style must be either \"decimal\", \"percent\", or \"currency\"", "decimal");
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000199 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000200 if (styleString == "decimal")
201 m_style = Style::Decimal;
202 else if (styleString == "percent")
203 m_style = Style::Percent;
204 else if (styleString == "currency")
205 m_style = Style::Currency;
206 else
207 ASSERT_NOT_REACHED();
208
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000209 String currency = intlStringOption(state, options, Identifier::fromString(&vm, "currency"), { }, nullptr, nullptr);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000210 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000211 if (!currency.isNull()) {
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000212 if (currency.length() != 3 || !currency.isAllSpecialCharacters<isASCIIAlpha>()) {
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000213 throwException(&state, scope, createRangeError(&state, "currency is not a well-formed currency code"_s));
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000214 return;
215 }
216 }
217
peavo@outlook.coma83d48a2016-05-02 21:20:15 +0000218 unsigned currencyDigits = 0;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000219 if (m_style == Style::Currency) {
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000220 if (currency.isNull()) {
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000221 throwTypeError(&state, scope, "currency must be a string"_s);
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000222 return;
223 }
224
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000225 currency = currency.convertToASCIIUppercase();
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000226 m_currency = currency;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000227 currencyDigits = computeCurrencyDigits(currency);
228 }
229
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000230 String currencyDisplayString = intlStringOption(state, options, Identifier::fromString(&vm, "currencyDisplay"), { "code", "symbol", "name" }, "currencyDisplay must be either \"code\", \"symbol\", or \"name\"", "symbol");
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000231 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000232 if (m_style == Style::Currency) {
233 if (currencyDisplayString == "code")
234 m_currencyDisplay = CurrencyDisplay::Code;
235 else if (currencyDisplayString == "symbol")
236 m_currencyDisplay = CurrencyDisplay::Symbol;
237 else if (currencyDisplayString == "name")
238 m_currencyDisplay = CurrencyDisplay::Name;
239 else
240 ASSERT_NOT_REACHED();
241 }
242
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000243 unsigned minimumIntegerDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "minimumIntegerDigits"), 1, 21, 1);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000244 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000245 m_minimumIntegerDigits = minimumIntegerDigits;
246
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000247 unsigned minimumFractionDigitsDefault = (m_style == Style::Currency) ? currencyDigits : 0;
248
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000249 unsigned minimumFractionDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "minimumFractionDigits"), 0, 20, minimumFractionDigitsDefault);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000250 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000251 m_minimumFractionDigits = minimumFractionDigits;
252
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000253 unsigned maximumFractionDigitsDefault;
254 if (m_style == Style::Currency)
255 maximumFractionDigitsDefault = std::max(minimumFractionDigits, currencyDigits);
commit-queue@webkit.org54264682018-05-13 14:28:39 +0000256 else if (m_style == Style::Percent)
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000257 maximumFractionDigitsDefault = minimumFractionDigits;
commit-queue@webkit.org54264682018-05-13 14:28:39 +0000258 else
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000259 maximumFractionDigitsDefault = std::max(minimumFractionDigits, 3u);
260
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000261 unsigned maximumFractionDigits = intlNumberOption(state, options, Identifier::fromString(&vm, "maximumFractionDigits"), minimumFractionDigits, 20, maximumFractionDigitsDefault);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000262 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000263 m_maximumFractionDigits = maximumFractionDigits;
264
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000265 JSValue minimumSignificantDigitsValue = options->get(&state, Identifier::fromString(&vm, "minimumSignificantDigits"));
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000266 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000267
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000268 JSValue maximumSignificantDigitsValue = options->get(&state, Identifier::fromString(&vm, "maximumSignificantDigits"));
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000269 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000270
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000271 if (!minimumSignificantDigitsValue.isUndefined() || !maximumSignificantDigitsValue.isUndefined()) {
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000272 unsigned minimumSignificantDigits = intlDefaultNumberOption(state, minimumSignificantDigitsValue, Identifier::fromString(&vm, "minimumSignificantDigits"), 1, 21, 1);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000273 RETURN_IF_EXCEPTION(scope, void());
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000274 unsigned maximumSignificantDigits = intlDefaultNumberOption(state, maximumSignificantDigitsValue, Identifier::fromString(&vm, "maximumSignificantDigits"), minimumSignificantDigits, 21, 21);
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000275 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000276 m_minimumSignificantDigits = minimumSignificantDigits;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000277 m_maximumSignificantDigits = maximumSignificantDigits;
278 }
279
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000280 bool usesFallback;
281 bool useGrouping = intlBooleanOption(state, options, Identifier::fromString(&vm, "useGrouping"), usesFallback);
282 if (usesFallback)
283 useGrouping = true;
mark.lam@apple.come1ab17c2016-09-26 19:11:17 +0000284 RETURN_IF_EXCEPTION(scope, void());
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000285 m_useGrouping = useGrouping;
286
commit-queue@webkit.org0cbf4f62018-01-31 04:47:43 +0000287 UNumberFormatStyle style = UNUM_DEFAULT;
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000288 switch (m_style) {
289 case Style::Decimal:
290 style = UNUM_DECIMAL;
291 break;
292 case Style::Percent:
293 style = UNUM_PERCENT;
294 break;
295 case Style::Currency:
296 switch (m_currencyDisplay) {
297 case CurrencyDisplay::Code:
298 style = UNUM_CURRENCY_ISO;
299 break;
300 case CurrencyDisplay::Symbol:
301 style = UNUM_CURRENCY;
302 break;
303 case CurrencyDisplay::Name:
304 style = UNUM_CURRENCY_PLURAL;
305 break;
306 default:
307 ASSERT_NOT_REACHED();
308 }
309 break;
310 default:
311 ASSERT_NOT_REACHED();
312 }
313
314 UErrorCode status = U_ZERO_ERROR;
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000315 m_numberFormat = std::unique_ptr<UNumberFormat, UNumberFormatDeleter>(unum_open(style, nullptr, 0, m_locale.utf8().data(), nullptr, &status));
316 if (U_FAILURE(status)) {
317 throwTypeError(&state, scope, "failed to initialize NumberFormat"_s);
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000318 return;
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000319 }
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000320
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000321 if (m_style == Style::Currency) {
322 unum_setTextAttribute(m_numberFormat.get(), UNUM_CURRENCY_CODE, StringView(m_currency).upconvertedCharacters(), m_currency.length(), &status);
323 if (U_FAILURE(status)) {
324 throwTypeError(&state, scope, "failed to initialize NumberFormat"_s);
325 return;
326 }
327 }
328 if (!m_minimumSignificantDigits) {
329 unum_setAttribute(m_numberFormat.get(), UNUM_MIN_INTEGER_DIGITS, m_minimumIntegerDigits);
330 unum_setAttribute(m_numberFormat.get(), UNUM_MIN_FRACTION_DIGITS, m_minimumFractionDigits);
331 unum_setAttribute(m_numberFormat.get(), UNUM_MAX_FRACTION_DIGITS, m_maximumFractionDigits);
332 } else {
333 unum_setAttribute(m_numberFormat.get(), UNUM_SIGNIFICANT_DIGITS_USED, true);
334 unum_setAttribute(m_numberFormat.get(), UNUM_MIN_SIGNIFICANT_DIGITS, m_minimumSignificantDigits);
335 unum_setAttribute(m_numberFormat.get(), UNUM_MAX_SIGNIFICANT_DIGITS, m_maximumSignificantDigits);
336 }
337 unum_setAttribute(m_numberFormat.get(), UNUM_GROUPING_USED, m_useGrouping);
338 unum_setAttribute(m_numberFormat.get(), UNUM_ROUNDING_MODE, UNUM_ROUND_HALFUP);
339
340 m_initializedNumberFormat = true;
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000341}
342
343JSValue IntlNumberFormat::formatNumber(ExecState& state, double number)
344{
mark.lam@apple.com284f4562016-08-30 20:54:54 +0000345 VM& vm = state.vm();
346 auto scope = DECLARE_THROW_SCOPE(vm);
347
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +0000348 // 11.3.4 FormatNumber abstract operation (ECMA-402 2.0)
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000349 if (!m_initializedNumberFormat)
350 return throwTypeError(&state, scope, "Intl.NumberFormat.prototype.format called on value that's not an object initialized as a NumberFormat"_s);
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +0000351
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000352 // Map negative zero to positive zero.
353 if (!number)
354 number = 0.0;
355
356 UErrorCode status = U_ZERO_ERROR;
357 Vector<UChar, 32> buffer(32);
358 auto length = unum_formatDouble(m_numberFormat.get(), number, buffer.data(), buffer.size(), nullptr, &status);
359 if (status == U_BUFFER_OVERFLOW_ERROR) {
360 buffer.grow(length);
361 status = U_ZERO_ERROR;
362 unum_formatDouble(m_numberFormat.get(), number, buffer.data(), length, nullptr, &status);
363 }
364 if (U_FAILURE(status))
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000365 return throwException(&state, scope, createError(&state, "Failed to format a number."_s));
sukolsak@gmail.com16e1a512016-02-20 01:58:06 +0000366
367 return jsString(&state, String(buffer.data(), length));
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +0000368}
369
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000370ASCIILiteral IntlNumberFormat::styleString(Style style)
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000371{
372 switch (style) {
373 case Style::Decimal:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000374 return "decimal"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000375 case Style::Percent:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000376 return "percent"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000377 case Style::Currency:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000378 return "currency"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000379 }
380 ASSERT_NOT_REACHED();
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000381 return ASCIILiteral::null();
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000382}
383
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000384ASCIILiteral IntlNumberFormat::currencyDisplayString(CurrencyDisplay currencyDisplay)
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000385{
386 switch (currencyDisplay) {
387 case CurrencyDisplay::Code:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000388 return "code"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000389 case CurrencyDisplay::Symbol:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000390 return "symbol"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000391 case CurrencyDisplay::Name:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000392 return "name"_s;
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000393 }
394 ASSERT_NOT_REACHED();
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000395 return ASCIILiteral::null();
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000396}
397
398JSObject* IntlNumberFormat::resolvedOptions(ExecState& state)
399{
mark.lam@apple.com451de992016-09-07 22:10:50 +0000400 VM& vm = state.vm();
401 auto scope = DECLARE_THROW_SCOPE(vm);
402
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000403 // 11.3.5 Intl.NumberFormat.prototype.resolvedOptions() (ECMA-402 2.0)
404 // The function returns a new object whose properties and attributes are set as if
405 // constructed by an object literal assigning to each of the following properties the
406 // value of the corresponding internal slot of this NumberFormat object (see 11.4):
407 // locale, numberingSystem, style, currency, currencyDisplay, minimumIntegerDigits,
408 // minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits,
409 // maximumSignificantDigits, and useGrouping. Properties whose corresponding internal
410 // slots are not present are not assigned.
411
412 if (!m_initializedNumberFormat) {
413 initializeNumberFormat(state, jsUndefined(), jsUndefined());
mark.lam@apple.comcce76562017-05-08 16:56:32 +0000414 scope.assertNoException();
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000415 }
416
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000417 JSObject* options = constructEmptyObject(&state);
418 options->putDirect(vm, vm.propertyNames->locale, jsString(&state, m_locale));
419 options->putDirect(vm, Identifier::fromString(&vm, "numberingSystem"), jsString(&state, m_numberingSystem));
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000420 options->putDirect(vm, Identifier::fromString(&vm, "style"), jsNontrivialString(&state, styleString(m_style)));
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000421 if (m_style == Style::Currency) {
422 options->putDirect(vm, Identifier::fromString(&vm, "currency"), jsNontrivialString(&state, m_currency));
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000423 options->putDirect(vm, Identifier::fromString(&vm, "currencyDisplay"), jsNontrivialString(&state, currencyDisplayString(m_currencyDisplay)));
sukolsak@gmail.com92059832016-02-11 21:24:52 +0000424 }
425 options->putDirect(vm, Identifier::fromString(&vm, "minimumIntegerDigits"), jsNumber(m_minimumIntegerDigits));
426 options->putDirect(vm, Identifier::fromString(&vm, "minimumFractionDigits"), jsNumber(m_minimumFractionDigits));
427 options->putDirect(vm, Identifier::fromString(&vm, "maximumFractionDigits"), jsNumber(m_maximumFractionDigits));
428 if (m_minimumSignificantDigits) {
429 ASSERT(m_maximumSignificantDigits);
430 options->putDirect(vm, Identifier::fromString(&vm, "minimumSignificantDigits"), jsNumber(m_minimumSignificantDigits));
431 options->putDirect(vm, Identifier::fromString(&vm, "maximumSignificantDigits"), jsNumber(m_maximumSignificantDigits));
432 }
433 options->putDirect(vm, Identifier::fromString(&vm, "useGrouping"), jsBoolean(m_useGrouping));
434 return options;
435}
436
437void IntlNumberFormat::setBoundFormat(VM& vm, JSBoundFunction* format)
438{
439 m_boundFormat.set(vm, this, format);
440}
441
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000442#if HAVE(ICU_FORMAT_DOUBLE_FOR_FIELDS)
443void IntlNumberFormat::UFieldPositionIteratorDeleter::operator()(UFieldPositionIterator* iterator) const
444{
445 if (iterator)
446 ufieldpositer_close(iterator);
447}
448
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000449ASCIILiteral IntlNumberFormat::partTypeString(UNumberFormatFields field, double value)
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000450{
451 switch (field) {
452 case UNUM_INTEGER_FIELD:
453 if (std::isnan(value))
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000454 return "nan"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000455 if (!std::isfinite(value))
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000456 return "infinity"_s;
457 return "integer"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000458 case UNUM_FRACTION_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000459 return "fraction"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000460 case UNUM_DECIMAL_SEPARATOR_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000461 return "decimal"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000462 case UNUM_GROUPING_SEPARATOR_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000463 return "group"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000464 case UNUM_CURRENCY_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000465 return "currency"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000466 case UNUM_PERCENT_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000467 return "percentSign"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000468 case UNUM_SIGN_FIELD:
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000469 return value < 0 ? "minusSign"_s : "plusSign"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000470 // These should not show up because there is no way to specify them in NumberFormat options.
commit-queue@webkit.org331da102018-08-01 21:21:39 +0000471 // If they do, they don't fit well into any of known part types, so consider it an "unknown".
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000472 case UNUM_PERMILL_FIELD:
473 case UNUM_EXPONENT_SYMBOL_FIELD:
474 case UNUM_EXPONENT_SIGN_FIELD:
475 case UNUM_EXPONENT_FIELD:
476#if !defined(U_HIDE_DEPRECATED_API)
477 case UNUM_FIELD_COUNT:
478#endif
ysuzuki@apple.com4a44b7f2019-03-21 19:09:10 +0000479 // Any newer additions to the UNumberFormatFields enum should just be considered an "unknown" part.
480 default:
commit-queue@webkit.org331da102018-08-01 21:21:39 +0000481 return "unknown"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000482 }
commit-queue@webkit.org331da102018-08-01 21:21:39 +0000483 return "unknown"_s;
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000484}
485
486JSValue IntlNumberFormat::formatToParts(ExecState& exec, double value)
487{
488 VM& vm = exec.vm();
489 auto scope = DECLARE_THROW_SCOPE(vm);
490
491 // FormatNumberToParts (ECMA-402)
492 // https://tc39.github.io/ecma402/#sec-formatnumbertoparts
493 // https://tc39.github.io/ecma402/#sec-partitionnumberpattern
494
commit-queue@webkit.org2071d4722018-07-24 01:05:33 +0000495 if (!m_initializedNumberFormat)
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000496 return throwTypeError(&exec, scope, "Intl.NumberFormat.prototype.formatToParts called on value that's not an object initialized as a NumberFormat"_s);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000497
498 UErrorCode status = U_ZERO_ERROR;
499 auto fieldItr = std::unique_ptr<UFieldPositionIterator, UFieldPositionIteratorDeleter>(ufieldpositer_open(&status));
500 if (U_FAILURE(status))
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000501 return throwTypeError(&exec, scope, "failed to open field position iterator"_s);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000502
503 status = U_ZERO_ERROR;
504 Vector<UChar, 32> result(32);
505 auto resultLength = unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), result.size(), fieldItr.get(), &status);
506 if (status == U_BUFFER_OVERFLOW_ERROR) {
507 status = U_ZERO_ERROR;
508 result.grow(resultLength);
509 unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), resultLength, fieldItr.get(), &status);
510 }
511 if (U_FAILURE(status))
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000512 return throwTypeError(&exec, scope, "failed to format a number."_s);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000513
andy@vanwagoner.familyb07618f2019-02-05 22:09:32 +0000514 int32_t literalFieldType = -1;
515 auto literalField = IntlNumberFormatField(literalFieldType, resultLength);
516 Vector<IntlNumberFormatField> fields(resultLength, literalField);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000517 int32_t beginIndex = 0;
518 int32_t endIndex = 0;
519 auto fieldType = ufieldpositer_next(fieldItr.get(), &beginIndex, &endIndex);
520 while (fieldType >= 0) {
andy@vanwagoner.familyb07618f2019-02-05 22:09:32 +0000521 auto size = endIndex - beginIndex;
522 for (auto i = beginIndex; i < endIndex; ++i) {
523 // Only override previous value if new value is more specific.
524 if (fields[i].size >= size)
525 fields[i] = IntlNumberFormatField(fieldType, size);
526 }
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000527 fieldType = ufieldpositer_next(fieldItr.get(), &beginIndex, &endIndex);
528 }
529
utatane.tea@gmail.comb860d692018-05-31 06:19:33 +0000530 JSGlobalObject* globalObject = exec.jsCallee()->globalObject(vm);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000531 JSArray* parts = JSArray::tryCreate(vm, globalObject->arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 0);
532 if (!parts)
533 return throwOutOfMemoryError(&exec, scope);
534 unsigned index = 0;
535
536 auto resultString = String(result.data(), resultLength);
537 auto typePropertyName = Identifier::fromString(&vm, "type");
utatane.tea@gmail.com84077632018-06-23 08:39:34 +0000538 auto literalString = jsString(&exec, "literal"_s);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000539
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000540 int32_t currentIndex = 0;
541 while (currentIndex < resultLength) {
andy@vanwagoner.familyb07618f2019-02-05 22:09:32 +0000542 auto startIndex = currentIndex;
543 auto fieldType = fields[currentIndex].type;
544 while (currentIndex < resultLength && fields[currentIndex].type == fieldType)
545 ++currentIndex;
546 auto partType = fieldType == literalFieldType ? literalString : jsString(&exec, partTypeString(UNumberFormatFields(fieldType), value));
547 auto partValue = jsSubstring(&vm, resultString, startIndex, currentIndex - startIndex);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000548 JSObject* part = constructEmptyObject(&exec);
andy@vanwagoner.familyb07618f2019-02-05 22:09:32 +0000549 part->putDirect(vm, typePropertyName, partType);
550 part->putDirect(vm, vm.propertyNames->value, partValue);
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000551 parts->putDirectIndex(&exec, index++, part);
552 RETURN_IF_EXCEPTION(scope, { });
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000553 }
554
commit-queue@webkit.org3b45a242018-05-16 20:38:32 +0000555 return parts;
556}
557#endif
558
commit-queue@webkit.org77e4cc22015-07-30 03:33:32 +0000559} // namespace JSC
560
561#endif // ENABLE(INTL)