NumberPrototype.cs 15 KB

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