/* * Copyright (C) 2015 Andy VanWagoner (andy@vanwagoner.family) * Copyright (C) 2016 Sukolsak Sakshuwong (sukolsak@gmail.com) * Copyright (C) 2016-2023 Apple Inc. All rights reserved. * Copyright (C) 2026 Igalia S.L. * 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 "AOTRemovableFeature.h" #include "Error.h" #include "IntlNumberFormatInlines.h" #include "IntlObjectInlines.h" #include "IntlPartObject.h" #include "JSBoundFunction.h" #include "JSCInlines.h" #include "ObjectConstructor.h" #include "ParseInt.h" #include #include #include #ifdef U_HIDE_DRAFT_API #undef U_HIDE_DRAFT_API #endif #include #include #define U_HIDE_DRAFT_API 1 WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN namespace JSC { const ClassInfo IntlNumberFormat::s_info = { "Object"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(IntlNumberFormat) }; NEVER_INLINE void IntlNumberFormat::destroy(JSCell* cell) { JSC_REMOVABLE_DEFINITION(IntlNumberFormat, &IntlNumberFormat::destroy); static_cast(cell)->IntlNumberFormat::~IntlNumberFormat(); } namespace IntlNumberFormatInternal { static constexpr bool verbose = false; } void UNumberFormatterDeleter::operator()(UNumberFormatter* formatter) { if (formatter) unumf_close(formatter); } void UNumberRangeFormatterDeleter::operator()(UNumberRangeFormatter* formatter) { if (formatter) unumrf_close(formatter); } IntlNumberFormat* IntlNumberFormat::create(VM& vm, Structure* structure) { IntlNumberFormat* format = new (NotNull, allocateCell(vm)) 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) { } template void IntlNumberFormat::visitChildrenImpl(JSCell* cell, Visitor& visitor) { IntlNumberFormat* thisObject = uncheckedDowncast(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); Base::visitChildren(thisObject, visitor); visitor.append(thisObject->m_boundFormat); if (thisObject->m_numberFormatter) visitor.reportExtraMemoryVisited(estimatedUNumberFormatterSize); if (thisObject->m_numberRangeFormatter) visitor.reportExtraMemoryVisited(estimatedUNumberRangeFormatterSize); } DEFINE_VISIT_CHILDREN(IntlNumberFormat); 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 LEGACY_NODELETE computeCurrencySortKey(const String& currency) { ASSERT(currency.length() == 3); ASSERT(currency.containsOnly()); return (currency[0] << 16) + (currency[1] << 8) + currency[2]; } static inline unsigned LEGACY_NODELETE computeCurrencySortKey(const std::array& currency) { ASSERT(containsOnly(std::span { currency })); return (currency[0] << 16) + (currency[1] << 8) + currency[2]; } static unsigned LEGACY_NODELETE extractCurrencySortKey(std::pair, unsigned>* 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, unsigned> currencyMinorUnits[] = { { { 'B', 'H', 'D' }, 3 }, { { 'B', 'I', 'F' }, 0 }, { { 'B', 'Y', 'R' }, 0 }, { { 'C', 'L', 'F' }, 4 }, { { 'C', 'L', 'P' }, 0 }, { { 'D', 'J', 'F' }, 0 }, { { 'G', 'N', 'F' }, 0 }, { { 'I', 'Q', 'D' }, 3 }, { { 'I', 'S', 'K' }, 0 }, { { 'J', 'O', 'D' }, 3 }, { { 'J', 'P', 'Y' }, 0 }, { { 'K', 'M', 'F' }, 0 }, { { 'K', 'R', 'W' }, 0 }, { { 'K', 'W', 'D' }, 3 }, { { 'L', 'Y', 'D' }, 3 }, { { 'O', 'M', 'R' }, 3 }, { { 'P', 'Y', 'G' }, 0 }, { { 'R', 'W', 'F' }, 0 }, { { 'T', 'N', 'D' }, 3 }, { { 'U', 'G', 'X' }, 0 }, { { 'U', 'Y', 'I' }, 0 }, { { 'V', 'N', 'D' }, 0 }, { { 'V', 'U', 'V' }, 0 }, { { 'X', 'A', 'F' }, 0 }, { { 'X', 'O', 'F' }, 0 }, { { 'X', 'P', 'F' }, 0 } }; auto* currencyMinorUnit = tryBinarySearch, unsigned>>(currencyMinorUnits, std::size(currencyMinorUnits), computeCurrencySortKey(currency), extractCurrencySortKey); if (currencyMinorUnit) return currencyMinorUnit->second; return 2; } static std::optional sanctionedSimpleUnitIdentifier(StringView unitIdentifier) { 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 std::nullopt; } struct WellFormedUnit { public: explicit WellFormedUnit(MeasureUnit numerator) : numerator(numerator) { } WellFormedUnit(MeasureUnit numerator, MeasureUnit denominator) : numerator(numerator) , denominator(denominator) { } MeasureUnit numerator; std::optional denominator; }; static std::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 std::nullopt; if (unitIdentifier.find(per, position + per.length()) != WTF::notFound) return std::nullopt; // If the result of IsSanctionedSimpleUnitIdentifier(numerator) is false, then return false. auto numerator = unitIdentifier.left(position); auto numeratorUnit = sanctionedSimpleUnitIdentifier(numerator); if (!numeratorUnit) return std::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 std::nullopt; return WellFormedUnit(numeratorUnit.value(), denominatorUnit.value()); } // We intentionally avoid using ICU's UNUM_APPROXIMATELY_SIGN_FIELD and define the same value here. // UNUM_APPROXIMATELY_SIGN_FIELD can be defined in the header after ICU 71. But dylib ICU can be newer while ICU header version is old. // We can define UNUM_APPROXIMATELY_SIGN_FIELD here so that we can support old ICU header + newer ICU library combination. static constexpr UNumberFormatFields UNUM_APPROXIMATELY_SIGN_FIELD = static_cast(UNUM_COMPACT_FIELD + 1); static ASCIILiteral partTypeString(UNumberFormatFields field, IntlNumberFormat::Style style, bool sign, IntlMathematicalValue::NumberType type) { switch (field) { case UNUM_INTEGER_FIELD: switch (type) { case IntlMathematicalValue::NumberType::NaN: return "nan"_s; case IntlMathematicalValue::NumberType::Infinity: return "infinity"_s; case IntlMathematicalValue::NumberType::Integer: return "integer"_s; } ASSERT_NOT_REACHED(); return "unknown"_s; case UNUM_FRACTION_FIELD: return "fraction"_s; case UNUM_DECIMAL_SEPARATOR_FIELD: return "decimal"_s; case UNUM_EXPONENT_SYMBOL_FIELD: return "exponentSeparator"_s; case UNUM_EXPONENT_SIGN_FIELD: return "exponentMinusSign"_s; case UNUM_EXPONENT_FIELD: return "exponentInteger"_s; case UNUM_GROUPING_SEPARATOR_FIELD: return "group"_s; case UNUM_CURRENCY_FIELD: return "currency"_s; case UNUM_PERCENT_FIELD: // If the style is "unit", we should report as unit. // JSTests/test262/test/intl402/NumberFormat/prototype/formatToParts/percent-en-US.js return (style == IntlNumberFormat::Style::Unit) ? "unit"_s : "percentSign"_s; case UNUM_SIGN_FIELD: return sign ? "minusSign"_s : "plusSign"_s; case UNUM_MEASURE_UNIT_FIELD: return "unit"_s; case UNUM_COMPACT_FIELD: return "compact"_s; IGNORE_GCC_WARNINGS_BEGIN("switch") case UNUM_APPROXIMATELY_SIGN_FIELD: return "approximatelySign"_s; IGNORE_GCC_WARNINGS_END // These should not show up because there is no way to specify them in NumberFormat options. // If they do, they don't fit well into any of known part types, so consider it an "unknown". case UNUM_PERMILL_FIELD: // Any newer additions to the UNumberFormatFields enum should just be considered an "unknown" part. default: return "unknown"_s; } return "unknown"_s; } // https://tc39.es/ecma402/#sec-intl.numberformat 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 = intlCoerceOptionsToObject(globalObject, optionsValue); 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, { }, { }, { }); 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; } const 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_dataLocale = resolved.dataLocale; m_style = intlOption