NumberPrototype.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Text;
  4. using Jint.Collections;
  5. using Jint.Native.Number.Dtoa;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Descriptors;
  9. using Jint.Runtime.Interop;
  10. namespace Jint.Native.Number
  11. {
  12. /// <summary>
  13. /// https://tc39.es/ecma262/#sec-properties-of-the-number-prototype-object
  14. /// </summary>
  15. internal sealed class NumberPrototype : NumberInstance
  16. {
  17. private readonly Realm _realm;
  18. private readonly NumberConstructor _constructor;
  19. internal NumberPrototype(
  20. Engine engine,
  21. Realm realm,
  22. NumberConstructor constructor,
  23. ObjectPrototype objectPrototype)
  24. : base(engine, InternalTypes.Object | InternalTypes.PlainObject)
  25. {
  26. _prototype = objectPrototype;
  27. _realm = realm;
  28. _constructor = constructor;
  29. }
  30. protected override void Initialize()
  31. {
  32. var properties = new PropertyDictionary(8, checkExistingKeys: false)
  33. {
  34. ["constructor"] = new PropertyDescriptor(_constructor, true, false, true),
  35. ["toString"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toString", ToNumberString, 1, PropertyFlag.Configurable), true, false, true),
  36. ["toLocaleString"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), true, false, true),
  37. ["valueOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "valueOf", ValueOf, 0, PropertyFlag.Configurable), true, false, true),
  38. ["toFixed"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toFixed", ToFixed, 1, PropertyFlag.Configurable), true, false, true),
  39. ["toExponential"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toExponential", ToExponential, 1, PropertyFlag.Configurable), true, false, true),
  40. ["toPrecision"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "toPrecision", ToPrecision, 1, PropertyFlag.Configurable), true, false, true)
  41. };
  42. SetProperties(properties);
  43. }
  44. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  45. {
  46. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  47. {
  48. ExceptionHelper.ThrowTypeError(_realm);
  49. }
  50. var m = TypeConverter.ToNumber(thisObject);
  51. if (double.IsNaN(m))
  52. {
  53. return "NaN";
  54. }
  55. if (m == 0)
  56. {
  57. return JsString.NumberZeroString;
  58. }
  59. if (m < 0)
  60. {
  61. return "-" + ToLocaleString(-m, arguments);
  62. }
  63. if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
  64. {
  65. return "Infinity";
  66. }
  67. if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
  68. {
  69. return "-Infinity";
  70. }
  71. var numberFormat = (NumberFormatInfo) Engine.Options.Culture.NumberFormat.Clone();
  72. try
  73. {
  74. if (arguments.Length > 0 && arguments[0].IsString())
  75. {
  76. var cultureArgument = arguments[0].ToString();
  77. numberFormat = (NumberFormatInfo) CultureInfo.GetCultureInfo(cultureArgument).NumberFormat.Clone();
  78. }
  79. int decDigitCount = NumberIntlHelper.GetDecimalDigitCount(m);
  80. numberFormat.NumberDecimalDigits = decDigitCount;
  81. }
  82. catch (CultureNotFoundException)
  83. {
  84. ExceptionHelper.ThrowRangeError(_realm, "Incorrect locale information provided");
  85. }
  86. return m.ToString("n", numberFormat);
  87. }
  88. private JsValue ValueOf(JsValue thisObject, JsValue[] arguments)
  89. {
  90. if (thisObject is NumberInstance ni)
  91. {
  92. return ni.NumberData;
  93. }
  94. if (thisObject is JsNumber)
  95. {
  96. return thisObject;
  97. }
  98. ExceptionHelper.ThrowTypeError(_realm);
  99. return null;
  100. }
  101. private const double Ten21 = 1e21;
  102. private JsValue ToFixed(JsValue thisObject, JsValue[] arguments)
  103. {
  104. var f = (int) TypeConverter.ToInteger(arguments.At(0, 0));
  105. if (f < 0 || f > 100)
  106. {
  107. ExceptionHelper.ThrowRangeError(_realm, "fractionDigits argument must be between 0 and 100");
  108. }
  109. // limitation with .NET, max is 99
  110. if (f == 100)
  111. {
  112. ExceptionHelper.ThrowRangeError(_realm, "100 fraction digits is not supported due to .NET format specifier limitation");
  113. }
  114. var x = TypeConverter.ToNumber(thisObject);
  115. if (double.IsNaN(x))
  116. {
  117. return "NaN";
  118. }
  119. if (x >= Ten21)
  120. {
  121. return ToNumberString(x);
  122. }
  123. // handle non-decimal with greater precision
  124. if (System.Math.Abs(x - (long) x) < JsNumber.DoubleIsIntegerTolerance)
  125. {
  126. return ((long) x).ToString("f" + f, CultureInfo.InvariantCulture);
  127. }
  128. return x.ToString("f" + f, CultureInfo.InvariantCulture);
  129. }
  130. /// <summary>
  131. /// https://www.ecma-international.org/ecma-262/6.0/#sec-number.prototype.toexponential
  132. /// </summary>
  133. private JsValue ToExponential(JsValue thisObject, JsValue[] arguments)
  134. {
  135. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  136. {
  137. ExceptionHelper.ThrowTypeError(_realm);
  138. }
  139. var x = TypeConverter.ToNumber(thisObject);
  140. var fractionDigits = arguments.At(0);
  141. if (fractionDigits.IsUndefined())
  142. {
  143. fractionDigits = JsNumber.PositiveZero;
  144. }
  145. var f = (int) TypeConverter.ToInteger(fractionDigits);
  146. if (double.IsNaN(x))
  147. {
  148. return "NaN";
  149. }
  150. if (double.IsInfinity(x))
  151. {
  152. return thisObject.ToString();
  153. }
  154. if (f < 0 || f > 100)
  155. {
  156. ExceptionHelper.ThrowRangeError(_realm, "fractionDigits argument must be between 0 and 100");
  157. }
  158. if (arguments.At(0).IsUndefined())
  159. {
  160. f = -1;
  161. }
  162. bool negative = false;
  163. if (x < 0)
  164. {
  165. x = -x;
  166. negative = true;
  167. }
  168. int decimalPoint;
  169. DtoaBuilder dtoaBuilder;
  170. if (f == -1)
  171. {
  172. dtoaBuilder = new DtoaBuilder();
  173. DtoaNumberFormatter.DoubleToAscii(
  174. dtoaBuilder,
  175. x,
  176. DtoaMode.Shortest,
  177. requested_digits: 0,
  178. out _,
  179. out decimalPoint);
  180. f = dtoaBuilder.Length - 1;
  181. }
  182. else
  183. {
  184. dtoaBuilder = new DtoaBuilder(101);
  185. DtoaNumberFormatter.DoubleToAscii(
  186. dtoaBuilder,
  187. x,
  188. DtoaMode.Precision,
  189. requested_digits: f + 1,
  190. out _,
  191. out decimalPoint);
  192. }
  193. Debug.Assert(dtoaBuilder.Length > 0);
  194. Debug.Assert(dtoaBuilder.Length <= f + 1);
  195. int exponent = decimalPoint - 1;
  196. var result = CreateExponentialRepresentation(dtoaBuilder, exponent, negative, f+1);
  197. return result;
  198. }
  199. private JsValue ToPrecision(JsValue thisObject, JsValue[] arguments)
  200. {
  201. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  202. {
  203. ExceptionHelper.ThrowTypeError(_realm);
  204. }
  205. var x = TypeConverter.ToNumber(thisObject);
  206. var precisionArgument = arguments.At(0);
  207. if (precisionArgument.IsUndefined())
  208. {
  209. return TypeConverter.ToString(x);
  210. }
  211. var p = (int) TypeConverter.ToInteger(precisionArgument);
  212. if (double.IsNaN(x))
  213. {
  214. return "NaN";
  215. }
  216. if (double.IsInfinity(x))
  217. {
  218. return thisObject.ToString();
  219. }
  220. if (p < 1 || p > 100)
  221. {
  222. ExceptionHelper.ThrowRangeError(_realm, "precision must be between 1 and 100");
  223. }
  224. var dtoaBuilder = new DtoaBuilder(101);
  225. DtoaNumberFormatter.DoubleToAscii(
  226. dtoaBuilder,
  227. x,
  228. DtoaMode.Precision,
  229. p,
  230. out var negative,
  231. out var decimalPoint);
  232. int exponent = decimalPoint - 1;
  233. if (exponent < -6 || exponent >= p)
  234. {
  235. return CreateExponentialRepresentation(dtoaBuilder, exponent, negative, p);
  236. }
  237. var sb = new ValueStringBuilder(stackalloc char[64]);
  238. // Use fixed notation.
  239. if (negative)
  240. {
  241. sb.Append('-');
  242. }
  243. if (decimalPoint <= 0)
  244. {
  245. sb.Append("0.");
  246. sb.Append('0', -decimalPoint);
  247. sb.Append(dtoaBuilder._chars.AsSpan(0, dtoaBuilder.Length));
  248. sb.Append('0', p - dtoaBuilder.Length);
  249. }
  250. else
  251. {
  252. int m = System.Math.Min(dtoaBuilder.Length, decimalPoint);
  253. sb.Append(dtoaBuilder._chars.AsSpan(0, m));
  254. sb.Append('0', System.Math.Max(0, decimalPoint - dtoaBuilder.Length));
  255. if (decimalPoint < p)
  256. {
  257. sb.Append('.');
  258. var extra = negative ? 2 : 1;
  259. if (dtoaBuilder.Length > decimalPoint)
  260. {
  261. int len = dtoaBuilder.Length - decimalPoint;
  262. int n = System.Math.Min(len, p - (sb.Length - extra));
  263. sb.Append(dtoaBuilder._chars.AsSpan(decimalPoint, n));
  264. }
  265. sb.Append('0', System.Math.Max(0, extra + (p - sb.Length)));
  266. }
  267. }
  268. return sb.ToString();
  269. }
  270. private static string CreateExponentialRepresentation(
  271. DtoaBuilder buffer,
  272. int exponent,
  273. bool negative,
  274. int significantDigits)
  275. {
  276. bool negativeExponent = false;
  277. if (exponent < 0)
  278. {
  279. negativeExponent = true;
  280. exponent = -exponent;
  281. }
  282. var sb = new ValueStringBuilder(stackalloc char[64]);
  283. if (negative)
  284. {
  285. sb.Append('-');
  286. }
  287. sb.Append(buffer._chars[0]);
  288. if (significantDigits != 1)
  289. {
  290. sb.Append('.');
  291. sb.Append(buffer._chars.AsSpan(1, buffer.Length - 1));
  292. int length = buffer.Length;
  293. sb.Append('0', significantDigits - length);
  294. }
  295. sb.Append('e');
  296. sb.Append(negativeExponent ? '-' : '+');
  297. sb.Append(exponent.ToString(CultureInfo.InvariantCulture));
  298. return sb.ToString();
  299. }
  300. private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
  301. {
  302. if (!thisObject.IsNumber() && (ReferenceEquals(thisObject.TryCast<NumberInstance>(), null)))
  303. {
  304. ExceptionHelper.ThrowTypeError(_realm);
  305. }
  306. var radix = arguments.At(0).IsUndefined()
  307. ? 10
  308. : (int) TypeConverter.ToInteger(arguments.At(0));
  309. if (radix < 2 || radix > 36)
  310. {
  311. ExceptionHelper.ThrowRangeError(_realm, "radix must be between 2 and 36");
  312. }
  313. var x = TypeConverter.ToNumber(thisObject);
  314. if (double.IsNaN(x))
  315. {
  316. return "NaN";
  317. }
  318. if (x == 0)
  319. {
  320. return JsString.NumberZeroString;
  321. }
  322. if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
  323. {
  324. return "Infinity";
  325. }
  326. if (x < 0)
  327. {
  328. return "-" + ToNumberString(-x, arguments);
  329. }
  330. if (radix == 10)
  331. {
  332. return ToNumberString(x);
  333. }
  334. var integer = (long) x;
  335. var fraction = x - integer;
  336. string result = NumberPrototype.ToBase(integer, radix);
  337. if (fraction != 0)
  338. {
  339. result += "." + NumberPrototype.ToFractionBase(fraction, radix);
  340. }
  341. return result;
  342. }
  343. internal static string ToBase(long n, int radix)
  344. {
  345. const string Digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  346. if (n == 0)
  347. {
  348. return "0";
  349. }
  350. using var sb = new ValueStringBuilder(stackalloc char[64]);
  351. while (n > 0)
  352. {
  353. var digit = (int) (n % radix);
  354. n /= radix;
  355. sb.Append(Digits[digit]);
  356. }
  357. #if NET6_0_OR_GREATER
  358. var charArray = sb.Length < 512 ? stackalloc char[sb.Length] : new char[sb.Length];
  359. sb.AsSpan().CopyTo(charArray);
  360. charArray.Reverse();
  361. #else
  362. var charArray = new char[sb.Length];
  363. sb.AsSpan().CopyTo(charArray);
  364. System.Array.Reverse(charArray);
  365. #endif
  366. return new string(charArray);
  367. }
  368. internal static string ToFractionBase(double n, int radix)
  369. {
  370. // based on the repeated multiplication method
  371. // http://www.mathpath.org/concepts/Num/frac.htm
  372. const string Digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  373. if (n == 0)
  374. {
  375. return "0";
  376. }
  377. using var result = new ValueStringBuilder(stackalloc char[64]);
  378. while (n > 0 && result.Length < 50) // arbitrary limit
  379. {
  380. var c = n*radix;
  381. var d = (int) c;
  382. n = c - d;
  383. result.Append(Digits[d]);
  384. }
  385. return result.ToString();
  386. }
  387. private static string ToNumberString(double m)
  388. {
  389. var stringBuilder = new ValueStringBuilder(stackalloc char[128]);
  390. NumberToString(m, new DtoaBuilder(), ref stringBuilder);
  391. return stringBuilder.ToString();
  392. }
  393. internal static void NumberToString(
  394. double m,
  395. DtoaBuilder builder,
  396. ref ValueStringBuilder stringBuilder)
  397. {
  398. if (double.IsNaN(m))
  399. {
  400. stringBuilder.Append("NaN");
  401. return;
  402. }
  403. if (m == 0)
  404. {
  405. stringBuilder.Append('0');
  406. return;
  407. }
  408. if (double.IsInfinity(m))
  409. {
  410. stringBuilder.Append(double.IsNegativeInfinity(m) ? "-Infinity" : "Infinity");
  411. return;
  412. }
  413. DtoaNumberFormatter.DoubleToAscii(
  414. builder,
  415. m,
  416. DtoaMode.Shortest,
  417. 0,
  418. out var negative,
  419. out var decimal_point);
  420. if (negative)
  421. {
  422. stringBuilder.Append('-');
  423. }
  424. if (builder.Length <= decimal_point && decimal_point <= 21)
  425. {
  426. // ECMA-262 section 9.8.1 step 6.
  427. stringBuilder.Append(builder._chars.AsSpan(0, builder.Length));
  428. stringBuilder.Append('0', decimal_point - builder.Length);
  429. }
  430. else if (0 < decimal_point && decimal_point <= 21)
  431. {
  432. // ECMA-262 section 9.8.1 step 7.
  433. stringBuilder.Append(builder._chars.AsSpan(0, decimal_point));
  434. stringBuilder.Append('.');
  435. stringBuilder.Append(builder._chars.AsSpan(decimal_point, builder.Length - decimal_point));
  436. }
  437. else if (decimal_point <= 0 && decimal_point > -6)
  438. {
  439. // ECMA-262 section 9.8.1 step 8.
  440. stringBuilder.Append("0.");
  441. stringBuilder.Append('0', -decimal_point);
  442. stringBuilder.Append(builder._chars.AsSpan(0, builder.Length));
  443. }
  444. else
  445. {
  446. // ECMA-262 section 9.8.1 step 9 and 10 combined.
  447. stringBuilder.Append(builder._chars[0]);
  448. if (builder.Length != 1)
  449. {
  450. stringBuilder.Append('.');
  451. stringBuilder.Append(builder._chars.AsSpan(1, builder.Length - 1));
  452. }
  453. stringBuilder.Append('e');
  454. stringBuilder.Append((decimal_point >= 0) ? '+' : '-');
  455. int exponent = decimal_point - 1;
  456. if (exponent < 0)
  457. {
  458. exponent = -exponent;
  459. }
  460. stringBuilder.Append(exponent.ToString(CultureInfo.InvariantCulture));
  461. }
  462. }
  463. }
  464. }