TypeConverter.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. using System.Globalization;
  2. using System.Numerics;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Extensions;
  7. using Jint.Native;
  8. using Jint.Native.Number;
  9. using Jint.Native.Number.Dtoa;
  10. using Jint.Native.Object;
  11. using Jint.Native.String;
  12. using Jint.Native.Symbol;
  13. using Jint.Pooling;
  14. using Jint.Runtime.Interop;
  15. namespace Jint.Runtime
  16. {
  17. [Flags]
  18. public enum Types
  19. {
  20. None = 0,
  21. Undefined = 1,
  22. Null = 2,
  23. Boolean = 4,
  24. String = 8,
  25. Number = 16,
  26. Symbol = 64,
  27. BigInt = 128,
  28. Object = 256
  29. }
  30. [Flags]
  31. internal enum InternalTypes
  32. {
  33. // should not be used, used for empty match
  34. None = 0,
  35. Undefined = 1,
  36. Null = 2,
  37. // primitive types range start
  38. Boolean = 4,
  39. String = 8,
  40. Number = 16,
  41. Integer = 32,
  42. Symbol = 64,
  43. BigInt = 128,
  44. // primitive types range end
  45. Object = 256,
  46. // internal usage
  47. ObjectEnvironmentRecord = 512,
  48. RequiresCloning = 1024,
  49. Module = 2048,
  50. Primitive = Boolean | String | Number | Integer | BigInt | Symbol,
  51. InternalFlags = ObjectEnvironmentRecord | RequiresCloning
  52. }
  53. public static class TypeConverter
  54. {
  55. // how many decimals to check when determining if double is actually an int
  56. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  57. internal static readonly string[] intToString = new string[1024];
  58. private static readonly string[] charToString = new string[256];
  59. static TypeConverter()
  60. {
  61. for (var i = 0; i < intToString.Length; ++i)
  62. {
  63. intToString[i] = i.ToString();
  64. }
  65. for (var i = 0; i < charToString.Length; ++i)
  66. {
  67. var c = (char) i;
  68. charToString[i] = c.ToString();
  69. }
  70. }
  71. /// <summary>
  72. /// https://tc39.es/ecma262/#sec-toprimitive
  73. /// </summary>
  74. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  75. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.None)
  76. {
  77. return input is not ObjectInstance oi
  78. ? input
  79. : ToPrimitiveObjectInstance(oi, preferredType);
  80. }
  81. private static JsValue ToPrimitiveObjectInstance(ObjectInstance oi, Types preferredType)
  82. {
  83. var exoticToPrim = oi.GetMethod(GlobalSymbolRegistry.ToPrimitive);
  84. if (exoticToPrim is not null)
  85. {
  86. var hint = preferredType switch
  87. {
  88. Types.String => JsString.StringString,
  89. Types.Number => JsString.NumberString,
  90. _ => JsString.DefaultString
  91. };
  92. var str = exoticToPrim.Call(oi, new JsValue[] { hint });
  93. if (str.IsPrimitive())
  94. {
  95. return str;
  96. }
  97. if (str.IsObject())
  98. {
  99. ExceptionHelper.ThrowTypeError(oi.Engine.Realm, "Cannot convert object to primitive value");
  100. }
  101. }
  102. return OrdinaryToPrimitive(oi, preferredType == Types.None ? Types.Number : preferredType);
  103. }
  104. /// <summary>
  105. /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
  106. /// </summary>
  107. internal static JsValue OrdinaryToPrimitive(ObjectInstance input, Types hint = Types.None)
  108. {
  109. JsString property1;
  110. JsString property2;
  111. if (hint == Types.String)
  112. {
  113. property1 = (JsString) "toString";
  114. property2 = (JsString) "valueOf";
  115. }
  116. else if (hint == Types.Number)
  117. {
  118. property1 = (JsString) "valueOf";
  119. property2 = (JsString) "toString";
  120. }
  121. else
  122. {
  123. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  124. return null;
  125. }
  126. if (input.Get(property1) is ICallable method1)
  127. {
  128. var val = method1.Call(input, Arguments.Empty);
  129. if (val.IsPrimitive())
  130. {
  131. return val;
  132. }
  133. }
  134. if (input.Get(property2) is ICallable method2)
  135. {
  136. var val = method2.Call(input, Arguments.Empty);
  137. if (val.IsPrimitive())
  138. {
  139. return val;
  140. }
  141. }
  142. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  143. return null;
  144. }
  145. /// <summary>
  146. /// https://tc39.es/ecma262/#sec-toboolean
  147. /// </summary>
  148. public static bool ToBoolean(JsValue o)
  149. {
  150. var type = o._type & ~InternalTypes.InternalFlags;
  151. switch (type)
  152. {
  153. case InternalTypes.Boolean:
  154. return ((JsBoolean) o)._value;
  155. case InternalTypes.Undefined:
  156. case InternalTypes.Null:
  157. return false;
  158. case InternalTypes.Integer:
  159. return (int) ((JsNumber) o)._value != 0;
  160. case InternalTypes.Number:
  161. var n = ((JsNumber) o)._value;
  162. return n != 0 && !double.IsNaN(n);
  163. case InternalTypes.String:
  164. return !((JsString) o).IsNullOrEmpty();
  165. case InternalTypes.BigInt:
  166. return ((JsBigInt) o)._value != 0;
  167. default:
  168. return true;
  169. }
  170. }
  171. /// <summary>
  172. /// https://tc39.es/ecma262/#sec-tonumeric
  173. /// </summary>
  174. public static JsValue ToNumeric(JsValue value)
  175. {
  176. if (value.IsNumber() || value.IsBigInt())
  177. {
  178. return value;
  179. }
  180. var primValue = ToPrimitive(value, Types.Number);
  181. if (primValue.IsBigInt())
  182. {
  183. return primValue;
  184. }
  185. return ToNumber(primValue);
  186. }
  187. /// <summary>
  188. /// https://tc39.es/ecma262/#sec-tonumber
  189. /// </summary>
  190. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  191. public static double ToNumber(JsValue o)
  192. {
  193. return o.IsNumber()
  194. ? ((JsNumber) o)._value
  195. : ToNumberUnlikely(o);
  196. }
  197. private static double ToNumberUnlikely(JsValue o)
  198. {
  199. var type = o._type & ~InternalTypes.InternalFlags;
  200. switch (type)
  201. {
  202. case InternalTypes.Undefined:
  203. return double.NaN;
  204. case InternalTypes.Null:
  205. return 0;
  206. case InternalTypes.Boolean:
  207. return ((JsBoolean) o)._value ? 1 : 0;
  208. case InternalTypes.String:
  209. return ToNumber(o.ToString());
  210. case InternalTypes.Symbol:
  211. case InternalTypes.BigInt:
  212. // TODO proper TypeError would require Engine instance and a lot of API changes
  213. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  214. return 0;
  215. default:
  216. return ToNumber(ToPrimitive(o, Types.Number));
  217. }
  218. }
  219. private static double ToNumber(string input)
  220. {
  221. // eager checks to save time and trimming
  222. if (string.IsNullOrEmpty(input))
  223. {
  224. return 0;
  225. }
  226. var first = input[0];
  227. if (input.Length == 1 && first >= '0' && first <= '9')
  228. {
  229. // simple constant number
  230. return first - '0';
  231. }
  232. var s = StringPrototype.TrimEx(input);
  233. if (s.Length == 0)
  234. {
  235. return 0;
  236. }
  237. if (s.Length == 8 || s.Length == 9)
  238. {
  239. if ("+Infinity" == s || "Infinity" == s)
  240. {
  241. return double.PositiveInfinity;
  242. }
  243. if ("-Infinity" == s)
  244. {
  245. return double.NegativeInfinity;
  246. }
  247. }
  248. // todo: use a common implementation with JavascriptParser
  249. try
  250. {
  251. if (s.Length > 2 && s[0] == '0' && char.IsLetter(s[1]))
  252. {
  253. var fromBase = 0;
  254. if (s[1] == 'x' || s[1] == 'X')
  255. {
  256. fromBase = 16;
  257. }
  258. if (s[1] == 'o' || s[1] == 'O')
  259. {
  260. fromBase = 8;
  261. }
  262. if (s[1] == 'b' || s[1] == 'B')
  263. {
  264. fromBase = 2;
  265. }
  266. if (fromBase > 0)
  267. {
  268. return Convert.ToInt32(s.Substring(2), fromBase);
  269. }
  270. }
  271. var start = s[0];
  272. if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
  273. {
  274. return double.NaN;
  275. }
  276. var n = double.Parse(s,
  277. NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  278. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  279. NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
  280. if (s.StartsWith("-") && n == 0)
  281. {
  282. return -0.0;
  283. }
  284. return n;
  285. }
  286. catch (OverflowException)
  287. {
  288. return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
  289. }
  290. catch
  291. {
  292. return double.NaN;
  293. }
  294. }
  295. /// <summary>
  296. /// https://tc39.es/ecma262/#sec-tolength
  297. /// </summary>
  298. public static ulong ToLength(JsValue o)
  299. {
  300. var len = ToInteger(o);
  301. if (len <= 0)
  302. {
  303. return 0;
  304. }
  305. return (ulong) Math.Min(len, NumberConstructor.MaxSafeInteger);
  306. }
  307. /// <summary>
  308. /// https://tc39.es/ecma262/#sec-tointegerorinfinity
  309. /// </summary>
  310. public static double ToIntegerOrInfinity(JsValue argument)
  311. {
  312. var number = ToNumber(argument);
  313. if (double.IsNaN(number) || number == 0)
  314. {
  315. return 0;
  316. }
  317. if (double.IsInfinity(number))
  318. {
  319. return number;
  320. }
  321. var integer = (long) Math.Floor(Math.Abs(number));
  322. if (number < 0)
  323. {
  324. integer *= -1;
  325. }
  326. return integer;
  327. }
  328. /// <summary>
  329. /// https://tc39.es/ecma262/#sec-tointeger
  330. /// </summary>
  331. public static double ToInteger(JsValue o)
  332. {
  333. var number = ToNumber(o);
  334. if (double.IsNaN(number))
  335. {
  336. return 0;
  337. }
  338. if (number == 0 || double.IsInfinity(number))
  339. {
  340. return number;
  341. }
  342. if (number is >= long.MinValue and <= long.MaxValue)
  343. {
  344. return (long) number;
  345. }
  346. var integer = Math.Floor(Math.Abs(number));
  347. if (number < 0)
  348. {
  349. integer *= -1;
  350. }
  351. return integer;
  352. }
  353. internal static double ToInteger(string o)
  354. {
  355. var number = ToNumber(o);
  356. if (double.IsNaN(number))
  357. {
  358. return 0;
  359. }
  360. if (number == 0 || double.IsInfinity(number))
  361. {
  362. return number;
  363. }
  364. return (long) number;
  365. }
  366. internal static int DoubleToInt32Slow(double o)
  367. {
  368. // Computes the integral value of the number mod 2^32.
  369. var doubleBits = BitConverter.DoubleToInt64Bits(o);
  370. var sign = (int) (doubleBits >> 63); // 0 if positive, -1 if negative
  371. var exponent = (int) ((doubleBits >> 52) & 0x7FF) - 1023;
  372. if ((uint) exponent >= 84)
  373. {
  374. // Anything with an exponent that is negative or >= 84 will convert to zero.
  375. // This includes infinities and NaNs, which have exponent = 1024
  376. // The 84 comes from 52 (bits in double mantissa) + 32 (bits in integer)
  377. return 0;
  378. }
  379. var mantissa = (doubleBits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
  380. var int32Value = exponent >= 52 ? (int) (mantissa << (exponent - 52)) : (int) (mantissa >> (52 - exponent));
  381. return (int32Value + sign) ^ sign;
  382. }
  383. /// <summary>
  384. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
  385. /// </summary>
  386. public static int ToInt32(JsValue o)
  387. {
  388. if (o._type == InternalTypes.Integer)
  389. {
  390. return o.AsInteger();
  391. }
  392. var doubleVal = ToNumber(o);
  393. if (doubleVal >= -(double) int.MinValue && doubleVal <= int.MaxValue)
  394. {
  395. // Double-to-int cast is correct in this range
  396. return (int) doubleVal;
  397. }
  398. return DoubleToInt32Slow(doubleVal);
  399. }
  400. /// <summary>
  401. /// https://tc39.es/ecma262/#sec-touint32
  402. /// </summary>
  403. public static uint ToUint32(JsValue o)
  404. {
  405. if (o._type == InternalTypes.Integer)
  406. {
  407. return (uint) o.AsInteger();
  408. }
  409. var doubleVal = ToNumber(o);
  410. if (doubleVal is >= 0.0 and <= uint.MaxValue)
  411. {
  412. // Double-to-uint cast is correct in this range
  413. return (uint) doubleVal;
  414. }
  415. return (uint) DoubleToInt32Slow(doubleVal);
  416. }
  417. /// <summary>
  418. /// https://tc39.es/ecma262/#sec-touint16
  419. /// </summary>
  420. public static ushort ToUint16(JsValue o)
  421. {
  422. if (o._type == InternalTypes.Integer)
  423. {
  424. var integer = o.AsInteger();
  425. if (integer is >= 0 and <= ushort.MaxValue)
  426. {
  427. return (ushort) integer;
  428. }
  429. }
  430. var number = ToNumber(o);
  431. if (double.IsNaN(number) || number == 0 || double.IsInfinity(number))
  432. {
  433. return 0;
  434. }
  435. var intValue = Math.Floor(Math.Abs(number));
  436. if (number < 0)
  437. {
  438. intValue *= -1;
  439. }
  440. var int16Bit = intValue % 65_536; // 2^16
  441. return (ushort) int16Bit;
  442. }
  443. /// <summary>
  444. /// https://tc39.es/ecma262/#sec-toint16
  445. /// </summary>
  446. internal static double ToInt16(JsValue o)
  447. {
  448. return o._type == InternalTypes.Integer
  449. ? (short) o.AsInteger()
  450. : (short) (long) ToNumber(o);
  451. }
  452. /// <summary>
  453. /// https://tc39.es/ecma262/#sec-toint8
  454. /// </summary>
  455. internal static double ToInt8(JsValue o)
  456. {
  457. return o._type == InternalTypes.Integer
  458. ? (sbyte) o.AsInteger()
  459. : (sbyte) (long) ToNumber(o);
  460. }
  461. /// <summary>
  462. /// https://tc39.es/ecma262/#sec-touint8
  463. /// </summary>
  464. internal static double ToUint8(JsValue o)
  465. {
  466. return o._type == InternalTypes.Integer
  467. ? (byte) o.AsInteger()
  468. : (byte) (long) ToNumber(o);
  469. }
  470. /// <summary>
  471. /// https://tc39.es/ecma262/#sec-touint8clamp
  472. /// </summary>
  473. internal static byte ToUint8Clamp(JsValue o)
  474. {
  475. if (o._type == InternalTypes.Integer)
  476. {
  477. var intValue = o.AsInteger();
  478. if (intValue is > -1 and < 256)
  479. {
  480. return (byte) intValue;
  481. }
  482. }
  483. return ToUint8ClampUnlikely(o);
  484. }
  485. private static byte ToUint8ClampUnlikely(JsValue o)
  486. {
  487. var number = ToNumber(o);
  488. if (double.IsNaN(number))
  489. {
  490. return 0;
  491. }
  492. if (number <= 0)
  493. {
  494. return 0;
  495. }
  496. if (number >= 255)
  497. {
  498. return 255;
  499. }
  500. var f = Math.Floor(number);
  501. if (f + 0.5 < number)
  502. {
  503. return (byte) (f + 1);
  504. }
  505. if (number < f + 0.5)
  506. {
  507. return (byte) f;
  508. }
  509. if (f % 2 != 0)
  510. {
  511. return (byte) (f + 1);
  512. }
  513. return (byte) f;
  514. }
  515. /// <summary>
  516. /// https://tc39.es/ecma262/#sec-tobigint
  517. /// </summary>
  518. public static BigInteger ToBigInt(JsValue value)
  519. {
  520. return value is JsBigInt bigInt
  521. ? bigInt._value
  522. : ToBigIntUnlikely(value);
  523. }
  524. private static BigInteger ToBigIntUnlikely(JsValue value)
  525. {
  526. var prim = ToPrimitive(value, Types.Number);
  527. switch (prim.Type)
  528. {
  529. case Types.BigInt:
  530. return ((JsBigInt) prim)._value;
  531. case Types.Boolean:
  532. return ((JsBoolean) prim)._value ? BigInteger.One : BigInteger.Zero;
  533. case Types.String:
  534. return StringToBigInt(prim.ToString());
  535. default:
  536. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  537. return BigInteger.One;
  538. }
  539. }
  540. internal static BigInteger StringToBigInt(string str)
  541. {
  542. if (!TryStringToBigInt(str, out var result))
  543. {
  544. throw new ParserException(" Cannot convert " + str + " to a BigInt");
  545. }
  546. return result;
  547. }
  548. internal static bool TryStringToBigInt(string str, out BigInteger result)
  549. {
  550. if (string.IsNullOrWhiteSpace(str))
  551. {
  552. result = BigInteger.Zero;
  553. return true;
  554. }
  555. str = str.Trim();
  556. for (var i = 0; i < str.Length; i++)
  557. {
  558. var c = str[i];
  559. if (!char.IsDigit(c))
  560. {
  561. if (i == 0 && (c == '-' || Character.IsDecimalDigit(c)))
  562. {
  563. // ok
  564. continue;
  565. }
  566. if (i != 1 && Character.IsHexDigit(c))
  567. {
  568. // ok
  569. continue;
  570. }
  571. if (i == 1 && (Character.IsDecimalDigit(c) || c is 'x' or 'X' or 'b' or 'B' or 'o' or 'O'))
  572. {
  573. // allowed, can be probably parsed
  574. continue;
  575. }
  576. result = default;
  577. return false;
  578. }
  579. }
  580. // check if we can get by using plain parsing
  581. if (BigInteger.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
  582. {
  583. return true;
  584. }
  585. if (str.Length > 2)
  586. {
  587. if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
  588. {
  589. // we get better precision if we don't hit floating point parsing that is performed by Esprima
  590. #if NETSTANDARD2_1_OR_GREATER
  591. var source = str.AsSpan(2);
  592. #else
  593. var source = str.Substring(2);
  594. #endif
  595. var c = source[0];
  596. if (c > 7 && Character.IsHexDigit(c))
  597. {
  598. // ensure we get positive number
  599. source = "0" + source.ToString();
  600. }
  601. if (BigInteger.TryParse(source, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
  602. {
  603. return true;
  604. }
  605. }
  606. else if (str.StartsWith("0o", StringComparison.OrdinalIgnoreCase) && Character.IsOctalDigit(str[2]))
  607. {
  608. // try parse large octal
  609. var bigInteger = new BigInteger();
  610. for (var i = 2; i < str.Length; i++)
  611. {
  612. var c = str[i];
  613. if (!Character.IsHexDigit(c))
  614. {
  615. return false;
  616. }
  617. bigInteger = bigInteger * 8 + c - '0';
  618. }
  619. result = bigInteger;
  620. return true;
  621. }
  622. else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase) && Character.IsDecimalDigit(str[2]))
  623. {
  624. // try parse large binary
  625. var bigInteger = new BigInteger();
  626. for (var i = 2; i < str.Length; i++)
  627. {
  628. var c = str[i];
  629. if (c != '0' && c != '1')
  630. {
  631. // not good
  632. return false;
  633. }
  634. bigInteger <<= 1;
  635. bigInteger += c == '1' ? 1 : 0;
  636. }
  637. result = bigInteger;
  638. return true;
  639. }
  640. }
  641. return false;
  642. }
  643. /// <summary>
  644. /// https://tc39.es/ecma262/#sec-tobigint64
  645. /// </summary>
  646. internal static long ToBigInt64(BigInteger value)
  647. {
  648. var int64bit = BigIntegerModulo(value, BigInteger.Pow(2, 64));
  649. if (int64bit >= BigInteger.Pow(2, 63))
  650. {
  651. return (long) (int64bit - BigInteger.Pow(2, 64));
  652. }
  653. return (long) int64bit;
  654. }
  655. /// <summary>
  656. /// https://tc39.es/ecma262/#sec-tobiguint64
  657. /// </summary>
  658. internal static ulong ToBigUint64(BigInteger value)
  659. {
  660. return (ulong) BigIntegerModulo(value, BigInteger.Pow(2, 64));
  661. }
  662. /// <summary>
  663. /// Implements the JS spec modulo operation as expected.
  664. /// </summary>
  665. internal static BigInteger BigIntegerModulo(BigInteger a, BigInteger n)
  666. {
  667. return (a %= n) < 0 && n > 0 || a > 0 && n < 0 ? a + n : a;
  668. }
  669. /// <summary>
  670. /// https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  671. /// </summary>
  672. internal static double? CanonicalNumericIndexString(JsValue value)
  673. {
  674. if (value is JsNumber jsNumber)
  675. {
  676. return jsNumber._value;
  677. }
  678. if (value is JsString jsString)
  679. {
  680. if (jsString.ToString() == "-0")
  681. {
  682. return JsNumber.NegativeZero._value;
  683. }
  684. var n = ToNumber(value);
  685. if (!JsValue.SameValue(ToString(n), value))
  686. {
  687. return null;
  688. }
  689. return n;
  690. }
  691. return null;
  692. }
  693. /// <summary>
  694. /// https://tc39.es/ecma262/#sec-toindex
  695. /// </summary>
  696. public static uint ToIndex(Realm realm, JsValue value)
  697. {
  698. if (value.IsUndefined())
  699. {
  700. return 0;
  701. }
  702. var integerIndex = ToIntegerOrInfinity(value);
  703. if (integerIndex < 0)
  704. {
  705. ExceptionHelper.ThrowRangeError(realm);
  706. }
  707. var index = ToLength(integerIndex);
  708. if (integerIndex != index)
  709. {
  710. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  711. }
  712. return (uint) Math.Min(uint.MaxValue, index);
  713. }
  714. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  715. internal static string ToString(long i)
  716. {
  717. return i >= 0 && i < intToString.Length
  718. ? intToString[i]
  719. : i.ToString();
  720. }
  721. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  722. internal static string ToString(int i)
  723. {
  724. return i >= 0 && i < intToString.Length
  725. ? intToString[i]
  726. : i.ToString();
  727. }
  728. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  729. internal static string ToString(uint i)
  730. {
  731. return i < (uint) intToString.Length
  732. ? intToString[i]
  733. : i.ToString();
  734. }
  735. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  736. internal static string ToString(char c)
  737. {
  738. return c >= 0 && c < charToString.Length
  739. ? charToString[c]
  740. : c.ToString();
  741. }
  742. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  743. internal static string ToString(ulong i)
  744. {
  745. return i >= 0 && i < (ulong) intToString.Length
  746. ? intToString[i]
  747. : i.ToString();
  748. }
  749. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  750. internal static string ToString(double d)
  751. {
  752. if (d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance)
  753. {
  754. // we are dealing with integer that can be cached
  755. return ToString((long) d);
  756. }
  757. using var stringBuilder = StringBuilderPool.Rent();
  758. // we can create smaller array as we know the format to be short
  759. return NumberPrototype.NumberToString(d, new DtoaBuilder(17), stringBuilder.Builder);
  760. }
  761. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  762. internal static string ToString(BigInteger bigInteger)
  763. {
  764. return bigInteger.ToString();
  765. }
  766. /// <summary>
  767. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  768. /// </summary>
  769. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  770. public static JsValue ToPropertyKey(JsValue o)
  771. {
  772. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  773. return (o._type & stringOrSymbol) != 0
  774. ? o
  775. : ToPropertyKeyNonString(o);
  776. }
  777. [MethodImpl(MethodImplOptions.NoInlining)]
  778. private static JsValue ToPropertyKeyNonString(JsValue o)
  779. {
  780. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  781. var primitive = ToPrimitive(o, Types.String);
  782. return (primitive._type & stringOrSymbol) != 0
  783. ? primitive
  784. : ToStringNonString(primitive);
  785. }
  786. /// <summary>
  787. /// http://www.ecma-international.org/ecma-262/6.0/#sec-tostring
  788. /// </summary>
  789. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  790. public static string ToString(JsValue o)
  791. {
  792. return o.IsString() ? o.ToString() : ToStringNonString(o);
  793. }
  794. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  795. internal static JsString ToJsString(JsValue o)
  796. {
  797. if (o is JsString s)
  798. {
  799. return s;
  800. }
  801. return JsString.Create(ToStringNonString(o));
  802. }
  803. private static string ToStringNonString(JsValue o)
  804. {
  805. var type = o._type & ~InternalTypes.InternalFlags;
  806. switch (type)
  807. {
  808. case InternalTypes.Boolean:
  809. return ((JsBoolean) o)._value ? "true" : "false";
  810. case InternalTypes.Integer:
  811. return ToString((int) ((JsNumber) o)._value);
  812. case InternalTypes.Number:
  813. return ToString(((JsNumber) o)._value);
  814. case InternalTypes.BigInt:
  815. return ToString(((JsBigInt) o)._value);
  816. case InternalTypes.Symbol:
  817. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  818. return null;
  819. case InternalTypes.Undefined:
  820. return Undefined.Text;
  821. case InternalTypes.Null:
  822. return Null.Text;
  823. case InternalTypes.Object when o is IObjectWrapper p:
  824. return p.Target?.ToString()!;
  825. default:
  826. return ToString(ToPrimitive(o, Types.String));
  827. }
  828. }
  829. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  830. public static ObjectInstance ToObject(Realm realm, JsValue value)
  831. {
  832. if (value is ObjectInstance oi)
  833. {
  834. return oi;
  835. }
  836. return ToObjectNonObject(realm, value);
  837. }
  838. /// <summary>
  839. /// https://tc39.es/ecma262/#sec-isintegralnumber
  840. /// </summary>
  841. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  842. internal static bool IsIntegralNumber(double value)
  843. {
  844. return !double.IsNaN(value)
  845. && !double.IsInfinity(value)
  846. && Math.Floor(Math.Abs(value)) == Math.Abs(value);
  847. }
  848. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  849. {
  850. var type = value._type & ~InternalTypes.InternalFlags;
  851. switch (type)
  852. {
  853. case InternalTypes.Boolean:
  854. return realm.Intrinsics.Boolean.Construct((JsBoolean) value);
  855. case InternalTypes.Number:
  856. case InternalTypes.Integer:
  857. return realm.Intrinsics.Number.Construct((JsNumber) value);
  858. case InternalTypes.BigInt:
  859. return realm.Intrinsics.BigInt.Construct((JsBigInt) value);
  860. case InternalTypes.String:
  861. return realm.Intrinsics.String.Construct(value.ToString());
  862. case InternalTypes.Symbol:
  863. return realm.Intrinsics.Symbol.Construct((JsSymbol) value);
  864. case InternalTypes.Null:
  865. case InternalTypes.Undefined:
  866. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  867. return null;
  868. default:
  869. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  870. return null;
  871. }
  872. }
  873. [MethodImpl(MethodImplOptions.NoInlining)]
  874. internal static void CheckObjectCoercible(
  875. Engine engine,
  876. JsValue o,
  877. Node sourceNode,
  878. string referenceName)
  879. {
  880. if (!engine._referenceResolver.CheckCoercible(o))
  881. {
  882. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  883. }
  884. }
  885. [MethodImpl(MethodImplOptions.NoInlining)]
  886. private static void ThrowMemberNullOrUndefinedError(
  887. Engine engine,
  888. JsValue o,
  889. Node sourceNode,
  890. string referencedName)
  891. {
  892. referencedName ??= "unknown";
  893. var message = $"Cannot read property '{referencedName}' of {o}";
  894. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message)
  895. .SetJavaScriptCallstack(engine, sourceNode.Location, overwriteExisting: true);
  896. }
  897. public static void CheckObjectCoercible(Engine engine, JsValue o)
  898. {
  899. if (o._type < InternalTypes.Boolean)
  900. {
  901. ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o);
  902. }
  903. }
  904. internal readonly record struct MethodMatch(MethodDescriptor Method, JsValue[] Arguments, int Score = 0) : IComparable<MethodMatch>
  905. {
  906. public int CompareTo(MethodMatch other) => Score.CompareTo(other.Score);
  907. }
  908. internal static IEnumerable<MethodMatch> FindBestMatch(
  909. Engine engine,
  910. MethodDescriptor[] methods,
  911. Func<MethodDescriptor, JsValue[]> argumentProvider)
  912. {
  913. List<MethodMatch>? matchingByParameterCount = null;
  914. foreach (var method in methods)
  915. {
  916. var parameterInfos = method.Parameters;
  917. var arguments = argumentProvider(method);
  918. if (arguments.Length <= parameterInfos.Length
  919. && arguments.Length >= parameterInfos.Length - method.ParameterDefaultValuesCount)
  920. {
  921. var score = CalculateMethodScore(engine, method, arguments);
  922. if (score == 0)
  923. {
  924. // perfect match
  925. yield return new MethodMatch(method, arguments);
  926. yield break;
  927. }
  928. if (score < 0)
  929. {
  930. // discard
  931. continue;
  932. }
  933. matchingByParameterCount ??= new List<MethodMatch>();
  934. matchingByParameterCount.Add(new MethodMatch(method, arguments, score));
  935. }
  936. }
  937. if (matchingByParameterCount == null)
  938. {
  939. yield break;
  940. }
  941. if (matchingByParameterCount.Count > 1)
  942. {
  943. matchingByParameterCount.Sort();
  944. }
  945. foreach (var match in matchingByParameterCount)
  946. {
  947. yield return match;
  948. }
  949. }
  950. /// <summary>
  951. /// Method's match score tells how far away it's from ideal candidate. 0 = ideal, bigger the the number,
  952. /// the farther away the candidate is from ideal match. Negative signals impossible match.
  953. /// </summary>
  954. private static int CalculateMethodScore(Engine engine, MethodDescriptor method, JsValue[] arguments)
  955. {
  956. if (method.Parameters.Length == 0 && arguments.Length == 0)
  957. {
  958. // perfect
  959. return 0;
  960. }
  961. var score = 0;
  962. for (var i = 0; i < arguments.Length; i++)
  963. {
  964. var jsValue = arguments[i];
  965. var paramType = method.Parameters[i].ParameterType;
  966. var parameterScore = CalculateMethodParameterScore(engine, jsValue, paramType);
  967. if (parameterScore < 0)
  968. {
  969. return parameterScore;
  970. }
  971. score += parameterScore;
  972. }
  973. return score;
  974. }
  975. internal readonly record struct AssignableResult(int Score, Type MatchingGivenType)
  976. {
  977. public bool IsAssignable => Score >= 0;
  978. }
  979. /// <summary>
  980. /// resources:
  981. /// https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection
  982. /// https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
  983. /// https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  984. /// This can be improved upon - specifically as mentioned in the above MS document:
  985. /// GetGenericParameterConstraints()
  986. /// and array handling - i.e.
  987. /// GetElementType()
  988. /// </summary>
  989. internal static AssignableResult IsAssignableToGenericType(Type givenType, Type genericType)
  990. {
  991. if (givenType is null)
  992. {
  993. return new AssignableResult(-1, typeof(void));
  994. }
  995. if (!genericType.IsConstructedGenericType)
  996. {
  997. // as mentioned here:
  998. // https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  999. // this effectively means this generic type is open (i.e. not closed) - so any type is "possible" - without looking at the code in the method we don't know
  1000. // whether any operations are being applied that "don't work"
  1001. return new AssignableResult(2, givenType);
  1002. }
  1003. var interfaceTypes = givenType.GetInterfaces();
  1004. foreach (var it in interfaceTypes)
  1005. {
  1006. if (it.IsGenericType)
  1007. {
  1008. var givenTypeGenericDef = it.GetGenericTypeDefinition();
  1009. if (givenTypeGenericDef == genericType)
  1010. {
  1011. return new AssignableResult(0, it);
  1012. }
  1013. else if (genericType.IsGenericType && (givenTypeGenericDef == genericType.GetGenericTypeDefinition()))
  1014. {
  1015. return new AssignableResult(0, it);
  1016. }
  1017. // TPC: we could also add a loop to recurse and iterate thru the iterfaces of generic type - because of covariance/contravariance
  1018. }
  1019. }
  1020. if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
  1021. {
  1022. return new AssignableResult(0, givenType);
  1023. }
  1024. Type baseType = givenType.BaseType;
  1025. if (baseType == null)
  1026. {
  1027. return new AssignableResult(-1, givenType);
  1028. }
  1029. return IsAssignableToGenericType(baseType, genericType);
  1030. }
  1031. /// <summary>
  1032. /// Determines how well parameter type matches target method's type.
  1033. /// </summary>
  1034. private static int CalculateMethodParameterScore(
  1035. Engine engine,
  1036. JsValue jsValue,
  1037. Type paramType)
  1038. {
  1039. var objectValue = jsValue.ToObject();
  1040. var objectValueType = objectValue?.GetType();
  1041. if (objectValueType == paramType)
  1042. {
  1043. return 0;
  1044. }
  1045. if (objectValue is null)
  1046. {
  1047. if (!TypeIsNullable(paramType))
  1048. {
  1049. // this is bad
  1050. return -1;
  1051. }
  1052. return 0;
  1053. }
  1054. if (paramType == typeof(JsValue))
  1055. {
  1056. // JsValue is convertible to. But it is still not a perfect match
  1057. return 1;
  1058. }
  1059. if (paramType == typeof(object))
  1060. {
  1061. // a catch-all, prefer others over it
  1062. return 5;
  1063. }
  1064. if (paramType == typeof(int) && jsValue.IsInteger())
  1065. {
  1066. return 0;
  1067. }
  1068. if (paramType == typeof(float) && objectValueType == typeof(double))
  1069. {
  1070. return jsValue.IsInteger() ? 1 : 2;
  1071. }
  1072. if (paramType.IsEnum &&
  1073. jsValue is JsNumber jsNumber
  1074. && jsNumber.IsInteger()
  1075. && paramType.GetEnumUnderlyingType() == typeof(int)
  1076. && Enum.IsDefined(paramType, jsNumber.AsInteger()))
  1077. {
  1078. // we can do conversion from int value to enum
  1079. return 0;
  1080. }
  1081. if (paramType.IsAssignableFrom(objectValueType))
  1082. {
  1083. // is-a-relation
  1084. return 1;
  1085. }
  1086. if (jsValue.IsArray() && paramType.IsArray)
  1087. {
  1088. // we have potential, TODO if we'd know JS array's internal type we could have exact match
  1089. return 2;
  1090. }
  1091. // not sure the best point to start generic type tests
  1092. if (paramType.IsGenericParameter)
  1093. {
  1094. var genericTypeAssignmentScore = IsAssignableToGenericType(objectValueType!, paramType);
  1095. if (genericTypeAssignmentScore.Score != -1)
  1096. {
  1097. return genericTypeAssignmentScore.Score;
  1098. }
  1099. }
  1100. if (CanChangeType(objectValue, paramType))
  1101. {
  1102. // forcing conversion isn't ideal, but works, especially for int -> double for example
  1103. return 3;
  1104. }
  1105. foreach (var m in objectValueType!.GetOperatorOverloadMethods())
  1106. {
  1107. if (paramType.IsAssignableFrom(m.ReturnType) && m.Name is "op_Implicit" or "op_Explicit")
  1108. {
  1109. // implicit/explicit operator conversion is OK, but not ideal
  1110. return 3;
  1111. }
  1112. }
  1113. if (ReflectionExtensions.TryConvertViaTypeCoercion(paramType, engine.Options.Interop.ValueCoercion, jsValue, out _))
  1114. {
  1115. // gray JS zone where we start to do odd things
  1116. return 10;
  1117. }
  1118. // will rarely succeed
  1119. return 100;
  1120. }
  1121. private static bool CanChangeType(object value, Type targetType)
  1122. {
  1123. if (value is null && !targetType.IsValueType)
  1124. {
  1125. return true;
  1126. }
  1127. if (value is not IConvertible)
  1128. {
  1129. return false;
  1130. }
  1131. try
  1132. {
  1133. Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
  1134. return true;
  1135. }
  1136. catch
  1137. {
  1138. // nope
  1139. return false;
  1140. }
  1141. }
  1142. internal static bool TypeIsNullable(Type type)
  1143. {
  1144. return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
  1145. }
  1146. }
  1147. }