NumberPrototype.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 const int SmallDtoaLength = FastDtoa.KFastDtoaMaximalLength + 8;
  18. private const int LargeDtoaLength = 101;
  19. private readonly Realm _realm;
  20. private readonly NumberConstructor _constructor;
  21. internal NumberPrototype(
  22. Engine engine,
  23. Realm realm,
  24. NumberConstructor constructor,
  25. ObjectPrototype objectPrototype)
  26. : base(engine, InternalTypes.Object | InternalTypes.PlainObject)
  27. {
  28. _prototype = objectPrototype;
  29. _realm = realm;
  30. _constructor = constructor;
  31. }
  32. protected override void Initialize()
  33. {
  34. var properties = new PropertyDictionary(8, checkExistingKeys: false)
  35. {
  36. ["constructor"] = new PropertyDescriptor(_constructor, true, false, true),
  37. ["toString"] = new PropertyDescriptor(new ClrFunction(Engine, "toString", ToNumberString, 1, PropertyFlag.Configurable), true, false, true),
  38. ["toLocaleString"] = new PropertyDescriptor(new ClrFunction(Engine, "toLocaleString", ToLocaleString, 0, PropertyFlag.Configurable), true, false, true),
  39. ["valueOf"] = new PropertyDescriptor(new ClrFunction(Engine, "valueOf", ValueOf, 0, PropertyFlag.Configurable), true, false, true),
  40. ["toFixed"] = new PropertyDescriptor(new ClrFunction(Engine, "toFixed", ToFixed, 1, PropertyFlag.Configurable), true, false, true),
  41. ["toExponential"] = new PropertyDescriptor(new ClrFunction(Engine, "toExponential", ToExponential, 1, PropertyFlag.Configurable), true, false, true),
  42. ["toPrecision"] = new PropertyDescriptor(new ClrFunction(Engine, "toPrecision", ToPrecision, 1, PropertyFlag.Configurable), true, false, true)
  43. };
  44. SetProperties(properties);
  45. }
  46. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  47. {
  48. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  49. {
  50. ExceptionHelper.ThrowTypeError(_realm);
  51. }
  52. var m = TypeConverter.ToNumber(thisObject);
  53. if (double.IsNaN(m))
  54. {
  55. return "NaN";
  56. }
  57. if (m == 0)
  58. {
  59. return JsString.NumberZeroString;
  60. }
  61. if (m < 0)
  62. {
  63. return "-" + ToLocaleString(-m, arguments);
  64. }
  65. if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
  66. {
  67. return "Infinity";
  68. }
  69. if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
  70. {
  71. return "-Infinity";
  72. }
  73. var numberFormat = (NumberFormatInfo) Engine.Options.Culture.NumberFormat.Clone();
  74. try
  75. {
  76. if (arguments.Length > 0 && arguments[0].IsString())
  77. {
  78. var cultureArgument = arguments[0].ToString();
  79. numberFormat = (NumberFormatInfo) CultureInfo.GetCultureInfo(cultureArgument).NumberFormat.Clone();
  80. }
  81. int decDigitCount = NumberIntlHelper.GetDecimalDigitCount(m);
  82. numberFormat.NumberDecimalDigits = decDigitCount;
  83. }
  84. catch (CultureNotFoundException)
  85. {
  86. ExceptionHelper.ThrowRangeError(_realm, "Incorrect locale information provided");
  87. }
  88. return m.ToString("n", numberFormat);
  89. }
  90. private JsValue ValueOf(JsValue thisObject, JsValue[] arguments)
  91. {
  92. if (thisObject is NumberInstance ni)
  93. {
  94. return ni.NumberData;
  95. }
  96. if (thisObject is JsNumber)
  97. {
  98. return thisObject;
  99. }
  100. ExceptionHelper.ThrowTypeError(_realm);
  101. return null;
  102. }
  103. private const double Ten21 = 1e21;
  104. private JsValue ToFixed(JsValue thisObject, JsValue[] arguments)
  105. {
  106. var f = (int) TypeConverter.ToInteger(arguments.At(0, 0));
  107. if (f < 0 || f > 100)
  108. {
  109. ExceptionHelper.ThrowRangeError(_realm, "fractionDigits argument must be between 0 and 100");
  110. }
  111. // limitation with .NET, max is 99
  112. if (f == 100)
  113. {
  114. ExceptionHelper.ThrowRangeError(_realm, "100 fraction digits is not supported due to .NET format specifier limitation");
  115. }
  116. var x = TypeConverter.ToNumber(thisObject);
  117. if (double.IsNaN(x))
  118. {
  119. return "NaN";
  120. }
  121. if (x >= Ten21)
  122. {
  123. return ToNumberString(x);
  124. }
  125. // handle non-decimal with greater precision
  126. if (System.Math.Abs(x - (long) x) < JsNumber.DoubleIsIntegerTolerance)
  127. {
  128. return ((long) x).ToString("f" + f, CultureInfo.InvariantCulture);
  129. }
  130. return x.ToString("f" + f, CultureInfo.InvariantCulture);
  131. }
  132. /// <summary>
  133. /// https://www.ecma-international.org/ecma-262/6.0/#sec-number.prototype.toexponential
  134. /// </summary>
  135. private JsValue ToExponential(JsValue thisObject, JsValue[] arguments)
  136. {
  137. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  138. {
  139. ExceptionHelper.ThrowTypeError(_realm);
  140. }
  141. var x = TypeConverter.ToNumber(thisObject);
  142. var fractionDigits = arguments.At(0);
  143. if (fractionDigits.IsUndefined())
  144. {
  145. fractionDigits = JsNumber.PositiveZero;
  146. }
  147. var f = (int) TypeConverter.ToInteger(fractionDigits);
  148. if (double.IsNaN(x))
  149. {
  150. return "NaN";
  151. }
  152. if (double.IsInfinity(x))
  153. {
  154. return thisObject.ToString();
  155. }
  156. if (f < 0 || f > 100)
  157. {
  158. ExceptionHelper.ThrowRangeError(_realm, "fractionDigits argument must be between 0 and 100");
  159. }
  160. if (arguments.At(0).IsUndefined())
  161. {
  162. f = -1;
  163. }
  164. bool negative = false;
  165. if (x < 0)
  166. {
  167. x = -x;
  168. negative = true;
  169. }
  170. int decimalPoint;
  171. var dtoaBuilder = new DtoaBuilder(stackalloc char[f == -1 ? SmallDtoaLength : LargeDtoaLength]);
  172. if (f == -1)
  173. {
  174. DtoaNumberFormatter.DoubleToAscii(
  175. ref dtoaBuilder,
  176. x,
  177. DtoaMode.Shortest,
  178. requested_digits: 0,
  179. out _,
  180. out decimalPoint);
  181. f = dtoaBuilder.Length - 1;
  182. }
  183. else
  184. {
  185. DtoaNumberFormatter.DoubleToAscii(
  186. ref 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(ref 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(stackalloc char[LargeDtoaLength]);
  225. DtoaNumberFormatter.DoubleToAscii(
  226. ref 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(ref dtoaBuilder, exponent, negative, p);
  236. }
  237. var sb = new ValueStringBuilder(stackalloc char[128]);
  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.Slice(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.Slice(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.Slice(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. ref 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[128]);
  283. if (negative)
  284. {
  285. sb.Append('-');
  286. }
  287. sb.Append(buffer[0]);
  288. if (significantDigits != 1)
  289. {
  290. sb.Append('.');
  291. sb.Append(buffer.Slice(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. 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. sb.Reverse();
  358. return sb.ToString();
  359. }
  360. internal static string ToFractionBase(double n, int radix)
  361. {
  362. // based on the repeated multiplication method
  363. // http://www.mathpath.org/concepts/Num/frac.htm
  364. const string Digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  365. if (n == 0)
  366. {
  367. return "0";
  368. }
  369. var result = new ValueStringBuilder(stackalloc char[64]);
  370. while (n > 0 && result.Length < 50) // arbitrary limit
  371. {
  372. var c = n*radix;
  373. var d = (int) c;
  374. n = c - d;
  375. result.Append(Digits[d]);
  376. }
  377. return result.ToString();
  378. }
  379. internal static string ToNumberString(double m)
  380. {
  381. if (double.IsNaN(m))
  382. {
  383. return "NaN";
  384. }
  385. if (m == 0)
  386. {
  387. return "0";
  388. }
  389. if (double.IsInfinity(m))
  390. {
  391. return double.IsNegativeInfinity(m) ? "-Infinity" : "Infinity";
  392. }
  393. var builder = new DtoaBuilder(stackalloc char[SmallDtoaLength]);
  394. DtoaNumberFormatter.DoubleToAscii(
  395. ref builder,
  396. m,
  397. DtoaMode.Shortest,
  398. 0,
  399. out var negative,
  400. out var decimal_point);
  401. var stringBuilder = new ValueStringBuilder(stackalloc char[64]);
  402. if (negative)
  403. {
  404. stringBuilder.Append('-');
  405. }
  406. if (builder.Length <= decimal_point && decimal_point <= 21)
  407. {
  408. // ECMA-262 section 9.8.1 step 6.
  409. stringBuilder.Append(builder._chars.Slice(0, builder.Length));
  410. stringBuilder.Append('0', decimal_point - builder.Length);
  411. }
  412. else if (0 < decimal_point && decimal_point <= 21)
  413. {
  414. // ECMA-262 section 9.8.1 step 7.
  415. stringBuilder.Append(builder._chars.Slice(0, decimal_point));
  416. stringBuilder.Append('.');
  417. stringBuilder.Append(builder._chars.Slice(decimal_point, builder.Length - decimal_point));
  418. }
  419. else if (decimal_point <= 0 && decimal_point > -6)
  420. {
  421. // ECMA-262 section 9.8.1 step 8.
  422. stringBuilder.Append("0.");
  423. stringBuilder.Append('0', -decimal_point);
  424. stringBuilder.Append(builder._chars.Slice(0, builder.Length));
  425. }
  426. else
  427. {
  428. // ECMA-262 section 9.8.1 step 9 and 10 combined.
  429. stringBuilder.Append(builder._chars[0]);
  430. if (builder.Length != 1)
  431. {
  432. stringBuilder.Append('.');
  433. stringBuilder.Append(builder._chars.Slice(1, builder.Length - 1));
  434. }
  435. stringBuilder.Append('e');
  436. stringBuilder.Append((decimal_point >= 0) ? '+' : '-');
  437. int exponent = decimal_point - 1;
  438. if (exponent < 0)
  439. {
  440. exponent = -exponent;
  441. }
  442. stringBuilder.Append(exponent.ToString(CultureInfo.InvariantCulture));
  443. }
  444. return stringBuilder.ToString();
  445. }
  446. }
  447. }