TypeConverter.cs 44 KB

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