TypeConverter.cs 43 KB

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