NumberFormatConstructor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. * Copyright (c) 2021-2022, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Array.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  10. #include <LibJS/Runtime/Intl/NumberFormatConstructor.h>
  11. #include <LibUnicode/Locale.h>
  12. namespace JS::Intl {
  13. // 15.1 The Intl.NumberFormat Constructor, https://tc39.es/ecma402/#sec-intl-numberformat-constructor
  14. NumberFormatConstructor::NumberFormatConstructor(GlobalObject& global_object)
  15. : NativeFunction(vm().names.NumberFormat.as_string(), *global_object.function_prototype())
  16. {
  17. }
  18. void NumberFormatConstructor::initialize(GlobalObject& global_object)
  19. {
  20. NativeFunction::initialize(global_object);
  21. auto& vm = this->vm();
  22. // 15.2.1 Intl.NumberFormat.prototype, https://tc39.es/ecma402/#sec-intl.numberformat.prototype
  23. define_direct_property(vm.names.prototype, global_object.intl_number_format_prototype(), 0);
  24. u8 attr = Attribute::Writable | Attribute::Configurable;
  25. define_native_function(vm.names.supportedLocalesOf, supported_locales_of, 1, attr);
  26. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  27. }
  28. // 15.1.1 Intl.NumberFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.numberformat
  29. ThrowCompletionOr<Value> NumberFormatConstructor::call()
  30. {
  31. // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget.
  32. return TRY(construct(*this));
  33. }
  34. // 15.1.1 Intl.NumberFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.numberformat
  35. ThrowCompletionOr<Object*> NumberFormatConstructor::construct(FunctionObject& new_target)
  36. {
  37. auto& vm = this->vm();
  38. auto& global_object = this->global_object();
  39. auto locales = vm.argument(0);
  40. auto options = vm.argument(1);
  41. // 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]] »).
  42. auto* number_format = TRY(ordinary_create_from_constructor<NumberFormat>(global_object, new_target, &GlobalObject::intl_number_format_prototype));
  43. // 3. Perform ? InitializeNumberFormat(numberFormat, locales, options).
  44. TRY(initialize_number_format(global_object, *number_format, locales, options));
  45. // 4. If the implementation supports the normative optional constructor mode of 4.3 Note 1, then
  46. // a. Let this be the this value.
  47. // b. Return ? ChainNumberFormat(numberFormat, NewTarget, this).
  48. // 5. Return numberFormat.
  49. return number_format;
  50. }
  51. // 15.2.2 Intl.NumberFormat.supportedLocalesOf ( locales [ , options ] ), https://tc39.es/ecma402/#sec-intl.numberformat.supportedlocalesof
  52. JS_DEFINE_NATIVE_FUNCTION(NumberFormatConstructor::supported_locales_of)
  53. {
  54. auto locales = vm.argument(0);
  55. auto options = vm.argument(1);
  56. // 1. Let availableLocales be %NumberFormat%.[[AvailableLocales]].
  57. // 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  58. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales));
  59. // 3. Return ? SupportedLocales(availableLocales, requestedLocales, options).
  60. return TRY(supported_locales(global_object, requested_locales, options));
  61. }
  62. // 15.1.2 InitializeNumberFormat ( numberFormat, locales, options ), https://tc39.es/ecma402/#sec-initializenumberformat
  63. ThrowCompletionOr<NumberFormat*> initialize_number_format(GlobalObject& global_object, NumberFormat& number_format, Value locales_value, Value options_value)
  64. {
  65. auto& vm = global_object.vm();
  66. // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  67. auto requested_locales = TRY(canonicalize_locale_list(global_object, locales_value));
  68. // 2. Set options to ? CoerceOptionsToObject(options).
  69. auto* options = TRY(coerce_options_to_object(global_object, options_value));
  70. // 3. Let opt be a new Record.
  71. LocaleOptions opt {};
  72. // 4. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit").
  73. auto matcher = TRY(get_option(global_object, *options, vm.names.localeMatcher, Value::Type::String, { "lookup"sv, "best fit"sv }, "best fit"sv));
  74. // 5. Set opt.[[localeMatcher]] to matcher.
  75. opt.locale_matcher = matcher;
  76. // 6. Let numberingSystem be ? GetOption(options, "numberingSystem", "string", undefined, undefined).
  77. auto numbering_system = TRY(get_option(global_object, *options, vm.names.numberingSystem, Value::Type::String, {}, Empty {}));
  78. // 7. If numberingSystem is not undefined, then
  79. if (!numbering_system.is_undefined()) {
  80. // a. If numberingSystem does not match the Unicode Locale Identifier type nonterminal, throw a RangeError exception.
  81. if (!Unicode::is_type_identifier(numbering_system.as_string().string()))
  82. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  83. // 8. Set opt.[[nu]] to numberingSystem.
  84. opt.nu = numbering_system.as_string().string();
  85. }
  86. // 9. Let localeData be %NumberFormat%.[[LocaleData]].
  87. // 10. Let r be ResolveLocale(%NumberFormat%.[[AvailableLocales]], requestedLocales, opt, %NumberFormat%.[[RelevantExtensionKeys]], localeData).
  88. auto result = resolve_locale(requested_locales, opt, NumberFormat::relevant_extension_keys());
  89. // 11. Set numberFormat.[[Locale]] to r.[[locale]].
  90. number_format.set_locale(move(result.locale));
  91. // 12. Set numberFormat.[[DataLocale]] to r.[[dataLocale]].
  92. number_format.set_data_locale(move(result.data_locale));
  93. // 13. Set numberFormat.[[NumberingSystem]] to r.[[nu]].
  94. if (result.nu.has_value())
  95. number_format.set_numbering_system(result.nu.release_value());
  96. // 14. Perform ? SetNumberFormatUnitOptions(numberFormat, options).
  97. TRY(set_number_format_unit_options(global_object, number_format, *options));
  98. // 15. Let style be numberFormat.[[Style]].
  99. auto style = number_format.style();
  100. int default_min_fraction_digits = 0;
  101. int default_max_fraction_digits = 0;
  102. // 16. If style is "currency", then
  103. if (style == NumberFormat::Style::Currency) {
  104. // a. Let currency be numberFormat.[[Currency]].
  105. auto const& currency = number_format.currency();
  106. // b. Let cDigits be CurrencyDigits(currency).
  107. int digits = currency_digits(currency);
  108. // c. Let mnfdDefault be cDigits.
  109. default_min_fraction_digits = digits;
  110. // d. Let mxfdDefault be cDigits.
  111. default_max_fraction_digits = digits;
  112. }
  113. // 17. Else,
  114. else {
  115. // a. Let mnfdDefault be 0.
  116. default_min_fraction_digits = 0;
  117. // b. If style is "percent", then
  118. // i. Let mxfdDefault be 0.
  119. // c. Else,
  120. // i. Let mxfdDefault be 3.
  121. default_max_fraction_digits = style == NumberFormat::Style::Percent ? 0 : 3;
  122. }
  123. // 18. Let notation be ? GetOption(options, "notation", "string", « "standard", "scientific", "engineering", "compact" », "standard").
  124. auto notation = TRY(get_option(global_object, *options, vm.names.notation, Value::Type::String, { "standard"sv, "scientific"sv, "engineering"sv, "compact"sv }, "standard"sv));
  125. // 19. Set numberFormat.[[Notation]] to notation.
  126. number_format.set_notation(notation.as_string().string());
  127. // 20. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault, mxfdDefault, notation).
  128. TRY(set_number_format_digit_options(global_object, number_format, *options, default_min_fraction_digits, default_max_fraction_digits, number_format.notation()));
  129. // 21. Let compactDisplay be ? GetOption(options, "compactDisplay", "string", « "short", "long" », "short").
  130. auto compact_display = TRY(get_option(global_object, *options, vm.names.compactDisplay, Value::Type::String, { "short"sv, "long"sv }, "short"sv));
  131. // 22. If notation is "compact", then
  132. if (number_format.notation() == NumberFormat::Notation::Compact) {
  133. // a. Set numberFormat.[[CompactDisplay]] to compactDisplay.
  134. number_format.set_compact_display(compact_display.as_string().string());
  135. }
  136. // 23. Let useGrouping be ? GetOption(options, "useGrouping", "boolean", undefined, true).
  137. auto use_grouping = TRY(get_option(global_object, *options, vm.names.useGrouping, Value::Type::Boolean, {}, true));
  138. // 24. Set numberFormat.[[UseGrouping]] to useGrouping.
  139. number_format.set_use_grouping(use_grouping.as_bool());
  140. // 25. Let signDisplay be ? GetOption(options, "signDisplay", "string", « "auto", "never", "always", "exceptZero" », "auto").
  141. auto sign_display = TRY(get_option(global_object, *options, vm.names.signDisplay, Value::Type::String, { "auto"sv, "never"sv, "always"sv, "exceptZero"sv }, "auto"sv));
  142. // 26. Set numberFormat.[[SignDisplay]] to signDisplay.
  143. number_format.set_sign_display(sign_display.as_string().string());
  144. // 27. Return numberFormat.
  145. return &number_format;
  146. }
  147. // 15.1.3 SetNumberFormatDigitOptions ( intlObj, options, mnfdDefault, mxfdDefault, notation ), https://tc39.es/ecma402/#sec-setnfdigitoptions
  148. ThrowCompletionOr<void> set_number_format_digit_options(GlobalObject& global_object, NumberFormatBase& intl_object, Object const& options, int default_min_fraction_digits, int default_max_fraction_digits, NumberFormat::Notation notation)
  149. {
  150. auto& vm = global_object.vm();
  151. // 1. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1).
  152. auto min_integer_digits = TRY(get_number_option(global_object, options, vm.names.minimumIntegerDigits, 1, 21, 1));
  153. // 2. Let mnfd be ? Get(options, "minimumFractionDigits").
  154. auto min_fraction_digits = TRY(options.get(vm.names.minimumFractionDigits));
  155. // 3. Let mxfd be ? Get(options, "maximumFractionDigits").
  156. auto max_fraction_digits = TRY(options.get(vm.names.maximumFractionDigits));
  157. // 4. Let mnsd be ? Get(options, "minimumSignificantDigits").
  158. auto min_significant_digits = TRY(options.get(vm.names.minimumSignificantDigits));
  159. // 5. Let mxsd be ? Get(options, "maximumSignificantDigits").
  160. auto max_significant_digits = TRY(options.get(vm.names.maximumSignificantDigits));
  161. // 6. Set intlObj.[[MinimumIntegerDigits]] to mnid.
  162. intl_object.set_min_integer_digits(*min_integer_digits);
  163. // 7. If mnsd is not undefined or mxsd is not undefined, then
  164. // a. Let hasSd be true.
  165. // 8. Else,
  166. // a. Let hasSd be false.
  167. bool has_significant_digits = !min_significant_digits.is_undefined() || !max_significant_digits.is_undefined();
  168. // 9. If mnfd is not undefined or mxfd is not undefined, then
  169. // a. Let hasFd be true.
  170. // 10. Else,
  171. // a. Let hasFd be false.
  172. bool has_fraction_digits = !min_fraction_digits.is_undefined() || !max_fraction_digits.is_undefined();
  173. // 11. Let needSd be hasSd.
  174. bool need_significant_digits = has_significant_digits;
  175. // 12. If hasSd is true, or hasFd is false and notation is "compact", then
  176. // a. Let needFd be false.
  177. // 13. Else,
  178. // a. Let needFd be true.
  179. bool need_fraction_digits = !has_significant_digits && (has_fraction_digits || (notation != NumberFormat::Notation::Compact));
  180. // 14. If needSd is true, then
  181. if (need_significant_digits) {
  182. // a. Assert: hasSd is true.
  183. VERIFY(has_significant_digits);
  184. // b. Set mnsd to ? DefaultNumberOption(mnsd, 1, 21, 1).
  185. auto min_digits = TRY(default_number_option(global_object, min_significant_digits, 1, 21, 1));
  186. // c. Set mxsd to ? DefaultNumberOption(mxsd, mnsd, 21, 21).
  187. auto max_digits = TRY(default_number_option(global_object, max_significant_digits, *min_digits, 21, 21));
  188. // d. Set intlObj.[[MinimumSignificantDigits]] to mnsd.
  189. intl_object.set_min_significant_digits(*min_digits);
  190. // e. Set intlObj.[[MaximumSignificantDigits]] to mxsd.
  191. intl_object.set_max_significant_digits(*max_digits);
  192. }
  193. // 15. If needFd is true, then
  194. if (need_fraction_digits) {
  195. // a. If hasFd is true, then
  196. if (has_fraction_digits) {
  197. // i. Set mnfd to ? DefaultNumberOption(mnfd, 0, 20, undefined).
  198. auto min_digits = TRY(default_number_option(global_object, min_fraction_digits, 0, 20, {}));
  199. // ii. Set mxfd to ? DefaultNumberOption(mxfd, 0, 20, undefined).
  200. auto max_digits = TRY(default_number_option(global_object, max_fraction_digits, 0, 20, {}));
  201. // iii. If mnfd is undefined, set mnfd to min(mnfdDefault, mxfd).
  202. if (!min_digits.has_value())
  203. min_digits = min(default_min_fraction_digits, *max_digits);
  204. // iv. Else if mxfd is undefined, set mxfd to max(mxfdDefault, mnfd).
  205. else if (!max_digits.has_value())
  206. max_digits = max(default_max_fraction_digits, *min_digits);
  207. // v. Else if mnfd is greater than mxfd, throw a RangeError exception.
  208. else if (*min_digits > *max_digits)
  209. return vm.throw_completion<RangeError>(global_object, ErrorType::IntlMinimumExceedsMaximum, *min_digits, *max_digits);
  210. // vi. Set intlObj.[[MinimumFractionDigits]] to mnfd.
  211. intl_object.set_min_fraction_digits(*min_digits);
  212. // vii. Set intlObj.[[MaximumFractionDigits]] to mxfd.
  213. intl_object.set_max_fraction_digits(*max_digits);
  214. }
  215. // b. Else,
  216. else {
  217. // i. Set intlObj.[[MinimumFractionDigits]] to mnfdDefault.
  218. intl_object.set_min_fraction_digits(default_min_fraction_digits);
  219. // ii. Set intlObj.[[MaximumFractionDigits]] to mxfdDefault.
  220. intl_object.set_max_fraction_digits(default_max_fraction_digits);
  221. }
  222. }
  223. // 16. If needSd is false and needFd is false, then
  224. if (!need_significant_digits && !need_fraction_digits) {
  225. // a. Set intlObj.[[RoundingType]] to compactRounding.
  226. intl_object.set_rounding_type(NumberFormatBase::RoundingType::CompactRounding);
  227. }
  228. // 17. Else if hasSd is true, then
  229. else if (has_significant_digits) {
  230. // a. Set intlObj.[[RoundingType]] to significantDigits.
  231. intl_object.set_rounding_type(NumberFormatBase::RoundingType::SignificantDigits);
  232. }
  233. // 18. Else,
  234. else {
  235. // a. Set intlObj.[[RoundingType]] to fractionDigits.
  236. intl_object.set_rounding_type(NumberFormatBase::RoundingType::FractionDigits);
  237. }
  238. return {};
  239. }
  240. // 15.1.4 SetNumberFormatUnitOptions ( intlObj, options ), https://tc39.es/ecma402/#sec-setnumberformatunitoptions
  241. ThrowCompletionOr<void> set_number_format_unit_options(GlobalObject& global_object, NumberFormat& intl_object, Object const& options)
  242. {
  243. auto& vm = global_object.vm();
  244. // 1. Assert: Type(intlObj) is Object.
  245. // 2. Assert: Type(options) is Object.
  246. // 3. Let style be ? GetOption(options, "style", "string", « "decimal", "percent", "currency", "unit" », "decimal").
  247. auto style = TRY(get_option(global_object, options, vm.names.style, Value::Type::String, { "decimal"sv, "percent"sv, "currency"sv, "unit"sv }, "decimal"sv));
  248. // 4. Set intlObj.[[Style]] to style.
  249. intl_object.set_style(style.as_string().string());
  250. // 5. Let currency be ? GetOption(options, "currency", "string", undefined, undefined).
  251. auto currency = TRY(get_option(global_object, options, vm.names.currency, Value::Type::String, {}, Empty {}));
  252. // 6. If currency is undefined, then
  253. if (currency.is_undefined()) {
  254. // a. If style is "currency", throw a TypeError exception.
  255. if (intl_object.style() == NumberFormat::Style::Currency)
  256. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "currency"sv, "style"sv, style);
  257. }
  258. // 7. Else,
  259. // a. If the result of IsWellFormedCurrencyCode(currency) is false, throw a RangeError exception.
  260. else if (!is_well_formed_currency_code(currency.as_string().string()))
  261. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, currency, "currency"sv);
  262. // 8. Let currencyDisplay be ? GetOption(options, "currencyDisplay", "string", « "code", "symbol", "narrowSymbol", "name" », "symbol").
  263. auto currency_display = TRY(get_option(global_object, options, vm.names.currencyDisplay, Value::Type::String, { "code"sv, "symbol"sv, "narrowSymbol"sv, "name"sv }, "symbol"sv));
  264. // 9. Let currencySign be ? GetOption(options, "currencySign", "string", « "standard", "accounting" », "standard").
  265. auto currency_sign = TRY(get_option(global_object, options, vm.names.currencySign, Value::Type::String, { "standard"sv, "accounting"sv }, "standard"sv));
  266. // 10. Let unit be ? GetOption(options, "unit", "string", undefined, undefined).
  267. auto unit = TRY(get_option(global_object, options, vm.names.unit, Value::Type::String, {}, Empty {}));
  268. // 11. If unit is undefined, then
  269. if (unit.is_undefined()) {
  270. // a. If style is "unit", throw a TypeError exception.
  271. if (intl_object.style() == NumberFormat::Style::Unit)
  272. return vm.throw_completion<TypeError>(global_object, ErrorType::IntlOptionUndefined, "unit"sv, "style"sv, style);
  273. }
  274. // 12. Else,
  275. // a. If the result of IsWellFormedUnitIdentifier(unit) is false, throw a RangeError exception.
  276. else if (!is_well_formed_unit_identifier(unit.as_string().string()))
  277. return vm.throw_completion<RangeError>(global_object, ErrorType::OptionIsNotValidValue, unit, "unit"sv);
  278. // 13. Let unitDisplay be ? GetOption(options, "unitDisplay", "string", « "short", "narrow", "long" », "short").
  279. auto unit_display = TRY(get_option(global_object, options, vm.names.unitDisplay, Value::Type::String, { "short"sv, "narrow"sv, "long"sv }, "short"sv));
  280. // 14. If style is "currency", then
  281. if (intl_object.style() == NumberFormat::Style::Currency) {
  282. // a. Let currency be the result of converting currency to upper case as specified in 6.1.
  283. // b. Set intlObj.[[Currency]] to currency.
  284. intl_object.set_currency(currency.as_string().string().to_uppercase());
  285. // c. Set intlObj.[[CurrencyDisplay]] to currencyDisplay.
  286. intl_object.set_currency_display(currency_display.as_string().string());
  287. // d. Set intlObj.[[CurrencySign]] to currencySign.
  288. intl_object.set_currency_sign(currency_sign.as_string().string());
  289. }
  290. // 15. If style is "unit", then
  291. if (intl_object.style() == NumberFormat::Style::Unit) {
  292. // a. Set intlObj.[[Unit]] to unit.
  293. intl_object.set_unit(unit.as_string().string());
  294. // b. Set intlObj.[[UnitDisplay]] to unitDisplay.
  295. intl_object.set_unit_display(unit_display.as_string().string());
  296. }
  297. return {};
  298. }
  299. }