2
0

TypeConverter.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 byte 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 (byte) intValue;
  436. }
  437. }
  438. return ToUint8ClampUnlikely(o);
  439. }
  440. private static byte ToUint8ClampUnlikely(JsValue o)
  441. {
  442. var number = ToNumber(o);
  443. if (double.IsNaN(number))
  444. {
  445. return 0;
  446. }
  447. if (number <= 0)
  448. {
  449. return 0;
  450. }
  451. if (number >= 255)
  452. {
  453. return 255;
  454. }
  455. var f = Math.Floor(number);
  456. if (f + 0.5 < number)
  457. {
  458. return (byte) (f + 1);
  459. }
  460. if (number < f + 0.5)
  461. {
  462. return (byte) f;
  463. }
  464. if (f % 2 != 0)
  465. {
  466. return (byte) (f + 1);
  467. }
  468. return (byte) f;
  469. }
  470. /// <summary>
  471. /// https://tc39.es/ecma262/#sec-tobigint
  472. /// </summary>
  473. public static double ToBigInt(JsValue value)
  474. {
  475. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  476. return 0;
  477. }
  478. /// <summary>
  479. /// https://tc39.es/ecma262/#sec-tobigint64
  480. /// </summary>
  481. internal static double ToBigInt64(JsValue value)
  482. {
  483. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  484. return 0;
  485. }
  486. /// <summary>
  487. /// https://tc39.es/ecma262/#sec-tobiguint64
  488. /// </summary>
  489. internal static double ToBigUint64(JsValue value)
  490. {
  491. ExceptionHelper.ThrowNotImplementedException("BigInt not implemented");
  492. return 0;
  493. }
  494. /// <summary>
  495. /// https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  496. /// </summary>
  497. internal static double? CanonicalNumericIndexString(JsValue value)
  498. {
  499. if (value is JsNumber jsNumber)
  500. {
  501. return jsNumber._value;
  502. }
  503. if (value is JsString jsString)
  504. {
  505. if (jsString.ToString() == "-0")
  506. {
  507. return -0d;
  508. }
  509. var n = ToNumber(value);
  510. if (!JsValue.SameValue(ToString(n), value))
  511. {
  512. return null;
  513. }
  514. return n;
  515. }
  516. return null;
  517. }
  518. /// <summary>
  519. /// https://tc39.es/ecma262/#sec-toindex
  520. /// </summary>
  521. public static uint ToIndex(Realm realm, JsValue value)
  522. {
  523. if (value.IsUndefined())
  524. {
  525. return 0;
  526. }
  527. var integerIndex = ToIntegerOrInfinity(value);
  528. if (integerIndex < 0)
  529. {
  530. ExceptionHelper.ThrowRangeError(realm);
  531. }
  532. var index = ToLength(integerIndex);
  533. if (integerIndex != index)
  534. {
  535. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  536. }
  537. return (uint) Math.Min(uint.MaxValue, index);
  538. }
  539. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  540. internal static string ToString(long i)
  541. {
  542. return i >= 0 && i < intToString.Length
  543. ? intToString[i]
  544. : i.ToString();
  545. }
  546. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  547. internal static string ToString(int i)
  548. {
  549. return i >= 0 && i < intToString.Length
  550. ? intToString[i]
  551. : i.ToString();
  552. }
  553. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  554. internal static string ToString(uint i)
  555. {
  556. return i < (uint) intToString.Length
  557. ? intToString[i]
  558. : i.ToString();
  559. }
  560. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  561. internal static string ToString(char c)
  562. {
  563. return c >= 0 && c < charToString.Length
  564. ? charToString[c]
  565. : c.ToString();
  566. }
  567. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  568. internal static string ToString(ulong i)
  569. {
  570. return i >= 0 && i < (ulong) intToString.Length
  571. ? intToString[i]
  572. : i.ToString();
  573. }
  574. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  575. internal static string ToString(double d)
  576. {
  577. if (d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance)
  578. {
  579. // we are dealing with integer that can be cached
  580. return ToString((long) d);
  581. }
  582. using var stringBuilder = StringBuilderPool.Rent();
  583. // we can create smaller array as we know the format to be short
  584. return NumberPrototype.NumberToString(d, new DtoaBuilder(17), stringBuilder.Builder);
  585. }
  586. /// <summary>
  587. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  588. /// </summary>
  589. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  590. public static JsValue ToPropertyKey(JsValue o)
  591. {
  592. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  593. return (o._type & stringOrSymbol) != 0
  594. ? o
  595. : ToPropertyKeyNonString(o);
  596. }
  597. [MethodImpl(MethodImplOptions.NoInlining)]
  598. private static JsValue ToPropertyKeyNonString(JsValue o)
  599. {
  600. const InternalTypes stringOrSymbol = InternalTypes.String | InternalTypes.Symbol;
  601. var primitive = ToPrimitive(o, Types.String);
  602. return (primitive._type & stringOrSymbol) != 0
  603. ? primitive
  604. : ToStringNonString(primitive);
  605. }
  606. /// <summary>
  607. /// http://www.ecma-international.org/ecma-262/6.0/#sec-tostring
  608. /// </summary>
  609. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  610. public static string ToString(JsValue o)
  611. {
  612. return o.IsString() ? o.ToString() : ToStringNonString(o);
  613. }
  614. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  615. internal static JsString ToJsString(JsValue o)
  616. {
  617. if (o is JsString s)
  618. {
  619. return s;
  620. }
  621. return JsString.Create(ToStringNonString(o));
  622. }
  623. private static string ToStringNonString(JsValue o)
  624. {
  625. var type = o._type & ~InternalTypes.InternalFlags;
  626. switch (type)
  627. {
  628. case InternalTypes.Boolean:
  629. return ((JsBoolean) o)._value ? "true" : "false";
  630. case InternalTypes.Integer:
  631. return ToString((int) ((JsNumber) o)._value);
  632. case InternalTypes.Number:
  633. return ToString(((JsNumber) o)._value);
  634. case InternalTypes.Symbol:
  635. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  636. return null;
  637. case InternalTypes.Undefined:
  638. return Undefined.Text;
  639. case InternalTypes.Null:
  640. return Null.Text;
  641. case InternalTypes.Object when o is IPrimitiveInstance p:
  642. return ToString(ToPrimitive(p.PrimitiveValue, Types.String));
  643. case InternalTypes.Object when o is IObjectWrapper p:
  644. return p.Target?.ToString();
  645. default:
  646. return ToString(ToPrimitive(o, Types.String));
  647. }
  648. }
  649. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  650. public static ObjectInstance ToObject(Realm realm, JsValue value)
  651. {
  652. if (value is ObjectInstance oi)
  653. {
  654. return oi;
  655. }
  656. return ToObjectNonObject(realm, value);
  657. }
  658. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  659. {
  660. var type = value._type & ~InternalTypes.InternalFlags;
  661. switch (type)
  662. {
  663. case InternalTypes.Boolean:
  664. return realm.Intrinsics.Boolean.Construct((JsBoolean) value);
  665. case InternalTypes.Number:
  666. case InternalTypes.Integer:
  667. return realm.Intrinsics.Number.Construct((JsNumber) value);
  668. case InternalTypes.String:
  669. return realm.Intrinsics.String.Construct(value.ToString());
  670. case InternalTypes.Symbol:
  671. return realm.Intrinsics.Symbol.Construct((JsSymbol) value);
  672. case InternalTypes.Null:
  673. case InternalTypes.Undefined:
  674. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  675. return null;
  676. default:
  677. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  678. return null;
  679. }
  680. }
  681. [MethodImpl(MethodImplOptions.NoInlining)]
  682. internal static void CheckObjectCoercible(
  683. Engine engine,
  684. JsValue o,
  685. Node sourceNode,
  686. string referenceName)
  687. {
  688. if (!engine._referenceResolver.CheckCoercible(o))
  689. {
  690. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  691. }
  692. }
  693. [MethodImpl(MethodImplOptions.NoInlining)]
  694. private static void ThrowMemberNullOrUndefinedError(
  695. Engine engine,
  696. JsValue o,
  697. Node sourceNode,
  698. string referencedName)
  699. {
  700. referencedName ??= "unknown";
  701. var message = $"Cannot read property '{referencedName}' of {o}";
  702. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message).SetCallstack(engine, sourceNode.Location);
  703. }
  704. public static void CheckObjectCoercible(Engine engine, JsValue o)
  705. {
  706. if (o._type < InternalTypes.Boolean)
  707. {
  708. ExceptionHelper.ThrowTypeError(engine.Realm);
  709. }
  710. }
  711. internal static IEnumerable<Tuple<MethodDescriptor, JsValue[]>> FindBestMatch(
  712. Engine engine,
  713. MethodDescriptor[] methods,
  714. Func<MethodDescriptor, JsValue[]> argumentProvider)
  715. {
  716. List<Tuple<MethodDescriptor, JsValue[]>> matchingByParameterCount = null;
  717. foreach (var m in methods)
  718. {
  719. var parameterInfos = m.Parameters;
  720. var arguments = argumentProvider(m);
  721. if (arguments.Length <= parameterInfos.Length
  722. && arguments.Length >= parameterInfos.Length - m.ParameterDefaultValuesCount)
  723. {
  724. if (methods.Length == 0 && arguments.Length == 0)
  725. {
  726. yield return new Tuple<MethodDescriptor, JsValue[]>(m, arguments);
  727. yield break;
  728. }
  729. matchingByParameterCount ??= new List<Tuple<MethodDescriptor, JsValue[]>>();
  730. matchingByParameterCount.Add(new Tuple<MethodDescriptor, JsValue[]>(m, arguments));
  731. }
  732. }
  733. if (matchingByParameterCount == null)
  734. {
  735. yield break;
  736. }
  737. List<Tuple<int, Tuple<MethodDescriptor, JsValue[]>>> scoredList = null;
  738. foreach (var tuple in matchingByParameterCount)
  739. {
  740. var score = 0;
  741. var parameters = tuple.Item1.Parameters;
  742. var arguments = tuple.Item2;
  743. for (var i = 0; i < arguments.Length; i++)
  744. {
  745. var jsValue = arguments[i];
  746. var arg = jsValue.ToObject();
  747. var argType = arg?.GetType();
  748. var paramType = parameters[i].ParameterType;
  749. if (arg == null)
  750. {
  751. if (!TypeIsNullable(paramType))
  752. {
  753. score -= 10000;
  754. }
  755. }
  756. else if (paramType == typeof(JsValue))
  757. {
  758. // JsValue is convertible to. But it is still not a perfect match
  759. score -= 1;
  760. }
  761. else if (argType != paramType)
  762. {
  763. // check if we can do conversion from int value to enum
  764. if (paramType.IsEnum &&
  765. jsValue is JsNumber jsNumber
  766. && jsNumber.IsInteger()
  767. && Enum.IsDefined(paramType, jsNumber.AsInteger()))
  768. {
  769. // OK
  770. }
  771. else
  772. {
  773. if (paramType.IsAssignableFrom(argType))
  774. {
  775. score -= 10;
  776. }
  777. else
  778. {
  779. if (argType.GetOperatorOverloadMethods()
  780. .Any(m => paramType.IsAssignableFrom(m.ReturnType) &&
  781. (m.Name == "op_Implicit" ||
  782. m.Name == "op_Explicit")))
  783. {
  784. score -= 100;
  785. }
  786. else
  787. {
  788. score -= 1000;
  789. }
  790. }
  791. }
  792. }
  793. }
  794. if (score == 0)
  795. {
  796. yield return Tuple.Create(tuple.Item1, arguments);
  797. yield break;
  798. }
  799. else
  800. {
  801. scoredList ??= new List<Tuple<int, Tuple<MethodDescriptor, JsValue[]>>>();
  802. scoredList.Add(Tuple.Create(score, tuple));
  803. }
  804. }
  805. if (scoredList != null)
  806. {
  807. foreach (var item in scoredList.OrderByDescending(x => x.Item1))
  808. {
  809. yield return item.Item2;
  810. }
  811. }
  812. }
  813. internal static bool TypeIsNullable(Type type)
  814. {
  815. return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
  816. }
  817. }
  818. }