TypeConverter.cs 44 KB

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