LibJS: Implement the Intl.NumberFormat constructor

This commit is contained in:
Timothy Flynn 2021-09-10 11:04:54 -04:00 committed by Linus Groh
parent cf1923edeb
commit e42ba7f748
Notes: sideshowbarker 2024-07-18 04:46:35 +09:00
6 changed files with 840 additions and 1 deletions

View File

@ -96,6 +96,7 @@ namespace JS {
P(clz32) \
P(codePointAt) \
P(collation) \
P(compactDisplay) \
P(compareExchange) \
P(compile) \
P(concat) \
@ -110,6 +111,9 @@ namespace JS {
P(count) \
P(countReset) \
P(create) \
P(currency) \
P(currencyDisplay) \
P(currencySign) \
P(dateAdd) \
P(dateFromFields) \
P(day) \
@ -293,6 +297,11 @@ namespace JS {
P(milliseconds) \
P(min) \
P(minimize) \
P(maximumFractionDigits) \
P(maximumSignificantDigits) \
P(minimumFractionDigits) \
P(minimumIntegerDigits) \
P(minimumSignificantDigits) \
P(minute) \
P(minutes) \
P(month) \
@ -306,6 +315,7 @@ namespace JS {
P(nanoseconds) \
P(negated) \
P(next) \
P(notation) \
P(now) \
P(numberingSystem) \
P(numeric) \
@ -382,6 +392,7 @@ namespace JS {
P(setYear) \
P(shift) \
P(sign) \
P(signDisplay) \
P(sin) \
P(since) \
P(sinh) \
@ -448,9 +459,12 @@ namespace JS {
P(undefined) \
P(unescape) \
P(unicode) \
P(unit) \
P(unitDisplay) \
P(until) \
P(unregister) \
P(unshift) \
P(useGrouping) \
P(value) \
P(valueOf) \
P(values) \

View File

@ -32,6 +32,9 @@
M(InOperatorWithObject, "'in' operator must be used on an object") \
M(InstanceOfOperatorBadPrototype, "'prototype' property of {} is not an object") \
M(IntlInvalidLanguageTag, "{} is not a structurally valid language tag") \
M(IntlMinimumExceedsMaximum, "Minimum value {} is larger than maximum value {}") \
M(IntlNumberIsNaNOrOutOfRange, "Value {} is NaN or is not between {} and {}") \
M(IntlOptionUndefined, "Option {} must be defined when option {} is {}") \
M(InvalidAssignToConst, "Invalid assignment to const variable") \
M(InvalidCodePoint, "Invalid code point {}, must be an integer no less than 0 and no greater than 0x10FFFF") \
M(InvalidFormat, "Invalid {} format") \

View File

@ -6,7 +6,9 @@
#include <AK/AllOf.h>
#include <AK/AnyOf.h>
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/Find.h>
#include <AK/Function.h>
#include <AK/QuickSort.h>
#include <AK/TypeCasts.h>
@ -121,7 +123,7 @@ String canonicalize_unicode_locale_id(Unicode::LocaleID& locale)
}
// 6.3.1 IsWellFormedCurrencyCode ( currency ), https://tc39.es/ecma402/#sec-canonicalcodefordisplaynames
static bool is_well_formed_currency_code(StringView currency)
bool is_well_formed_currency_code(StringView currency)
{
// 1. Let normalized be the result of mapping currency to upper case as described in 6.1.
// 2. If the number of elements in normalized is not 3, return false.
@ -136,6 +138,53 @@ static bool is_well_formed_currency_code(StringView currency)
return true;
}
// 6.5.1 IsWellFormedUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-iswellformedunitidentifier
bool is_well_formed_unit_identifier(StringView unit_identifier)
{
// 6.5.2 IsSanctionedSimpleUnitIdentifier ( unitIdentifier ), https://tc39.es/ecma402/#sec-iswellformedunitidentifier
constexpr auto is_sanctioned_simple_unit_identifier = [](StringView unit_identifier) {
// 1. If unitIdentifier is listed in Table 2 below, return true.
// 2. Else, return false.
static constexpr auto sanctioned_units = AK::Array { "acre"sv, "bit"sv, "byte"sv, "celsius"sv, "centimeter"sv, "day"sv, "degree"sv, "fahrenheit"sv, "fluid-ounce"sv, "foot"sv, "gallon"sv, "gigabit"sv, "gigabyte"sv, "gram"sv, "hectare"sv, "hour"sv, "inch"sv, "kilobit"sv, "kilobyte"sv, "kilogram"sv, "kilometer"sv, "liter"sv, "megabit"sv, "megabyte"sv, "meter"sv, "mile"sv, "mile-scandinavian"sv, "milliliter"sv, "millimeter"sv, "millisecond"sv, "minute"sv, "month"sv, "ounce"sv, "percent"sv, "petabyte"sv, "pound"sv, "second"sv, "stone"sv, "terabit"sv, "terabyte"sv, "week"sv, "yard"sv, "year"sv };
return find(sanctioned_units.begin(), sanctioned_units.end(), unit_identifier) != sanctioned_units.end();
};
// 1. If the result of IsSanctionedSimpleUnitIdentifier(unitIdentifier) is true, then
if (is_sanctioned_simple_unit_identifier(unit_identifier)) {
// a. Return true.
return true;
}
auto indices = unit_identifier.find_all("-per-"sv);
// 2. If the substring "-per-" does not occur exactly once in unitIdentifier, then
if (indices.size() != 1) {
// a. Return false.
return false;
}
// 3. Let numerator be the substring of unitIdentifier from the beginning to just before "-per-".
auto numerator = unit_identifier.substring_view(0, indices[0]);
// 4. If the result of IsSanctionedSimpleUnitIdentifier(numerator) is false, then
if (!is_sanctioned_simple_unit_identifier(numerator)) {
// a. Return false.
return false;
}
// 5. Let denominator be the substring of unitIdentifier from just after "-per-" to the end.
auto denominator = unit_identifier.substring_view(indices[0] + 5);
// 6. If the result of IsSanctionedSimpleUnitIdentifier(denominator) is false, then
if (!is_sanctioned_simple_unit_identifier(denominator)) {
// a. Return false.
return false;
}
// 7. Return true.
return true;
}
// 9.2.1 CanonicalizeLocaleList ( locales ), https://tc39.es/ecma402/#sec-canonicalizelocalelist
Vector<String> canonicalize_locale_list(GlobalObject& global_object, Value locales)
{
@ -328,6 +377,9 @@ String insert_unicode_extension_and_canonicalize(Unicode::LocaleID locale, Unico
template<typename T>
static auto& find_key_in_value(T& value, StringView key)
{
if (key == "nu"sv)
return value.nu;
// If you hit this point, you must add any missing keys from [[RelevantExtensionKeys]] to LocaleOptions and LocaleResult.
VERIFY_NOT_REACHED();
}
@ -615,6 +667,45 @@ Value get_option(GlobalObject& global_object, Value options, PropertyName const&
return value;
}
// 9.2.14 DefaultNumberOption ( value, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-defaultnumberoption
Optional<int> default_number_option(GlobalObject& global_object, Value value, int minimum, int maximum, Optional<int> fallback)
{
auto& vm = global_object.vm();
// 1. If value is undefined, return fallback.
if (value.is_undefined())
return fallback;
// 2. Let value be ? ToNumber(value).
value = value.to_number(global_object);
if (vm.exception())
return {};
// 3. If value is NaN or less than minimum or greater than maximum, throw a RangeError exception.
if (value.is_nan() || (value.as_double() < minimum) || (value.as_double() > maximum)) {
vm.throw_exception<RangeError>(global_object, ErrorType::IntlNumberIsNaNOrOutOfRange, value, minimum, maximum);
return {};
}
// 4. Return floor(value).
return floor(value.as_double());
}
// 9.2.15 GetNumberOption ( options, property, minimum, maximum, fallback ), https://tc39.es/ecma402/#sec-getnumberoption
Optional<int> get_number_option(GlobalObject& global_object, Object& options, PropertyName const& property, int minimum, int maximum, Optional<int> fallback)
{
auto& vm = global_object.vm();
// 1. Assert: Type(options) is Object.
// 2. Let value be ? Get(options, property).
auto value = options.get(property);
if (vm.exception())
return {};
// 3. Return ? DefaultNumberOption(value, minimum, maximum, fallback).
return default_number_option(global_object, value, minimum, maximum, fallback);
}
// 9.2.16 PartitionPattern ( pattern ), https://tc39.es/ecma402/#sec-partitionpattern
Vector<PatternPartition> partition_pattern(StringView pattern)
{

View File

@ -20,11 +20,13 @@ using Fallback = Variant<Empty, bool, StringView>;
struct LocaleOptions {
Value locale_matcher;
Optional<String> nu;
};
struct LocaleResult {
String locale;
String data_locale;
Optional<String> nu;
};
struct PatternPartition {
@ -33,6 +35,8 @@ struct PatternPartition {
};
Optional<Unicode::LocaleID> is_structurally_valid_language_tag(StringView locale);
bool is_well_formed_currency_code(StringView currency);
bool is_well_formed_unit_identifier(StringView unit_identifier);
String canonicalize_unicode_locale_id(Unicode::LocaleID& locale);
Vector<String> canonicalize_locale_list(GlobalObject&, Value locales);
Optional<String> best_available_locale(StringView const& locale);
@ -41,6 +45,8 @@ Vector<String> lookup_supported_locales(Vector<String> const& requested_locales)
Array* supported_locales(GlobalObject&, Vector<String> const& requested_locales, Value options);
Object* coerce_options_to_object(GlobalObject& global_object, Value options);
Value get_option(GlobalObject& global_object, Value options, PropertyName const& property, Value::Type type, Vector<StringView> const& values, Fallback fallback);
Optional<int> default_number_option(GlobalObject& global_object, Value value, int minimum, int maximum, Optional<int> fallback);
Optional<int> get_number_option(GlobalObject& global_object, Object& options, PropertyName const& property, int minimum, int maximum, Optional<int> fallback);
Vector<PatternPartition> partition_pattern(StringView pattern);
String insert_unicode_extension_and_canonicalize(Unicode::LocaleID locale_id, Unicode::LocaleExtension extension);
LocaleResult resolve_locale(Vector<String> const& requested_locales, LocaleOptions const& options, Vector<StringView> const& relevant_extension_keys);

View File

@ -6,11 +6,376 @@
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/Intl/AbstractOperations.h>
#include <LibJS/Runtime/Intl/NumberFormat.h>
#include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
#include <LibUnicode/CurrencyCode.h>
#include <LibUnicode/Locale.h>
namespace JS::Intl {
static Vector<StringView> const& number_format_relevant_extension_keys()
{
// 15.3.3 Internal slots, https://tc39.es/ecma402/#sec-intl.numberformat-internal-slots
// The value of the [[RelevantExtensionKeys]] internal slot is « "nu" ».
static Vector<StringView> relevant_extension_keys { "nu"sv };
return relevant_extension_keys;
}
// 15.1.1 SetNumberFormatDigitOptions ( intlObj, options, mnfdDefault, mxfdDefault, notation ), https://tc39.es/ecma402/#sec-setnfdigitoptions
static void set_number_format_digit_options(GlobalObject& global_object, NumberFormat& intl_object, Object& options, int default_min_fraction_digits, int default_max_fraction_digits, NumberFormat::Notation notation)
{
auto& vm = global_object.vm();
// 1. Assert: Type(intlObj) is Object.
// 2. Assert: Type(options) is Object.
// 3. Assert: Type(mnfdDefault) is Number.
// 4. Assert: Type(mxfdDefault) is Number.
// 5. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1).
auto min_integer_digits = get_number_option(global_object, options, vm.names.minimumIntegerDigits, 1, 21, 1);
if (vm.exception())
return;
// 6. Let mnfd be ? Get(options, "minimumFractionDigits").
auto min_fraction_digits = options.get(vm.names.minimumFractionDigits);
if (vm.exception())
return;
// 7. Let mxfd be ? Get(options, "maximumFractionDigits").
auto max_fraction_digits = options.get(vm.names.maximumFractionDigits);
if (vm.exception())
return;
// 8. Let mnsd be ? Get(options, "minimumSignificantDigits").
auto min_significant_digits = options.get(vm.names.minimumSignificantDigits);
if (vm.exception())
return;
// 9. Let mxsd be ? Get(options, "maximumSignificantDigits").
auto max_significant_digits = options.get(vm.names.maximumSignificantDigits);
if (vm.exception())
return;
// 10. Set intlObj.[[MinimumIntegerDigits]] to mnid.
intl_object.set_min_integer_digits(*min_integer_digits);
// 11. If mnsd is not undefined or mxsd is not undefined, then
if (!min_significant_digits.is_undefined() || !max_significant_digits.is_undefined()) {
// a. Set intlObj.[[RoundingType]] to significantDigits.
intl_object.set_rounding_type(NumberFormat::RoundingType::SignificantDigits);
// b. Let mnsd be ? DefaultNumberOption(mnsd, 1, 21, 1).
auto min_digits = default_number_option(global_object, min_significant_digits, 1, 21, 1);
if (vm.exception())
return;
// c. Let mxsd be ? DefaultNumberOption(mxsd, mnsd, 21, 21).
auto max_digits = default_number_option(global_object, max_significant_digits, *min_digits, 21, 21);
if (vm.exception())
return;
// d. Set intlObj.[[MinimumSignificantDigits]] to mnsd.
intl_object.set_min_significant_digits(*min_digits);
// e. Set intlObj.[[MaximumSignificantDigits]] to mxsd.
intl_object.set_max_significant_digits(*max_digits);
}
// 12. Else if mnfd is not undefined or mxfd is not undefined, then
else if (!min_fraction_digits.is_undefined() || !max_fraction_digits.is_undefined()) {
// a. Set intlObj.[[RoundingType]] to fractionDigits.
intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
// b. Let mnfd be ? DefaultNumberOption(mnfd, 0, 20, undefined).
auto min_digits = default_number_option(global_object, min_fraction_digits, 0, 20, {});
if (vm.exception())
return;
// c. Let mxfd be ? DefaultNumberOption(mxfd, 0, 20, undefined).
auto max_digits = default_number_option(global_object, max_fraction_digits, 0, 20, {});
if (vm.exception())
return;
// d. If mnfd is undefined, set mnfd to min(mnfdDefault, mxfd).
if (!min_digits.has_value()) {
min_digits = min(default_min_fraction_digits, *max_digits);
}
// e. Else if mxfd is undefined, set mxfd to max(mxfdDefault, mnfd).
else if (!max_digits.has_value()) {
max_digits = max(default_max_fraction_digits, *min_digits);
}
// f. Else if mnfd is greater than mxfd, throw a RangeError exception.
else if (*min_digits > *max_digits) {
vm.throw_exception<RangeError>(global_object, ErrorType::IntlMinimumExceedsMaximum, *min_digits, *max_digits);
return;
}
// g. Set intlObj.[[MinimumFractionDigits]] to mnfd.
intl_object.set_min_fraction_digits(*min_digits);
// h. Set intlObj.[[MaximumFractionDigits]] to mxfd.
intl_object.set_max_fraction_digits(*max_digits);
}
// 13. Else if notation is "compact", then
else if (notation == NumberFormat::Notation::Compact) {
// a. Set intlObj.[[RoundingType]] to compactRounding.
intl_object.set_rounding_type(NumberFormat::RoundingType::CompactRounding);
}
// 14. Else,
else {
// a. Set intlObj.[[RoundingType]] to fractionDigits.
intl_object.set_rounding_type(NumberFormat::RoundingType::FractionDigits);
// b. Set intlObj.[[MinimumFractionDigits]] to mnfdDefault.
intl_object.set_min_fraction_digits(default_min_fraction_digits);
// c. Set intlObj.[[MaximumFractionDigits]] to mxfdDefault.
intl_object.set_max_fraction_digits(default_max_fraction_digits);
}
}
// 15.1.3 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
static int currency_digits(StringView currency)
{
// 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
// unit value corresponding to the currency from the list; otherwise, return 2.
if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
return currency_code->minor_unit.value_or(2);
return 2;
}
// 15.1.13 SetNumberFormatUnitOptions ( intlObj, options ), https://tc39.es/ecma402/#sec-setnumberformatunitoptions
static void set_number_format_unit_options(GlobalObject& global_object, NumberFormat& intl_object, Object& options)
{
auto& vm = global_object.vm();
// 1. Assert: Type(intlObj) is Object.
// 2. Assert: Type(options) is Object.
// 3. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
auto style = get_option(global_object, &options, vm.names.style, Value::Type::String, { "decimal"sv, "percent"sv, "currency"sv, "unit"sv }, "decimal"sv);
if (vm.exception())
return;
// 4. Set intlObj.[[Style]] to style.
intl_object.set_style(style.as_string().string());
// 5. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
auto currency = get_option(global_object, &options, vm.names.currency, Value::Type::String, {}, Empty {});
if (vm.exception())
return;
// 6. If currency is undefined, then
if (currency.is_undefined()) {
// a. If style is "currency", throw a TypeError exception.
if (intl_object.style() == NumberFormat::Style::Currency) {
vm.throw_exception<TypeError>(global_object, ErrorType::IntlOptionUndefined, "currency"sv, "style"sv, style);
return;
}
}
// 7. Else,
// a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
else if (!is_well_formed_currency_code(currency.as_string().string())) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, currency, "currency"sv);
return;
}
// 8. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
auto currency_display = get_option(global_object, &options, vm.names.currencyDisplay, Value::Type::String, { "code"sv, "symbol"sv, "narrowSymbol"sv, "name"sv }, "symbol"sv);
if (vm.exception())
return;
// 9. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
auto currency_sign = get_option(global_object, &options, vm.names.currencySign, Value::Type::String, { "standard"sv, "accounting"sv }, "standard"sv);
if (vm.exception())
return;
// 10. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
auto unit = get_option(global_object, &options, vm.names.unit, Value::Type::String, {}, Empty {});
if (vm.exception())
return;
// 11. If unit is undefined, then
if (unit.is_undefined()) {
// a. If style is "unit", throw a TypeError exception.
if (intl_object.style() == NumberFormat::Style::Unit) {
vm.throw_exception<TypeError>(global_object, ErrorType::IntlOptionUndefined, "unit"sv, "style"sv, style);
return;
}
}
// 12. Else,
// a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
else if (!is_well_formed_unit_identifier(unit.as_string().string())) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "unit"sv);
return;
}
// 13. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
auto unit_display = get_option(global_object, &options, vm.names.unitDisplay, Value::Type::String, { "short"sv, "narrow"sv, "long"sv }, "short"sv);
if (vm.exception())
return;
// 14. If style is "currency", then
if (intl_object.style() == NumberFormat::Style::Currency) {
// a. Let currency be the result of converting currency to upper case as specified in 6.1.
// b. Set intlObj.[[Currency]] to currency.
intl_object.set_currency(currency.as_string().string().to_uppercase());
// c. Set intlObj.[[CurrencyDisplay]] to currencyDisplay.
intl_object.set_currency_display(currency_display.as_string().string());
// d. Set intlObj.[[CurrencySign]] to currencySign.
intl_object.set_currency_sign(currency_sign.as_string().string());
}
// 15. If style is "unit", then
if (intl_object.style() == NumberFormat::Style::Unit) {
// a. Set intlObj.[[Unit]] to unit.
intl_object.set_unit(unit.as_string().string());
// b. Set intlObj.[[UnitDisplay]] to unitDisplay.
intl_object.set_unit_display(unit_display.as_string().string());
}
}
// 15.1.2 InitializeNumberFormat ( numberFormat, locales, options ), https://tc39.es/ecma402/#sec-initializenumberformat
static NumberFormat* initialize_number_format(GlobalObject& global_object, NumberFormat& number_format, Value locales, Value options)
{
auto& vm = global_object.vm();
// 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
auto requested_locales = canonicalize_locale_list(global_object, locales);
if (vm.exception())
return {};
// 2. Set options to ? CoerceOptionsToObject(options).
options = coerce_options_to_object(global_object, options);
if (vm.exception())
return {};
// 3. Let opt be a new Record.
LocaleOptions opt {};
// 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
auto matcher = get_option(global_object, options, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv);
if (vm.exception())
return {};
// 5. Set opt.[[localeMatcher]] to matcher.
opt.locale_matcher = matcher;
// 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
auto numbering_system = get_option(global_object, options, vm.names.numberingSystem, Value::Type::String, {}, Empty {});
if (vm.exception())
return {};
// 7. If numberingSystem is not undefined, then
if (!numbering_system.is_undefined()) {
// a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
if (!Unicode::is_type_identifier(numbering_system.as_string().string())) {
vm.throw_exception<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
return {};
}
// 8. Set opt.[[nu]] to numberingSystem.
opt.nu = numbering_system.as_string().string();
}
// 9. Let localeData be %NumberFormat%.[[LocaleData]].
// 10. Let r be ResolveLocale(%NumberFormat%.[[AvailableLocales]], requestedLocales, opt, %NumberFormat%.[[RelevantExtensionKeys]], localeData).
auto result = resolve_locale(requested_locales, opt, number_format_relevant_extension_keys());
// 11. Set numberFormat.[[Locale]] to r.[[locale]].
number_format.set_locale(move(result.locale));
// 12. Set numberFormat.[[DataLocale]] to r.[[dataLocale]].
number_format.set_data_locale(move(result.data_locale));
// 13. Set numberFormat.[[NumberingSystem]] to r.[[nu]].
number_format.set_numbering_system(result.nu.release_value());
// 14. Perform ? SetNumberFormatUnitOptions(numberFormat, options).
set_number_format_unit_options(global_object, number_format, options.as_object());
if (vm.exception())
return {};
// 15. Let style be numberFormat.[[Style]].
auto style = number_format.style();
int default_min_fraction_digits = 0;
int default_max_fraction_digits = 0;
// 16. If style is "currency", then
if (style == NumberFormat::Style::Currency) {
// a. Let currency be numberFormat.[[Currency]].
auto const& currency = number_format.currency();
// b. Let cDigits be CurrencyDigits(currency).
int digits = currency_digits(currency);
// c. Let mnfdDefault be cDigits.
default_min_fraction_digits = digits;
// d. Let mxfdDefault be cDigits.
default_max_fraction_digits = digits;
}
// 17. Else,
else {
// a. Let mnfdDefault be 0.
default_min_fraction_digits = 0;
// b. If style is "percent", then
// i. Let mxfdDefault be 0.
// c. Else,
// i. Let mxfdDefault be 3.
default_max_fraction_digits = style == NumberFormat::Style::Percent ? 0 : 3;
}
// 18. Let notation be ? GetOption(options, "notation", "string", « "standard", "scientific", "engineering", "compact" », "standard").
auto notation = get_option(global_object, options, vm.names.notation, Value::Type::String, { "standard"sv, "scientific"sv, "engineering"sv, "compact"sv }, "standard"sv);
if (vm.exception())
return {};
// 19. Set numberFormat.[[Notation]] to notation.
number_format.set_notation(notation.as_string().string());
// 20. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation).
set_number_format_digit_options(global_object, number_format, options.as_object(), default_min_fraction_digits, default_max_fraction_digits, number_format.notation());
if (vm.exception())
return {};
// 21. Let compactDisplay be ? GetOption(options, "compactDisplay", "string", « "short", "long" », "short").
auto compact_display = get_option(global_object, options, vm.names.compactDisplay, Value::Type::String, { "short"sv, "long"sv }, "short"sv);
if (vm.exception())
return {};
// 22. If notation is "compact", then
if (number_format.notation() == NumberFormat::Notation::Compact) {
// a. Set numberFormat.[[CompactDisplay]] to compactDisplay.
number_format.set_compact_display(compact_display.as_string().string());
}
// 23. Let useGrouping be ? GetOption(options, "useGrouping", "boolean", undefined, true).
auto use_grouping = get_option(global_object, options, vm.names.useGrouping, Value::Type::Boolean, {}, true);
if (vm.exception())
return {};
// 24. Set numberFormat.[[UseGrouping]] to useGrouping.
number_format.set_use_grouping(use_grouping.as_bool());
// 25. Let signDisplay be ? GetOption(options, "signDisplay", "string", « "auto", "never", "always", "exceptZero" », "auto").
auto sign_display = get_option(global_object, options, vm.names.signDisplay, Value::Type::String, { "auto"sv, "never"sv, "always"sv, "exceptZero"sv }, "auto"sv);
if (vm.exception())
return {};
// 26. Set numberFormat.[[SignDisplay]] to signDisplay.
number_format.set_sign_display(sign_display.as_string().string());
// 27. Return numberFormat.
return &number_format;
}
// 15.2 The Intl.NumberFormat Constructor, https://tc39.es/ecma402/#sec-intl-numberformat-constructor
NumberFormatConstructor::NumberFormatConstructor(GlobalObject& global_object)
: NativeFunction(vm().names.NumberFormat.as_string(), *global_object.function_prototype())
@ -41,11 +406,23 @@ Value NumberFormatConstructor::construct(FunctionObject& new_target)
auto& vm = this->vm();
auto& global_object = this->global_object();
auto locales = vm.argument(0);
auto options = vm.argument(1);
// 2. Let numberFormat be ? OrdinaryCreateFromConstructor(newTarget, "%NumberFormat.prototype%", « [[InitializedNumberFormat]], [[Locale]], [[DataLocale]], [[NumberingSystem]], [[Style]], [[Unit]], [[UnitDisplay]], [[Currency]], [[CurrencyDisplay]], [[CurrencySign]], [[MinimumIntegerDigits]], [[MinimumFractionDigits]], [[MaximumFractionDigits]], [[MinimumSignificantDigits]], [[MaximumSignificantDigits]], [[RoundingType]], [[Notation]], [[CompactDisplay]], [[UseGrouping]], [[SignDisplay]], [[BoundFormat]] »).
auto* number_format = ordinary_create_from_constructor<NumberFormat>(global_object, new_target, &GlobalObject::intl_number_format_prototype);
if (vm.exception())
return {};
// 3. Perform ? InitializeNumberFormat(numberFormat, locales, options).
initialize_number_format(global_object, *number_format, locales, options);
if (vm.exception())
return {};
// 4. If the implementation supports the normative optional constructor mode of 4.3 Note 1, then
// a. Let this be the this value.
// b. Return ? ChainNumberFormat(numberFormat, NewTarget, this).
// 5. Return numberFormat.
return number_format;
}

View File

@ -1,5 +1,353 @@
describe("errors", () => {
test("structurally invalid tag", () => {
expect(() => {
new Intl.NumberFormat("root");
}).toThrowWithMessage(RangeError, "root is not a structurally valid language tag");
expect(() => {
new Intl.NumberFormat("en-");
}).toThrowWithMessage(RangeError, "en- is not a structurally valid language tag");
expect(() => {
new Intl.NumberFormat("Latn");
}).toThrowWithMessage(RangeError, "Latn is not a structurally valid language tag");
expect(() => {
new Intl.NumberFormat("en-u-aa-U-aa");
}).toThrowWithMessage(RangeError, "en-u-aa-U-aa is not a structurally valid language tag");
});
test("options is an invalid type", () => {
expect(() => {
new Intl.NumberFormat("en", null);
}).toThrowWithMessage(TypeError, "ToObject on null or undefined");
});
test("localeMatcher option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { localeMatcher: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option localeMatcher");
});
test("numberingSystem option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { numberingSystem: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option numberingSystem");
});
test("style option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { style: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option style");
});
test("currency option is undefined when required ", () => {
expect(() => {
new Intl.NumberFormat("en", { style: "currency" });
}).toThrowWithMessage(
TypeError,
"Option currency must be defined when option style is currency"
);
});
test("currency option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { currency: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option currency");
});
test("currencyDisplay option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { currencyDisplay: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option currencyDisplay");
});
test("currencySign option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { currencySign: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option currencySign");
});
test("unit option is undefined when required ", () => {
expect(() => {
new Intl.NumberFormat("en", { style: "unit" });
}).toThrowWithMessage(TypeError, "Option unit must be defined when option style is unit");
});
test("unit option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { unit: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option unit");
expect(() => {
new Intl.NumberFormat("en", { unit: "acre-bit" });
}).toThrowWithMessage(RangeError, "acre-bit is not a valid value for option unit");
expect(() => {
new Intl.NumberFormat("en", { unit: "acre-per-bit-per-byte" });
}).toThrowWithMessage(
RangeError,
"acre-per-bit-per-byte is not a valid value for option unit"
);
});
test("unitDisplay option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { unitDisplay: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option unitDisplay");
});
test("notation option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { notation: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option notation");
});
test("minimumIntegerDigits option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { minimumIntegerDigits: 1n });
}).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
expect(() => {
new Intl.NumberFormat("en", { minimumIntegerDigits: "hello!" });
}).toThrowWithMessage(RangeError, "Value NaN is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { minimumIntegerDigits: 0 });
}).toThrowWithMessage(RangeError, "Value 0 is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { minimumIntegerDigits: 22 });
}).toThrowWithMessage(RangeError, "Value 22 is NaN or is not between 1 and 21");
});
test("minimumFractionDigits option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: 1n });
}).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: "hello!" });
}).toThrowWithMessage(RangeError, "Value NaN is NaN or is not between 0 and 20");
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: -1 });
}).toThrowWithMessage(RangeError, "Value -1 is NaN or is not between 0 and 20");
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: 21 });
}).toThrowWithMessage(RangeError, "Value 21 is NaN or is not between 0 and 20");
});
test("maximumFractionDigits option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { maximumFractionDigits: 1n });
}).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
expect(() => {
new Intl.NumberFormat("en", { maximumFractionDigits: "hello!" });
}).toThrowWithMessage(RangeError, "Value NaN is NaN or is not between 0 and 20");
expect(() => {
new Intl.NumberFormat("en", { maximumFractionDigits: -1 });
}).toThrowWithMessage(RangeError, "Value -1 is NaN or is not between 0 and 20");
expect(() => {
new Intl.NumberFormat("en", { maximumFractionDigits: 21 });
}).toThrowWithMessage(RangeError, "Value 21 is NaN or is not between 0 and 20");
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: 10, maximumFractionDigits: 5 });
}).toThrowWithMessage(RangeError, "Minimum value 10 is larger than maximum value 5");
});
test("minimumSignificantDigits option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { minimumSignificantDigits: 1n });
}).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
expect(() => {
new Intl.NumberFormat("en", { minimumSignificantDigits: "hello!" });
}).toThrowWithMessage(RangeError, "Value NaN is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { minimumSignificantDigits: 0 });
}).toThrowWithMessage(RangeError, "Value 0 is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { minimumSignificantDigits: 22 });
}).toThrowWithMessage(RangeError, "Value 22 is NaN or is not between 1 and 21");
});
test("maximumSignificantDigits option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { maximumSignificantDigits: 1n });
}).toThrowWithMessage(TypeError, "Cannot convert BigInt to number");
expect(() => {
new Intl.NumberFormat("en", { maximumSignificantDigits: "hello!" });
}).toThrowWithMessage(RangeError, "Value NaN is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { maximumSignificantDigits: 0 });
}).toThrowWithMessage(RangeError, "Value 0 is NaN or is not between 1 and 21");
expect(() => {
new Intl.NumberFormat("en", { maximumSignificantDigits: 22 });
}).toThrowWithMessage(RangeError, "Value 22 is NaN or is not between 1 and 21");
});
test("compactDisplay option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { compactDisplay: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option compactDisplay");
});
test("signDisplay option is invalid ", () => {
expect(() => {
new Intl.NumberFormat("en", { signDisplay: "hello!" });
}).toThrowWithMessage(RangeError, "hello! is not a valid value for option signDisplay");
});
});
describe("normal behavior", () => {
test("length is 0", () => {
expect(Intl.NumberFormat).toHaveLength(0);
});
test("all valid localeMatcher options", () => {
["lookup", "best fit"].forEach(localeMatcher => {
expect(() => {
new Intl.NumberFormat("en", { localeMatcher: localeMatcher });
}).not.toThrow();
});
});
test("valid numberingSystem options", () => {
["latn", "arab", "abc-def-ghi"].forEach(numberingSystem => {
expect(() => {
new Intl.NumberFormat("en", { numberingSystem: numberingSystem });
}).not.toThrow();
});
});
test("all valid style options", () => {
["decimal", "percent"].forEach(style => {
expect(() => {
new Intl.NumberFormat("en", { style: style });
}).not.toThrow();
});
expect(() => {
new Intl.NumberFormat("en", { style: "currency", currency: "USD" });
}).not.toThrow();
expect(() => {
new Intl.NumberFormat("en", { style: "unit", unit: "degree" });
}).not.toThrow();
});
test("valid currency options", () => {
["USD", "EUR", "XAG"].forEach(currency => {
expect(() => {
new Intl.NumberFormat("en", { currency: currency });
}).not.toThrow();
});
});
test("all valid currencyDisplay options", () => {
["code", "symbol", "narrowSymbol", "name"].forEach(currencyDisplay => {
expect(() => {
new Intl.NumberFormat("en", { currencyDisplay: currencyDisplay });
}).not.toThrow();
});
});
test("all valid currencySign options", () => {
["standard", "accounting"].forEach(currencySign => {
expect(() => {
new Intl.NumberFormat("en", { currencySign: currencySign });
}).not.toThrow();
});
});
test("valid unit options", () => {
["acre", "acre-per-bit"].forEach(unit => {
expect(() => {
new Intl.NumberFormat("en", { unit: unit });
}).not.toThrow();
});
});
test("all valid unitDisplay options", () => {
["short", "narrow", "long"].forEach(unitDisplay => {
expect(() => {
new Intl.NumberFormat("en", { unitDisplay: unitDisplay });
}).not.toThrow();
});
});
test("all valid notation options", () => {
["standard", "scientific", "engineering", "compact"].forEach(notation => {
expect(() => {
new Intl.NumberFormat("en", { notation: notation });
}).not.toThrow();
});
});
test("all valid minimumIntegerDigits options", () => {
for (let i = 1; i <= 21; ++i) {
expect(() => {
new Intl.NumberFormat("en", { minimumIntegerDigits: i });
}).not.toThrow();
}
});
test("all valid minimumFractionDigits options", () => {
for (let i = 0; i <= 20; ++i) {
expect(() => {
new Intl.NumberFormat("en", { minimumFractionDigits: i });
}).not.toThrow();
}
});
test("all valid maximumFractionDigits options", () => {
for (let i = 0; i <= 20; ++i) {
expect(() => {
new Intl.NumberFormat("en", { maximumFractionDigits: i });
}).not.toThrow();
}
});
test("all valid minimumSignificantDigits options", () => {
for (let i = 1; i <= 21; ++i) {
expect(() => {
new Intl.NumberFormat("en", { minimumSignificantDigits: i });
}).not.toThrow();
}
});
test("all valid maximumSignificantDigits options", () => {
for (let i = 1; i <= 21; ++i) {
expect(() => {
new Intl.NumberFormat("en", { maximumSignificantDigits: i });
}).not.toThrow();
}
});
test("all valid compactDisplay options", () => {
["short", "long"].forEach(compactDisplay => {
expect(() => {
new Intl.NumberFormat("en", { compactDisplay: compactDisplay });
}).not.toThrow();
});
});
test("all valid signDisplay options", () => {
["auto", "never", "always", "exceptZero"].forEach(signDisplay => {
expect(() => {
new Intl.NumberFormat("en", { signDisplay: signDisplay });
}).not.toThrow();
});
});
});