TypeConverter.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. using System.Globalization;
  2. using System.Numerics;
  3. using System.Runtime.CompilerServices;
  4. using Jint.Native;
  5. using Jint.Native.Number;
  6. using Jint.Native.Object;
  7. using Jint.Native.String;
  8. using Jint.Native.Symbol;
  9. using Jint.Runtime.Interop;
  10. using Jint.Extensions;
  11. namespace Jint.Runtime
  12. {
  13. public static class TypeConverter
  14. {
  15. // how many decimals to check when determining if double is actually an int
  16. private const double DoubleIsIntegerTolerance = double.Epsilon * 100;
  17. private static readonly string[] intToString = new string[1024];
  18. private static readonly string[] charToString = new string[256];
  19. static TypeConverter()
  20. {
  21. for (var i = 0; i < intToString.Length; ++i)
  22. {
  23. intToString[i] = i.ToString(CultureInfo.InvariantCulture);
  24. }
  25. for (var i = 0; i < charToString.Length; ++i)
  26. {
  27. var c = (char) i;
  28. charToString[i] = c.ToString();
  29. }
  30. }
  31. /// <summary>
  32. /// https://tc39.es/ecma262/#sec-toprimitive
  33. /// </summary>
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public static JsValue ToPrimitive(JsValue input, Types preferredType = Types.Empty)
  36. {
  37. return input is not ObjectInstance oi
  38. ? input
  39. : ToPrimitiveObjectInstance(oi, preferredType);
  40. }
  41. private static JsValue ToPrimitiveObjectInstance(ObjectInstance oi, Types preferredType)
  42. {
  43. var exoticToPrim = oi.GetMethod(GlobalSymbolRegistry.ToPrimitive);
  44. if (exoticToPrim is not null)
  45. {
  46. var hint = preferredType switch
  47. {
  48. Types.String => JsString.StringString,
  49. Types.Number => JsString.NumberString,
  50. _ => JsString.DefaultString
  51. };
  52. var str = exoticToPrim.Call(oi, new JsValue[] { hint });
  53. if (str.IsPrimitive())
  54. {
  55. return str;
  56. }
  57. if (str.IsObject())
  58. {
  59. ExceptionHelper.ThrowTypeError(oi.Engine.Realm, "Cannot convert object to primitive value");
  60. }
  61. }
  62. return OrdinaryToPrimitive(oi, preferredType == Types.Empty ? Types.Number : preferredType);
  63. }
  64. /// <summary>
  65. /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
  66. /// </summary>
  67. internal static JsValue OrdinaryToPrimitive(ObjectInstance input, Types hint = Types.Empty)
  68. {
  69. JsString property1;
  70. JsString property2;
  71. if (hint == Types.String)
  72. {
  73. property1 = (JsString) "toString";
  74. property2 = (JsString) "valueOf";
  75. }
  76. else if (hint == Types.Number)
  77. {
  78. property1 = (JsString) "valueOf";
  79. property2 = (JsString) "toString";
  80. }
  81. else
  82. {
  83. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  84. return null;
  85. }
  86. if (input.Get(property1) is ICallable method1)
  87. {
  88. var val = method1.Call(input, Arguments.Empty);
  89. if (val.IsPrimitive())
  90. {
  91. return val;
  92. }
  93. }
  94. if (input.Get(property2) is ICallable method2)
  95. {
  96. var val = method2.Call(input, Arguments.Empty);
  97. if (val.IsPrimitive())
  98. {
  99. return val;
  100. }
  101. }
  102. ExceptionHelper.ThrowTypeError(input.Engine.Realm);
  103. return null;
  104. }
  105. /// <summary>
  106. /// https://tc39.es/ecma262/#sec-toboolean
  107. /// </summary>
  108. public static bool ToBoolean(JsValue o) => o.ToBoolean();
  109. /// <summary>
  110. /// https://tc39.es/ecma262/#sec-tonumeric
  111. /// </summary>
  112. public static JsValue ToNumeric(JsValue value)
  113. {
  114. if (value.IsNumber() || value.IsBigInt())
  115. {
  116. return value;
  117. }
  118. var primValue = ToPrimitive(value, Types.Number);
  119. if (primValue.IsBigInt())
  120. {
  121. return primValue;
  122. }
  123. return ToNumber(primValue);
  124. }
  125. /// <summary>
  126. /// https://tc39.es/ecma262/#sec-tonumber
  127. /// </summary>
  128. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  129. public static double ToNumber(JsValue o)
  130. {
  131. return o.IsNumber()
  132. ? ((JsNumber) o)._value
  133. : ToNumberUnlikely(o);
  134. }
  135. private static double ToNumberUnlikely(JsValue o)
  136. {
  137. var type = o._type & ~InternalTypes.InternalFlags;
  138. switch (type)
  139. {
  140. case InternalTypes.Undefined:
  141. return double.NaN;
  142. case InternalTypes.Null:
  143. return 0;
  144. case InternalTypes.Boolean:
  145. return ((JsBoolean) o)._value ? 1 : 0;
  146. case InternalTypes.String:
  147. return ToNumber(o.ToString());
  148. case InternalTypes.Symbol:
  149. case InternalTypes.BigInt:
  150. case InternalTypes.Empty:
  151. // TODO proper TypeError would require Engine instance and a lot of API changes
  152. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  153. return 0;
  154. default:
  155. return ToNumber(ToPrimitive(o, Types.Number));
  156. }
  157. }
  158. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  159. public static JsNumber ToJsNumber(JsValue o)
  160. {
  161. return o.IsNumber() ? (JsNumber) o : ToJsNumberUnlikely(o);
  162. }
  163. private static JsNumber ToJsNumberUnlikely(JsValue o)
  164. {
  165. var type = o._type & ~InternalTypes.InternalFlags;
  166. switch (type)
  167. {
  168. case InternalTypes.Undefined:
  169. return JsNumber.DoubleNaN;
  170. case InternalTypes.Null:
  171. return JsNumber.PositiveZero;
  172. case InternalTypes.Boolean:
  173. return ((JsBoolean) o)._value ? JsNumber.PositiveOne : JsNumber.PositiveZero;
  174. case InternalTypes.String:
  175. return new JsNumber(ToNumber(o.ToString()));
  176. case InternalTypes.Symbol:
  177. case InternalTypes.BigInt:
  178. case InternalTypes.Empty:
  179. // TODO proper TypeError would require Engine instance and a lot of API changes
  180. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + type + " value to a number");
  181. return JsNumber.PositiveZero;
  182. default:
  183. return new JsNumber(ToNumber(ToPrimitive(o, Types.Number)));
  184. }
  185. }
  186. private static double ToNumber(string input)
  187. {
  188. if (string.IsNullOrWhiteSpace(input))
  189. {
  190. return 0;
  191. }
  192. var firstChar = input[0];
  193. if (input.Length == 1)
  194. {
  195. return firstChar is >= '0' and <= '9' ? firstChar - '0' : double.NaN;
  196. }
  197. input = StringPrototype.TrimEx(input);
  198. firstChar = input[0];
  199. const NumberStyles NumberStyles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
  200. NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
  201. NumberStyles.AllowExponent;
  202. if (long.TryParse(input, NumberStyles, CultureInfo.InvariantCulture, out var longValue))
  203. {
  204. return longValue == 0 && firstChar == '-' ? -0.0 : longValue;
  205. }
  206. if (input.Length is 8 or 9)
  207. {
  208. switch (input)
  209. {
  210. case "+Infinity":
  211. case "Infinity":
  212. return double.PositiveInfinity;
  213. case "-Infinity":
  214. return double.NegativeInfinity;
  215. }
  216. if (input.EndsWith("infinity", StringComparison.OrdinalIgnoreCase))
  217. {
  218. // we don't accept other that case-sensitive
  219. return double.NaN;
  220. }
  221. }
  222. if (input.Length > 2 && firstChar == '0' && char.IsLetter(input[1]))
  223. {
  224. var fromBase = input[1] switch
  225. {
  226. 'x' or 'X' => 16,
  227. 'o' or 'O' => 8,
  228. 'b' or 'B' => 2,
  229. _ => 0
  230. };
  231. if (fromBase > 0)
  232. {
  233. try
  234. {
  235. return Convert.ToInt32(input.Substring(2), fromBase);
  236. }
  237. catch
  238. {
  239. return double.NaN;
  240. }
  241. }
  242. }
  243. if (double.TryParse(input, NumberStyles, CultureInfo.InvariantCulture, out var n))
  244. {
  245. return n == 0 && firstChar == '-' ? -0.0 : n;
  246. }
  247. return double.NaN;
  248. }
  249. /// <summary>
  250. /// https://tc39.es/ecma262/#sec-tolength
  251. /// </summary>
  252. public static ulong ToLength(JsValue o)
  253. {
  254. var len = ToInteger(o);
  255. if (len <= 0)
  256. {
  257. return 0;
  258. }
  259. return (ulong) Math.Min(len, NumberConstructor.MaxSafeInteger);
  260. }
  261. /// <summary>
  262. /// https://tc39.es/ecma262/#sec-tointegerorinfinity
  263. /// </summary>
  264. public static double ToIntegerOrInfinity(JsValue argument)
  265. {
  266. var number = ToNumber(argument);
  267. if (double.IsNaN(number) || number == 0)
  268. {
  269. return 0;
  270. }
  271. if (double.IsInfinity(number))
  272. {
  273. return number;
  274. }
  275. var integer = (long) Math.Floor(Math.Abs(number));
  276. if (number < 0)
  277. {
  278. integer *= -1;
  279. }
  280. return integer;
  281. }
  282. /// <summary>
  283. /// https://tc39.es/ecma262/#sec-tointeger
  284. /// </summary>
  285. public static double ToInteger(JsValue o)
  286. {
  287. return ToInteger(ToNumber(o));
  288. }
  289. /// <summary>
  290. /// https://tc39.es/ecma262/#sec-tointeger
  291. /// </summary>
  292. internal static double ToInteger(double number)
  293. {
  294. if (double.IsNaN(number))
  295. {
  296. return 0;
  297. }
  298. if (number == 0 || double.IsInfinity(number))
  299. {
  300. return number;
  301. }
  302. if (number is >= long.MinValue and <= long.MaxValue)
  303. {
  304. return (long) number;
  305. }
  306. var integer = Math.Floor(Math.Abs(number));
  307. if (number < 0)
  308. {
  309. integer *= -1;
  310. }
  311. return integer;
  312. }
  313. internal static int DoubleToInt32Slow(double o)
  314. {
  315. // Computes the integral value of the number mod 2^32.
  316. var doubleBits = BitConverter.DoubleToInt64Bits(o);
  317. var sign = (int) (doubleBits >> 63); // 0 if positive, -1 if negative
  318. var exponent = (int) ((doubleBits >> 52) & 0x7FF) - 1023;
  319. if ((uint) exponent >= 84)
  320. {
  321. // Anything with an exponent that is negative or >= 84 will convert to zero.
  322. // This includes infinities and NaNs, which have exponent = 1024
  323. // The 84 comes from 52 (bits in double mantissa) + 32 (bits in integer)
  324. return 0;
  325. }
  326. var mantissa = (doubleBits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
  327. var int32Value = exponent >= 52 ? (int) (mantissa << (exponent - 52)) : (int) (mantissa >> (52 - exponent));
  328. return (int32Value + sign) ^ sign;
  329. }
  330. /// <summary>
  331. /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5
  332. /// </summary>
  333. public static int ToInt32(JsValue o)
  334. {
  335. if (o._type == InternalTypes.Integer)
  336. {
  337. return o.AsInteger();
  338. }
  339. var doubleVal = ToNumber(o);
  340. if (doubleVal >= -(double) int.MinValue && doubleVal <= int.MaxValue)
  341. {
  342. // Double-to-int cast is correct in this range
  343. return (int) doubleVal;
  344. }
  345. return DoubleToInt32Slow(doubleVal);
  346. }
  347. /// <summary>
  348. /// https://tc39.es/ecma262/#sec-touint32
  349. /// </summary>
  350. public static uint ToUint32(JsValue o)
  351. {
  352. if (o._type == InternalTypes.Integer)
  353. {
  354. return (uint) o.AsInteger();
  355. }
  356. var doubleVal = ToNumber(o);
  357. if (doubleVal is >= 0.0 and <= uint.MaxValue)
  358. {
  359. // Double-to-uint cast is correct in this range
  360. return (uint) doubleVal;
  361. }
  362. return (uint) DoubleToInt32Slow(doubleVal);
  363. }
  364. /// <summary>
  365. /// https://tc39.es/ecma262/#sec-touint16
  366. /// </summary>
  367. public static ushort ToUint16(JsValue o)
  368. {
  369. if (o._type == InternalTypes.Integer)
  370. {
  371. var integer = o.AsInteger();
  372. if (integer is >= 0 and <= ushort.MaxValue)
  373. {
  374. return (ushort) integer;
  375. }
  376. }
  377. var number = ToNumber(o);
  378. if (double.IsNaN(number) || number == 0 || double.IsInfinity(number))
  379. {
  380. return 0;
  381. }
  382. var intValue = Math.Floor(Math.Abs(number));
  383. if (number < 0)
  384. {
  385. intValue *= -1;
  386. }
  387. var int16Bit = intValue % 65_536; // 2^16
  388. return (ushort) int16Bit;
  389. }
  390. /// <summary>
  391. /// https://tc39.es/ecma262/#sec-toint16
  392. /// </summary>
  393. internal static double ToInt16(JsValue o)
  394. {
  395. return o._type == InternalTypes.Integer
  396. ? (short) o.AsInteger()
  397. : (short) (long) ToNumber(o);
  398. }
  399. /// <summary>
  400. /// https://tc39.es/ecma262/#sec-toint8
  401. /// </summary>
  402. internal static double ToInt8(JsValue o)
  403. {
  404. return o._type == InternalTypes.Integer
  405. ? (sbyte) o.AsInteger()
  406. : (sbyte) (long) ToNumber(o);
  407. }
  408. /// <summary>
  409. /// https://tc39.es/ecma262/#sec-touint8
  410. /// </summary>
  411. internal static double ToUint8(JsValue o)
  412. {
  413. return o._type == InternalTypes.Integer
  414. ? (byte) o.AsInteger()
  415. : (byte) (long) ToNumber(o);
  416. }
  417. /// <summary>
  418. /// https://tc39.es/ecma262/#sec-touint8clamp
  419. /// </summary>
  420. internal static byte ToUint8Clamp(JsValue o)
  421. {
  422. if (o._type == InternalTypes.Integer)
  423. {
  424. var intValue = o.AsInteger();
  425. if (intValue is > -1 and < 256)
  426. {
  427. return (byte) intValue;
  428. }
  429. }
  430. return ToUint8ClampUnlikely(o);
  431. }
  432. private static byte ToUint8ClampUnlikely(JsValue o)
  433. {
  434. var number = ToNumber(o);
  435. if (double.IsNaN(number))
  436. {
  437. return 0;
  438. }
  439. if (number <= 0)
  440. {
  441. return 0;
  442. }
  443. if (number >= 255)
  444. {
  445. return 255;
  446. }
  447. var f = Math.Floor(number);
  448. if (f + 0.5 < number)
  449. {
  450. return (byte) (f + 1);
  451. }
  452. if (number < f + 0.5)
  453. {
  454. return (byte) f;
  455. }
  456. if (f % 2 != 0)
  457. {
  458. return (byte) (f + 1);
  459. }
  460. return (byte) f;
  461. }
  462. /// <summary>
  463. /// https://tc39.es/ecma262/#sec-tobigint
  464. /// </summary>
  465. public static BigInteger ToBigInt(JsValue value)
  466. {
  467. return value is JsBigInt bigInt
  468. ? bigInt._value
  469. : ToBigIntUnlikely(value);
  470. }
  471. private static BigInteger ToBigIntUnlikely(JsValue value)
  472. {
  473. var prim = ToPrimitive(value, Types.Number);
  474. switch (prim.Type)
  475. {
  476. case Types.BigInt:
  477. return ((JsBigInt) prim)._value;
  478. case Types.Boolean:
  479. return ((JsBoolean) prim)._value ? BigInteger.One : BigInteger.Zero;
  480. case Types.String:
  481. return StringToBigInt(prim.ToString());
  482. default:
  483. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  484. return BigInteger.One;
  485. }
  486. }
  487. public static JsBigInt ToJsBigInt(JsValue value)
  488. {
  489. return value as JsBigInt ?? ToJsBigIntUnlikely(value);
  490. }
  491. private static JsBigInt ToJsBigIntUnlikely(JsValue value)
  492. {
  493. var prim = ToPrimitive(value, Types.Number);
  494. switch (prim.Type)
  495. {
  496. case Types.BigInt:
  497. return (JsBigInt) prim;
  498. case Types.Boolean:
  499. return ((JsBoolean) prim)._value ? JsBigInt.One : JsBigInt.Zero;
  500. case Types.String:
  501. return new JsBigInt(StringToBigInt(prim.ToString()));
  502. default:
  503. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a " + prim.Type + " to a BigInt");
  504. return JsBigInt.One;
  505. }
  506. }
  507. internal static BigInteger StringToBigInt(string str)
  508. {
  509. if (!TryStringToBigInt(str, out var result))
  510. {
  511. // TODO: this doesn't seem a JS syntax error, use a dedicated exception type?
  512. throw new SyntaxError("CannotConvertToBigInt", " Cannot convert " + str + " to a BigInt").ToException();
  513. }
  514. return result;
  515. }
  516. internal static bool TryStringToBigInt(string str, out BigInteger result)
  517. {
  518. if (string.IsNullOrWhiteSpace(str))
  519. {
  520. result = BigInteger.Zero;
  521. return true;
  522. }
  523. str = str.Trim();
  524. for (var i = 0; i < str.Length; i++)
  525. {
  526. var c = str[i];
  527. if (!char.IsDigit(c))
  528. {
  529. if (i == 0 && (c == '-' || Character.IsDecimalDigit(c)))
  530. {
  531. // ok
  532. continue;
  533. }
  534. if (i != 1 && Character.IsHexDigit(c))
  535. {
  536. // ok
  537. continue;
  538. }
  539. if (i == 1 && (Character.IsDecimalDigit(c) || c is 'x' or 'X' or 'b' or 'B' or 'o' or 'O'))
  540. {
  541. // allowed, can be probably parsed
  542. continue;
  543. }
  544. result = default;
  545. return false;
  546. }
  547. }
  548. // check if we can get by using plain parsing
  549. if (BigInteger.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result))
  550. {
  551. return true;
  552. }
  553. if (str.Length > 2)
  554. {
  555. if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
  556. {
  557. // we get better precision if we don't hit floating point parsing that is performed by Esprima
  558. #if SUPPORTS_SPAN_PARSE
  559. var source = str.AsSpan(2);
  560. #else
  561. var source = str.Substring(2);
  562. #endif
  563. var c = source[0];
  564. if (c > 7 && Character.IsHexDigit(c))
  565. {
  566. // ensure we get positive number
  567. source = "0" + source.ToString();
  568. }
  569. if (BigInteger.TryParse(source, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result))
  570. {
  571. return true;
  572. }
  573. }
  574. else if (str.StartsWith("0o", StringComparison.OrdinalIgnoreCase) && Character.IsOctalDigit(str[2]))
  575. {
  576. // try parse large octal
  577. var bigInteger = new BigInteger();
  578. for (var i = 2; i < str.Length; i++)
  579. {
  580. var c = str[i];
  581. if (!Character.IsHexDigit(c))
  582. {
  583. return false;
  584. }
  585. bigInteger = bigInteger * 8 + c - '0';
  586. }
  587. result = bigInteger;
  588. return true;
  589. }
  590. else if (str.StartsWith("0b", StringComparison.OrdinalIgnoreCase) && Character.IsDecimalDigit(str[2]))
  591. {
  592. // try parse large binary
  593. var bigInteger = new BigInteger();
  594. for (var i = 2; i < str.Length; i++)
  595. {
  596. var c = str[i];
  597. if (c != '0' && c != '1')
  598. {
  599. // not good
  600. return false;
  601. }
  602. bigInteger <<= 1;
  603. bigInteger += c == '1' ? 1 : 0;
  604. }
  605. result = bigInteger;
  606. return true;
  607. }
  608. }
  609. return false;
  610. }
  611. /// <summary>
  612. /// https://tc39.es/ecma262/#sec-tobigint64
  613. /// </summary>
  614. internal static long ToBigInt64(BigInteger value)
  615. {
  616. var int64bit = BigIntegerModulo(value, BigInteger.Pow(2, 64));
  617. if (int64bit >= BigInteger.Pow(2, 63))
  618. {
  619. return (long) (int64bit - BigInteger.Pow(2, 64));
  620. }
  621. return (long) int64bit;
  622. }
  623. /// <summary>
  624. /// https://tc39.es/ecma262/#sec-tobiguint64
  625. /// </summary>
  626. internal static ulong ToBigUint64(BigInteger value)
  627. {
  628. return (ulong) BigIntegerModulo(value, BigInteger.Pow(2, 64));
  629. }
  630. /// <summary>
  631. /// Implements the JS spec modulo operation as expected.
  632. /// </summary>
  633. internal static BigInteger BigIntegerModulo(BigInteger a, BigInteger n)
  634. {
  635. return (a %= n) < 0 && n > 0 || a > 0 && n < 0 ? a + n : a;
  636. }
  637. /// <summary>
  638. /// https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  639. /// </summary>
  640. internal static double? CanonicalNumericIndexString(JsValue value)
  641. {
  642. if (value is JsNumber jsNumber)
  643. {
  644. return jsNumber._value;
  645. }
  646. if (value is JsString jsString)
  647. {
  648. if (string.Equals(jsString.ToString(), "-0", StringComparison.Ordinal))
  649. {
  650. return JsNumber.NegativeZero._value;
  651. }
  652. var n = ToNumber(value);
  653. if (!JsValue.SameValue(ToString(n), value))
  654. {
  655. return null;
  656. }
  657. return n;
  658. }
  659. return null;
  660. }
  661. /// <summary>
  662. /// https://tc39.es/ecma262/#sec-toindex
  663. /// </summary>
  664. public static uint ToIndex(Realm realm, JsValue value)
  665. {
  666. if (value.IsUndefined())
  667. {
  668. return 0;
  669. }
  670. var integerIndex = ToIntegerOrInfinity(value);
  671. if (integerIndex < 0)
  672. {
  673. ExceptionHelper.ThrowRangeError(realm);
  674. }
  675. var index = ToLength(integerIndex);
  676. if (integerIndex != index)
  677. {
  678. ExceptionHelper.ThrowRangeError(realm, "Invalid index");
  679. }
  680. return (uint) Math.Min(uint.MaxValue, index);
  681. }
  682. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  683. internal static string ToString(long i)
  684. {
  685. var temp = intToString;
  686. return (ulong) i < (ulong) temp.Length
  687. ? temp[i]
  688. : i.ToString(CultureInfo.InvariantCulture);
  689. }
  690. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  691. internal static string ToString(int i)
  692. {
  693. var temp = intToString;
  694. return (uint) i < (uint) temp.Length
  695. ? temp[i]
  696. : i.ToString(CultureInfo.InvariantCulture);
  697. }
  698. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  699. internal static string ToString(uint i)
  700. {
  701. var temp = intToString;
  702. return i < (uint) temp.Length
  703. ? temp[i]
  704. : i.ToString(CultureInfo.InvariantCulture);
  705. }
  706. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  707. internal static string ToString(char c)
  708. {
  709. var temp = charToString;
  710. return (uint) c < (uint) temp.Length
  711. ? temp[c]
  712. : c.ToString();
  713. }
  714. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  715. internal static string ToString(ulong i)
  716. {
  717. var temp = intToString;
  718. return i < (ulong) temp.Length
  719. ? temp[i]
  720. : i.ToString(CultureInfo.InvariantCulture);
  721. }
  722. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  723. internal static string ToString(double d)
  724. {
  725. if (CanBeStringifiedAsLong(d))
  726. {
  727. // we are dealing with integer that can be cached
  728. return ToString((long) d);
  729. }
  730. return NumberPrototype.ToNumberString(d);
  731. }
  732. /// <summary>
  733. /// Returns true if <see cref="ToString(long)"/> can be used for the
  734. /// provided value <paramref name="d"/>, otherwise false.
  735. /// </summary>
  736. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  737. internal static bool CanBeStringifiedAsLong(double d)
  738. {
  739. return d > long.MinValue && d < long.MaxValue && Math.Abs(d % 1) <= DoubleIsIntegerTolerance;
  740. }
  741. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  742. internal static string ToString(BigInteger bigInteger)
  743. {
  744. return bigInteger.ToString(CultureInfo.InvariantCulture);
  745. }
  746. /// <summary>
  747. /// http://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey
  748. /// </summary>
  749. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  750. public static JsValue ToPropertyKey(JsValue o)
  751. {
  752. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  753. return (o._type & PropertyKeys) != InternalTypes.Empty
  754. ? o
  755. : ToPropertyKeyNonString(o);
  756. }
  757. [MethodImpl(MethodImplOptions.NoInlining)]
  758. private static JsValue ToPropertyKeyNonString(JsValue o)
  759. {
  760. const InternalTypes PropertyKeys = InternalTypes.String | InternalTypes.Symbol | InternalTypes.PrivateName;
  761. var primitive = ToPrimitive(o, Types.String);
  762. return (primitive._type & PropertyKeys) != InternalTypes.Empty
  763. ? primitive
  764. : ToStringNonString(primitive);
  765. }
  766. /// <summary>
  767. /// https://tc39.es/ecma262/#sec-tostring
  768. /// </summary>
  769. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  770. public static string ToString(JsValue o)
  771. {
  772. return o.IsString() ? o.ToString() : ToStringNonString(o);
  773. }
  774. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  775. internal static JsString ToJsString(JsValue o)
  776. {
  777. if (o is JsString s)
  778. {
  779. return s;
  780. }
  781. return JsString.Create(ToStringNonString(o));
  782. }
  783. private static string ToStringNonString(JsValue o)
  784. {
  785. var type = o._type & ~InternalTypes.InternalFlags;
  786. switch (type)
  787. {
  788. case InternalTypes.Boolean:
  789. return ((JsBoolean) o)._value ? "true" : "false";
  790. case InternalTypes.Integer:
  791. return ToString((int) ((JsNumber) o)._value);
  792. case InternalTypes.Number:
  793. return ToString(((JsNumber) o)._value);
  794. case InternalTypes.BigInt:
  795. return ToString(((JsBigInt) o)._value);
  796. case InternalTypes.Symbol:
  797. ExceptionHelper.ThrowTypeErrorNoEngine("Cannot convert a Symbol value to a string");
  798. return null;
  799. case InternalTypes.Undefined:
  800. return "undefined";
  801. case InternalTypes.Null:
  802. return "null";
  803. case InternalTypes.PrivateName:
  804. return o.ToString();
  805. case InternalTypes.Object when o is IObjectWrapper p:
  806. return p.Target?.ToString()!;
  807. default:
  808. return ToString(ToPrimitive(o, Types.String));
  809. }
  810. }
  811. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  812. public static ObjectInstance ToObject(Realm realm, JsValue value)
  813. {
  814. if (value is ObjectInstance oi)
  815. {
  816. return oi;
  817. }
  818. return ToObjectNonObject(realm, value);
  819. }
  820. /// <summary>
  821. /// https://tc39.es/ecma262/#sec-isintegralnumber
  822. /// </summary>
  823. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  824. internal static bool IsIntegralNumber(double value)
  825. {
  826. return !double.IsNaN(value) && !double.IsInfinity(value) && value % 1 == 0;
  827. }
  828. private static ObjectInstance ToObjectNonObject(Realm realm, JsValue value)
  829. {
  830. var type = value._type & ~InternalTypes.InternalFlags;
  831. var intrinsics = realm.Intrinsics;
  832. switch (type)
  833. {
  834. case InternalTypes.Boolean:
  835. return intrinsics.Boolean.Construct((JsBoolean) value);
  836. case InternalTypes.Number:
  837. case InternalTypes.Integer:
  838. return intrinsics.Number.Construct((JsNumber) value);
  839. case InternalTypes.BigInt:
  840. return intrinsics.BigInt.Construct((JsBigInt) value);
  841. case InternalTypes.String:
  842. return intrinsics.String.Construct(value as JsString ?? JsString.Create(value.ToString()));
  843. case InternalTypes.Symbol:
  844. return intrinsics.Symbol.Construct((JsSymbol) value);
  845. case InternalTypes.Null:
  846. case InternalTypes.Undefined:
  847. ExceptionHelper.ThrowTypeError(realm, "Cannot convert undefined or null to object");
  848. return null;
  849. default:
  850. ExceptionHelper.ThrowTypeError(realm, "Cannot convert given item to object");
  851. return null;
  852. }
  853. }
  854. [MethodImpl(MethodImplOptions.NoInlining)]
  855. internal static void CheckObjectCoercible(
  856. Engine engine,
  857. JsValue o,
  858. Node sourceNode,
  859. string referenceName)
  860. {
  861. if (!engine._referenceResolver.CheckCoercible(o))
  862. {
  863. ThrowMemberNullOrUndefinedError(engine, o, sourceNode, referenceName);
  864. }
  865. }
  866. [MethodImpl(MethodImplOptions.NoInlining)]
  867. private static void ThrowMemberNullOrUndefinedError(
  868. Engine engine,
  869. JsValue o,
  870. Node sourceNode,
  871. string referencedName)
  872. {
  873. referencedName ??= "unknown";
  874. var message = $"Cannot read property '{referencedName}' of {o}";
  875. throw new JavaScriptException(engine.Realm.Intrinsics.TypeError, message)
  876. .SetJavaScriptCallstack(engine, sourceNode.Location, overwriteExisting: true);
  877. }
  878. public static void CheckObjectCoercible(Engine engine, JsValue o)
  879. {
  880. if (o._type < InternalTypes.Boolean)
  881. {
  882. ExceptionHelper.ThrowTypeError(engine.Realm, "Cannot call method on " + o);
  883. }
  884. }
  885. }
  886. }