TypeConverter.cs 42 KB

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