TypeConverter.cs 43 KB

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