TypeConverter.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using Esprima.Ast;
  7. using Jint.Extensions;
  8. using Jint.Native;
  9. using Jint.Native.Number;
  10. using Jint.Native.Number.Dtoa;
  11. using Jint.Native.Object;
  12. using Jint.Native.String;
  13. using Jint.Native.Symbol;
  14. using Jint.Pooling;
  15. using Jint.Runtime.Interop;
  16. namespace Jint.Runtime
  17. {
  18. [Flags]
  19. public enum Types
  20. {
  21. None = 0,
  22. Undefined = 1,
  23. Null = 2,
  24. Boolean = 4,
  25. String = 8,
  26. Number = 16,
  27. Symbol = 64,
  28. Object = 128
  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. // primitive types range end
  44. Object = 128,
  45. // internal usage
  46. ObjectEnvironmentRecord = 512,
  47. RequiresCloning = 1024,
  48. Primitive = Boolean | String | Number | Integer | Symbol,
  49. InternalFlags = ObjectEnvironmentRecord | RequiresCloning
  50. }
  51. public static class TypeConverter
  52. {
  53. // how many decimals to check when determining if double is actually an int
  54. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  55. internal static readonly string[] intToString = new string[1024];
  56. private static readonly string[] charToString = new string[256];
  57. static TypeConverter()
  58. {
  59. for (var i = 0; i < intToString.Length; ++i)
  60. {
  61. intToString[i] = i.ToString();
  62. }
  63. for (var i = 0; i < charToString.Length; ++i)
  64. {
  65. var c = (char) i;
  66. charToString[i] = c.ToString();
  67. }
  68. }
  69. /// <summary>
  70. /// https://tc39.es/ecma262/#sec-toprimitive
  71. /// </summary>
  72. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  73. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.None)
  74. {
  75. return input is not ObjectInstance oi
  76. ? input
  77. : ToPrimitiveObjectInstance(oi, preferredType);
  78. }
  79. private static JsValue ToPrimitiveObjectInstance(ObjectInstance oi, Types preferredType)
  80. {
  81. var hint = preferredType switch
  82. {
  83. Types.String => JsString.StringString,
  84. Types.Number => JsString.NumberString,
  85. _ => JsString.DefaultString
  86. };
  87. var exoticToPrim = oi.GetMethod(GlobalSymbolRegistry.ToPrimitive);
  88. if (exoticToPrim is object)
  89. {
  90. var str = exoticToPrim.Call(oi, new JsValue[] { hint });
  91. if (str.IsPrimitive())
  92. {
  93. return str;
  94. }
  95. if (str.IsObject())
  96. {
  97. ExceptionHelper.ThrowTypeError(oi.Engine.Realm, "Cannot convert object to primitive value");
  98. }
  99. }
  100. return OrdinaryToPrimitive(oi, preferredType == Types.None ? Types.Number : preferredType);
  101. }
  102. /// <summary>
  103. /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
  104. /// </summary>
  105. internal static JsValue OrdinaryToPrimitive(ObjectInstance input, Types hint = Types.None)
  106. {
  107. JsString property1;
  108. JsString property2;
  109. if (hint == Types.String)
  110. {
  111. property1 = (JsString) "toString";
  112. property2 = (JsString) "valueOf";
  113. }
  114. else if (hint == Types.Number)
  115. {
  116. property1 = (JsString) "valueOf";
  117. property2 = (JsString) "toString";
  118. }
  119. else
  120. {
  121. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  122. return null;
  123. }
  124. if (input.Get(property1) is ICallable method1)
  125. {
  126. var val = method1.Call(input, Arguments.Empty);
  127. if (val.IsPrimitive())
  128. {
  129. return val;
  130. }
  131. }
  132. if (input.Get(property2) is ICallable method2)
  133. {
  134. var val = method2.Call(input, Arguments.Empty);
  135. if (val.IsPrimitive())
  136. {
  137. return val;
  138. }
  139. }
  140. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  141. return null;
  142. }
  143. /// <summary>
  144. /// https://tc39.es/ecma262/#sec-toboolean
  145. /// </summary>
  146. public static bool ToBoolean(JsValue o)
  147. {
  148. var type = o._type & ~InternalTypes.InternalFlags;
  149. switch (type)
  150. {
  151. case InternalTypes.Boolean:
  152. return ((JsBoolean) o)._value;
  153. case InternalTypes.Undefined:
  154. case InternalTypes.Null:
  155. return false;
  156. case InternalTypes.Integer:
  157. return (int) ((JsNumber) o)._value != 0;
  158. case InternalTypes.Number:
  159. var n = ((JsNumber) o)._value;
  160. return n != 0 && !double.IsNaN(n);
  161. case InternalTypes.String:
  162. return !((JsString) o).IsNullOrEmpty();
  163. default:
  164. return true;
  165. }
  166. }
  167. /// <summary>
  168. /// https://tc39.es/ecma262/#sec-tonumber
  169. /// </summary>
  170. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  171. public static double ToNumber(JsValue o)
  172. {
  173. return o.IsNumber()
  174. ? ((JsNumber) o)._value
  175. : ToNumberUnlikely(o);
  176. }
  177. private static double ToNumberUnlikely(JsValue o)
  178. {
  179. var type = o._type & ~InternalTypes.InternalFlags;
  180. switch (type)
  181. {
  182. case InternalTypes.Undefined:
  183. return double.NaN;
  184. case InternalTypes.Null:
  185. return 0;
  186. case InternalTypes.Object when o is IPrimitiveInstance p:
  187. return ToNumber(ToPrimitive(p.PrimitiveValue, Types.Number));
  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. // TODO proper TypeError would require Engine instance and a lot of API changes
  194. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a number");
  195. return 0;
  196. default:
  197. return ToNumber(ToPrimitive(o, Types.Number));
  198. }
  199. }
  200. private static double ToNumber(string input)
  201. {
  202. // eager checks to save time and trimming
  203. if (string.IsNullOrEmpty(input))
  204. {
  205. return 0;
  206. }
  207. var first = input[0];
  208. if (input.Length == 1 && first >= '0' && first <= '9')
  209. {
  210. // simple constant number
  211. return first - '0';
  212. }
  213. var s = StringPrototype.TrimEx(input);
  214. if (s.Length == 0)
  215. {
  216. return 0;
  217. }
  218. if (s.Length == 8 || s.Length == 9)
  219. {
  220. if ("+Infinity" == s || "Infinity" == s)
  221. {
  222. return double.PositiveInfinity;
  223. }
  224. if ("-Infinity" == s)
  225. {
  226. return double.NegativeInfinity;
  227. }
  228. }
  229. // todo: use a common implementation with JavascriptParser
  230. try
  231. {
  232. if (s.Length > 2 && s[0] == '0' && char.IsLetter(s[1]))
  233. {
  234. var fromBase = 0;
  235. if (s[1] == 'x' || s[1] == 'X')
  236. {
  237. fromBase = 16;
  238. }
  239. if (s[1] == 'o' || s[1] == 'O')
  240. {
  241. fromBase = 8;
  242. }
  243. if (s[1] == 'b' || s[1] == 'B')
  244. {
  245. fromBase = 2;
  246. }
  247. if (fromBase > 0)
  248. {
  249. return Convert.ToInt32(s.Substring(2), fromBase);
  250. }
  251. }
  252. var start = s[0];
  253. if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
  254. {
  255. return double.NaN;
  256. }
  257. var n = double.Parse(s,
  258. NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  259. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  260. NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
  261. if (s.StartsWith("-") && n == 0)
  262. {
  263. return -0.0;
  264. }
  265. return n;
  266. }
  267. catch (OverflowException)
  268. {
  269. return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
  270. }
  271. catch
  272. {
  273. return double.NaN;
  274. }
  275. }
  276. /// <summary>
  277. /// https://tc39.es/ecma262/#sec-tolength
  278. /// </summary>
  279. public static ulong ToLength(JsValue o)
  280. {
  281. var len = ToInteger(o);
  282. if (len <= 0)
  283. {
  284. return 0;
  285. }
  286. return (ulong) Math.Min(len, NumberConstructor.MaxSafeInteger);
  287. }
  288. /// <summary>
  289. /// https://tc39.es/ecma262/#sec-tointegerorinfinity
  290. /// </summary>
  291. public static double ToIntegerOrInfinity(JsValue argument)
  292. {
  293. var number = ToNumber(argument);
  294. if (double.IsNaN(number) || number == 0)
  295. {
  296. return 0;
  297. }
  298. if (double.IsInfinity(number))
  299. {
  300. return number;
  301. }
  302. var integer = (long) Math.Floor(Math.Abs(number));
  303. if (number < 0)
  304. {
  305. integer *= -1;
  306. }
  307. return integer;
  308. }
  309. /// <summary>
  310. /// https://tc39.es/ecma262/#sec-tointeger
  311. /// </summary>
  312. public static double ToInteger(JsValue o)
  313. {
  314. var number = ToNumber(o);
  315. if (double.IsNaN(number))
  316. {
  317. return 0;
  318. }
  319. if (number == 0 || double.IsInfinity(number))
  320. {
  321. return number;
  322. }
  323. return (long) number;
  324. }
  325. internal static double ToInteger(string o)
  326. {
  327. var number = ToNumber(o);
  328. if (double.IsNaN(number))
  329. {
  330. return 0;
  331. }
  332. if (number == 0 || double.IsInfinity(number))
  333. {
  334. return number;
  335. }
  336. return (long) number;
  337. }
  338. internal static int DoubleToInt32Slow(double o)
  339. {
  340. // Computes the integral value of the number mod 2^32.
  341. var doubleBits = BitConverter.DoubleToInt64Bits(o);
  342. var sign = (int) (doubleBits >> 63); // 0 if positive, -1 if negative
  343. var exponent = (int) ((doubleBits >> 52) & 0x7FF) - 1023;
  344. if ((uint) exponent >= 84)
  345. {
  346. // Anything with an exponent that is negative or >= 84 will convert to zero.
  347. // This includes infinities and NaNs, which have exponent = 1024
  348. // The 84 comes from 52 (bits in double mantissa) + 32 (bits in integer)
  349. return 0;
  350. }
  351. var mantissa = (doubleBits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
  352. var int32Value = exponent >= 52 ? (int) (mantissa << (exponent - 52)) : (int) (mantissa >> (52 - exponent));
  353. return (int32Value + sign) ^ sign;
  354. }
  355. /// <summary>
  356. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
  357. /// </summary>
  358. public static int ToInt32(JsValue o)
  359. {
  360. if (o._type == InternalTypes.Integer)
  361. {
  362. return o.AsInteger();
  363. }
  364. var doubleVal = ToNumber(o);
  365. if (doubleVal >= -(double) int.MinValue && doubleVal <= int.MaxValue)
  366. {
  367. // Double-to-int cast is correct in this range
  368. return (int) doubleVal;
  369. }
  370. return DoubleToInt32Slow(doubleVal);
  371. }
  372. /// <summary>
  373. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6
  374. /// </summary>
  375. public static uint ToUint32(JsValue o)
  376. {
  377. if (o._type == InternalTypes.Integer)
  378. {
  379. return (uint) o.AsInteger();
  380. }
  381. var doubleVal = ToNumber(o);
  382. if (doubleVal >= 0.0 && doubleVal <= uint.MaxValue)
  383. {
  384. // Double-to-uint cast is correct in this range
  385. return (uint) doubleVal;
  386. }
  387. return (uint) DoubleToInt32Slow(doubleVal);
  388. }
  389. /// <summary>
  390. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7
  391. /// </summary>
  392. public static ushort ToUint16(JsValue o)
  393. {
  394. return o._type == InternalTypes.Integer
  395. ? (ushort) (uint) o.AsInteger()
  396. : (ushort) (uint) ToNumber(o);
  397. }
  398. /// <summary>
  399. /// https://tc39.es/ecma262/#sec-toint16
  400. /// </summary>
  401. internal static double ToInt16(JsValue o)
  402. {
  403. return o._type == InternalTypes.Integer
  404. ? (short) o.AsInteger()
  405. : (short) (long) ToNumber(o);
  406. }
  407. /// <summary>
  408. /// https://tc39.es/ecma262/#sec-toint8
  409. /// </summary>
  410. internal static double ToInt8(JsValue o)
  411. {
  412. return o._type == InternalTypes.Integer
  413. ? (sbyte) o.AsInteger()
  414. : (sbyte) (long) ToNumber(o);
  415. }
  416. /// <summary>
  417. /// https://tc39.es/ecma262/#sec-touint8
  418. /// </summary>
  419. internal static double ToUint8(JsValue o)
  420. {
  421. return o._type == InternalTypes.Integer
  422. ? (byte) o.AsInteger()
  423. : (byte) (long) ToNumber(o);
  424. }
  425. /// <summary>
  426. /// https://tc39.es/ecma262/#sec-touint8clamp
  427. /// </summary>
  428. internal static double ToUint8Clamp(JsValue o)
  429. {
  430. if (o._type == InternalTypes.Integer)
  431. {
  432. var intValue = o.AsInteger();
  433. if (intValue is > -1 and < 256)
  434. {
  435. return intValue;
  436. }
  437. }
  438. var number = ToNumber(o);
  439. if (double.IsNaN(number))
  440. {
  441. return 0;
  442. }
  443. if (number <= 0)
  444. {
  445. return 0;
  446. }
  447. if (number >= 255)
  448. {
  449. return 255;
  450. }
  451. var f = Math.Floor(number);
  452. if (f + 0.5 < number)
  453. {
  454. return f + 1;
  455. }
  456. if (number < f + 0.5)
  457. {
  458. return f;
  459. }
  460. if (f % 2 != 0)
  461. {
  462. return f + 1;
  463. }
  464. return f;
  465. }
  466. /// <summary>
  467. /// https://tc39.es/ecma262/#sec-tobigint64
  468. /// </summary>
  469. internal static double ToBigInt64(JsValue value)
  470. {
  471. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  472. return 0;
  473. }
  474. /// <summary>
  475. /// https://tc39.es/ecma262/#sec-tobiguint64
  476. /// </summary>
  477. internal static double ToBigUint64(JsValue value)
  478. {
  479. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  480. return 0;
  481. }
  482. /// <summary>
  483. /// https://tc39.es/ecma262/#sec-toindex
  484. /// </summary>
  485. public static uint ToIndex(Realm realm, JsValue value)
  486. {
  487. if (value.IsUndefined())
  488. {
  489. return 0;
  490. }
  491. var integerIndex = ToIntegerOrInfinity(value);
  492. if (integerIndex < 0)
  493. {
  494. ExceptionHelper.ThrowRangeError(realm);
  495. }
  496. var index = ToLength(integerIndex);
  497. if (integerIndex != index)
  498. {
  499. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  500. }
  501. return (uint) Math.Min(uint.MaxValue, index);
  502. }
  503. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  504. internal static string ToString(long i)
  505. {
  506. return i >= 0 && i < intToString.Length
  507. ? intToString[i]
  508. : i.ToString();
  509. }
  510. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  511. internal static string ToString(int i)
  512. {
  513. return i >= 0 && i < intToString.Length
  514. ? intToString[i]
  515. : i.ToString();
  516. }
  517. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  518. internal static string ToString(uint i)
  519. {
  520. return i < (uint) intToString.Length
  521. ? intToString[i]
  522. : i.ToString();
  523. }
  524. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  525. internal static string ToString(char c)
  526. {
  527. return c >= 0 && c < charToString.Length
  528. ? charToString[c]
  529. : c.ToString();
  530. }
  531. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  532. internal static string ToString(ulong i)
  533. {
  534. return i >= 0 && i < (ulong) intToString.Length
  535. ? intToString[i]
  536. : i.ToString();
  537. }
  538. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  539. internal static string ToString(double d)
  540. {
  541. if (d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance)
  542. {
  543. // we are dealing with integer that can be cached
  544. return ToString((long) d);
  545. }
  546. using var stringBuilder = StringBuilderPool.Rent();
  547. // we can create smaller array as we know the format to be short
  548. return NumberPrototype.NumberToString(d, new DtoaBuilder(17), stringBuilder.Builder);
  549. }
  550. /// <summary>
  551. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  552. /// </summary>
  553. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  554. public static JsValue ToPropertyKey(JsValue o)
  555. {
  556. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  557. return (o._type & stringOrSymbol) != 0
  558. ? o
  559. : ToPropertyKeyNonString(o);
  560. }
  561. [MethodImpl(MethodImplOptions.NoInlining)]
  562. private static JsValue ToPropertyKeyNonString(JsValue o)
  563. {
  564. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  565. var primitive = ToPrimitive(o, Types.String);
  566. return (primitive._type & stringOrSymbol) != 0
  567. ? primitive
  568. : ToStringNonString(primitive);
  569. }
  570. /// <summary>
  571. /// http://www.ecma-international.org/ecma-262/6.0/#sec-tostring
  572. /// </summary>
  573. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  574. public static string ToString(JsValue o)
  575. {
  576. return o.IsString() ? o.ToString() : ToStringNonString(o);
  577. }
  578. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  579. internal static JsString ToJsString(JsValue o)
  580. {
  581. if (o is JsString s)
  582. {
  583. return s;
  584. }
  585. return JsString.Create(ToStringNonString(o));
  586. }
  587. private static string ToStringNonString(JsValue o)
  588. {
  589. var type = o._type & ~InternalTypes.InternalFlags;
  590. switch (type)
  591. {
  592. case InternalTypes.Boolean:
  593. return ((JsBoolean) o)._value ? "true" : "false";
  594. case InternalTypes.Integer:
  595. return ToString((int) ((JsNumber) o)._value);
  596. case InternalTypes.Number:
  597. return ToString(((JsNumber) o)._value);
  598. case InternalTypes.Symbol:
  599. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  600. return null;
  601. case InternalTypes.Undefined:
  602. return Undefined.Text;
  603. case InternalTypes.Null:
  604. return Null.Text;
  605. case InternalTypes.Object when o is IPrimitiveInstance p:
  606. return ToString(ToPrimitive(p.PrimitiveValue, Types.String));
  607. case InternalTypes.Object when o is IObjectWrapper p:
  608. return p.Target?.ToString();
  609. default:
  610. return ToString(ToPrimitive(o, Types.String));
  611. }
  612. }
  613. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  614. public static ObjectInstance ToObject(Realm realm, JsValue value)
  615. {
  616. if (value is ObjectInstance oi)
  617. {
  618. return oi;
  619. }
  620. return ToObjectNonObject(realm, value);
  621. }
  622. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  623. {
  624. var type = value._type & ~InternalTypes.InternalFlags;
  625. switch (type)
  626. {
  627. case InternalTypes.Boolean:
  628. return realm.Intrinsics.Boolean.Construct((JsBoolean) value);
  629. case InternalTypes.Number:
  630. case InternalTypes.Integer:
  631. return realm.Intrinsics.Number.Construct((JsNumber) value);
  632. case InternalTypes.String:
  633. return realm.Intrinsics.String.Construct(value.ToString());
  634. case InternalTypes.Symbol:
  635. return realm.Intrinsics.Symbol.Construct((JsSymbol) value);
  636. case InternalTypes.Null:
  637. case InternalTypes.Undefined:
  638. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  639. return null;
  640. default:
  641. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  642. return null;
  643. }
  644. }
  645. [MethodImpl(MethodImplOptions.NoInlining)]
  646. internal static void CheckObjectCoercible(
  647. Engine engine,
  648. JsValue o,
  649. Node sourceNode,
  650. string referenceName)
  651. {
  652. if (!engine.Options.ReferenceResolver.CheckCoercible(o))
  653. {
  654. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  655. }
  656. }
  657. [MethodImpl(MethodImplOptions.NoInlining)]
  658. private static void ThrowMemberNullOrUndefinedError(
  659. Engine engine,
  660. JsValue o,
  661. Node sourceNode,
  662. string referencedName)
  663. {
  664. referencedName ??= "unknown";
  665. var message = $"Cannot read property '{referencedName}' of {o}";
  666. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message).SetCallstack(engine, sourceNode.Location);
  667. }
  668. public static void CheckObjectCoercible(Engine engine, JsValue o)
  669. {
  670. if (o._type < InternalTypes.Boolean)
  671. {
  672. ExceptionHelper.ThrowTypeError(engine.Realm);
  673. }
  674. }
  675. internal static IEnumerable<Tuple<MethodDescriptor, JsValue[]>> FindBestMatch(
  676. Engine engine,
  677. MethodDescriptor[] methods,
  678. Func<MethodDescriptor, JsValue[]> argumentProvider)
  679. {
  680. List<Tuple<MethodDescriptor, JsValue[]>> matchingByParameterCount = null;
  681. foreach (var m in methods)
  682. {
  683. var parameterInfos = m.Parameters;
  684. var arguments = argumentProvider(m);
  685. if (arguments.Length <= parameterInfos.Length
  686. && arguments.Length >= parameterInfos.Length - m.ParameterDefaultValuesCount)
  687. {
  688. if (methods.Length == 0 && arguments.Length == 0)
  689. {
  690. yield return new Tuple<MethodDescriptor, JsValue[]>(m, arguments);
  691. yield break;
  692. }
  693. matchingByParameterCount ??= new List<Tuple<MethodDescriptor, JsValue[]>>();
  694. matchingByParameterCount.Add(new Tuple<MethodDescriptor, JsValue[]>(m, arguments));
  695. }
  696. }
  697. if (matchingByParameterCount == null)
  698. {
  699. yield break;
  700. }
  701. List<Tuple<int, Tuple<MethodDescriptor, JsValue[]>>> scoredList = null;
  702. foreach (var tuple in matchingByParameterCount)
  703. {
  704. var score = 0;
  705. var parameters = tuple.Item1.Parameters;
  706. var arguments = tuple.Item2;
  707. for (var i = 0; i < arguments.Length; i++)
  708. {
  709. var jsValue = arguments[i];
  710. var arg = jsValue.ToObject();
  711. var argType = arg?.GetType();
  712. var paramType = parameters[i].ParameterType;
  713. if (arg == null)
  714. {
  715. if (!TypeIsNullable(paramType))
  716. {
  717. score -= 10000;
  718. }
  719. }
  720. else if (paramType == typeof(JsValue))
  721. {
  722. // JsValue is convertible to. But it is still not a perfect match
  723. score -= 1;
  724. }
  725. else if (argType != paramType)
  726. {
  727. // check if we can do conversion from int value to enum
  728. if (paramType.IsEnum &&
  729. jsValue is JsNumber jsNumber
  730. && jsNumber.IsInteger()
  731. && Enum.IsDefined(paramType, jsNumber.AsInteger()))
  732. {
  733. // OK
  734. }
  735. else
  736. {
  737. if (paramType.IsAssignableFrom(argType))
  738. {
  739. score -= 10;
  740. }
  741. else
  742. {
  743. if (argType.GetOperatorOverloadMethods()
  744. .Any(m => paramType.IsAssignableFrom(m.ReturnType) &&
  745. (m.Name == "op_Implicit" ||
  746. m.Name == "op_Explicit")))
  747. {
  748. score -= 100;
  749. }
  750. else
  751. {
  752. score -= 1000;
  753. }
  754. }
  755. }
  756. }
  757. }
  758. if (score == 0)
  759. {
  760. yield return Tuple.Create(tuple.Item1, arguments);
  761. yield break;
  762. }
  763. else
  764. {
  765. scoredList ??= new List<Tuple<int, Tuple<MethodDescriptor, JsValue[]>>>();
  766. scoredList.Add(Tuple.Create(score, tuple));
  767. }
  768. }
  769. if (scoredList != null)
  770. {
  771. foreach (var item in scoredList.OrderByDescending(x => x.Item1))
  772. {
  773. yield return item.Item2;
  774. }
  775. }
  776. }
  777. internal static bool TypeIsNullable(Type type)
  778. {
  779. return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
  780. }
  781. }
  782. }