NumberFormat.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/Utf8View.h>
  8. #include <LibCrypto/BigInt/SignedBigInteger.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/BigInt.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Intl/NumberFormat.h>
  14. #include <LibJS/Runtime/Intl/NumberFormatFunction.h>
  15. #include <LibJS/Runtime/Intl/PluralRules.h>
  16. #include <LibJS/Runtime/ThrowableStringBuilder.h>
  17. #include <LibUnicode/CurrencyCode.h>
  18. #include <math.h>
  19. #include <stdlib.h>
  20. namespace JS::Intl {
  21. NumberFormatBase::NumberFormatBase(Object& prototype)
  22. : Object(ConstructWithPrototypeTag::Tag, prototype)
  23. {
  24. }
  25. // 15 NumberFormat Objects, https://tc39.es/ecma402/#numberformat-objects
  26. NumberFormat::NumberFormat(Object& prototype)
  27. : NumberFormatBase(prototype)
  28. {
  29. }
  30. void NumberFormat::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Base::visit_edges(visitor);
  33. if (m_bound_format)
  34. visitor.visit(m_bound_format);
  35. }
  36. void NumberFormat::set_style(StringView style)
  37. {
  38. if (style == "decimal"sv)
  39. m_style = Style::Decimal;
  40. else if (style == "percent"sv)
  41. m_style = Style::Percent;
  42. else if (style == "currency"sv)
  43. m_style = Style::Currency;
  44. else if (style == "unit"sv)
  45. m_style = Style::Unit;
  46. else
  47. VERIFY_NOT_REACHED();
  48. }
  49. StringView NumberFormat::style_string() const
  50. {
  51. switch (m_style) {
  52. case Style::Decimal:
  53. return "decimal"sv;
  54. case Style::Percent:
  55. return "percent"sv;
  56. case Style::Currency:
  57. return "currency"sv;
  58. case Style::Unit:
  59. return "unit"sv;
  60. default:
  61. VERIFY_NOT_REACHED();
  62. }
  63. }
  64. void NumberFormat::set_currency_display(StringView currency_display)
  65. {
  66. m_resolved_currency_display.clear();
  67. if (currency_display == "code"sv)
  68. m_currency_display = CurrencyDisplay::Code;
  69. else if (currency_display == "symbol"sv)
  70. m_currency_display = CurrencyDisplay::Symbol;
  71. else if (currency_display == "narrowSymbol"sv)
  72. m_currency_display = CurrencyDisplay::NarrowSymbol;
  73. else if (currency_display == "name"sv)
  74. m_currency_display = CurrencyDisplay::Name;
  75. else
  76. VERIFY_NOT_REACHED();
  77. }
  78. StringView NumberFormat::resolve_currency_display()
  79. {
  80. if (m_resolved_currency_display.has_value())
  81. return *m_resolved_currency_display;
  82. switch (currency_display()) {
  83. case NumberFormat::CurrencyDisplay::Code:
  84. m_resolved_currency_display = currency();
  85. break;
  86. case NumberFormat::CurrencyDisplay::Symbol:
  87. m_resolved_currency_display = ::Locale::get_locale_short_currency_mapping(data_locale(), currency());
  88. break;
  89. case NumberFormat::CurrencyDisplay::NarrowSymbol:
  90. m_resolved_currency_display = ::Locale::get_locale_narrow_currency_mapping(data_locale(), currency());
  91. break;
  92. case NumberFormat::CurrencyDisplay::Name:
  93. m_resolved_currency_display = ::Locale::get_locale_numeric_currency_mapping(data_locale(), currency());
  94. break;
  95. default:
  96. VERIFY_NOT_REACHED();
  97. }
  98. if (!m_resolved_currency_display.has_value())
  99. m_resolved_currency_display = currency();
  100. return *m_resolved_currency_display;
  101. }
  102. StringView NumberFormat::currency_display_string() const
  103. {
  104. VERIFY(m_currency_display.has_value());
  105. switch (*m_currency_display) {
  106. case CurrencyDisplay::Code:
  107. return "code"sv;
  108. case CurrencyDisplay::Symbol:
  109. return "symbol"sv;
  110. case CurrencyDisplay::NarrowSymbol:
  111. return "narrowSymbol"sv;
  112. case CurrencyDisplay::Name:
  113. return "name"sv;
  114. default:
  115. VERIFY_NOT_REACHED();
  116. }
  117. }
  118. void NumberFormat::set_currency_sign(StringView currency_sign)
  119. {
  120. if (currency_sign == "standard"sv)
  121. m_currency_sign = CurrencySign::Standard;
  122. else if (currency_sign == "accounting"sv)
  123. m_currency_sign = CurrencySign::Accounting;
  124. else
  125. VERIFY_NOT_REACHED();
  126. }
  127. StringView NumberFormat::currency_sign_string() const
  128. {
  129. VERIFY(m_currency_sign.has_value());
  130. switch (*m_currency_sign) {
  131. case CurrencySign::Standard:
  132. return "standard"sv;
  133. case CurrencySign::Accounting:
  134. return "accounting"sv;
  135. default:
  136. VERIFY_NOT_REACHED();
  137. }
  138. }
  139. StringView NumberFormatBase::rounding_type_string() const
  140. {
  141. switch (m_rounding_type) {
  142. case RoundingType::SignificantDigits:
  143. return "significantDigits"sv;
  144. case RoundingType::FractionDigits:
  145. return "fractionDigits"sv;
  146. case RoundingType::MorePrecision:
  147. return "morePrecision"sv;
  148. case RoundingType::LessPrecision:
  149. return "lessPrecision"sv;
  150. default:
  151. VERIFY_NOT_REACHED();
  152. }
  153. }
  154. StringView NumberFormatBase::rounding_mode_string() const
  155. {
  156. switch (m_rounding_mode) {
  157. case RoundingMode::Ceil:
  158. return "ceil"sv;
  159. case RoundingMode::Expand:
  160. return "expand"sv;
  161. case RoundingMode::Floor:
  162. return "floor"sv;
  163. case RoundingMode::HalfCeil:
  164. return "halfCeil"sv;
  165. case RoundingMode::HalfEven:
  166. return "halfEven"sv;
  167. case RoundingMode::HalfExpand:
  168. return "halfExpand"sv;
  169. case RoundingMode::HalfFloor:
  170. return "halfFloor"sv;
  171. case RoundingMode::HalfTrunc:
  172. return "halfTrunc"sv;
  173. case RoundingMode::Trunc:
  174. return "trunc"sv;
  175. default:
  176. VERIFY_NOT_REACHED();
  177. }
  178. }
  179. void NumberFormatBase::set_rounding_mode(StringView rounding_mode)
  180. {
  181. if (rounding_mode == "ceil"sv)
  182. m_rounding_mode = RoundingMode::Ceil;
  183. else if (rounding_mode == "expand"sv)
  184. m_rounding_mode = RoundingMode::Expand;
  185. else if (rounding_mode == "floor"sv)
  186. m_rounding_mode = RoundingMode::Floor;
  187. else if (rounding_mode == "halfCeil"sv)
  188. m_rounding_mode = RoundingMode::HalfCeil;
  189. else if (rounding_mode == "halfEven"sv)
  190. m_rounding_mode = RoundingMode::HalfEven;
  191. else if (rounding_mode == "halfExpand"sv)
  192. m_rounding_mode = RoundingMode::HalfExpand;
  193. else if (rounding_mode == "halfFloor"sv)
  194. m_rounding_mode = RoundingMode::HalfFloor;
  195. else if (rounding_mode == "halfTrunc"sv)
  196. m_rounding_mode = RoundingMode::HalfTrunc;
  197. else if (rounding_mode == "trunc"sv)
  198. m_rounding_mode = RoundingMode::Trunc;
  199. else
  200. VERIFY_NOT_REACHED();
  201. }
  202. StringView NumberFormatBase::trailing_zero_display_string() const
  203. {
  204. switch (m_trailing_zero_display) {
  205. case TrailingZeroDisplay::Auto:
  206. return "auto"sv;
  207. case TrailingZeroDisplay::StripIfInteger:
  208. return "stripIfInteger"sv;
  209. default:
  210. VERIFY_NOT_REACHED();
  211. }
  212. }
  213. void NumberFormatBase::set_trailing_zero_display(StringView trailing_zero_display)
  214. {
  215. if (trailing_zero_display == "auto"sv)
  216. m_trailing_zero_display = TrailingZeroDisplay::Auto;
  217. else if (trailing_zero_display == "stripIfInteger"sv)
  218. m_trailing_zero_display = TrailingZeroDisplay::StripIfInteger;
  219. else
  220. VERIFY_NOT_REACHED();
  221. }
  222. Value NumberFormat::use_grouping_to_value(VM& vm) const
  223. {
  224. switch (m_use_grouping) {
  225. case UseGrouping::Always:
  226. return PrimitiveString::create(vm, "always"sv);
  227. case UseGrouping::Auto:
  228. return PrimitiveString::create(vm, "auto"sv);
  229. case UseGrouping::Min2:
  230. return PrimitiveString::create(vm, "min2"sv);
  231. case UseGrouping::False:
  232. return Value(false);
  233. default:
  234. VERIFY_NOT_REACHED();
  235. }
  236. }
  237. void NumberFormat::set_use_grouping(StringOrBoolean const& use_grouping)
  238. {
  239. use_grouping.visit(
  240. [this](StringView grouping) {
  241. if (grouping == "always"sv)
  242. m_use_grouping = UseGrouping::Always;
  243. else if (grouping == "auto"sv)
  244. m_use_grouping = UseGrouping::Auto;
  245. else if (grouping == "min2"sv)
  246. m_use_grouping = UseGrouping::Min2;
  247. else
  248. VERIFY_NOT_REACHED();
  249. },
  250. [this](bool grouping) {
  251. VERIFY(!grouping);
  252. m_use_grouping = UseGrouping::False;
  253. });
  254. }
  255. void NumberFormat::set_notation(StringView notation)
  256. {
  257. if (notation == "standard"sv)
  258. m_notation = Notation::Standard;
  259. else if (notation == "scientific"sv)
  260. m_notation = Notation::Scientific;
  261. else if (notation == "engineering"sv)
  262. m_notation = Notation::Engineering;
  263. else if (notation == "compact"sv)
  264. m_notation = Notation::Compact;
  265. else
  266. VERIFY_NOT_REACHED();
  267. }
  268. StringView NumberFormat::notation_string() const
  269. {
  270. switch (m_notation) {
  271. case Notation::Standard:
  272. return "standard"sv;
  273. case Notation::Scientific:
  274. return "scientific"sv;
  275. case Notation::Engineering:
  276. return "engineering"sv;
  277. case Notation::Compact:
  278. return "compact"sv;
  279. default:
  280. VERIFY_NOT_REACHED();
  281. }
  282. }
  283. void NumberFormat::set_compact_display(StringView compact_display)
  284. {
  285. if (compact_display == "short"sv)
  286. m_compact_display = CompactDisplay::Short;
  287. else if (compact_display == "long"sv)
  288. m_compact_display = CompactDisplay::Long;
  289. else
  290. VERIFY_NOT_REACHED();
  291. }
  292. StringView NumberFormat::compact_display_string() const
  293. {
  294. VERIFY(m_compact_display.has_value());
  295. switch (*m_compact_display) {
  296. case CompactDisplay::Short:
  297. return "short"sv;
  298. case CompactDisplay::Long:
  299. return "long"sv;
  300. default:
  301. VERIFY_NOT_REACHED();
  302. }
  303. }
  304. void NumberFormat::set_sign_display(StringView sign_display)
  305. {
  306. if (sign_display == "auto"sv)
  307. m_sign_display = SignDisplay::Auto;
  308. else if (sign_display == "never"sv)
  309. m_sign_display = SignDisplay::Never;
  310. else if (sign_display == "always"sv)
  311. m_sign_display = SignDisplay::Always;
  312. else if (sign_display == "exceptZero"sv)
  313. m_sign_display = SignDisplay::ExceptZero;
  314. else if (sign_display == "negative"sv)
  315. m_sign_display = SignDisplay::Negative;
  316. else
  317. VERIFY_NOT_REACHED();
  318. }
  319. StringView NumberFormat::sign_display_string() const
  320. {
  321. switch (m_sign_display) {
  322. case SignDisplay::Auto:
  323. return "auto"sv;
  324. case SignDisplay::Never:
  325. return "never"sv;
  326. case SignDisplay::Always:
  327. return "always"sv;
  328. case SignDisplay::ExceptZero:
  329. return "exceptZero"sv;
  330. case SignDisplay::Negative:
  331. return "negative"sv;
  332. default:
  333. VERIFY_NOT_REACHED();
  334. }
  335. }
  336. // 15.5.1 CurrencyDigits ( currency ), https://tc39.es/ecma402/#sec-currencydigits
  337. int currency_digits(StringView currency)
  338. {
  339. // 1. If the ISO 4217 currency and funds code list contains currency as an alphabetic code, return the minor
  340. // unit value corresponding to the currency from the list; otherwise, return 2.
  341. if (auto currency_code = Unicode::get_currency_code(currency); currency_code.has_value())
  342. return currency_code->minor_unit.value_or(2);
  343. return 2;
  344. }
  345. // 15.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/ecma402/#sec-formatnumberstring
  346. // 1.5.3 FormatNumericToString ( intlObject, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumberstring
  347. ThrowCompletionOr<FormatResult> format_numeric_to_string(VM& vm, NumberFormatBase const& intl_object, MathematicalValue number)
  348. {
  349. bool is_negative = false;
  350. // 1. If x is negative-zero, then
  351. if (number.is_negative_zero()) {
  352. // a. Let isNegative be true.
  353. is_negative = true;
  354. // b. Set x to 0.
  355. number = MathematicalValue(0.0);
  356. }
  357. // 2. Else,
  358. else {
  359. // a. Assert: x is a mathematical value.
  360. VERIFY(number.is_mathematical_value());
  361. // b. If x < 0, let isNegative be true; else let isNegative be false.
  362. is_negative = number.is_negative();
  363. // c. If isNegative, then
  364. if (is_negative) {
  365. // i. Set x to -x.
  366. number.negate();
  367. }
  368. }
  369. // 3. Let unsignedRoundingMode be GetUnsignedRoundingMode(intlObject.[[RoundingMode]], isNegative).
  370. // FIXME: Spec issue: Intl.PluralRules does not have [[RoundingMode]], see https://github.com/tc39/proposal-intl-numberformat-v3/issues/103
  371. Optional<NumberFormat::UnsignedRoundingMode> unsigned_rounding_mode;
  372. if (intl_object.rounding_mode() != NumberFormat::RoundingMode::Invalid)
  373. unsigned_rounding_mode = get_unsigned_rounding_mode(intl_object.rounding_mode(), is_negative);
  374. RawFormatResult result {};
  375. switch (intl_object.rounding_type()) {
  376. // 4. If intlObject.[[RoundingType]] is significantDigits, then
  377. case NumberFormatBase::RoundingType::SignificantDigits:
  378. // a. Let result be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  379. result = MUST_OR_THROW_OOM(to_raw_precision(vm, number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode));
  380. break;
  381. // 5. Else if intlObject.[[RoundingType]] is fractionDigits, then
  382. case NumberFormatBase::RoundingType::FractionDigits:
  383. // a. Let result be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  384. result = MUST_OR_THROW_OOM(to_raw_fixed(vm, number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode));
  385. break;
  386. // 6. Else,
  387. case NumberFormatBase::RoundingType::MorePrecision:
  388. case NumberFormatBase::RoundingType::LessPrecision: {
  389. // a. Let sResult be ToRawPrecision(x, intlObject.[[MinimumSignificantDigits]], intlObject.[[MaximumSignificantDigits]], unsignedRoundingMode).
  390. auto significant_result = MUST_OR_THROW_OOM(to_raw_precision(vm, number, intl_object.min_significant_digits(), intl_object.max_significant_digits(), unsigned_rounding_mode));
  391. // b. Let fResult be ToRawFixed(x, intlObject.[[MinimumFractionDigits]], intlObject.[[MaximumFractionDigits]], intlObject.[[RoundingIncrement]], unsignedRoundingMode).
  392. auto fraction_result = MUST_OR_THROW_OOM(to_raw_fixed(vm, number, intl_object.min_fraction_digits(), intl_object.max_fraction_digits(), intl_object.rounding_increment(), unsigned_rounding_mode));
  393. // c. If intlObj.[[RoundingType]] is morePrecision, then
  394. if (intl_object.rounding_type() == NumberFormatBase::RoundingType::MorePrecision) {
  395. // i. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  396. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  397. // 1. Let result be sResult.
  398. result = move(significant_result);
  399. }
  400. // ii. Else,
  401. else {
  402. // 2. Let result be fResult.
  403. result = move(fraction_result);
  404. }
  405. }
  406. // d. Else,
  407. else {
  408. // i. Assert: intlObj.[[RoundingType]] is lessPrecision.
  409. VERIFY(intl_object.rounding_type() == NumberFormatBase::RoundingType::LessPrecision);
  410. // ii. If sResult.[[RoundingMagnitude]] ≤ fResult.[[RoundingMagnitude]], then
  411. if (significant_result.rounding_magnitude <= fraction_result.rounding_magnitude) {
  412. // 1. Let result be fResult.
  413. result = move(fraction_result);
  414. }
  415. // iii. Else,
  416. else {
  417. // 1. Let result be sResult.
  418. result = move(significant_result);
  419. }
  420. }
  421. break;
  422. }
  423. default:
  424. VERIFY_NOT_REACHED();
  425. }
  426. // 7. Let x be result.[[RoundedNumber]].
  427. number = move(result.rounded_number);
  428. // 8. Let string be result.[[FormattedString]].
  429. auto string = move(result.formatted_string);
  430. // 9. If intlObject.[[TrailingZeroDisplay]] is "stripIfInteger" and x modulo 1 = 0, then
  431. if ((intl_object.trailing_zero_display() == NumberFormat::TrailingZeroDisplay::StripIfInteger) && number.modulo_is_zero(1)) {
  432. // a. If string contains ".", then
  433. if (auto index = string.find_byte_offset('.'); index.has_value()) {
  434. // i. Set string to the substring of string from index 0 to the index of ".".
  435. string = TRY_OR_THROW_OOM(vm, string.substring_from_byte_offset(0, *index));
  436. }
  437. }
  438. // 10. Let int be result.[[IntegerDigitsCount]].
  439. int digits = result.digits;
  440. // 11. Let minInteger be intlObject.[[MinimumIntegerDigits]].
  441. int min_integer = intl_object.min_integer_digits();
  442. // 12. If int < minInteger, then
  443. if (digits < min_integer) {
  444. // a. Let forwardZeros be the String consisting of minInteger - int occurrences of the code unit 0x0030 (DIGIT ZERO).
  445. auto forward_zeros = TRY_OR_THROW_OOM(vm, String::repeated('0', min_integer - digits));
  446. // b. Set string to the string-concatenation of forwardZeros and string.
  447. string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", forward_zeros, string));
  448. }
  449. // 13. If isNegative and x is 0, then
  450. if (is_negative && number.is_zero()) {
  451. // a. Let x be -0.
  452. number = MathematicalValue { MathematicalValue::Symbol::NegativeZero };
  453. }
  454. // 14. Else if isNegative, then
  455. else if (is_negative) {
  456. // b. Let x be -x.
  457. number.negate();
  458. }
  459. // 15. Return the Record { [[RoundedNumber]]: x, [[FormattedString]]: string }.
  460. return FormatResult { move(string), move(number) };
  461. }
  462. // 15.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-partitionnumberpattern
  463. // 1.5.4 PartitionNumberPattern ( numberFormat, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnumberpattern
  464. ThrowCompletionOr<Vector<PatternPartition>> partition_number_pattern(VM& vm, NumberFormat& number_format, MathematicalValue number)
  465. {
  466. // 1. Let exponent be 0.
  467. int exponent = 0;
  468. String formatted_string;
  469. // 2. If x is not-a-number, then
  470. if (number.is_nan()) {
  471. // a. Let n be an implementation- and locale-dependent (ILD) String value indicating the NaN value.
  472. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::NaN).value_or("NaN"sv);
  473. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  474. }
  475. // 3. Else if x is positive-infinity, then
  476. else if (number.is_positive_infinity()) {
  477. // a. Let n be an ILD String value indicating positive infinity.
  478. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  479. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  480. }
  481. // 4. Else if x is negative-infinity, then
  482. else if (number.is_negative_infinity()) {
  483. // a. Let n be an ILD String value indicating negative infinity.
  484. // NOTE: The CLDR does not contain unique strings for negative infinity. The negative sign will
  485. // be inserted by the pattern returned from GetNumberFormatPattern.
  486. auto symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Infinity).value_or("infinity"sv);
  487. formatted_string = TRY_OR_THROW_OOM(vm, String::from_utf8(symbol));
  488. }
  489. // 5. Else,
  490. else {
  491. // a. If x is not negative-zero,
  492. if (!number.is_negative_zero()) {
  493. // i. Assert: x is a mathematical value.
  494. VERIFY(number.is_mathematical_value());
  495. // ii. If numberFormat.[[Style]] is "percent", let x be 100 × x.
  496. if (number_format.style() == NumberFormat::Style::Percent)
  497. number = number.multiplied_by(100);
  498. // iii. Let exponent be ComputeExponent(numberFormat, x).
  499. exponent = MUST_OR_THROW_OOM(compute_exponent(vm, number_format, number));
  500. // iv. Let x be x × 10^-exponent.
  501. number = number.multiplied_by_power(-exponent);
  502. }
  503. // b. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  504. auto format_number_result = MUST_OR_THROW_OOM(format_numeric_to_string(vm, number_format, move(number)));
  505. // c. Let n be formatNumberResult.[[FormattedString]].
  506. formatted_string = move(format_number_result.formatted_string);
  507. // d. Let x be formatNumberResult.[[RoundedNumber]].
  508. number = move(format_number_result.rounded_number);
  509. }
  510. ::Locale::NumberFormat found_pattern {};
  511. // 6. Let pattern be GetNumberFormatPattern(numberFormat, x).
  512. auto pattern = MUST_OR_THROW_OOM(get_number_format_pattern(vm, number_format, number, found_pattern));
  513. if (!pattern.has_value())
  514. return Vector<PatternPartition> {};
  515. // 7. Let result be a new empty List.
  516. Vector<PatternPartition> result;
  517. // 8. Let patternParts be PartitionPattern(pattern).
  518. auto pattern_parts = MUST_OR_THROW_OOM(pattern->visit([&](auto const& p) { return partition_pattern(vm, p); }));
  519. // 9. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  520. for (auto& pattern_part : pattern_parts) {
  521. // a. Let p be patternPart.[[Type]].
  522. auto part = pattern_part.type;
  523. // b. If p is "literal", then
  524. if (part == "literal"sv) {
  525. // i. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  526. result.append({ "literal"sv, move(pattern_part.value) });
  527. }
  528. // c. Else if p is equal to "number", then
  529. else if (part == "number"sv) {
  530. // i. Let notationSubParts be PartitionNotationSubPattern(numberFormat, x, n, exponent).
  531. auto notation_sub_parts = MUST_OR_THROW_OOM(partition_notation_sub_pattern(vm, number_format, number, formatted_string, exponent));
  532. // ii. Append all elements of notationSubParts to result.
  533. result.extend(move(notation_sub_parts));
  534. }
  535. // d. Else if p is equal to "plusSign", then
  536. else if (part == "plusSign"sv) {
  537. // i. Let plusSignSymbol be the ILND String representing the plus sign.
  538. auto plus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PlusSign).value_or("+"sv);
  539. // ii. Append a new Record { [[Type]]: "plusSign", [[Value]]: plusSignSymbol } as the last element of result.
  540. result.append({ "plusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(plus_sign_symbol)) });
  541. }
  542. // e. Else if p is equal to "minusSign", then
  543. else if (part == "minusSign"sv) {
  544. // i. Let minusSignSymbol be the ILND String representing the minus sign.
  545. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  546. // ii. Append a new Record { [[Type]]: "minusSign", [[Value]]: minusSignSymbol } as the last element of result.
  547. result.append({ "minusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) });
  548. }
  549. // f. Else if p is equal to "percentSign" and numberFormat.[[Style]] is "percent", then
  550. else if ((part == "percentSign"sv) && (number_format.style() == NumberFormat::Style::Percent)) {
  551. // i. Let percentSignSymbol be the ILND String representing the percent sign.
  552. auto percent_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::PercentSign).value_or("%"sv);
  553. // ii. Append a new Record { [[Type]]: "percentSign", [[Value]]: percentSignSymbol } as the last element of result.
  554. result.append({ "percentSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(percent_sign_symbol)) });
  555. }
  556. // g. Else if p is equal to "unitPrefix" and numberFormat.[[Style]] is "unit", then
  557. // h. Else if p is equal to "unitSuffix" and numberFormat.[[Style]] is "unit", then
  558. else if ((part.starts_with("unitIdentifier:"sv)) && (number_format.style() == NumberFormat::Style::Unit)) {
  559. // Note: Our implementation combines "unitPrefix" and "unitSuffix" into one field, "unitIdentifier".
  560. auto identifier_index = part.substring_view("unitIdentifier:"sv.length()).to_uint();
  561. VERIFY(identifier_index.has_value());
  562. // i. Let unit be numberFormat.[[Unit]].
  563. // ii. Let unitDisplay be numberFormat.[[UnitDisplay]].
  564. // iii. Let mu be an ILD String value representing unit before x in unitDisplay form, which may depend on x in languages having different plural forms.
  565. auto unit_identifier = found_pattern.identifiers[*identifier_index];
  566. // iv. Append a new Record { [[Type]]: "unit", [[Value]]: mu } as the last element of result.
  567. result.append({ "unit"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(unit_identifier)) });
  568. }
  569. // i. Else if p is equal to "currencyCode" and numberFormat.[[Style]] is "currency", then
  570. // j. Else if p is equal to "currencyPrefix" and numberFormat.[[Style]] is "currency", then
  571. // k. Else if p is equal to "currencySuffix" and numberFormat.[[Style]] is "currency", then
  572. //
  573. // Note: Our implementation manipulates the format string to inject/remove spacing around the
  574. // currency code during GetNumberFormatPattern so that we do not have to do currency
  575. // display / plurality lookups more than once.
  576. else if ((part == "currency"sv) && (number_format.style() == NumberFormat::Style::Currency)) {
  577. auto currency = number_format.resolve_currency_display();
  578. result.append({ "currency"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(currency)) });
  579. }
  580. // l. Else,
  581. else {
  582. // i. Let unknown be an ILND String based on x and p.
  583. // ii. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  584. // LibUnicode doesn't generate any "unknown" patterns.
  585. VERIFY_NOT_REACHED();
  586. }
  587. }
  588. // 10. Return result.
  589. return result;
  590. }
  591. static Vector<StringView> separate_integer_into_groups(::Locale::NumberGroupings const& grouping_sizes, StringView integer, NumberFormat::UseGrouping use_grouping)
  592. {
  593. Utf8View utf8_integer { integer };
  594. if (utf8_integer.length() <= grouping_sizes.primary_grouping_size)
  595. return { integer };
  596. size_t index = utf8_integer.length() - grouping_sizes.primary_grouping_size;
  597. switch (use_grouping) {
  598. case NumberFormat::UseGrouping::Min2:
  599. if (utf8_integer.length() < 5)
  600. return { integer };
  601. break;
  602. case NumberFormat::UseGrouping::Auto:
  603. if (index < grouping_sizes.minimum_grouping_digits)
  604. return { integer };
  605. break;
  606. case NumberFormat::UseGrouping::Always:
  607. break;
  608. default:
  609. VERIFY_NOT_REACHED();
  610. }
  611. Vector<StringView> groups;
  612. auto add_group = [&](size_t index, size_t length) {
  613. groups.prepend(utf8_integer.unicode_substring_view(index, length).as_string());
  614. };
  615. add_group(index, grouping_sizes.primary_grouping_size);
  616. while (index > grouping_sizes.secondary_grouping_size) {
  617. index -= grouping_sizes.secondary_grouping_size;
  618. add_group(index, grouping_sizes.secondary_grouping_size);
  619. }
  620. if (index > 0)
  621. add_group(0, index);
  622. return groups;
  623. }
  624. // 15.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/ecma402/#sec-partitionnotationsubpattern
  625. // 1.5.5 PartitionNotationSubPattern ( numberFormat, x, n, exponent ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnotationsubpattern
  626. ThrowCompletionOr<Vector<PatternPartition>> partition_notation_sub_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, String formatted_string, int exponent)
  627. {
  628. // 1. Let result be a new empty List.
  629. Vector<PatternPartition> result;
  630. auto grouping_sizes = ::Locale::get_number_system_groupings(number_format.data_locale(), number_format.numbering_system());
  631. if (!grouping_sizes.has_value())
  632. return Vector<PatternPartition> {};
  633. // 2. If x is NaN, then
  634. if (number.is_nan()) {
  635. // a. Append a new Record { [[Type]]: "nan", [[Value]]: n } as the last element of result.
  636. result.append({ "nan"sv, move(formatted_string) });
  637. }
  638. // 3. Else if x is a non-finite Number, then
  639. else if (number.is_positive_infinity() || number.is_negative_infinity()) {
  640. // a. Append a new Record { [[Type]]: "infinity", [[Value]]: n } as the last element of result.
  641. result.append({ "infinity"sv, move(formatted_string) });
  642. }
  643. // 4. Else,
  644. else {
  645. // a. Let notationSubPattern be GetNotationSubPattern(numberFormat, exponent).
  646. auto notation_sub_pattern = get_notation_sub_pattern(number_format, exponent);
  647. if (!notation_sub_pattern.has_value())
  648. return Vector<PatternPartition> {};
  649. // b. Let patternParts be PartitionPattern(notationSubPattern).
  650. auto pattern_parts = MUST_OR_THROW_OOM(partition_pattern(vm, *notation_sub_pattern));
  651. // c. For each Record { [[Type]], [[Value]] } patternPart of patternParts, do
  652. for (auto& pattern_part : pattern_parts) {
  653. // i. Let p be patternPart.[[Type]].
  654. auto part = pattern_part.type;
  655. // ii. If p is "literal", then
  656. if (part == "literal"sv) {
  657. // 1. Append a new Record { [[Type]]: "literal", [[Value]]: patternPart.[[Value]] } as the last element of result.
  658. result.append({ "literal"sv, move(pattern_part.value) });
  659. }
  660. // iii. Else if p is equal to "number", then
  661. else if (part == "number"sv) {
  662. // 1. If the numberFormat.[[NumberingSystem]] matches one of the values in the "Numbering System" column of Table 12 below, then
  663. // a. Let digits be a List whose elements are the code points specified in the "Digits" column of the matching row in Table 13.
  664. // b. Assert: The length of digits is 10.
  665. // c. Let transliterated be the empty String.
  666. // d. Let len be the length of n.
  667. // e. Let position be 0.
  668. // f. Repeat, while position < len,
  669. // i. Let c be the code unit at index position within n.
  670. // ii. If 0x0030 ≤ c ≤ 0x0039, then
  671. // i. NOTE: c is an ASCII digit.
  672. // ii. Let i be c - 0x0030.
  673. // iii. Set c to CodePointsToString(« digits[i] »).
  674. // iii. Set transliterated to the string-concatenation of transliterated and c.
  675. // iv. Set position to position + 1.
  676. // g. Set n to transliterated.
  677. // 2. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
  678. formatted_string = TRY_OR_THROW_OOM(vm, ::Locale::replace_digits_for_number_system(number_format.numbering_system(), formatted_string));
  679. // 3. Let decimalSepIndex be StringIndexOf(n, ".", 0).
  680. auto decimal_sep_index = formatted_string.find_byte_offset('.');
  681. StringView integer;
  682. Optional<StringView> fraction;
  683. // 4. If decimalSepIndex > 0, then
  684. if (decimal_sep_index.has_value() && (*decimal_sep_index > 0)) {
  685. // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
  686. integer = formatted_string.bytes_as_string_view().substring_view(0, *decimal_sep_index);
  687. // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
  688. fraction = formatted_string.bytes_as_string_view().substring_view(*decimal_sep_index + 1);
  689. }
  690. // 5. Else,
  691. else {
  692. // a. Let integer be n.
  693. integer = formatted_string.bytes_as_string_view();
  694. // b. Let fraction be undefined.
  695. }
  696. // 6. If the numberFormat.[[UseGrouping]] is false, then
  697. if (number_format.use_grouping() == NumberFormat::UseGrouping::False) {
  698. // a. Append a new Record { [[Type]]: "integer", [[Value]]: integer } as the last element of result.
  699. result.append({ "integer"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(integer)) });
  700. }
  701. // 7. Else,
  702. else {
  703. // a. Let groupSepSymbol be the implementation-, locale-, and numbering system-dependent (ILND) String representing the grouping separator.
  704. auto group_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Group).value_or(","sv);
  705. // b. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer, which may depend on the value of numberFormat.[[UseGrouping]].
  706. auto groups = separate_integer_into_groups(*grouping_sizes, integer, number_format.use_grouping());
  707. // c. Assert: The number of elements in groups List is greater than 0.
  708. VERIFY(!groups.is_empty());
  709. // d. Repeat, while groups List is not empty,
  710. while (!groups.is_empty()) {
  711. // i. Remove the first element from groups and let integerGroup be the value of that element.
  712. auto integer_group = groups.take_first();
  713. // ii. Append a new Record { [[Type]]: "integer", [[Value]]: integerGroup } as the last element of result.
  714. result.append({ "integer"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(integer_group)) });
  715. // iii. If groups List is not empty, then
  716. if (!groups.is_empty()) {
  717. // i. Append a new Record { [[Type]]: "group", [[Value]]: groupSepSymbol } as the last element of result.
  718. result.append({ "group"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(group_sep_symbol)) });
  719. }
  720. }
  721. }
  722. // 8. If fraction is not undefined, then
  723. if (fraction.has_value()) {
  724. // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
  725. auto decimal_sep_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Decimal).value_or("."sv);
  726. // b. Append a new Record { [[Type]]: "decimal", [[Value]]: decimalSepSymbol } as the last element of result.
  727. result.append({ "decimal"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(decimal_sep_symbol)) });
  728. // c. Append a new Record { [[Type]]: "fraction", [[Value]]: fraction } as the last element of result.
  729. result.append({ "fraction"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(*fraction)) });
  730. }
  731. }
  732. // iv. Else if p is equal to "compactSymbol", then
  733. // v. Else if p is equal to "compactName", then
  734. else if (part.starts_with("compactIdentifier:"sv)) {
  735. // Note: Our implementation combines "compactSymbol" and "compactName" into one field, "compactIdentifier".
  736. auto identifier_index = part.substring_view("compactIdentifier:"sv.length()).to_uint();
  737. VERIFY(identifier_index.has_value());
  738. // 1. Let compactSymbol be an ILD string representing exponent in short form, which may depend on x in languages having different plural forms. The implementation must be able to provide this string, or else the pattern would not have a "{compactSymbol}" placeholder.
  739. auto compact_identifier = number_format.compact_format().identifiers[*identifier_index];
  740. // 2. Append a new Record { [[Type]]: "compact", [[Value]]: compactSymbol } as the last element of result.
  741. result.append({ "compact"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(compact_identifier)) });
  742. }
  743. // vi. Else if p is equal to "scientificSeparator", then
  744. else if (part == "scientificSeparator"sv) {
  745. // 1. Let scientificSeparator be the ILND String representing the exponent separator.
  746. auto scientific_separator = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::Exponential).value_or("E"sv);
  747. // 2. Append a new Record { [[Type]]: "exponentSeparator", [[Value]]: scientificSeparator } as the last element of result.
  748. result.append({ "exponentSeparator"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(scientific_separator)) });
  749. }
  750. // vii. Else if p is equal to "scientificExponent", then
  751. else if (part == "scientificExponent"sv) {
  752. // 1. If exponent < 0, then
  753. if (exponent < 0) {
  754. // a. Let minusSignSymbol be the ILND String representing the minus sign.
  755. auto minus_sign_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::MinusSign).value_or("-"sv);
  756. // b. Append a new Record { [[Type]]: "exponentMinusSign", [[Value]]: minusSignSymbol } as the last element of result.
  757. result.append({ "exponentMinusSign"sv, TRY_OR_THROW_OOM(vm, String::from_utf8(minus_sign_symbol)) });
  758. // c. Let exponent be -exponent.
  759. exponent *= -1;
  760. }
  761. // 2. Let exponentResult be ToRawFixed(exponent, 0, 0, 1, undefined).
  762. auto exponent_value = MathematicalValue { static_cast<double>(exponent) };
  763. auto exponent_result = MUST_OR_THROW_OOM(to_raw_fixed(vm, exponent_value, 0, 0, 1, {}));
  764. // FIXME: The spec does not say to do this, but all of major engines perform this replacement.
  765. // Without this, formatting with non-Latin numbering systems will produce non-localized results.
  766. exponent_result.formatted_string = TRY_OR_THROW_OOM(vm, ::Locale::replace_digits_for_number_system(number_format.numbering_system(), exponent_result.formatted_string));
  767. // 3. Append a new Record { [[Type]]: "exponentInteger", [[Value]]: exponentResult.[[FormattedString]] } as the last element of result.
  768. result.append({ "exponentInteger"sv, move(exponent_result.formatted_string) });
  769. }
  770. // viii. Else,
  771. else {
  772. // 1. Let unknown be an ILND String based on x and p.
  773. // 2. Append a new Record { [[Type]]: "unknown", [[Value]]: unknown } as the last element of result.
  774. // LibUnicode doesn't generate any "unknown" patterns.
  775. VERIFY_NOT_REACHED();
  776. }
  777. }
  778. }
  779. // 5. Return result.
  780. return result;
  781. }
  782. // 15.5.6 FormatNumeric ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumber
  783. ThrowCompletionOr<String> format_numeric(VM& vm, NumberFormat& number_format, MathematicalValue number)
  784. {
  785. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  786. auto parts = TRY(partition_number_pattern(vm, number_format, move(number)));
  787. // 2. Let result be the empty String.
  788. ThrowableStringBuilder result(vm);
  789. // 3. For each Record { [[Type]], [[Value]] } part in parts, do
  790. for (auto& part : parts) {
  791. // a. Set result to the string-concatenation of result and part.[[Value]].
  792. TRY(result.append(part.value));
  793. }
  794. // 4. Return result.
  795. return result.to_string();
  796. }
  797. // 15.5.7 FormatNumericToParts ( numberFormat, x ), https://tc39.es/ecma402/#sec-formatnumbertoparts
  798. ThrowCompletionOr<Array*> format_numeric_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue number)
  799. {
  800. auto& realm = *vm.current_realm();
  801. // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
  802. auto parts = TRY(partition_number_pattern(vm, number_format, move(number)));
  803. // 2. Let result be ! ArrayCreate(0).
  804. auto result = MUST(Array::create(realm, 0));
  805. // 3. Let n be 0.
  806. size_t n = 0;
  807. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  808. for (auto& part : parts) {
  809. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  810. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  811. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  812. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  813. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  814. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  815. // d. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  816. MUST(result->create_data_property_or_throw(n, object));
  817. // e. Increment n by 1.
  818. ++n;
  819. }
  820. // 5. Return result.
  821. return result.ptr();
  822. }
  823. static ErrorOr<String> cut_trailing_zeroes(StringView string, int cut)
  824. {
  825. // These steps are exactly the same between ToRawPrecision and ToRawFixed.
  826. // Repeat, while cut > 0 and the last code unit of m is 0x0030 (DIGIT ZERO),
  827. while ((cut > 0) && string.ends_with('0')) {
  828. // Remove the last code unit from m.
  829. string = string.substring_view(0, string.length() - 1);
  830. // Decrease cut by 1.
  831. --cut;
  832. }
  833. // If the last code unit of m is 0x002E (FULL STOP), then
  834. if (string.ends_with('.')) {
  835. // Remove the last code unit from m.
  836. string = string.substring_view(0, string.length() - 1);
  837. }
  838. return String::from_utf8(string);
  839. }
  840. enum class PreferredResult {
  841. LessThanNumber,
  842. GreaterThanNumber,
  843. };
  844. struct RawPrecisionResult {
  845. MathematicalValue number;
  846. int exponent { 0 };
  847. MathematicalValue rounded;
  848. };
  849. // ToRawPrecisionFn, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#eqn-ToRawPrecisionFn
  850. static ThrowCompletionOr<RawPrecisionResult> to_raw_precision_function(VM& vm, MathematicalValue const& number, int precision, PreferredResult mode)
  851. {
  852. RawPrecisionResult result {};
  853. result.exponent = number.logarithmic_floor();
  854. if (number.is_number()) {
  855. result.number = number.divided_by_power(result.exponent - precision + 1);
  856. switch (mode) {
  857. case PreferredResult::LessThanNumber:
  858. result.number = MathematicalValue { floor(result.number.as_number()) };
  859. break;
  860. case PreferredResult::GreaterThanNumber:
  861. result.number = MathematicalValue { ceil(result.number.as_number()) };
  862. break;
  863. }
  864. } else {
  865. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  866. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  867. result.number = number.divided_by_power(result.exponent - precision);
  868. // FIXME: Can we do this without string conversion?
  869. auto digits = MUST_OR_THROW_OOM(result.number.to_string(vm));
  870. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  871. result.number = result.number.divided_by(10);
  872. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  873. result.number = result.number.plus(1);
  874. }
  875. result.rounded = result.number.multiplied_by_power(result.exponent - precision + 1);
  876. return result;
  877. }
  878. // 15.5.8 ToRawPrecision ( x, minPrecision, maxPrecision ), https://tc39.es/ecma402/#sec-torawprecision
  879. // 1.5.8 ToRawPrecision ( x, minPrecision, maxPrecision, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-torawprecision
  880. ThrowCompletionOr<RawFormatResult> to_raw_precision(VM& vm, MathematicalValue const& number, int min_precision, int max_precision, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
  881. {
  882. RawFormatResult result {};
  883. // 1. Let p be maxPrecision.
  884. int precision = max_precision;
  885. int exponent = 0;
  886. // 2. If x = 0, then
  887. if (number.is_zero()) {
  888. // a. Let m be the String consisting of p occurrences of the code unit 0x0030 (DIGIT ZERO).
  889. result.formatted_string = TRY_OR_THROW_OOM(vm, String::repeated('0', precision));
  890. // b. Let e be 0.
  891. exponent = 0;
  892. // c. Let xFinal be 0.
  893. result.rounded_number = MathematicalValue { 0.0 };
  894. }
  895. // 3. Else,
  896. else {
  897. // a. Let n1 and e1 each be an integer and r1 a mathematical value, with r1 = ToRawPrecisionFn(n1, e1, p), such that r1 ≤ x and r1 is maximized.
  898. auto [number1, exponent1, rounded1] = MUST_OR_THROW_OOM(to_raw_precision_function(vm, number, precision, PreferredResult::LessThanNumber));
  899. // b. Let n2 and e2 each be an integer and r2 a mathematical value, with r2 = ToRawPrecisionFn(n2, e2, p), such that r2 ≥ x and r2 is minimized.
  900. auto [number2, exponent2, rounded2] = MUST_OR_THROW_OOM(to_raw_precision_function(vm, number, precision, PreferredResult::GreaterThanNumber));
  901. // c. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  902. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  903. MathematicalValue n;
  904. // d. If r is r1, then
  905. if (rounded == RoundingDecision::LowerValue) {
  906. // i. Let n be n1.
  907. n = move(number1);
  908. // ii. Let e be e1.
  909. exponent = exponent1;
  910. // iii. Let xFinal be r1.
  911. result.rounded_number = move(rounded1);
  912. }
  913. // e. Else,
  914. else {
  915. // i. Let n be n2.
  916. n = move(number2);
  917. // ii. Let e be e2.
  918. exponent = exponent2;
  919. // iii. Let xFinal be r2.
  920. result.rounded_number = move(rounded2);
  921. }
  922. // f. Let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  923. result.formatted_string = MUST_OR_THROW_OOM(n.to_string(vm));
  924. }
  925. // 4. If e ≥ (p – 1), then
  926. if (exponent >= (precision - 1)) {
  927. // a. Set m to the string-concatenation of m and e - p + 1 occurrences of the code unit 0x0030 (DIGIT ZERO).
  928. result.formatted_string = TRY_OR_THROW_OOM(vm,
  929. String::formatted(
  930. "{}{}",
  931. result.formatted_string,
  932. TRY_OR_THROW_OOM(vm, String::repeated('0', exponent - precision + 1))));
  933. // b. Let int be e + 1.
  934. result.digits = exponent + 1;
  935. }
  936. // 5. Else if e ≥ 0, then
  937. else if (exponent >= 0) {
  938. // a. Set m to the string-concatenation of the first e + 1 code units of m, the code unit 0x002E (FULL STOP), and the remaining p - (e + 1) code units of m.
  939. result.formatted_string = TRY_OR_THROW_OOM(vm,
  940. String::formatted(
  941. "{}.{}",
  942. result.formatted_string.bytes_as_string_view().substring_view(0, exponent + 1),
  943. result.formatted_string.bytes_as_string_view().substring_view(exponent + 1)));
  944. // b. Let int be e + 1.
  945. result.digits = exponent + 1;
  946. }
  947. // 6. Else,
  948. else {
  949. // a. Assert: e < 0.
  950. // b. Set m to the string-concatenation of "0.", -(e + 1) occurrences of the code unit 0x0030 (DIGIT ZERO), and m.
  951. result.formatted_string = TRY_OR_THROW_OOM(vm,
  952. String::formatted(
  953. "0.{}{}",
  954. TRY_OR_THROW_OOM(vm, String::repeated('0', -1 * (exponent + 1))),
  955. result.formatted_string));
  956. // c. Let int be 1.
  957. result.digits = 1;
  958. }
  959. // 7. If m contains the code unit 0x002E (FULL STOP) and maxPrecision > minPrecision, then
  960. if (result.formatted_string.contains('.') && (max_precision > min_precision)) {
  961. // a. Let cut be maxPrecision – minPrecision.
  962. int cut = max_precision - min_precision;
  963. // Steps 8b-8c are implemented by cut_trailing_zeroes.
  964. result.formatted_string = TRY_OR_THROW_OOM(vm, cut_trailing_zeroes(result.formatted_string, cut));
  965. }
  966. // 8. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: e–p+1 }.
  967. result.rounding_magnitude = exponent - precision + 1;
  968. return result;
  969. }
  970. struct RawFixedResult {
  971. MathematicalValue number;
  972. MathematicalValue rounded;
  973. };
  974. // ToRawFixedFn, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#eqn-ToRawFixedFn
  975. static ThrowCompletionOr<RawFixedResult> to_raw_fixed_function(VM& vm, MathematicalValue const& number, int fraction, int rounding_increment, PreferredResult mode)
  976. {
  977. RawFixedResult result {};
  978. if (number.is_number()) {
  979. result.number = number.multiplied_by_power(fraction);
  980. switch (mode) {
  981. case PreferredResult::LessThanNumber:
  982. result.number = MathematicalValue { floor(result.number.as_number()) };
  983. break;
  984. case PreferredResult::GreaterThanNumber:
  985. result.number = MathematicalValue { ceil(result.number.as_number()) };
  986. break;
  987. }
  988. } else {
  989. // NOTE: In order to round the BigInt to the proper precision, this computation is initially off by a
  990. // factor of 10. This lets us inspect the ones digit and then round up if needed.
  991. result.number = number.multiplied_by_power(fraction - 1);
  992. // FIXME: Can we do this without string conversion?
  993. auto digits = MUST_OR_THROW_OOM(result.number.to_string(vm));
  994. auto digit = digits.bytes_as_string_view().substring_view(digits.bytes_as_string_view().length() - 1);
  995. result.number = result.number.multiplied_by(10);
  996. if (mode == PreferredResult::GreaterThanNumber && digit.to_uint().value() != 0)
  997. result.number = result.number.plus(1);
  998. }
  999. while (!result.number.modulo_is_zero(rounding_increment)) {
  1000. switch (mode) {
  1001. case PreferredResult::LessThanNumber:
  1002. result.number = result.number.minus(1);
  1003. break;
  1004. case PreferredResult::GreaterThanNumber:
  1005. result.number = result.number.plus(1);
  1006. break;
  1007. }
  1008. }
  1009. result.rounded = result.number.divided_by_power(fraction);
  1010. return result;
  1011. }
  1012. // 15.5.9 ToRawFixed ( x, minInteger, minFraction, maxFraction ), https://tc39.es/ecma402/#sec-torawfixed
  1013. // 1.5.9 ToRawFixed ( x, minFraction, maxFraction, roundingIncrement, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-torawfixed
  1014. ThrowCompletionOr<RawFormatResult> to_raw_fixed(VM& vm, MathematicalValue const& number, int min_fraction, int max_fraction, int rounding_increment, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
  1015. {
  1016. RawFormatResult result {};
  1017. // 1. Let f be maxFraction.
  1018. int fraction = max_fraction;
  1019. // 2. Let n1 be an integer and r1 a mathematical value, with r1 = ToRawFixedFn(n1, f), such that n1 modulo roundingIncrement = 0, r1 ≤ x, and r1 is maximized.
  1020. auto [number1, rounded1] = MUST_OR_THROW_OOM(to_raw_fixed_function(vm, number, fraction, rounding_increment, PreferredResult::LessThanNumber));
  1021. // 3. Let n2 be an integer and r2 a mathematical value, with r2 = ToRawFixedFn(n2, f), such that n2 modulo roundingIncrement = 0, r2 ≥ x, and r2 is minimized.
  1022. auto [number2, rounded2] = MUST_OR_THROW_OOM(to_raw_fixed_function(vm, number, fraction, rounding_increment, PreferredResult::GreaterThanNumber));
  1023. // 4. Let r be ApplyUnsignedRoundingMode(x, r1, r2, unsignedRoundingMode).
  1024. auto rounded = apply_unsigned_rounding_mode(number, rounded1, rounded2, unsigned_rounding_mode);
  1025. MathematicalValue n;
  1026. // 5. If r is r1, then
  1027. if (rounded == RoundingDecision::LowerValue) {
  1028. // a. Let n be n1.
  1029. n = move(number1);
  1030. // b. Let xFinal be r1.
  1031. result.rounded_number = move(rounded1);
  1032. }
  1033. // 6. Else,
  1034. else {
  1035. // a. Let n be n2.
  1036. n = move(number2);
  1037. // b. Let xFinal be r2.
  1038. result.rounded_number = move(rounded2);
  1039. }
  1040. // 7. If n = 0, let m be "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  1041. result.formatted_string = n.is_zero()
  1042. ? String::from_utf8_short_string("0"sv)
  1043. : MUST_OR_THROW_OOM(n.to_string(vm));
  1044. // 8. If f ≠ 0, then
  1045. if (fraction != 0) {
  1046. // a. Let k be the length of m.
  1047. auto decimals = result.formatted_string.bytes_as_string_view().length();
  1048. // b. If k ≤ f, then
  1049. if (decimals <= static_cast<size_t>(fraction)) {
  1050. // i. Let z be the String value consisting of f + 1 - k occurrences of the code unit 0x0030 (DIGIT ZERO).
  1051. auto zeroes = TRY_OR_THROW_OOM(vm, String::repeated('0', fraction + 1 - decimals));
  1052. // ii. Let m be the string-concatenation of z and m.
  1053. result.formatted_string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", zeroes, result.formatted_string));
  1054. // iii. Let k be f + 1.
  1055. decimals = fraction + 1;
  1056. }
  1057. // c. Let a be the first k - f code units of m, and let b be the remaining f code units of m.
  1058. auto a = result.formatted_string.bytes_as_string_view().substring_view(0, decimals - fraction);
  1059. auto b = result.formatted_string.bytes_as_string_view().substring_view(decimals - fraction, fraction);
  1060. // d. Let m be the string-concatenation of a, ".", and b.
  1061. result.formatted_string = TRY_OR_THROW_OOM(vm, String::formatted("{}.{}", a, b));
  1062. // e. Let int be the length of a.
  1063. result.digits = a.length();
  1064. }
  1065. // 9. Else, let int be the length of m.
  1066. else {
  1067. result.digits = result.formatted_string.bytes_as_string_view().length();
  1068. }
  1069. // 10. Let cut be maxFraction – minFraction.
  1070. int cut = max_fraction - min_fraction;
  1071. // Steps 11-12 are implemented by cut_trailing_zeroes.
  1072. result.formatted_string = TRY_OR_THROW_OOM(vm, cut_trailing_zeroes(result.formatted_string, cut));
  1073. // 13. Return the Record { [[FormattedString]]: m, [[RoundedNumber]]: xFinal, [[IntegerDigitsCount]]: int, [[RoundingMagnitude]]: –f }.
  1074. result.rounding_magnitude = -fraction;
  1075. return result;
  1076. }
  1077. // 15.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/ecma402/#sec-getnumberformatpattern
  1078. // 1.5.11 GetNumberFormatPattern ( numberFormat, x ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-getnumberformatpattern
  1079. ThrowCompletionOr<Optional<Variant<StringView, String>>> get_number_format_pattern(VM& vm, NumberFormat& number_format, MathematicalValue const& number, ::Locale::NumberFormat& found_pattern)
  1080. {
  1081. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1082. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1083. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1084. // 4. Let patterns be dataLocaleData.[[patterns]].
  1085. // 5. Assert: patterns is a Record (see 15.3.3).
  1086. Optional<::Locale::NumberFormat> patterns;
  1087. // 6. Let style be numberFormat.[[Style]].
  1088. switch (number_format.style()) {
  1089. // 7. If style is "percent", then
  1090. case NumberFormat::Style::Percent:
  1091. // a. Let patterns be patterns.[[percent]].
  1092. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Percent);
  1093. break;
  1094. // 8. Else if style is "unit", then
  1095. case NumberFormat::Style::Unit: {
  1096. // a. Let unit be numberFormat.[[Unit]].
  1097. // b. Let unitDisplay be numberFormat.[[UnitDisplay]].
  1098. // c. Let patterns be patterns.[[unit]].
  1099. // d. If patterns doesn't have a field [[<unit>]], then
  1100. // i. Let unit be "fallback".
  1101. // e. Let patterns be patterns.[[<unit>]].
  1102. // f. Let patterns be patterns.[[<unitDisplay>]].
  1103. auto formats = ::Locale::get_unit_formats(number_format.data_locale(), number_format.unit(), number_format.unit_display());
  1104. auto plurality = MUST_OR_THROW_OOM(resolve_plural(vm, number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm)));
  1105. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality; }); it != formats.end())
  1106. patterns = move(*it);
  1107. break;
  1108. }
  1109. // 9. Else if style is "currency", then
  1110. case NumberFormat::Style::Currency:
  1111. // a. Let currency be numberFormat.[[Currency]].
  1112. // b. Let currencyDisplay be numberFormat.[[CurrencyDisplay]].
  1113. // c. Let currencySign be numberFormat.[[CurrencySign]].
  1114. // d. Let patterns be patterns.[[currency]].
  1115. // e. If patterns doesn't have a field [[<currency>]], then
  1116. // i. Let currency be "fallback".
  1117. // f. Let patterns be patterns.[[<currency>]].
  1118. // g. Let patterns be patterns.[[<currencyDisplay>]].
  1119. // h. Let patterns be patterns.[[<currencySign>]].
  1120. // Handling of other [[CurrencyDisplay]] options will occur after [[SignDisplay]].
  1121. if (number_format.currency_display() == NumberFormat::CurrencyDisplay::Name) {
  1122. auto formats = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyUnit);
  1123. auto plurality = MUST_OR_THROW_OOM(resolve_plural(vm, number_format, ::Locale::PluralForm::Cardinal, number.to_value(vm)));
  1124. if (auto it = formats.find_if([&](auto& p) { return p.plurality == plurality; }); it != formats.end()) {
  1125. patterns = move(*it);
  1126. break;
  1127. }
  1128. }
  1129. switch (number_format.currency_sign()) {
  1130. case NumberFormat::CurrencySign::Standard:
  1131. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Currency);
  1132. break;
  1133. case NumberFormat::CurrencySign::Accounting:
  1134. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Accounting);
  1135. break;
  1136. }
  1137. break;
  1138. // 10. Else,
  1139. case NumberFormat::Style::Decimal:
  1140. // a. Assert: style is "decimal".
  1141. // b. Let patterns be patterns.[[decimal]].
  1142. patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Decimal);
  1143. break;
  1144. default:
  1145. VERIFY_NOT_REACHED();
  1146. }
  1147. if (!patterns.has_value())
  1148. return OptionalNone {};
  1149. StringView pattern;
  1150. // 11. Let signDisplay be numberFormat.[[SignDisplay]].
  1151. switch (number_format.sign_display()) {
  1152. // 12. If signDisplay is "never", then
  1153. case NumberFormat::SignDisplay::Never:
  1154. // a. Let pattern be patterns.[[zeroPattern]].
  1155. pattern = patterns->zero_format;
  1156. break;
  1157. // 13. Else if signDisplay is "auto", then
  1158. case NumberFormat::SignDisplay::Auto:
  1159. // a. If x is 0 or x > 0 or x is NaN, then
  1160. if (number.is_zero() || number.is_positive() || number.is_nan()) {
  1161. // i. Let pattern be patterns.[[zeroPattern]].
  1162. pattern = patterns->zero_format;
  1163. }
  1164. // b. Else,
  1165. else {
  1166. // i. Let pattern be patterns.[[negativePattern]].
  1167. pattern = patterns->negative_format;
  1168. }
  1169. break;
  1170. // 14. Else if signDisplay is "always", then
  1171. case NumberFormat::SignDisplay::Always:
  1172. // a. If x is 0 or x > 0 or x is NaN, then
  1173. if (number.is_zero() || number.is_positive() || number.is_nan()) {
  1174. // i. Let pattern be patterns.[[positivePattern]].
  1175. pattern = patterns->positive_format;
  1176. }
  1177. // b. Else,
  1178. else {
  1179. // i. Let pattern be patterns.[[negativePattern]].
  1180. pattern = patterns->negative_format;
  1181. }
  1182. break;
  1183. // 15. Else if signDisplay is "exceptZero", then
  1184. case NumberFormat::SignDisplay::ExceptZero:
  1185. // a. If x is 0 or x is -0 or x is NaN, then
  1186. if (number.is_zero() || number.is_negative_zero() || number.is_nan()) {
  1187. // i. Let pattern be patterns.[[zeroPattern]].
  1188. pattern = patterns->zero_format;
  1189. }
  1190. // b. Else if x > 0, then
  1191. else if (number.is_positive()) {
  1192. // i. Let pattern be patterns.[[positivePattern]].
  1193. pattern = patterns->positive_format;
  1194. }
  1195. // c. Else,
  1196. else {
  1197. // i. Let pattern be patterns.[[negativePattern]].
  1198. pattern = patterns->negative_format;
  1199. }
  1200. break;
  1201. // 16. Else,
  1202. case NumberFormat::SignDisplay::Negative:
  1203. // a. Assert: signDisplay is "negative".
  1204. // b. If x is 0 or x is -0 or x > 0 or x is NaN, then
  1205. if (number.is_zero() || number.is_negative_zero() || number.is_positive() || number.is_nan()) {
  1206. // i. Let pattern be patterns.[[zeroPattern]].
  1207. pattern = patterns->zero_format;
  1208. }
  1209. // c. Else,
  1210. else {
  1211. // i. Let pattern be patterns.[[negativePattern]].
  1212. pattern = patterns->negative_format;
  1213. }
  1214. break;
  1215. default:
  1216. VERIFY_NOT_REACHED();
  1217. }
  1218. found_pattern = patterns.release_value();
  1219. // Handling of steps 9b/9g: Depending on the currency display and the format pattern found above,
  1220. // we might need to mutate the format pattern to inject a space between the currency display and
  1221. // the currency number.
  1222. if (number_format.style() == NumberFormat::Style::Currency) {
  1223. auto modified_pattern = TRY_OR_THROW_OOM(vm, ::Locale::augment_currency_format_pattern(number_format.resolve_currency_display(), pattern));
  1224. if (modified_pattern.has_value())
  1225. return modified_pattern.release_value();
  1226. }
  1227. // 16. Return pattern.
  1228. return pattern;
  1229. }
  1230. // 15.5.12 GetNotationSubPattern ( numberFormat, exponent ), https://tc39.es/ecma402/#sec-getnotationsubpattern
  1231. Optional<StringView> get_notation_sub_pattern(NumberFormat& number_format, int exponent)
  1232. {
  1233. // 1. Let localeData be %NumberFormat%.[[LocaleData]].
  1234. // 2. Let dataLocale be numberFormat.[[DataLocale]].
  1235. // 3. Let dataLocaleData be localeData.[[<dataLocale>]].
  1236. // 4. Let notationSubPatterns be dataLocaleData.[[notationSubPatterns]].
  1237. // 5. Assert: notationSubPatterns is a Record (see 15.3.3).
  1238. // 6. Let notation be numberFormat.[[Notation]].
  1239. auto notation = number_format.notation();
  1240. // 7. If notation is "scientific" or notation is "engineering", then
  1241. if ((notation == NumberFormat::Notation::Scientific) || (notation == NumberFormat::Notation::Engineering)) {
  1242. // a. Return notationSubPatterns.[[scientific]].
  1243. auto notation_sub_patterns = ::Locale::get_standard_number_system_format(number_format.data_locale(), number_format.numbering_system(), ::Locale::StandardNumberFormatType::Scientific);
  1244. if (!notation_sub_patterns.has_value())
  1245. return {};
  1246. return notation_sub_patterns->zero_format;
  1247. }
  1248. // 8. Else if exponent is not 0, then
  1249. else if (exponent != 0) {
  1250. // a. Assert: notation is "compact".
  1251. VERIFY(notation == NumberFormat::Notation::Compact);
  1252. // b. Let compactDisplay be numberFormat.[[CompactDisplay]].
  1253. // c. Let compactPatterns be notationSubPatterns.[[compact]].[[<compactDisplay>]].
  1254. // d. Return compactPatterns.[[<exponent>]].
  1255. if (number_format.has_compact_format())
  1256. return number_format.compact_format().zero_format;
  1257. }
  1258. // 9. Else,
  1259. // a. Return "{number}".
  1260. return "{number}"sv;
  1261. }
  1262. // 15.5.13 ComputeExponent ( numberFormat, x ), https://tc39.es/ecma402/#sec-computeexponent
  1263. ThrowCompletionOr<int> compute_exponent(VM& vm, NumberFormat& number_format, MathematicalValue number)
  1264. {
  1265. // 1. If x = 0, then
  1266. if (number.is_zero()) {
  1267. // a. Return 0.
  1268. return 0;
  1269. }
  1270. // 2. If x < 0, then
  1271. if (number.is_negative()) {
  1272. // a. Let x = -x.
  1273. number.negate();
  1274. }
  1275. // 3. Let magnitude be the base 10 logarithm of x rounded down to the nearest integer.
  1276. int magnitude = number.logarithmic_floor();
  1277. // 4. Let exponent be ComputeExponentForMagnitude(numberFormat, magnitude).
  1278. int exponent = compute_exponent_for_magnitude(number_format, magnitude);
  1279. // 5. Let x be x × 10^(-exponent).
  1280. number = number.multiplied_by_power(-exponent);
  1281. // 6. Let formatNumberResult be FormatNumericToString(numberFormat, x).
  1282. auto format_number_result = MUST_OR_THROW_OOM(format_numeric_to_string(vm, number_format, move(number)));
  1283. // 7. If formatNumberResult.[[RoundedNumber]] = 0, then
  1284. if (format_number_result.rounded_number.is_zero()) {
  1285. // a. Return exponent.
  1286. return exponent;
  1287. }
  1288. // 8. Let newMagnitude be the base 10 logarithm of formatNumberResult.[[RoundedNumber]] rounded down to the nearest integer.
  1289. int new_magnitude = format_number_result.rounded_number.logarithmic_floor();
  1290. // 9. If newMagnitude is magnitude - exponent, then
  1291. if (new_magnitude == magnitude - exponent) {
  1292. // a. Return exponent.
  1293. return exponent;
  1294. }
  1295. // 10. Return ComputeExponentForMagnitude(numberFormat, magnitude + 1).
  1296. return compute_exponent_for_magnitude(number_format, magnitude + 1);
  1297. }
  1298. // 15.5.14 ComputeExponentForMagnitude ( numberFormat, magnitude ), https://tc39.es/ecma402/#sec-computeexponentformagnitude
  1299. int compute_exponent_for_magnitude(NumberFormat& number_format, int magnitude)
  1300. {
  1301. // 1. Let notation be numberFormat.[[Notation]].
  1302. switch (number_format.notation()) {
  1303. // 2. If notation is "standard", then
  1304. case NumberFormat::Notation::Standard:
  1305. // a. Return 0.
  1306. return 0;
  1307. // 3. Else if notation is "scientific", then
  1308. case NumberFormat::Notation::Scientific:
  1309. // a. Return magnitude.
  1310. return magnitude;
  1311. // 4. Else if notation is "engineering", then
  1312. case NumberFormat::Notation::Engineering: {
  1313. // a. Let thousands be the greatest integer that is not greater than magnitude / 3.
  1314. double thousands = floor(static_cast<double>(magnitude) / 3.0);
  1315. // b. Return thousands × 3.
  1316. return static_cast<int>(thousands) * 3;
  1317. }
  1318. // 5. Else,
  1319. case NumberFormat::Notation::Compact: {
  1320. // a. Assert: notation is "compact".
  1321. VERIFY(number_format.has_compact_display());
  1322. // b. Let exponent be an implementation- and locale-dependent (ILD) integer by which to scale a number of the given magnitude in compact notation for the current locale.
  1323. // c. Return exponent.
  1324. Vector<::Locale::NumberFormat> format_rules;
  1325. if (number_format.style() == NumberFormat::Style::Currency)
  1326. format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::CurrencyShort);
  1327. else if (number_format.compact_display() == NumberFormat::CompactDisplay::Long)
  1328. format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalLong);
  1329. else
  1330. format_rules = ::Locale::get_compact_number_system_formats(number_format.data_locale(), number_format.numbering_system(), ::Locale::CompactNumberFormatType::DecimalShort);
  1331. ::Locale::NumberFormat const* best_number_format = nullptr;
  1332. for (auto const& format_rule : format_rules) {
  1333. if (format_rule.magnitude > magnitude)
  1334. break;
  1335. best_number_format = &format_rule;
  1336. }
  1337. if (best_number_format == nullptr)
  1338. return 0;
  1339. number_format.set_compact_format(*best_number_format);
  1340. return best_number_format->exponent;
  1341. }
  1342. default:
  1343. VERIFY_NOT_REACHED();
  1344. }
  1345. }
  1346. // 1.5.16 ToIntlMathematicalValue ( value ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-tointlmathematicalvalue
  1347. ThrowCompletionOr<MathematicalValue> to_intl_mathematical_value(VM& vm, Value value)
  1348. {
  1349. // 1. Let primValue be ? ToPrimitive(value, number).
  1350. auto primitive_value = TRY(value.to_primitive(vm, Value::PreferredType::Number));
  1351. // 2. If Type(primValue) is BigInt, return the mathematical value of primValue.
  1352. if (primitive_value.is_bigint())
  1353. return primitive_value.as_bigint().big_integer();
  1354. // FIXME: The remaining steps are being refactored into a new Runtime Semantic, StringIntlMV.
  1355. // We short-circuit some of these steps to avoid known pitfalls.
  1356. // See: https://github.com/tc39/proposal-intl-numberformat-v3/pull/82
  1357. if (!primitive_value.is_string()) {
  1358. auto number = TRY(primitive_value.to_number(vm));
  1359. return number.as_double();
  1360. }
  1361. // 3. If Type(primValue) is String,
  1362. // a. Let str be primValue.
  1363. auto string = TRY(primitive_value.as_string().utf8_string());
  1364. // Step 4 handled separately by the FIXME above.
  1365. // 5. If the grammar cannot interpret str as an expansion of StringNumericLiteral, return not-a-number.
  1366. // 6. Let mv be the MV, a mathematical value, of ? ToNumber(str), as described in 7.1.4.1.1.
  1367. auto mathematical_value = TRY(primitive_value.to_number(vm)).as_double();
  1368. // 7. If mv is 0 and the first non white space code point in str is -, return negative-zero.
  1369. if (mathematical_value == 0.0 && string.bytes_as_string_view().trim_whitespace(TrimMode::Left).starts_with('-'))
  1370. return MathematicalValue::Symbol::NegativeZero;
  1371. // 8. If mv is 10^10000 and str contains Infinity, return positive-infinity.
  1372. if (mathematical_value == pow(10, 10000) && string.contains("Infinity"sv))
  1373. return MathematicalValue::Symbol::PositiveInfinity;
  1374. // 9. If mv is -10^10000 and str contains Infinity, return negative-infinity.
  1375. if (mathematical_value == pow(-10, 10000) && string.contains("Infinity"sv))
  1376. return MathematicalValue::Symbol::NegativeInfinity;
  1377. // 10. Return mv.
  1378. return mathematical_value;
  1379. }
  1380. // 1.5.17 GetUnsignedRoundingMode ( roundingMode, isNegative ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-getunsignedroundingmode
  1381. NumberFormat::UnsignedRoundingMode get_unsigned_rounding_mode(NumberFormat::RoundingMode rounding_mode, bool is_negative)
  1382. {
  1383. // 1. If isNegative is true, return the specification type in the third column of Table 2 where the first column is roundingMode and the second column is "negative".
  1384. // 2. Else, return the specification type in the third column of Table 2 where the first column is roundingMode and the second column is "positive".
  1385. // Table 2: Conversion from rounding mode to unsigned rounding mode, https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#table-intl-unsigned-rounding-modes
  1386. switch (rounding_mode) {
  1387. case NumberFormat::RoundingMode::Ceil:
  1388. return is_negative ? NumberFormat::UnsignedRoundingMode::Zero : NumberFormat::UnsignedRoundingMode::Infinity;
  1389. case NumberFormat::RoundingMode::Floor:
  1390. return is_negative ? NumberFormat::UnsignedRoundingMode::Infinity : NumberFormat::UnsignedRoundingMode::Zero;
  1391. case NumberFormat::RoundingMode::Expand:
  1392. return NumberFormat::UnsignedRoundingMode::Infinity;
  1393. case NumberFormat::RoundingMode::Trunc:
  1394. return NumberFormat::UnsignedRoundingMode::Zero;
  1395. case NumberFormat::RoundingMode::HalfCeil:
  1396. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfZero : NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1397. case NumberFormat::RoundingMode::HalfFloor:
  1398. return is_negative ? NumberFormat::UnsignedRoundingMode::HalfInfinity : NumberFormat::UnsignedRoundingMode::HalfZero;
  1399. case NumberFormat::RoundingMode::HalfExpand:
  1400. return NumberFormat::UnsignedRoundingMode::HalfInfinity;
  1401. case NumberFormat::RoundingMode::HalfTrunc:
  1402. return NumberFormat::UnsignedRoundingMode::HalfZero;
  1403. case NumberFormat::RoundingMode::HalfEven:
  1404. return NumberFormat::UnsignedRoundingMode::HalfEven;
  1405. default:
  1406. VERIFY_NOT_REACHED();
  1407. };
  1408. }
  1409. // 1.5.18 ApplyUnsignedRoundingMode ( x, r1, r2, unsignedRoundingMode ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-applyunsignedroundingmode
  1410. RoundingDecision apply_unsigned_rounding_mode(MathematicalValue const& x, MathematicalValue const& r1, MathematicalValue const& r2, Optional<NumberFormat::UnsignedRoundingMode> const& unsigned_rounding_mode)
  1411. {
  1412. // 1. If x is equal to r1, return r1.
  1413. if (x.is_equal_to(r1))
  1414. return RoundingDecision::LowerValue;
  1415. // FIXME: We skip this assertion due floating point inaccuracies. For example, entering "1.2345"
  1416. // in the JS REPL results in "1.234499999999999", and may cause this assertion to fail.
  1417. //
  1418. // This should be resolved when the "Intl mathematical value" is implemented to support
  1419. // arbitrarily precise decimals.
  1420. // https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#intl-mathematical-value
  1421. // 2. Assert: r1 < x < r2.
  1422. // 3. Assert: unsignedRoundingMode is not undefined.
  1423. VERIFY(unsigned_rounding_mode.has_value());
  1424. // 4. If unsignedRoundingMode is zero, return r1.
  1425. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Zero)
  1426. return RoundingDecision::LowerValue;
  1427. // 5. If unsignedRoundingMode is infinity, return r2.
  1428. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::Infinity)
  1429. return RoundingDecision::HigherValue;
  1430. // 6. Let d1 be x – r1.
  1431. auto d1 = x.minus(r1);
  1432. // 7. Let d2 be r2 – x.
  1433. auto d2 = r2.minus(x);
  1434. // 8. If d1 < d2, return r1.
  1435. if (d1.is_less_than(d2))
  1436. return RoundingDecision::LowerValue;
  1437. // 9. If d2 < d1, return r2.
  1438. if (d2.is_less_than(d1))
  1439. return RoundingDecision::HigherValue;
  1440. // 10. Assert: d1 is equal to d2.
  1441. VERIFY(d1.is_equal_to(d2));
  1442. // 11. If unsignedRoundingMode is half-zero, return r1.
  1443. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfZero)
  1444. return RoundingDecision::LowerValue;
  1445. // 12. If unsignedRoundingMode is half-infinity, return r2.
  1446. if (unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfInfinity)
  1447. return RoundingDecision::HigherValue;
  1448. // 13. Assert: unsignedRoundingMode is half-even.
  1449. VERIFY(unsigned_rounding_mode == NumberFormat::UnsignedRoundingMode::HalfEven);
  1450. // 14. Let cardinality be (r1 / (r2 – r1)) modulo 2.
  1451. auto cardinality = r1.divided_by(r2.minus(r1));
  1452. // 15. If cardinality is 0, return r1.
  1453. if (cardinality.modulo_is_zero(2))
  1454. return RoundingDecision::LowerValue;
  1455. // 16. Return r2.
  1456. return RoundingDecision::HigherValue;
  1457. }
  1458. // 1.5.19 PartitionNumberRangePattern ( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-partitionnumberrangepattern
  1459. ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_number_range_pattern(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1460. {
  1461. // 1. If x is NaN or y is NaN, throw a RangeError exception.
  1462. if (start.is_nan())
  1463. return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaN, "start"sv);
  1464. if (end.is_nan())
  1465. return vm.throw_completion<RangeError>(ErrorType::IntlNumberIsNaN, "end"sv);
  1466. // 2. Let result be a new empty List.
  1467. Vector<PatternPartitionWithSource> result;
  1468. // 3. Let xResult be ? PartitionNumberPattern(numberFormat, x).
  1469. auto raw_start_result = TRY(partition_number_pattern(vm, number_format, move(start)));
  1470. auto start_result = PatternPartitionWithSource::create_from_parent_list(move(raw_start_result));
  1471. // 4. Let yResult be ? PartitionNumberPattern(numberFormat, y).
  1472. auto raw_end_result = TRY(partition_number_pattern(vm, number_format, move(end)));
  1473. auto end_result = PatternPartitionWithSource::create_from_parent_list(move(raw_end_result));
  1474. // 5. If xResult is equal to yResult, then
  1475. if (start_result == end_result) {
  1476. // a. Let appxResult be ? FormatApproximately(numberFormat, xResult).
  1477. auto approximate_result = TRY(format_approximately(vm, number_format, move(start_result)));
  1478. // b. For each r in appxResult, do
  1479. for (auto& result : approximate_result) {
  1480. // i. Set r.[[Source]] to "shared".
  1481. result.source = "shared"sv;
  1482. }
  1483. // c. Return appxResult.
  1484. return approximate_result;
  1485. }
  1486. // 6. For each r in xResult, do
  1487. for (auto& part : start_result) {
  1488. // i. Set r.[[Source]] to "startRange".
  1489. part.source = "startRange"sv;
  1490. }
  1491. // 7. Add all elements in xResult to result in order.
  1492. result = move(start_result);
  1493. // 8. Let rangeSeparator be an ILND String value used to separate two numbers.
  1494. auto range_separator_symbol = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::RangeSeparator).value_or("-"sv);
  1495. auto range_separator = TRY_OR_THROW_OOM(vm, ::Locale::augment_range_pattern(range_separator_symbol, result.last().value, end_result[0].value));
  1496. // 9. Append a new Record { [[Type]]: "literal", [[Value]]: rangeSeparator, [[Source]]: "shared" } element to result.
  1497. PatternPartitionWithSource part;
  1498. part.type = "literal"sv;
  1499. part.value = range_separator.has_value()
  1500. ? range_separator.release_value()
  1501. : TRY_OR_THROW_OOM(vm, String::from_utf8(range_separator_symbol));
  1502. part.source = "shared"sv;
  1503. result.append(move(part));
  1504. // 10. For each r in yResult, do
  1505. for (auto& part : end_result) {
  1506. // a. Set r.[[Source]] to "endRange".
  1507. part.source = "endRange"sv;
  1508. }
  1509. // 11. Add all elements in yResult to result in order.
  1510. result.extend(move(end_result));
  1511. // 12. Return ! CollapseNumberRange(result).
  1512. return collapse_number_range(move(result));
  1513. }
  1514. // 1.5.20 FormatApproximately ( numberFormat, result ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatapproximately
  1515. ThrowCompletionOr<Vector<PatternPartitionWithSource>> format_approximately(VM& vm, NumberFormat& number_format, Vector<PatternPartitionWithSource> result)
  1516. {
  1517. // 1. Let i be an index into result, determined by an implementation-defined algorithm based on numberFormat and result.
  1518. // 2. Let approximatelySign be an ILND String value used to signify that a number is approximate.
  1519. auto approximately_sign = ::Locale::get_number_system_symbol(number_format.data_locale(), number_format.numbering_system(), ::Locale::NumericSymbol::ApproximatelySign).value_or("~"sv);
  1520. // 3. Insert a new Record { [[Type]]: "approximatelySign", [[Value]]: approximatelySign } at index i in result.
  1521. PatternPartitionWithSource partition;
  1522. partition.type = "approximatelySign"sv;
  1523. partition.value = TRY_OR_THROW_OOM(vm, String::from_utf8(approximately_sign));
  1524. result.insert_before_matching(move(partition), [](auto const& part) {
  1525. return part.type.is_one_of("integer"sv, "decimal"sv, "plusSign"sv, "minusSign"sv, "percentSign"sv, "currency"sv);
  1526. });
  1527. // 4. Return result.
  1528. return result;
  1529. }
  1530. // 1.5.21 CollapseNumberRange ( result ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-collapsenumberrange
  1531. Vector<PatternPartitionWithSource> collapse_number_range(Vector<PatternPartitionWithSource> result)
  1532. {
  1533. // Returning result unmodified is guaranteed to be a correct implementation of CollapseNumberRange.
  1534. return result;
  1535. }
  1536. // 1.5.22 FormatNumericRange( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumericrange
  1537. ThrowCompletionOr<String> format_numeric_range(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1538. {
  1539. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1540. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1541. // 2. Let result be the empty String.
  1542. ThrowableStringBuilder result(vm);
  1543. // 3. For each part in parts, do
  1544. for (auto& part : parts) {
  1545. // a. Set result to the string-concatenation of result and part.[[Value]].
  1546. TRY(result.append(part.value));
  1547. }
  1548. // 4. Return result.
  1549. return result.to_string();
  1550. }
  1551. // 1.5.23 FormatNumericRangeToParts( numberFormat, x, y ), https://tc39.es/proposal-intl-numberformat-v3/out/numberformat/proposed.html#sec-formatnumericrangetoparts
  1552. ThrowCompletionOr<Array*> format_numeric_range_to_parts(VM& vm, NumberFormat& number_format, MathematicalValue start, MathematicalValue end)
  1553. {
  1554. auto& realm = *vm.current_realm();
  1555. // 1. Let parts be ? PartitionNumberRangePattern(numberFormat, x, y).
  1556. auto parts = TRY(partition_number_range_pattern(vm, number_format, move(start), move(end)));
  1557. // 2. Let result be ! ArrayCreate(0).
  1558. auto result = MUST(Array::create(realm, 0));
  1559. // 3. Let n be 0.
  1560. size_t n = 0;
  1561. // 4. For each Record { [[Type]], [[Value]] } part in parts, do
  1562. for (auto& part : parts) {
  1563. // a. Let O be OrdinaryObjectCreate(%Object.prototype%).
  1564. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  1565. // b. Perform ! CreateDataPropertyOrThrow(O, "type", part.[[Type]]).
  1566. MUST(object->create_data_property_or_throw(vm.names.type, PrimitiveString::create(vm, part.type)));
  1567. // c. Perform ! CreateDataPropertyOrThrow(O, "value", part.[[Value]]).
  1568. MUST(object->create_data_property_or_throw(vm.names.value, PrimitiveString::create(vm, move(part.value))));
  1569. // d. Perform ! CreateDataPropertyOrThrow(O, "source", part.[[Source]]).
  1570. MUST(object->create_data_property_or_throw(vm.names.source, PrimitiveString::create(vm, part.source)));
  1571. // e. Perform ! CreateDataPropertyOrThrow(result, ! ToString(n), O).
  1572. MUST(result->create_data_property_or_throw(n, object));
  1573. // f. Increment n by 1.
  1574. ++n;
  1575. }
  1576. // 5. Return result.
  1577. return result.ptr();
  1578. }
  1579. }