TypeConverter.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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.Object;
  11. using Jint.Native.String;
  12. using Jint.Native.Symbol;
  13. using Jint.Runtime.Interop;
  14. namespace Jint.Runtime
  15. {
  16. [Flags]
  17. public enum Types
  18. {
  19. Empty = 0,
  20. Undefined = 1,
  21. Null = 2,
  22. Boolean = 4,
  23. String = 8,
  24. Number = 16,
  25. Symbol = 64,
  26. BigInt = 128,
  27. Object = 256
  28. }
  29. [Flags]
  30. internal enum InternalTypes
  31. {
  32. // should not be used, used for empty match
  33. Empty = 0,
  34. Undefined = 1,
  35. Null = 2,
  36. // primitive types range start
  37. Boolean = 4,
  38. String = 8,
  39. Number = 16,
  40. Integer = 32,
  41. Symbol = 64,
  42. BigInt = 128,
  43. // primitive types range end
  44. Object = 256,
  45. PrivateName = 512,
  46. // internal usage
  47. ObjectEnvironmentRecord = 1024,
  48. RequiresCloning = 2048,
  49. Module = 4096,
  50. // the object doesn't override important GetOwnProperty etc which change behavior
  51. PlainObject = 8192,
  52. // our native array
  53. Array = 16384,
  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(CultureInfo.InvariantCulture);
  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.Empty)
  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.Empty ? 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.Empty)
  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. case InternalTypes.Empty:
  195. // TODO proper TypeError would require Engine instance and a lot of API changes
  196. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  197. return 0;
  198. default:
  199. return ToNumber(ToPrimitive(o, Types.Number));
  200. }
  201. }
  202. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  203. public static JsNumber ToJsNumber(JsValue o)
  204. {
  205. return o.IsNumber() ? (JsNumber) o : ToJsNumberUnlikely(o);
  206. }
  207. private static JsNumber ToJsNumberUnlikely(JsValue o)
  208. {
  209. var type = o._type & ~InternalTypes.InternalFlags;
  210. switch (type)
  211. {
  212. case InternalTypes.Undefined:
  213. return JsNumber.DoubleNaN;
  214. case InternalTypes.Null:
  215. return JsNumber.PositiveZero;
  216. case InternalTypes.Boolean:
  217. return ((JsBoolean) o)._value ? JsNumber.PositiveOne : JsNumber.PositiveZero;
  218. case InternalTypes.String:
  219. return new JsNumber(ToNumber(o.ToString()));
  220. case InternalTypes.Symbol:
  221. case InternalTypes.BigInt:
  222. case InternalTypes.Empty:
  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. return NumberPrototype.ToNumberString(d);
  774. }
  775. /// <summary>
  776. /// Returns true if <see cref="ToString(long)"/> can be used for the
  777. /// provided value <paramref name="d"/>, otherwise false.
  778. /// </summary>
  779. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  780. internal static bool CanBeStringifiedAsLong(double d)
  781. {
  782. return d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance;
  783. }
  784. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  785. internal static string ToString(BigInteger bigInteger)
  786. {
  787. return bigInteger.ToString(CultureInfo.InvariantCulture);
  788. }
  789. /// <summary>
  790. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  791. /// </summary>
  792. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  793. public static JsValue ToPropertyKey(JsValue o)
  794. {
  795. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  796. return (o._type & PropertyKeys) != InternalTypes.Empty
  797. ? o
  798. : ToPropertyKeyNonString(o);
  799. }
  800. [MethodImpl(MethodImplOptions.NoInlining)]
  801. private static JsValue ToPropertyKeyNonString(JsValue o)
  802. {
  803. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  804. var primitive = ToPrimitive(o, Types.String);
  805. return (primitive._type & PropertyKeys) != InternalTypes.Empty
  806. ? primitive
  807. : ToStringNonString(primitive);
  808. }
  809. /// <summary>
  810. /// https://tc39.es/ecma262/#sec-tostring
  811. /// </summary>
  812. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  813. public static string ToString(JsValue o)
  814. {
  815. return o.IsString() ? o.ToString() : ToStringNonString(o);
  816. }
  817. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  818. internal static JsString ToJsString(JsValue o)
  819. {
  820. if (o is JsString s)
  821. {
  822. return s;
  823. }
  824. return JsString.Create(ToStringNonString(o));
  825. }
  826. private static string ToStringNonString(JsValue o)
  827. {
  828. var type = o._type & ~InternalTypes.InternalFlags;
  829. switch (type)
  830. {
  831. case InternalTypes.Boolean:
  832. return ((JsBoolean) o)._value ? "true" : "false";
  833. case InternalTypes.Integer:
  834. return ToString((int) ((JsNumber) o)._value);
  835. case InternalTypes.Number:
  836. return ToString(((JsNumber) o)._value);
  837. case InternalTypes.BigInt:
  838. return ToString(((JsBigInt) o)._value);
  839. case InternalTypes.Symbol:
  840. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  841. return null;
  842. case InternalTypes.Undefined:
  843. return "undefined";
  844. case InternalTypes.Null:
  845. return "null";
  846. case InternalTypes.PrivateName:
  847. return o.ToString();
  848. case InternalTypes.Object when o is IObjectWrapper p:
  849. return p.Target?.ToString()!;
  850. default:
  851. return ToString(ToPrimitive(o, Types.String));
  852. }
  853. }
  854. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  855. public static ObjectInstance ToObject(Realm realm, JsValue value)
  856. {
  857. if (value is ObjectInstance oi)
  858. {
  859. return oi;
  860. }
  861. return ToObjectNonObject(realm, value);
  862. }
  863. /// <summary>
  864. /// https://tc39.es/ecma262/#sec-isintegralnumber
  865. /// </summary>
  866. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  867. internal static bool IsIntegralNumber(double value)
  868. {
  869. return !double.IsNaN(value) && !double.IsInfinity(value) && value % 1 == 0;
  870. }
  871. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  872. {
  873. var type = value._type & ~InternalTypes.InternalFlags;
  874. switch (type)
  875. {
  876. case InternalTypes.Boolean:
  877. return realm.Intrinsics.Boolean.Construct((JsBoolean) value);
  878. case InternalTypes.Number:
  879. case InternalTypes.Integer:
  880. return realm.Intrinsics.Number.Construct((JsNumber) value);
  881. case InternalTypes.BigInt:
  882. return realm.Intrinsics.BigInt.Construct((JsBigInt) value);
  883. case InternalTypes.String:
  884. return realm.Intrinsics.String.Construct(value.ToString());
  885. case InternalTypes.Symbol:
  886. return realm.Intrinsics.Symbol.Construct((JsSymbol) value);
  887. case InternalTypes.Null:
  888. case InternalTypes.Undefined:
  889. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  890. return null;
  891. default:
  892. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  893. return null;
  894. }
  895. }
  896. [MethodImpl(MethodImplOptions.NoInlining)]
  897. internal static void CheckObjectCoercible(
  898. Engine engine,
  899. JsValue o,
  900. Node sourceNode,
  901. string referenceName)
  902. {
  903. if (!engine._referenceResolver.CheckCoercible(o))
  904. {
  905. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  906. }
  907. }
  908. [MethodImpl(MethodImplOptions.NoInlining)]
  909. private static void ThrowMemberNullOrUndefinedError(
  910. Engine engine,
  911. JsValue o,
  912. Node sourceNode,
  913. string referencedName)
  914. {
  915. referencedName ??= "unknown";
  916. var message = $"Cannot read property '{referencedName}' of {o}";
  917. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message)
  918. .SetJavaScriptCallstack(engine, sourceNode.Location, overwriteExisting: true);
  919. }
  920. public static void CheckObjectCoercible(Engine engine, JsValue o)
  921. {
  922. if (o._type < InternalTypes.Boolean)
  923. {
  924. ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o);
  925. }
  926. }
  927. internal readonly record struct MethodMatch(MethodDescriptor Method, JsValue[] Arguments, int Score = 0) : IComparable<MethodMatch>
  928. {
  929. public int CompareTo(MethodMatch other) => Score.CompareTo(other.Score);
  930. }
  931. internal static IEnumerable<MethodMatch> FindBestMatch(
  932. Engine engine,
  933. MethodDescriptor[] methods,
  934. Func<MethodDescriptor, JsValue[]> argumentProvider)
  935. {
  936. List<MethodMatch>? matchingByParameterCount = null;
  937. foreach (var method in methods)
  938. {
  939. var parameterInfos = method.Parameters;
  940. var arguments = argumentProvider(method);
  941. if (arguments.Length <= parameterInfos.Length
  942. && arguments.Length >= parameterInfos.Length - method.ParameterDefaultValuesCount)
  943. {
  944. var score = CalculateMethodScore(engine, method, arguments);
  945. if (score == 0)
  946. {
  947. // perfect match
  948. yield return new MethodMatch(method, arguments);
  949. yield break;
  950. }
  951. if (score < 0)
  952. {
  953. // discard
  954. continue;
  955. }
  956. matchingByParameterCount ??= new List<MethodMatch>();
  957. matchingByParameterCount.Add(new MethodMatch(method, arguments, score));
  958. }
  959. }
  960. if (matchingByParameterCount == null)
  961. {
  962. yield break;
  963. }
  964. if (matchingByParameterCount.Count > 1)
  965. {
  966. matchingByParameterCount.Sort();
  967. }
  968. foreach (var match in matchingByParameterCount)
  969. {
  970. yield return match;
  971. }
  972. }
  973. /// <summary>
  974. /// Method's match score tells how far away it's from ideal candidate. 0 = ideal, bigger the the number,
  975. /// the farther away the candidate is from ideal match. Negative signals impossible match.
  976. /// </summary>
  977. private static int CalculateMethodScore(Engine engine, MethodDescriptor method, JsValue[] arguments)
  978. {
  979. if (method.Parameters.Length == 0 && arguments.Length == 0)
  980. {
  981. // perfect
  982. return 0;
  983. }
  984. var score = 0;
  985. for (var i = 0; i < arguments.Length; i++)
  986. {
  987. var jsValue = arguments[i];
  988. var parameterScore = CalculateMethodParameterScore(engine, method.Parameters[i], jsValue);
  989. if (parameterScore < 0)
  990. {
  991. return parameterScore;
  992. }
  993. score += parameterScore;
  994. }
  995. return score;
  996. }
  997. internal readonly record struct AssignableResult(int Score, Type MatchingGivenType)
  998. {
  999. public bool IsAssignable => Score >= 0;
  1000. }
  1001. /// <summary>
  1002. /// resources:
  1003. /// https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection
  1004. /// https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
  1005. /// https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  1006. /// This can be improved upon - specifically as mentioned in the above MS document:
  1007. /// GetGenericParameterConstraints()
  1008. /// and array handling - i.e.
  1009. /// GetElementType()
  1010. /// </summary>
  1011. internal static AssignableResult IsAssignableToGenericType(Type givenType, Type genericType)
  1012. {
  1013. if (givenType is null)
  1014. {
  1015. return new AssignableResult(-1, typeof(void));
  1016. }
  1017. if (!genericType.IsConstructedGenericType)
  1018. {
  1019. // as mentioned here:
  1020. // https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  1021. // 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
  1022. // whether any operations are being applied that "don't work"
  1023. return new AssignableResult(2, givenType);
  1024. }
  1025. var interfaceTypes = givenType.GetInterfaces();
  1026. foreach (var it in interfaceTypes)
  1027. {
  1028. if (it.IsGenericType)
  1029. {
  1030. var givenTypeGenericDef = it.GetGenericTypeDefinition();
  1031. if (givenTypeGenericDef == genericType)
  1032. {
  1033. return new AssignableResult(0, it);
  1034. }
  1035. else if (genericType.IsGenericType && (givenTypeGenericDef == genericType.GetGenericTypeDefinition()))
  1036. {
  1037. return new AssignableResult(0, it);
  1038. }
  1039. // TPC: we could also add a loop to recurse and iterate thru the iterfaces of generic type - because of covariance/contravariance
  1040. }
  1041. }
  1042. if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
  1043. {
  1044. return new AssignableResult(0, givenType);
  1045. }
  1046. var baseType = givenType.BaseType;
  1047. if (baseType == null)
  1048. {
  1049. return new AssignableResult(-1, givenType);
  1050. }
  1051. return IsAssignableToGenericType(baseType, genericType);
  1052. }
  1053. /// <summary>
  1054. /// Determines how well parameter type matches target method's type.
  1055. /// </summary>
  1056. private static int CalculateMethodParameterScore(Engine engine, ParameterInfo parameter, JsValue parameterValue)
  1057. {
  1058. var paramType = parameter.ParameterType;
  1059. var objectValue = parameterValue.ToObject();
  1060. var objectValueType = objectValue?.GetType();
  1061. if (objectValueType == paramType)
  1062. {
  1063. return 0;
  1064. }
  1065. if (objectValue is null)
  1066. {
  1067. if (!parameter.IsOptional && !TypeIsNullable(paramType))
  1068. {
  1069. // this is bad
  1070. return -1;
  1071. }
  1072. return 0;
  1073. }
  1074. if (paramType == typeof(JsValue))
  1075. {
  1076. // JsValue is convertible to. But it is still not a perfect match
  1077. return 1;
  1078. }
  1079. if (paramType == typeof(object))
  1080. {
  1081. // a catch-all, prefer others over it
  1082. return 5;
  1083. }
  1084. if (paramType == typeof(int) && parameterValue.IsInteger())
  1085. {
  1086. return 0;
  1087. }
  1088. if (paramType == typeof(float) && objectValueType == typeof(double))
  1089. {
  1090. return parameterValue.IsInteger() ? 1 : 2;
  1091. }
  1092. if (paramType.IsEnum &&
  1093. parameterValue is JsNumber jsNumber
  1094. && jsNumber.IsInteger()
  1095. && paramType.GetEnumUnderlyingType() == typeof(int)
  1096. && Enum.IsDefined(paramType, jsNumber.AsInteger()))
  1097. {
  1098. // we can do conversion from int value to enum
  1099. return 0;
  1100. }
  1101. if (paramType.IsAssignableFrom(objectValueType))
  1102. {
  1103. // is-a-relation
  1104. return 1;
  1105. }
  1106. if (parameterValue.IsArray() && paramType.IsArray)
  1107. {
  1108. // we have potential, TODO if we'd know JS array's internal type we could have exact match
  1109. return 2;
  1110. }
  1111. // not sure the best point to start generic type tests
  1112. if (paramType.IsGenericParameter)
  1113. {
  1114. var genericTypeAssignmentScore = IsAssignableToGenericType(objectValueType!, paramType);
  1115. if (genericTypeAssignmentScore.Score != -1)
  1116. {
  1117. return genericTypeAssignmentScore.Score;
  1118. }
  1119. }
  1120. if (CanChangeType(objectValue, paramType))
  1121. {
  1122. // forcing conversion isn't ideal, but works, especially for int -> double for example
  1123. return 3;
  1124. }
  1125. foreach (var m in objectValueType!.GetOperatorOverloadMethods())
  1126. {
  1127. if (paramType.IsAssignableFrom(m.ReturnType) && m.Name is "op_Implicit" or "op_Explicit")
  1128. {
  1129. // implicit/explicit operator conversion is OK, but not ideal
  1130. return 3;
  1131. }
  1132. }
  1133. if (ReflectionExtensions.TryConvertViaTypeCoercion(paramType, engine.Options.Interop.ValueCoercion, parameterValue, out _))
  1134. {
  1135. // gray JS zone where we start to do odd things
  1136. return 10;
  1137. }
  1138. // will rarely succeed
  1139. return 100;
  1140. }
  1141. private static bool CanChangeType(object value, Type targetType)
  1142. {
  1143. if (value is null && !targetType.IsValueType)
  1144. {
  1145. return true;
  1146. }
  1147. if (value is not IConvertible)
  1148. {
  1149. return false;
  1150. }
  1151. try
  1152. {
  1153. Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
  1154. return true;
  1155. }
  1156. catch
  1157. {
  1158. // nope
  1159. return false;
  1160. }
  1161. }
  1162. internal static bool TypeIsNullable(Type type)
  1163. {
  1164. return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
  1165. }
  1166. }
  1167. }