TypeConverter.cs 30 KB

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