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