NumberPrototype.cs 15 KB

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