TypeConverter.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. using System.Globalization;
  2. using System.Numerics;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Native;
  7. using Jint.Native.Number;
  8. using Jint.Native.Object;
  9. using Jint.Native.String;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime.Interop;
  12. namespace Jint.Runtime
  13. {
  14. public static class TypeConverter
  15. {
  16. // how many decimals to check when determining if double is actually an int
  17. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  18. private static readonly string[] intToString = new string[1024];
  19. private static readonly string[] charToString = new string[256];
  20. static TypeConverter()
  21. {
  22. for (var i = 0; i < intToString.Length; ++i)
  23. {
  24. intToString[i] = i.ToString(CultureInfo.InvariantCulture);
  25. }
  26. for (var i = 0; i < charToString.Length; ++i)
  27. {
  28. var c = (char) i;
  29. charToString[i] = c.ToString();
  30. }
  31. }
  32. /// <summary>
  33. /// https://tc39.es/ecma262/#sec-toprimitive
  34. /// </summary>
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.Empty)
  37. {
  38. return input is not ObjectInstance oi
  39. ? input
  40. : ToPrimitiveObjectInstance(oi, preferredType);
  41. }
  42. private static JsValue ToPrimitiveObjectInstance(ObjectInstance oi, Types preferredType)
  43. {
  44. var exoticToPrim = oi.GetMethod(GlobalSymbolRegistry.ToPrimitive);
  45. if (exoticToPrim is not null)
  46. {
  47. var hint = preferredType switch
  48. {
  49. Types.String => JsString.StringString,
  50. Types.Number => JsString.NumberString,
  51. _ => JsString.DefaultString
  52. };
  53. var str = exoticToPrim.Call(oi, new JsValue[] { hint });
  54. if (str.IsPrimitive())
  55. {
  56. return str;
  57. }
  58. if (str.IsObject())
  59. {
  60. ExceptionHelper.ThrowTypeError(oi.Engine.Realm, "Cannot convert object to primitive value");
  61. }
  62. }
  63. return OrdinaryToPrimitive(oi, preferredType == Types.Empty ? Types.Number : preferredType);
  64. }
  65. /// <summary>
  66. /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
  67. /// </summary>
  68. internal static JsValue OrdinaryToPrimitive(ObjectInstance input, Types hint = Types.Empty)
  69. {
  70. JsString property1;
  71. JsString property2;
  72. if (hint == Types.String)
  73. {
  74. property1 = (JsString) "toString";
  75. property2 = (JsString) "valueOf";
  76. }
  77. else if (hint == Types.Number)
  78. {
  79. property1 = (JsString) "valueOf";
  80. property2 = (JsString) "toString";
  81. }
  82. else
  83. {
  84. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  85. return null;
  86. }
  87. if (input.Get(property1) is ICallable method1)
  88. {
  89. var val = method1.Call(input, Arguments.Empty);
  90. if (val.IsPrimitive())
  91. {
  92. return val;
  93. }
  94. }
  95. if (input.Get(property2) is ICallable method2)
  96. {
  97. var val = method2.Call(input, Arguments.Empty);
  98. if (val.IsPrimitive())
  99. {
  100. return val;
  101. }
  102. }
  103. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  104. return null;
  105. }
  106. /// <summary>
  107. /// https://tc39.es/ecma262/#sec-toboolean
  108. /// </summary>
  109. public static bool ToBoolean(JsValue o) => o.ToBoolean();
  110. /// <summary>
  111. /// https://tc39.es/ecma262/#sec-tonumeric
  112. /// </summary>
  113. public static JsValue ToNumeric(JsValue value)
  114. {
  115. if (value.IsNumber() || value.IsBigInt())
  116. {
  117. return value;
  118. }
  119. var primValue = ToPrimitive(value, Types.Number);
  120. if (primValue.IsBigInt())
  121. {
  122. return primValue;
  123. }
  124. return ToNumber(primValue);
  125. }
  126. /// <summary>
  127. /// https://tc39.es/ecma262/#sec-tonumber
  128. /// </summary>
  129. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  130. public static double ToNumber(JsValue o)
  131. {
  132. return o.IsNumber()
  133. ? ((JsNumber) o)._value
  134. : ToNumberUnlikely(o);
  135. }
  136. private static double ToNumberUnlikely(JsValue o)
  137. {
  138. var type = o._type & ~InternalTypes.InternalFlags;
  139. switch (type)
  140. {
  141. case InternalTypes.Undefined:
  142. return double.NaN;
  143. case InternalTypes.Null:
  144. return 0;
  145. case InternalTypes.Boolean:
  146. return ((JsBoolean) o)._value ? 1 : 0;
  147. case InternalTypes.String:
  148. return ToNumber(o.ToString());
  149. case InternalTypes.Symbol:
  150. case InternalTypes.BigInt:
  151. case InternalTypes.Empty:
  152. // TODO proper TypeError would require Engine instance and a lot of API changes
  153. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  154. return 0;
  155. default:
  156. return ToNumber(ToPrimitive(o, Types.Number));
  157. }
  158. }
  159. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  160. public static JsNumber ToJsNumber(JsValue o)
  161. {
  162. return o.IsNumber() ? (JsNumber) o : ToJsNumberUnlikely(o);
  163. }
  164. private static JsNumber ToJsNumberUnlikely(JsValue o)
  165. {
  166. var type = o._type & ~InternalTypes.InternalFlags;
  167. switch (type)
  168. {
  169. case InternalTypes.Undefined:
  170. return JsNumber.DoubleNaN;
  171. case InternalTypes.Null:
  172. return JsNumber.PositiveZero;
  173. case InternalTypes.Boolean:
  174. return ((JsBoolean) o)._value ? JsNumber.PositiveOne : JsNumber.PositiveZero;
  175. case InternalTypes.String:
  176. return new JsNumber(ToNumber(o.ToString()));
  177. case InternalTypes.Symbol:
  178. case InternalTypes.BigInt:
  179. case InternalTypes.Empty:
  180. // TODO proper TypeError would require Engine instance and a lot of API changes
  181. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  182. return JsNumber.PositiveZero;
  183. default:
  184. return new JsNumber(ToNumber(ToPrimitive(o, Types.Number)));
  185. }
  186. }
  187. private static double ToNumber(string input)
  188. {
  189. if (string.IsNullOrWhiteSpace(input))
  190. {
  191. return 0;
  192. }
  193. var firstChar = input[0];
  194. if (input.Length == 1)
  195. {
  196. return firstChar is >= '0' and <= '9' ? firstChar - '0' : double.NaN;
  197. }
  198. input = StringPrototype.TrimEx(input);
  199. firstChar = input[0];
  200. const NumberStyles NumberStyles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  201. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  202. NumberStyles.AllowExponent;
  203. if (long.TryParse(input, NumberStyles, CultureInfo.InvariantCulture, out var longValue))
  204. {
  205. return longValue == 0 && firstChar == '-' ? -0.0 : longValue;
  206. }
  207. if (input.Length is 8 or 9)
  208. {
  209. switch (input)
  210. {
  211. case "+Infinity":
  212. case "Infinity":
  213. return double.PositiveInfinity;
  214. case "-Infinity":
  215. return double.NegativeInfinity;
  216. }
  217. if (input.EndsWith("infinity", StringComparison.OrdinalIgnoreCase))
  218. {
  219. // we don't accept other that case-sensitive
  220. return double.NaN;
  221. }
  222. }
  223. if (input.Length > 2 && firstChar == '0' && char.IsLetter(input[1]))
  224. {
  225. var fromBase = input[1] switch
  226. {
  227. 'x' or 'X' => 16,
  228. 'o' or 'O' => 8,
  229. 'b' or 'B' => 2,
  230. _ => 0
  231. };
  232. if (fromBase > 0)
  233. {
  234. try
  235. {
  236. return Convert.ToInt32(input.Substring(2), fromBase);
  237. }
  238. catch
  239. {
  240. return double.NaN;
  241. }
  242. }
  243. }
  244. if (double.TryParse(input, NumberStyles, CultureInfo.InvariantCulture, out var n))
  245. {
  246. return n == 0 && firstChar == '-' ? -0.0 : n;
  247. }
  248. return double.NaN;
  249. }
  250. /// <summary>
  251. /// https://tc39.es/ecma262/#sec-tolength
  252. /// </summary>
  253. public static ulong ToLength(JsValue o)
  254. {
  255. var len = ToInteger(o);
  256. if (len <= 0)
  257. {
  258. return 0;
  259. }
  260. return (ulong) Math.Min(len, NumberConstructor.MaxSafeInteger);
  261. }
  262. /// <summary>
  263. /// https://tc39.es/ecma262/#sec-tointegerorinfinity
  264. /// </summary>
  265. public static double ToIntegerOrInfinity(JsValue argument)
  266. {
  267. var number = ToNumber(argument);
  268. if (double.IsNaN(number) || number == 0)
  269. {
  270. return 0;
  271. }
  272. if (double.IsInfinity(number))
  273. {
  274. return number;
  275. }
  276. var integer = (long) Math.Floor(Math.Abs(number));
  277. if (number < 0)
  278. {
  279. integer *= -1;
  280. }
  281. return integer;
  282. }
  283. /// <summary>
  284. /// https://tc39.es/ecma262/#sec-tointeger
  285. /// </summary>
  286. public static double ToInteger(JsValue o)
  287. {
  288. return ToInteger(ToNumber(o));
  289. }
  290. /// <summary>
  291. /// https://tc39.es/ecma262/#sec-tointeger
  292. /// </summary>
  293. internal static double ToInteger(double number)
  294. {
  295. if (double.IsNaN(number))
  296. {
  297. return 0;
  298. }
  299. if (number == 0 || double.IsInfinity(number))
  300. {
  301. return number;
  302. }
  303. if (number is >= long.MinValue and <= long.MaxValue)
  304. {
  305. return (long) number;
  306. }
  307. var integer = Math.Floor(Math.Abs(number));
  308. if (number < 0)
  309. {
  310. integer *= -1;
  311. }
  312. return integer;
  313. }
  314. internal static int DoubleToInt32Slow(double o)
  315. {
  316. // Computes the integral value of the number mod 2^32.
  317. var doubleBits = BitConverter.DoubleToInt64Bits(o);
  318. var sign = (int) (doubleBits >> 63); // 0 if positive, -1 if negative
  319. var exponent = (int) ((doubleBits >> 52) & 0x7FF) - 1023;
  320. if ((uint) exponent >= 84)
  321. {
  322. // Anything with an exponent that is negative or >= 84 will convert to zero.
  323. // This includes infinities and NaNs, which have exponent = 1024
  324. // The 84 comes from 52 (bits in double mantissa) + 32 (bits in integer)
  325. return 0;
  326. }
  327. var mantissa = (doubleBits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
  328. var int32Value = exponent >= 52 ? (int) (mantissa << (exponent - 52)) : (int) (mantissa >> (52 - exponent));
  329. return (int32Value + sign) ^ sign;
  330. }
  331. /// <summary>
  332. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
  333. /// </summary>
  334. public static int ToInt32(JsValue o)
  335. {
  336. if (o._type == InternalTypes.Integer)
  337. {
  338. return o.AsInteger();
  339. }
  340. var doubleVal = ToNumber(o);
  341. if (doubleVal >= -(double) int.MinValue && doubleVal <= int.MaxValue)
  342. {
  343. // Double-to-int cast is correct in this range
  344. return (int) doubleVal;
  345. }
  346. return DoubleToInt32Slow(doubleVal);
  347. }
  348. /// <summary>
  349. /// https://tc39.es/ecma262/#sec-touint32
  350. /// </summary>
  351. public static uint ToUint32(JsValue o)
  352. {
  353. if (o._type == InternalTypes.Integer)
  354. {
  355. return (uint) o.AsInteger();
  356. }
  357. var doubleVal = ToNumber(o);
  358. if (doubleVal is >= 0.0 and <= uint.MaxValue)
  359. {
  360. // Double-to-uint cast is correct in this range
  361. return (uint) doubleVal;
  362. }
  363. return (uint) DoubleToInt32Slow(doubleVal);
  364. }
  365. /// <summary>
  366. /// https://tc39.es/ecma262/#sec-touint16
  367. /// </summary>
  368. public static ushort ToUint16(JsValue o)
  369. {
  370. if (o._type == InternalTypes.Integer)
  371. {
  372. var integer = o.AsInteger();
  373. if (integer is >= 0 and <= ushort.MaxValue)
  374. {
  375. return (ushort) integer;
  376. }
  377. }
  378. var number = ToNumber(o);
  379. if (double.IsNaN(number) || number == 0 || double.IsInfinity(number))
  380. {
  381. return 0;
  382. }
  383. var intValue = Math.Floor(Math.Abs(number));
  384. if (number < 0)
  385. {
  386. intValue *= -1;
  387. }
  388. var int16Bit = intValue % 65_536; // 2^16
  389. return (ushort) int16Bit;
  390. }
  391. /// <summary>
  392. /// https://tc39.es/ecma262/#sec-toint16
  393. /// </summary>
  394. internal static double ToInt16(JsValue o)
  395. {
  396. return o._type == InternalTypes.Integer
  397. ? (short) o.AsInteger()
  398. : (short) (long) ToNumber(o);
  399. }
  400. /// <summary>
  401. /// https://tc39.es/ecma262/#sec-toint8
  402. /// </summary>
  403. internal static double ToInt8(JsValue o)
  404. {
  405. return o._type == InternalTypes.Integer
  406. ? (sbyte) o.AsInteger()
  407. : (sbyte) (long) ToNumber(o);
  408. }
  409. /// <summary>
  410. /// https://tc39.es/ecma262/#sec-touint8
  411. /// </summary>
  412. internal static double ToUint8(JsValue o)
  413. {
  414. return o._type == InternalTypes.Integer
  415. ? (byte) o.AsInteger()
  416. : (byte) (long) ToNumber(o);
  417. }
  418. /// <summary>
  419. /// https://tc39.es/ecma262/#sec-touint8clamp
  420. /// </summary>
  421. internal static byte ToUint8Clamp(JsValue o)
  422. {
  423. if (o._type == InternalTypes.Integer)
  424. {
  425. var intValue = o.AsInteger();
  426. if (intValue is > -1 and < 256)
  427. {
  428. return (byte) intValue;
  429. }
  430. }
  431. return ToUint8ClampUnlikely(o);
  432. }
  433. private static byte ToUint8ClampUnlikely(JsValue o)
  434. {
  435. var number = ToNumber(o);
  436. if (double.IsNaN(number))
  437. {
  438. return 0;
  439. }
  440. if (number <= 0)
  441. {
  442. return 0;
  443. }
  444. if (number >= 255)
  445. {
  446. return 255;
  447. }
  448. var f = Math.Floor(number);
  449. if (f + 0.5 < number)
  450. {
  451. return (byte) (f + 1);
  452. }
  453. if (number < f + 0.5)
  454. {
  455. return (byte) f;
  456. }
  457. if (f % 2 != 0)
  458. {
  459. return (byte) (f + 1);
  460. }
  461. return (byte) f;
  462. }
  463. /// <summary>
  464. /// https://tc39.es/ecma262/#sec-tobigint
  465. /// </summary>
  466. public static BigInteger ToBigInt(JsValue value)
  467. {
  468. return value is JsBigInt bigInt
  469. ? bigInt._value
  470. : ToBigIntUnlikely(value);
  471. }
  472. private static BigInteger ToBigIntUnlikely(JsValue value)
  473. {
  474. var prim = ToPrimitive(value, Types.Number);
  475. switch (prim.Type)
  476. {
  477. case Types.BigInt:
  478. return ((JsBigInt) prim)._value;
  479. case Types.Boolean:
  480. return ((JsBoolean) prim)._value ? BigInteger.One : BigInteger.Zero;
  481. case Types.String:
  482. return StringToBigInt(prim.ToString());
  483. default:
  484. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  485. return BigInteger.One;
  486. }
  487. }
  488. public static JsBigInt ToJsBigInt(JsValue value)
  489. {
  490. return value as JsBigInt ?? ToJsBigIntUnlikely(value);
  491. }
  492. private static JsBigInt ToJsBigIntUnlikely(JsValue value)
  493. {
  494. var prim = ToPrimitive(value, Types.Number);
  495. switch (prim.Type)
  496. {
  497. case Types.BigInt:
  498. return (JsBigInt) prim;
  499. case Types.Boolean:
  500. return ((JsBoolean) prim)._value ? JsBigInt.One : JsBigInt.Zero;
  501. case Types.String:
  502. return new JsBigInt(StringToBigInt(prim.ToString()));
  503. default:
  504. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  505. return JsBigInt.One;
  506. }
  507. }
  508. internal static BigInteger StringToBigInt(string str)
  509. {
  510. if (!TryStringToBigInt(str, out var result))
  511. {
  512. throw new ParserException(" Cannot convert " + str + " to a BigInt");
  513. }
  514. return result;
  515. }
  516. internal static bool TryStringToBigInt(string str, out BigInteger result)
  517. {
  518. if (string.IsNullOrWhiteSpace(str))
  519. {
  520. result = BigInteger.Zero;
  521. return true;
  522. }
  523. str = str.Trim();
  524. for (var i = 0; i < str.Length; i++)
  525. {
  526. var c = str[i];
  527. if (!char.IsDigit(c))
  528. {
  529. if (i == 0 && (c == '-' || Character.IsDecimalDigit(c)))
  530. {
  531. // ok
  532. continue;
  533. }
  534. if (i != 1 && Character.IsHexDigit(c))
  535. {
  536. // ok
  537. continue;
  538. }
  539. if (i == 1 && (Character.IsDecimalDigit(c) || c is 'x' or 'X' or 'b' or 'B' or 'o' or 'O'))
  540. {
  541. // allowed, can be probably parsed
  542. continue;
  543. }
  544. result = default;
  545. return false;
  546. }
  547. }
  548. // check if we can get by using plain parsing
  549. if (BigInteger.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
  550. {
  551. return true;
  552. }
  553. if (str.Length > 2)
  554. {
  555. if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
  556. {
  557. // we get better precision if we don't hit floating point parsing that is performed by Esprima
  558. #if SUPPORTS_SPAN_PARSE
  559. var source = str.AsSpan(2);
  560. #else
  561. var source = str.Substring(2);
  562. #endif
  563. var c = source[0];
  564. if (c > 7 && Character.IsHexDigit(c))
  565. {
  566. // ensure we get positive number
  567. source = "0" + source.ToString();
  568. }
  569. if (BigInteger.TryParse(source, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
  570. {
  571. return true;
  572. }
  573. }
  574. else if (str.StartsWith("0o", StringComparison.OrdinalIgnoreCase) && Character.IsOctalDigit(str[2]))
  575. {
  576. // try parse large octal
  577. var bigInteger = new BigInteger();
  578. for (var i = 2; i < str.Length; i++)
  579. {
  580. var c = str[i];
  581. if (!Character.IsHexDigit(c))
  582. {
  583. return false;
  584. }
  585. bigInteger = bigInteger * 8 + c - '0';
  586. }
  587. result = bigInteger;
  588. return true;
  589. }
  590. else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase) && Character.IsDecimalDigit(str[2]))
  591. {
  592. // try parse large binary
  593. var bigInteger = new BigInteger();
  594. for (var i = 2; i < str.Length; i++)
  595. {
  596. var c = str[i];
  597. if (c != '0' && c != '1')
  598. {
  599. // not good
  600. return false;
  601. }
  602. bigInteger <<= 1;
  603. bigInteger += c == '1' ? 1 : 0;
  604. }
  605. result = bigInteger;
  606. return true;
  607. }
  608. }
  609. return false;
  610. }
  611. /// <summary>
  612. /// https://tc39.es/ecma262/#sec-tobigint64
  613. /// </summary>
  614. internal static long ToBigInt64(BigInteger value)
  615. {
  616. var int64bit = BigIntegerModulo(value, BigInteger.Pow(2, 64));
  617. if (int64bit >= BigInteger.Pow(2, 63))
  618. {
  619. return (long) (int64bit - BigInteger.Pow(2, 64));
  620. }
  621. return (long) int64bit;
  622. }
  623. /// <summary>
  624. /// https://tc39.es/ecma262/#sec-tobiguint64
  625. /// </summary>
  626. internal static ulong ToBigUint64(BigInteger value)
  627. {
  628. return (ulong) BigIntegerModulo(value, BigInteger.Pow(2, 64));
  629. }
  630. /// <summary>
  631. /// Implements the JS spec modulo operation as expected.
  632. /// </summary>
  633. internal static BigInteger BigIntegerModulo(BigInteger a, BigInteger n)
  634. {
  635. return (a %= n) < 0 && n > 0 || a > 0 && n < 0 ? a + n : a;
  636. }
  637. /// <summary>
  638. /// https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  639. /// </summary>
  640. internal static double? CanonicalNumericIndexString(JsValue value)
  641. {
  642. if (value is JsNumber jsNumber)
  643. {
  644. return jsNumber._value;
  645. }
  646. if (value is JsString jsString)
  647. {
  648. if (string.Equals(jsString.ToString(), "-0", StringComparison.Ordinal))
  649. {
  650. return JsNumber.NegativeZero._value;
  651. }
  652. var n = ToNumber(value);
  653. if (!JsValue.SameValue(ToString(n), value))
  654. {
  655. return null;
  656. }
  657. return n;
  658. }
  659. return null;
  660. }
  661. /// <summary>
  662. /// https://tc39.es/ecma262/#sec-toindex
  663. /// </summary>
  664. public static uint ToIndex(Realm realm, JsValue value)
  665. {
  666. if (value.IsUndefined())
  667. {
  668. return 0;
  669. }
  670. var integerIndex = ToIntegerOrInfinity(value);
  671. if (integerIndex < 0)
  672. {
  673. ExceptionHelper.ThrowRangeError(realm);
  674. }
  675. var index = ToLength(integerIndex);
  676. if (integerIndex != index)
  677. {
  678. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  679. }
  680. return (uint) Math.Min(uint.MaxValue, index);
  681. }
  682. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  683. internal static string ToString(long i)
  684. {
  685. var temp = intToString;
  686. return (ulong) i < (ulong) temp.Length
  687. ? temp[i]
  688. : i.ToString(CultureInfo.InvariantCulture);
  689. }
  690. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  691. internal static string ToString(int i)
  692. {
  693. var temp = intToString;
  694. return (uint) i < (uint) temp.Length
  695. ? temp[i]
  696. : i.ToString(CultureInfo.InvariantCulture);
  697. }
  698. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  699. internal static string ToString(uint i)
  700. {
  701. var temp = intToString;
  702. return i < (uint) temp.Length
  703. ? temp[i]
  704. : i.ToString(CultureInfo.InvariantCulture);
  705. }
  706. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  707. internal static string ToString(char c)
  708. {
  709. var temp = charToString;
  710. return (uint) c < (uint) temp.Length
  711. ? temp[c]
  712. : c.ToString();
  713. }
  714. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  715. internal static string ToString(ulong i)
  716. {
  717. var temp = intToString;
  718. return i < (ulong) temp.Length
  719. ? temp[i]
  720. : i.ToString(CultureInfo.InvariantCulture);
  721. }
  722. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  723. internal static string ToString(double d)
  724. {
  725. if (CanBeStringifiedAsLong(d))
  726. {
  727. // we are dealing with integer that can be cached
  728. return ToString((long) d);
  729. }
  730. return NumberPrototype.ToNumberString(d);
  731. }
  732. /// <summary>
  733. /// Returns true if <see cref="ToString(long)"/> can be used for the
  734. /// provided value <paramref name="d"/>, otherwise false.
  735. /// </summary>
  736. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  737. internal static bool CanBeStringifiedAsLong(double d)
  738. {
  739. return d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance;
  740. }
  741. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  742. internal static string ToString(BigInteger bigInteger)
  743. {
  744. return bigInteger.ToString(CultureInfo.InvariantCulture);
  745. }
  746. /// <summary>
  747. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  748. /// </summary>
  749. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  750. public static JsValue ToPropertyKey(JsValue o)
  751. {
  752. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  753. return (o._type & PropertyKeys) != InternalTypes.Empty
  754. ? o
  755. : ToPropertyKeyNonString(o);
  756. }
  757. [MethodImpl(MethodImplOptions.NoInlining)]
  758. private static JsValue ToPropertyKeyNonString(JsValue o)
  759. {
  760. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  761. var primitive = ToPrimitive(o, Types.String);
  762. return (primitive._type & PropertyKeys) != InternalTypes.Empty
  763. ? primitive
  764. : ToStringNonString(primitive);
  765. }
  766. /// <summary>
  767. /// https://tc39.es/ecma262/#sec-tostring
  768. /// </summary>
  769. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  770. public static string ToString(JsValue o)
  771. {
  772. return o.IsString() ? o.ToString() : ToStringNonString(o);
  773. }
  774. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  775. internal static JsString ToJsString(JsValue o)
  776. {
  777. if (o is JsString s)
  778. {
  779. return s;
  780. }
  781. return JsString.Create(ToStringNonString(o));
  782. }
  783. private static string ToStringNonString(JsValue o)
  784. {
  785. var type = o._type & ~InternalTypes.InternalFlags;
  786. switch (type)
  787. {
  788. case InternalTypes.Boolean:
  789. return ((JsBoolean) o)._value ? "true" : "false";
  790. case InternalTypes.Integer:
  791. return ToString((int) ((JsNumber) o)._value);
  792. case InternalTypes.Number:
  793. return ToString(((JsNumber) o)._value);
  794. case InternalTypes.BigInt:
  795. return ToString(((JsBigInt) o)._value);
  796. case InternalTypes.Symbol:
  797. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  798. return null;
  799. case InternalTypes.Undefined:
  800. return "undefined";
  801. case InternalTypes.Null:
  802. return "null";
  803. case InternalTypes.PrivateName:
  804. return o.ToString();
  805. case InternalTypes.Object when o is IObjectWrapper p:
  806. return p.Target?.ToString()!;
  807. default:
  808. return ToString(ToPrimitive(o, Types.String));
  809. }
  810. }
  811. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  812. public static ObjectInstance ToObject(Realm realm, JsValue value)
  813. {
  814. if (value is ObjectInstance oi)
  815. {
  816. return oi;
  817. }
  818. return ToObjectNonObject(realm, value);
  819. }
  820. /// <summary>
  821. /// https://tc39.es/ecma262/#sec-isintegralnumber
  822. /// </summary>
  823. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  824. internal static bool IsIntegralNumber(double value)
  825. {
  826. return !double.IsNaN(value) && !double.IsInfinity(value) && value % 1 == 0;
  827. }
  828. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  829. {
  830. var type = value._type & ~InternalTypes.InternalFlags;
  831. var intrinsics = realm.Intrinsics;
  832. switch (type)
  833. {
  834. case InternalTypes.Boolean:
  835. return intrinsics.Boolean.Construct((JsBoolean) value);
  836. case InternalTypes.Number:
  837. case InternalTypes.Integer:
  838. return intrinsics.Number.Construct((JsNumber) value);
  839. case InternalTypes.BigInt:
  840. return intrinsics.BigInt.Construct((JsBigInt) value);
  841. case InternalTypes.String:
  842. return intrinsics.String.Construct(value as JsString ?? JsString.Create(value.ToString()));
  843. case InternalTypes.Symbol:
  844. return intrinsics.Symbol.Construct((JsSymbol) value);
  845. case InternalTypes.Null:
  846. case InternalTypes.Undefined:
  847. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  848. return null;
  849. default:
  850. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  851. return null;
  852. }
  853. }
  854. [MethodImpl(MethodImplOptions.NoInlining)]
  855. internal static void CheckObjectCoercible(
  856. Engine engine,
  857. JsValue o,
  858. Node sourceNode,
  859. string referenceName)
  860. {
  861. if (!engine._referenceResolver.CheckCoercible(o))
  862. {
  863. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  864. }
  865. }
  866. [MethodImpl(MethodImplOptions.NoInlining)]
  867. private static void ThrowMemberNullOrUndefinedError(
  868. Engine engine,
  869. JsValue o,
  870. Node sourceNode,
  871. string referencedName)
  872. {
  873. referencedName ??= "unknown";
  874. var message = $"Cannot read property '{referencedName}' of {o}";
  875. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message)
  876. .SetJavaScriptCallstack(engine, sourceNode.Location, overwriteExisting: true);
  877. }
  878. public static void CheckObjectCoercible(Engine engine, JsValue o)
  879. {
  880. if (o._type < InternalTypes.Boolean)
  881. {
  882. ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o);
  883. }
  884. }
  885. }
  886. }