TypeConverter.cs 42 KB

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