TypeConverter.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. using System.Globalization;
  2. using System.Numerics;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Extensions;
  7. using Jint.Native;
  8. using Jint.Native.Number;
  9. using Jint.Native.Number.Dtoa;
  10. using Jint.Native.Object;
  11. using Jint.Native.String;
  12. using Jint.Native.Symbol;
  13. using Jint.Pooling;
  14. using Jint.Runtime.Interop;
  15. namespace Jint.Runtime
  16. {
  17. [Flags]
  18. public enum Types
  19. {
  20. None = 0,
  21. Undefined = 1,
  22. Null = 2,
  23. Boolean = 4,
  24. String = 8,
  25. Number = 16,
  26. Symbol = 64,
  27. BigInt = 128,
  28. Object = 256
  29. }
  30. [Flags]
  31. internal enum InternalTypes
  32. {
  33. // should not be used, used for empty match
  34. None = 0,
  35. Undefined = 1,
  36. Null = 2,
  37. // primitive types range start
  38. Boolean = 4,
  39. String = 8,
  40. Number = 16,
  41. Integer = 32,
  42. Symbol = 64,
  43. BigInt = 128,
  44. // primitive types range end
  45. Object = 256,
  46. // internal usage
  47. ObjectEnvironmentRecord = 512,
  48. RequiresCloning = 1024,
  49. Module = 2048,
  50. // the object doesn't override important GetOwnProperty etc which change behavior
  51. PlainObject = 4096,
  52. // our native array
  53. Array = 8192,
  54. Primitive = Boolean | String | Number | Integer | BigInt | Symbol,
  55. InternalFlags = ObjectEnvironmentRecord | RequiresCloning | PlainObject | Array | Module
  56. }
  57. public static class TypeConverter
  58. {
  59. // how many decimals to check when determining if double is actually an int
  60. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  61. private static readonly string[] intToString = new string[1024];
  62. private static readonly string[] charToString = new string[256];
  63. static TypeConverter()
  64. {
  65. for (var i = 0; i < intToString.Length; ++i)
  66. {
  67. intToString[i] = i.ToString();
  68. }
  69. for (var i = 0; i < charToString.Length; ++i)
  70. {
  71. var c = (char) i;
  72. charToString[i] = c.ToString();
  73. }
  74. }
  75. /// <summary>
  76. /// https://tc39.es/ecma262/#sec-toprimitive
  77. /// </summary>
  78. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  79. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.None)
  80. {
  81. return input is not ObjectInstance oi
  82. ? input
  83. : ToPrimitiveObjectInstance(oi, preferredType);
  84. }
  85. private static JsValue ToPrimitiveObjectInstance(ObjectInstance oi, Types preferredType)
  86. {
  87. var exoticToPrim = oi.GetMethod(GlobalSymbolRegistry.ToPrimitive);
  88. if (exoticToPrim is not null)
  89. {
  90. var hint = preferredType switch
  91. {
  92. Types.String => JsString.StringString,
  93. Types.Number => JsString.NumberString,
  94. _ => JsString.DefaultString
  95. };
  96. var str = exoticToPrim.Call(oi, new JsValue[] { hint });
  97. if (str.IsPrimitive())
  98. {
  99. return str;
  100. }
  101. if (str.IsObject())
  102. {
  103. ExceptionHelper.ThrowTypeError(oi.Engine.Realm, "Cannot convert object to primitive value");
  104. }
  105. }
  106. return OrdinaryToPrimitive(oi, preferredType == Types.None ? Types.Number : preferredType);
  107. }
  108. /// <summary>
  109. /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
  110. /// </summary>
  111. internal static JsValue OrdinaryToPrimitive(ObjectInstance input, Types hint = Types.None)
  112. {
  113. JsString property1;
  114. JsString property2;
  115. if (hint == Types.String)
  116. {
  117. property1 = (JsString) "toString";
  118. property2 = (JsString) "valueOf";
  119. }
  120. else if (hint == Types.Number)
  121. {
  122. property1 = (JsString) "valueOf";
  123. property2 = (JsString) "toString";
  124. }
  125. else
  126. {
  127. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  128. return null;
  129. }
  130. if (input.Get(property1) is ICallable method1)
  131. {
  132. var val = method1.Call(input, Arguments.Empty);
  133. if (val.IsPrimitive())
  134. {
  135. return val;
  136. }
  137. }
  138. if (input.Get(property2) is ICallable method2)
  139. {
  140. var val = method2.Call(input, Arguments.Empty);
  141. if (val.IsPrimitive())
  142. {
  143. return val;
  144. }
  145. }
  146. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  147. return null;
  148. }
  149. /// <summary>
  150. /// https://tc39.es/ecma262/#sec-toboolean
  151. /// </summary>
  152. public static bool ToBoolean(JsValue o) => o.ToBoolean();
  153. /// <summary>
  154. /// https://tc39.es/ecma262/#sec-tonumeric
  155. /// </summary>
  156. public static JsValue ToNumeric(JsValue value)
  157. {
  158. if (value.IsNumber() || value.IsBigInt())
  159. {
  160. return value;
  161. }
  162. var primValue = ToPrimitive(value, Types.Number);
  163. if (primValue.IsBigInt())
  164. {
  165. return primValue;
  166. }
  167. return ToNumber(primValue);
  168. }
  169. /// <summary>
  170. /// https://tc39.es/ecma262/#sec-tonumber
  171. /// </summary>
  172. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  173. public static double ToNumber(JsValue o)
  174. {
  175. return o.IsNumber()
  176. ? ((JsNumber) o)._value
  177. : ToNumberUnlikely(o);
  178. }
  179. private static double ToNumberUnlikely(JsValue o)
  180. {
  181. var type = o._type & ~InternalTypes.InternalFlags;
  182. switch (type)
  183. {
  184. case InternalTypes.Undefined:
  185. return double.NaN;
  186. case InternalTypes.Null:
  187. return 0;
  188. case InternalTypes.Boolean:
  189. return ((JsBoolean) o)._value ? 1 : 0;
  190. case InternalTypes.String:
  191. return ToNumber(o.ToString());
  192. case InternalTypes.Symbol:
  193. case InternalTypes.BigInt:
  194. // TODO proper TypeError would require Engine instance and a lot of API changes
  195. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  196. return 0;
  197. default:
  198. return ToNumber(ToPrimitive(o, Types.Number));
  199. }
  200. }
  201. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  202. public static JsNumber ToJsNumber(JsValue o)
  203. {
  204. return o.IsNumber() ? (JsNumber) o : ToJsNumberUnlikely(o);
  205. }
  206. private static JsNumber ToJsNumberUnlikely(JsValue o)
  207. {
  208. var type = o._type & ~InternalTypes.InternalFlags;
  209. switch (type)
  210. {
  211. case InternalTypes.Undefined:
  212. return JsNumber.DoubleNaN;
  213. case InternalTypes.Null:
  214. return JsNumber.PositiveZero;
  215. case InternalTypes.Boolean:
  216. return ((JsBoolean) o)._value ? JsNumber.PositiveOne : JsNumber.PositiveZero;
  217. case InternalTypes.String:
  218. return new JsNumber(ToNumber(o.ToString()));
  219. case InternalTypes.Symbol:
  220. case InternalTypes.BigInt:
  221. // TODO proper TypeError would require Engine instance and a lot of API changes
  222. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  223. return JsNumber.PositiveZero;
  224. default:
  225. return new JsNumber(ToNumber(ToPrimitive(o, Types.Number)));
  226. }
  227. }
  228. private static double ToNumber(string input)
  229. {
  230. // eager checks to save time and trimming
  231. if (string.IsNullOrEmpty(input))
  232. {
  233. return 0;
  234. }
  235. var first = input[0];
  236. if (input.Length == 1 && first >= '0' && first <= '9')
  237. {
  238. // simple constant number
  239. return first - '0';
  240. }
  241. var s = StringPrototype.TrimEx(input);
  242. if (s.Length == 0)
  243. {
  244. return 0;
  245. }
  246. if (s.Length == 8 || s.Length == 9)
  247. {
  248. if ("+Infinity" == s || "Infinity" == s)
  249. {
  250. return double.PositiveInfinity;
  251. }
  252. if ("-Infinity" == s)
  253. {
  254. return double.NegativeInfinity;
  255. }
  256. }
  257. // todo: use a common implementation with JavascriptParser
  258. try
  259. {
  260. if (s.Length > 2 && s[0] == '0' && char.IsLetter(s[1]))
  261. {
  262. var fromBase = 0;
  263. if (s[1] == 'x' || s[1] == 'X')
  264. {
  265. fromBase = 16;
  266. }
  267. if (s[1] == 'o' || s[1] == 'O')
  268. {
  269. fromBase = 8;
  270. }
  271. if (s[1] == 'b' || s[1] == 'B')
  272. {
  273. fromBase = 2;
  274. }
  275. if (fromBase > 0)
  276. {
  277. return Convert.ToInt32(s.Substring(2), fromBase);
  278. }
  279. }
  280. var start = s[0];
  281. if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
  282. {
  283. return double.NaN;
  284. }
  285. var n = double.Parse(s,
  286. NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  287. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  288. NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
  289. if (s.StartsWith("-") && n == 0)
  290. {
  291. return -0.0;
  292. }
  293. return n;
  294. }
  295. catch (OverflowException)
  296. {
  297. return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
  298. }
  299. catch
  300. {
  301. return double.NaN;
  302. }
  303. }
  304. /// <summary>
  305. /// https://tc39.es/ecma262/#sec-tolength
  306. /// </summary>
  307. public static ulong ToLength(JsValue o)
  308. {
  309. var len = ToInteger(o);
  310. if (len <= 0)
  311. {
  312. return 0;
  313. }
  314. return (ulong) Math.Min(len, NumberConstructor.MaxSafeInteger);
  315. }
  316. /// <summary>
  317. /// https://tc39.es/ecma262/#sec-tointegerorinfinity
  318. /// </summary>
  319. public static double ToIntegerOrInfinity(JsValue argument)
  320. {
  321. var number = ToNumber(argument);
  322. if (double.IsNaN(number) || number == 0)
  323. {
  324. return 0;
  325. }
  326. if (double.IsInfinity(number))
  327. {
  328. return number;
  329. }
  330. var integer = (long) Math.Floor(Math.Abs(number));
  331. if (number < 0)
  332. {
  333. integer *= -1;
  334. }
  335. return integer;
  336. }
  337. /// <summary>
  338. /// https://tc39.es/ecma262/#sec-tointeger
  339. /// </summary>
  340. public static double ToInteger(JsValue o)
  341. {
  342. return ToInteger(ToNumber(o));
  343. }
  344. /// <summary>
  345. /// https://tc39.es/ecma262/#sec-tointeger
  346. /// </summary>
  347. internal static double ToInteger(double number)
  348. {
  349. if (double.IsNaN(number))
  350. {
  351. return 0;
  352. }
  353. if (number == 0 || double.IsInfinity(number))
  354. {
  355. return number;
  356. }
  357. if (number is >= long.MinValue and <= long.MaxValue)
  358. {
  359. return (long) number;
  360. }
  361. var integer = Math.Floor(Math.Abs(number));
  362. if (number < 0)
  363. {
  364. integer *= -1;
  365. }
  366. return integer;
  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. public static JsBigInt ToJsBigInt(JsValue value)
  543. {
  544. return value as JsBigInt ?? ToJsBigIntUnlikely(value);
  545. }
  546. private static JsBigInt ToJsBigIntUnlikely(JsValue value)
  547. {
  548. var prim = ToPrimitive(value, Types.Number);
  549. switch (prim.Type)
  550. {
  551. case Types.BigInt:
  552. return (JsBigInt) prim;
  553. case Types.Boolean:
  554. return ((JsBoolean) prim)._value ? JsBigInt.One : JsBigInt.Zero;
  555. case Types.String:
  556. return new JsBigInt(StringToBigInt(prim.ToString()));
  557. default:
  558. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  559. return JsBigInt.One;
  560. }
  561. }
  562. internal static BigInteger StringToBigInt(string str)
  563. {
  564. if (!TryStringToBigInt(str, out var result))
  565. {
  566. throw new ParserException(" Cannot convert " + str + " to a BigInt");
  567. }
  568. return result;
  569. }
  570. internal static bool TryStringToBigInt(string str, out BigInteger result)
  571. {
  572. if (string.IsNullOrWhiteSpace(str))
  573. {
  574. result = BigInteger.Zero;
  575. return true;
  576. }
  577. str = str.Trim();
  578. for (var i = 0; i < str.Length; i++)
  579. {
  580. var c = str[i];
  581. if (!char.IsDigit(c))
  582. {
  583. if (i == 0 && (c == '-' || Character.IsDecimalDigit(c)))
  584. {
  585. // ok
  586. continue;
  587. }
  588. if (i != 1 && Character.IsHexDigit(c))
  589. {
  590. // ok
  591. continue;
  592. }
  593. if (i == 1 && (Character.IsDecimalDigit(c) || c is 'x' or 'X' or 'b' or 'B' or 'o' or 'O'))
  594. {
  595. // allowed, can be probably parsed
  596. continue;
  597. }
  598. result = default;
  599. return false;
  600. }
  601. }
  602. // check if we can get by using plain parsing
  603. if (BigInteger.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
  604. {
  605. return true;
  606. }
  607. if (str.Length > 2)
  608. {
  609. if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
  610. {
  611. // we get better precision if we don't hit floating point parsing that is performed by Esprima
  612. #if NETSTANDARD2_1_OR_GREATER
  613. var source = str.AsSpan(2);
  614. #else
  615. var source = str.Substring(2);
  616. #endif
  617. var c = source[0];
  618. if (c > 7 && Character.IsHexDigit(c))
  619. {
  620. // ensure we get positive number
  621. source = "0" + source.ToString();
  622. }
  623. if (BigInteger.TryParse(source, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
  624. {
  625. return true;
  626. }
  627. }
  628. else if (str.StartsWith("0o", StringComparison.OrdinalIgnoreCase) && Character.IsOctalDigit(str[2]))
  629. {
  630. // try parse large octal
  631. var bigInteger = new BigInteger();
  632. for (var i = 2; i < str.Length; i++)
  633. {
  634. var c = str[i];
  635. if (!Character.IsHexDigit(c))
  636. {
  637. return false;
  638. }
  639. bigInteger = bigInteger * 8 + c - '0';
  640. }
  641. result = bigInteger;
  642. return true;
  643. }
  644. else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase) && Character.IsDecimalDigit(str[2]))
  645. {
  646. // try parse large binary
  647. var bigInteger = new BigInteger();
  648. for (var i = 2; i < str.Length; i++)
  649. {
  650. var c = str[i];
  651. if (c != '0' && c != '1')
  652. {
  653. // not good
  654. return false;
  655. }
  656. bigInteger <<= 1;
  657. bigInteger += c == '1' ? 1 : 0;
  658. }
  659. result = bigInteger;
  660. return true;
  661. }
  662. }
  663. return false;
  664. }
  665. /// <summary>
  666. /// https://tc39.es/ecma262/#sec-tobigint64
  667. /// </summary>
  668. internal static long ToBigInt64(BigInteger value)
  669. {
  670. var int64bit = BigIntegerModulo(value, BigInteger.Pow(2, 64));
  671. if (int64bit >= BigInteger.Pow(2, 63))
  672. {
  673. return (long) (int64bit - BigInteger.Pow(2, 64));
  674. }
  675. return (long) int64bit;
  676. }
  677. /// <summary>
  678. /// https://tc39.es/ecma262/#sec-tobiguint64
  679. /// </summary>
  680. internal static ulong ToBigUint64(BigInteger value)
  681. {
  682. return (ulong) BigIntegerModulo(value, BigInteger.Pow(2, 64));
  683. }
  684. /// <summary>
  685. /// Implements the JS spec modulo operation as expected.
  686. /// </summary>
  687. internal static BigInteger BigIntegerModulo(BigInteger a, BigInteger n)
  688. {
  689. return (a %= n) < 0 && n > 0 || a > 0 && n < 0 ? a + n : a;
  690. }
  691. /// <summary>
  692. /// https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  693. /// </summary>
  694. internal static double? CanonicalNumericIndexString(JsValue value)
  695. {
  696. if (value is JsNumber jsNumber)
  697. {
  698. return jsNumber._value;
  699. }
  700. if (value is JsString jsString)
  701. {
  702. if (jsString.ToString() == "-0")
  703. {
  704. return JsNumber.NegativeZero._value;
  705. }
  706. var n = ToNumber(value);
  707. if (!JsValue.SameValue(ToString(n), value))
  708. {
  709. return null;
  710. }
  711. return n;
  712. }
  713. return null;
  714. }
  715. /// <summary>
  716. /// https://tc39.es/ecma262/#sec-toindex
  717. /// </summary>
  718. public static uint ToIndex(Realm realm, JsValue value)
  719. {
  720. if (value.IsUndefined())
  721. {
  722. return 0;
  723. }
  724. var integerIndex = ToIntegerOrInfinity(value);
  725. if (integerIndex < 0)
  726. {
  727. ExceptionHelper.ThrowRangeError(realm);
  728. }
  729. var index = ToLength(integerIndex);
  730. if (integerIndex != index)
  731. {
  732. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  733. }
  734. return (uint) Math.Min(uint.MaxValue, index);
  735. }
  736. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  737. internal static string ToString(long i)
  738. {
  739. return i >= 0 && i < intToString.Length
  740. ? intToString[i]
  741. : i.ToString();
  742. }
  743. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  744. internal static string ToString(int i)
  745. {
  746. return i >= 0 && i < intToString.Length
  747. ? intToString[i]
  748. : i.ToString();
  749. }
  750. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  751. internal static string ToString(uint i)
  752. {
  753. return i < (uint) intToString.Length
  754. ? intToString[i]
  755. : i.ToString();
  756. }
  757. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  758. internal static string ToString(char c)
  759. {
  760. return c >= 0 && c < charToString.Length
  761. ? charToString[c]
  762. : c.ToString();
  763. }
  764. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  765. internal static string ToString(ulong i)
  766. {
  767. return i >= 0 && i < (ulong) intToString.Length
  768. ? intToString[i]
  769. : i.ToString();
  770. }
  771. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  772. internal static string ToString(double d)
  773. {
  774. if (d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance)
  775. {
  776. // we are dealing with integer that can be cached
  777. return ToString((long) d);
  778. }
  779. using var stringBuilder = StringBuilderPool.Rent();
  780. // we can create smaller array as we know the format to be short
  781. return NumberPrototype.NumberToString(d, new DtoaBuilder(17), stringBuilder.Builder);
  782. }
  783. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  784. internal static string ToString(BigInteger bigInteger)
  785. {
  786. return bigInteger.ToString();
  787. }
  788. /// <summary>
  789. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  790. /// </summary>
  791. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  792. public static JsValue ToPropertyKey(JsValue o)
  793. {
  794. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  795. return (o._type & stringOrSymbol) != 0
  796. ? o
  797. : ToPropertyKeyNonString(o);
  798. }
  799. [MethodImpl(MethodImplOptions.NoInlining)]
  800. private static JsValue ToPropertyKeyNonString(JsValue o)
  801. {
  802. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  803. var primitive = ToPrimitive(o, Types.String);
  804. return (primitive._type & stringOrSymbol) != 0
  805. ? primitive
  806. : ToStringNonString(primitive);
  807. }
  808. /// <summary>
  809. /// https://tc39.es/ecma262/#sec-tostring
  810. /// </summary>
  811. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  812. public static string ToString(JsValue o)
  813. {
  814. return o.IsString() ? o.ToString() : ToStringNonString(o);
  815. }
  816. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  817. internal static JsString ToJsString(JsValue o)
  818. {
  819. if (o is JsString s)
  820. {
  821. return s;
  822. }
  823. return JsString.Create(ToStringNonString(o));
  824. }
  825. private static string ToStringNonString(JsValue o)
  826. {
  827. var type = o._type & ~InternalTypes.InternalFlags;
  828. switch (type)
  829. {
  830. case InternalTypes.Boolean:
  831. return ((JsBoolean) o)._value ? "true" : "false";
  832. case InternalTypes.Integer:
  833. return ToString((int) ((JsNumber) o)._value);
  834. case InternalTypes.Number:
  835. return ToString(((JsNumber) o)._value);
  836. case InternalTypes.BigInt:
  837. return ToString(((JsBigInt) o)._value);
  838. case InternalTypes.Symbol:
  839. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  840. return null;
  841. case InternalTypes.Undefined:
  842. return "undefined";
  843. case InternalTypes.Null:
  844. return "null";
  845. case InternalTypes.Object when o is IObjectWrapper p:
  846. return p.Target?.ToString()!;
  847. default:
  848. return ToString(ToPrimitive(o, Types.String));
  849. }
  850. }
  851. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  852. public static ObjectInstance ToObject(Realm realm, JsValue value)
  853. {
  854. if (value is ObjectInstance oi)
  855. {
  856. return oi;
  857. }
  858. return ToObjectNonObject(realm, value);
  859. }
  860. /// <summary>
  861. /// https://tc39.es/ecma262/#sec-isintegralnumber
  862. /// </summary>
  863. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  864. internal static bool IsIntegralNumber(double value)
  865. {
  866. return !double.IsNaN(value) && !double.IsInfinity(value) && value % 1 == 0;
  867. }
  868. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  869. {
  870. var type = value._type & ~InternalTypes.InternalFlags;
  871. switch (type)
  872. {
  873. case InternalTypes.Boolean:
  874. return realm.Intrinsics.Boolean.Construct((JsBoolean) value);
  875. case InternalTypes.Number:
  876. case InternalTypes.Integer:
  877. return realm.Intrinsics.Number.Construct((JsNumber) value);
  878. case InternalTypes.BigInt:
  879. return realm.Intrinsics.BigInt.Construct((JsBigInt) value);
  880. case InternalTypes.String:
  881. return realm.Intrinsics.String.Construct(value.ToString());
  882. case InternalTypes.Symbol:
  883. return realm.Intrinsics.Symbol.Construct((JsSymbol) value);
  884. case InternalTypes.Null:
  885. case InternalTypes.Undefined:
  886. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  887. return null;
  888. default:
  889. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  890. return null;
  891. }
  892. }
  893. [MethodImpl(MethodImplOptions.NoInlining)]
  894. internal static void CheckObjectCoercible(
  895. Engine engine,
  896. JsValue o,
  897. Node sourceNode,
  898. string referenceName)
  899. {
  900. if (!engine._referenceResolver.CheckCoercible(o))
  901. {
  902. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  903. }
  904. }
  905. [MethodImpl(MethodImplOptions.NoInlining)]
  906. private static void ThrowMemberNullOrUndefinedError(
  907. Engine engine,
  908. JsValue o,
  909. Node sourceNode,
  910. string referencedName)
  911. {
  912. referencedName ??= "unknown";
  913. var message = $"Cannot read property '{referencedName}' of {o}";
  914. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message)
  915. .SetJavaScriptCallstack(engine, sourceNode.Location, overwriteExisting: true);
  916. }
  917. public static void CheckObjectCoercible(Engine engine, JsValue o)
  918. {
  919. if (o._type < InternalTypes.Boolean)
  920. {
  921. ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o);
  922. }
  923. }
  924. internal readonly record struct MethodMatch(MethodDescriptor Method, JsValue[] Arguments, int Score = 0) : IComparable<MethodMatch>
  925. {
  926. public int CompareTo(MethodMatch other) => Score.CompareTo(other.Score);
  927. }
  928. internal static IEnumerable<MethodMatch> FindBestMatch(
  929. Engine engine,
  930. MethodDescriptor[] methods,
  931. Func<MethodDescriptor, JsValue[]> argumentProvider)
  932. {
  933. List<MethodMatch>? matchingByParameterCount = null;
  934. foreach (var method in methods)
  935. {
  936. var parameterInfos = method.Parameters;
  937. var arguments = argumentProvider(method);
  938. if (arguments.Length <= parameterInfos.Length
  939. && arguments.Length >= parameterInfos.Length - method.ParameterDefaultValuesCount)
  940. {
  941. var score = CalculateMethodScore(engine, method, arguments);
  942. if (score == 0)
  943. {
  944. // perfect match
  945. yield return new MethodMatch(method, arguments);
  946. yield break;
  947. }
  948. if (score < 0)
  949. {
  950. // discard
  951. continue;
  952. }
  953. matchingByParameterCount ??= new List<MethodMatch>();
  954. matchingByParameterCount.Add(new MethodMatch(method, arguments, score));
  955. }
  956. }
  957. if (matchingByParameterCount == null)
  958. {
  959. yield break;
  960. }
  961. if (matchingByParameterCount.Count > 1)
  962. {
  963. matchingByParameterCount.Sort();
  964. }
  965. foreach (var match in matchingByParameterCount)
  966. {
  967. yield return match;
  968. }
  969. }
  970. /// <summary>
  971. /// Method's match score tells how far away it's from ideal candidate. 0 = ideal, bigger the the number,
  972. /// the farther away the candidate is from ideal match. Negative signals impossible match.
  973. /// </summary>
  974. private static int CalculateMethodScore(Engine engine, MethodDescriptor method, JsValue[] arguments)
  975. {
  976. if (method.Parameters.Length == 0 && arguments.Length == 0)
  977. {
  978. // perfect
  979. return 0;
  980. }
  981. var score = 0;
  982. for (var i = 0; i < arguments.Length; i++)
  983. {
  984. var jsValue = arguments[i];
  985. var paramType = method.Parameters[i].ParameterType;
  986. var parameterScore = CalculateMethodParameterScore(engine, jsValue, paramType);
  987. if (parameterScore < 0)
  988. {
  989. return parameterScore;
  990. }
  991. score += parameterScore;
  992. }
  993. return score;
  994. }
  995. internal readonly record struct AssignableResult(int Score, Type MatchingGivenType)
  996. {
  997. public bool IsAssignable => Score >= 0;
  998. }
  999. /// <summary>
  1000. /// resources:
  1001. /// https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection
  1002. /// https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
  1003. /// https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  1004. /// This can be improved upon - specifically as mentioned in the above MS document:
  1005. /// GetGenericParameterConstraints()
  1006. /// and array handling - i.e.
  1007. /// GetElementType()
  1008. /// </summary>
  1009. internal static AssignableResult IsAssignableToGenericType(Type givenType, Type genericType)
  1010. {
  1011. if (givenType is null)
  1012. {
  1013. return new AssignableResult(-1, typeof(void));
  1014. }
  1015. if (!genericType.IsConstructedGenericType)
  1016. {
  1017. // as mentioned here:
  1018. // https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  1019. // 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
  1020. // whether any operations are being applied that "don't work"
  1021. return new AssignableResult(2, givenType);
  1022. }
  1023. var interfaceTypes = givenType.GetInterfaces();
  1024. foreach (var it in interfaceTypes)
  1025. {
  1026. if (it.IsGenericType)
  1027. {
  1028. var givenTypeGenericDef = it.GetGenericTypeDefinition();
  1029. if (givenTypeGenericDef == genericType)
  1030. {
  1031. return new AssignableResult(0, it);
  1032. }
  1033. else if (genericType.IsGenericType && (givenTypeGenericDef == genericType.GetGenericTypeDefinition()))
  1034. {
  1035. return new AssignableResult(0, it);
  1036. }
  1037. // TPC: we could also add a loop to recurse and iterate thru the iterfaces of generic type - because of covariance/contravariance
  1038. }
  1039. }
  1040. if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
  1041. {
  1042. return new AssignableResult(0, givenType);
  1043. }
  1044. Type baseType = givenType.BaseType;
  1045. if (baseType == null)
  1046. {
  1047. return new AssignableResult(-1, givenType);
  1048. }
  1049. return IsAssignableToGenericType(baseType, genericType);
  1050. }
  1051. /// <summary>
  1052. /// Determines how well parameter type matches target method's type.
  1053. /// </summary>
  1054. private static int CalculateMethodParameterScore(
  1055. Engine engine,
  1056. JsValue jsValue,
  1057. Type paramType)
  1058. {
  1059. var objectValue = jsValue.ToObject();
  1060. var objectValueType = objectValue?.GetType();
  1061. if (objectValueType == paramType)
  1062. {
  1063. return 0;
  1064. }
  1065. if (objectValue is null)
  1066. {
  1067. if (!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) && jsValue.IsInteger())
  1085. {
  1086. return 0;
  1087. }
  1088. if (paramType == typeof(float) && objectValueType == typeof(double))
  1089. {
  1090. return jsValue.IsInteger() ? 1 : 2;
  1091. }
  1092. if (paramType.IsEnum &&
  1093. jsValue 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 (jsValue.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, jsValue, 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. }