TypeConverter.cs 44 KB

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