/* * Copyright (C) 2015 Andy VanWagoner (andy@vanwagoner.family) * Copyright (C) 2016 Sukolsak Sakshuwong (sukolsak@gmail.com) * Copyright (C) 2016-2020 Apple Inc. All rights reserved. * Copyright (C) 2020 Sony Interactive Entertainment Inc. * * 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. AND ITS CONTRIBUTORS ``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 ITS 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. */ #include "config.h" #include "IntlNumberFormat.h" #include "Error.h" #include "IntlNumberFormatInlines.h" #include "IntlObjectInlines.h" #include "JSBoundFunction.h" #include "JSCInlines.h" #include "ObjectConstructor.h" #include namespace JSC { const ClassInfo IntlNumberFormat::s_info = { "Object", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(IntlNumberFormat) }; namespace IntlNumberFormatInternal { static constexpr bool verbose = false; } struct IntlNumberFormatField { int32_t type; size_t size; }; IntlNumberFormat* IntlNumberFormat::create(VM& vm, Structure* structure) { IntlNumberFormat* format = new (NotNull, allocateCell(vm.heap)) IntlNumberFormat(vm, structure); format->finishCreation(vm); return format; } Structure* IntlNumberFormat::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype) { return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info()); } IntlNumberFormat::IntlNumberFormat(VM& vm, Structure* structure) : Base(vm, structure) { } void IntlNumberFormat::finishCreation(VM& vm) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); } void IntlNumberFormat::visitChildren(JSCell* cell, SlotVisitor& visitor) { IntlNumberFormat* thisObject = jsCast(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); Base::visitChildren(thisObject, visitor); visitor.append(thisObject->m_boundFormat); } Vector IntlNumberFormat::localeData(const String& locale, RelevantExtensionKey key) { // 9.1 Internal slots of Service Constructors & 11.2.3 Internal slots (ECMA-402 2.0) ASSERT_UNUSED(key, key == RelevantExtensionKey::Nu); return numberingSystemsForLocale(locale); } static inline unsigned computeCurrencySortKey(const String& currency) { ASSERT(currency.length() == 3); ASSERT(currency.isAllSpecialCharacters()); return (currency[0] << 16) + (currency[1] << 8) + currency[2]; } static inline unsigned computeCurrencySortKey(const char* currency) { ASSERT(strlen(currency) == 3); ASSERT(isAllSpecialCharacters(currency, 3)); return (currency[0] << 16) + (currency[1] << 8) + currency[2]; } static unsigned extractCurrencySortKey(std::pair* currencyMinorUnit) { return computeCurrencySortKey(currencyMinorUnit->first); } static unsigned computeCurrencyDigits(const String& currency) { // 11.1.1 The abstract operation CurrencyDigits (currency) // "If the ISO 4217 currency and funds code list contains currency as an alphabetic code, // then return the minor unit value corresponding to the currency from the list; else return 2. static constexpr std::pair currencyMinorUnits[] = { { "BHD", 3 }, { "BIF", 0 }, { "BYR", 0 }, { "CLF", 4 }, { "CLP", 0 }, { "DJF", 0 }, { "GNF", 0 }, { "IQD", 3 }, { "ISK", 0 }, { "JOD", 3 }, { "JPY", 0 }, { "KMF", 0 }, { "KRW", 0 }, { "KWD", 3 }, { "LYD", 3 }, { "OMR", 3 }, { "PYG", 0 }, { "RWF", 0 }, { "TND", 3 }, { "UGX", 0 }, { "UYI", 0 }, { "VND", 0 }, { "VUV", 0 }, { "XAF", 0 }, { "XOF", 0 }, { "XPF", 0 } }; auto* currencyMinorUnit = tryBinarySearch>(currencyMinorUnits, WTF_ARRAY_LENGTH(currencyMinorUnits), computeCurrencySortKey(currency), extractCurrencySortKey); if (currencyMinorUnit) return currencyMinorUnit->second; return 2; } // Create MeasureUnit like ICU4J. struct MeasureUnit { ASCIILiteral type; ASCIILiteral subType; }; static Optional sanctionedSimpleUnitIdentifier(StringView unitIdentifier) { static constexpr MeasureUnit simpleUnits[] = { { "area"_s, "acre"_s }, { "digital"_s, "bit"_s }, { "digital"_s, "byte"_s }, { "temperature"_s, "celsius"_s }, { "length"_s, "centimeter"_s }, { "duration"_s, "day"_s }, { "angle"_s, "degree"_s }, { "temperature"_s, "fahrenheit"_s }, { "volume"_s, "fluid-ounce"_s }, { "length"_s, "foot"_s }, { "volume"_s, "gallon"_s }, { "digital"_s, "gigabit"_s }, { "digital"_s, "gigabyte"_s }, { "mass"_s, "gram"_s }, { "area"_s, "hectare"_s }, { "duration"_s, "hour"_s }, { "length"_s, "inch"_s }, { "digital"_s, "kilobit"_s }, { "digital"_s, "kilobyte"_s }, { "mass"_s, "kilogram"_s }, { "length"_s, "kilometer"_s }, { "volume"_s, "liter"_s }, { "digital"_s, "megabit"_s }, { "digital"_s, "megabyte"_s }, { "length"_s, "meter"_s }, { "length"_s, "mile"_s }, { "length"_s, "mile-scandinavian"_s }, { "volume"_s, "milliliter"_s }, { "length"_s, "millimeter"_s }, { "duration"_s, "millisecond"_s }, { "duration"_s, "minute"_s }, { "duration"_s, "month"_s }, { "mass"_s, "ounce"_s }, { "concentr"_s, "percent"_s }, { "digital"_s, "petabyte"_s }, { "mass"_s, "pound"_s }, { "duration"_s, "second"_s }, { "mass"_s, "stone"_s }, { "digital"_s, "terabit"_s }, { "digital"_s, "terabyte"_s }, { "duration"_s, "week"_s }, { "length"_s, "yard"_s }, { "duration"_s, "year"_s }, }; ASSERT( std::is_sorted(std::begin(simpleUnits), std::end(simpleUnits), [](const MeasureUnit& a, const MeasureUnit& b) { return WTF::codePointCompare(StringView(a.subType), StringView(b.subType)) < 0; })); auto iterator = std::lower_bound(std::begin(simpleUnits), std::end(simpleUnits), unitIdentifier, [](const MeasureUnit& unit, StringView unitIdentifier) { return WTF::codePointCompare(StringView(unit.subType), unitIdentifier) < 0; }); if (iterator != std::end(simpleUnits) && iterator->subType == unitIdentifier) return *iterator; return WTF::nullopt; } struct WellFormedUnit { public: explicit WellFormedUnit(MeasureUnit numerator) : numerator(numerator) { } WellFormedUnit(MeasureUnit numerator, MeasureUnit denominator) : numerator(numerator) , denominator(denominator) { } MeasureUnit numerator; Optional denominator; }; static Optional wellFormedUnitIdentifier(StringView unitIdentifier) { // https://tc39.es/ecma402/#sec-iswellformedunitidentifier if (auto unit = sanctionedSimpleUnitIdentifier(unitIdentifier)) return WellFormedUnit(unit.value()); // If the substring "-per-" does not occur exactly once in unitIdentifier, then return false. auto per = StringView("-per-"_s); auto position = unitIdentifier.find(per); if (position == WTF::notFound) return WTF::nullopt; if (unitIdentifier.find(per, position + per.length()) != WTF::notFound) return WTF::nullopt; // If the result of IsSanctionedSimpleUnitIdentifier(numerator) is false, then return false. auto numerator = unitIdentifier.substring(0, position); auto numeratorUnit = sanctionedSimpleUnitIdentifier(numerator); if (!numeratorUnit) return WTF::nullopt; // If the result of IsSanctionedSimpleUnitIdentifier(denominator) is false, then return false. auto denominator = unitIdentifier.substring(position + per.length()); auto denominatorUnit = sanctionedSimpleUnitIdentifier(denominator); if (!denominatorUnit) return WTF::nullopt; return WellFormedUnit(numeratorUnit.value(), denominatorUnit.value()); } // https://tc39.github.io/ecma402/#sec-initializenumberformat void IntlNumberFormat::initializeNumberFormat(JSGlobalObject* globalObject, JSValue locales, JSValue optionsValue) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); auto requestedLocales = canonicalizeLocaleList(globalObject, locales); RETURN_IF_EXCEPTION(scope, void()); JSObject* options; if (optionsValue.isUndefined()) options = constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); else { options = optionsValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, void()); } ResolveLocaleOptions localeOptions; LocaleMatcher localeMatcher = intlOption(globalObject, options, vm.propertyNames->localeMatcher, { { "lookup"_s, LocaleMatcher::Lookup }, { "best fit"_s, LocaleMatcher::BestFit } }, "localeMatcher must be either \"lookup\" or \"best fit\""_s, LocaleMatcher::BestFit); RETURN_IF_EXCEPTION(scope, void()); String numberingSystem = intlStringOption(globalObject, options, vm.propertyNames->numberingSystem, { }, nullptr, nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!numberingSystem.isNull()) { if (!isUnicodeLocaleIdentifierType(numberingSystem)) { throwRangeError(globalObject, scope, "numberingSystem is not a well-formed numbering system value"_s); return; } localeOptions[static_cast(RelevantExtensionKey::Nu)] = numberingSystem; } auto& availableLocales = intlNumberFormatAvailableLocales(); auto resolved = resolveLocale(globalObject, availableLocales, requestedLocales, localeMatcher, localeOptions, { RelevantExtensionKey::Nu }, localeData); m_locale = resolved.locale; if (m_locale.isEmpty()) { throwTypeError(globalObject, scope, "failed to initialize NumberFormat due to invalid locale"_s); return; } m_numberingSystem = resolved.extensions[static_cast(RelevantExtensionKey::Nu)]; m_style = intlOption