JintExpression.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. using System.Numerics;
  2. using System.Runtime.CompilerServices;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Number;
  7. namespace Jint.Runtime.Interpreter.Expressions
  8. {
  9. internal abstract class JintExpression
  10. {
  11. protected internal readonly Expression _expression;
  12. protected JintExpression(Expression expression)
  13. {
  14. _expression = expression;
  15. }
  16. /// <summary>
  17. /// Resolves the underlying value for this expression.
  18. /// By default uses the Engine for resolving.
  19. /// </summary>
  20. /// <param name="context"></param>
  21. /// <seealso cref="JintLiteralExpression"/>
  22. public virtual JsValue GetValue(EvaluationContext context)
  23. {
  24. var result = Evaluate(context);
  25. if (result is not Reference reference)
  26. {
  27. return (JsValue) result;
  28. }
  29. return context.Engine.GetValue(reference, returnReferenceToPool: true);
  30. }
  31. [MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions) 512)]
  32. public object Evaluate(EvaluationContext context)
  33. {
  34. var oldSyntaxElement = context.LastSyntaxElement;
  35. context.PrepareFor(_expression);
  36. var result = EvaluateInternal(context);
  37. context.LastSyntaxElement = oldSyntaxElement;
  38. return result;
  39. }
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. internal object EvaluateWithoutNodeTracking(EvaluationContext context)
  42. {
  43. return EvaluateInternal(context);
  44. }
  45. protected abstract object EvaluateInternal(EvaluationContext context);
  46. /// <summary>
  47. /// If we'd get Esprima source, we would just refer to it, but this makes error messages easier to decipher.
  48. /// </summary>
  49. internal string SourceText => ToString(_expression) ?? "*unknown*";
  50. internal static string? ToString(Expression expression)
  51. {
  52. while (true)
  53. {
  54. if (expression is Literal literal)
  55. {
  56. return EsprimaExtensions.LiteralKeyToString(literal);
  57. }
  58. if (expression is Identifier identifier)
  59. {
  60. return identifier.Name;
  61. }
  62. if (expression is MemberExpression memberExpression)
  63. {
  64. return ToString(memberExpression.Object) + "." + ToString(memberExpression.Property);
  65. }
  66. if (expression is CallExpression callExpression)
  67. {
  68. expression = callExpression.Callee;
  69. continue;
  70. }
  71. return null;
  72. }
  73. }
  74. protected internal static JintExpression Build(Expression expression)
  75. {
  76. if (expression.AssociatedData is JintExpression preparedExpression)
  77. {
  78. return preparedExpression;
  79. }
  80. var result = expression.Type switch
  81. {
  82. Nodes.AssignmentExpression => JintAssignmentExpression.Build((AssignmentExpression) expression),
  83. Nodes.ArrayExpression => JintArrayExpression.Build((ArrayExpression) expression),
  84. Nodes.ArrowFunctionExpression => new JintArrowFunctionExpression((ArrowFunctionExpression) expression),
  85. Nodes.BinaryExpression => JintBinaryExpression.Build((BinaryExpression) expression),
  86. Nodes.CallExpression => new JintCallExpression((CallExpression) expression),
  87. Nodes.ConditionalExpression => new JintConditionalExpression((ConditionalExpression) expression),
  88. Nodes.FunctionExpression => new JintFunctionExpression((FunctionExpression) expression),
  89. Nodes.Identifier => new JintIdentifierExpression((Identifier) expression),
  90. Nodes.PrivateIdentifier => new JintPrivateIdentifierExpression((PrivateIdentifier) expression),
  91. Nodes.Literal => JintLiteralExpression.Build((Literal) expression),
  92. Nodes.LogicalExpression => ((BinaryExpression) expression).Operator switch
  93. {
  94. BinaryOperator.LogicalAnd => new JintLogicalAndExpression((BinaryExpression) expression),
  95. BinaryOperator.LogicalOr => new JintLogicalOrExpression((BinaryExpression) expression),
  96. BinaryOperator.NullishCoalescing => new NullishCoalescingExpression((BinaryExpression) expression),
  97. _ => null
  98. },
  99. Nodes.MemberExpression => new JintMemberExpression((MemberExpression) expression),
  100. Nodes.NewExpression => new JintNewExpression((NewExpression) expression),
  101. Nodes.ObjectExpression => JintObjectExpression.Build((ObjectExpression) expression),
  102. Nodes.SequenceExpression => new JintSequenceExpression((SequenceExpression) expression),
  103. Nodes.ThisExpression => new JintThisExpression((ThisExpression) expression),
  104. Nodes.UpdateExpression => new JintUpdateExpression((UpdateExpression) expression),
  105. Nodes.UnaryExpression => JintUnaryExpression.Build((UnaryExpression) expression),
  106. Nodes.SpreadElement => new JintSpreadExpression((SpreadElement) expression),
  107. Nodes.TemplateLiteral => new JintTemplateLiteralExpression((TemplateLiteral) expression),
  108. Nodes.TaggedTemplateExpression => new JintTaggedTemplateExpression((TaggedTemplateExpression) expression),
  109. Nodes.ClassExpression => new JintClassExpression((ClassExpression) expression),
  110. Nodes.ImportExpression => new JintImportExpression((ImportExpression) expression),
  111. Nodes.Super => new JintSuperExpression((Super) expression),
  112. Nodes.MetaProperty => new JintMetaPropertyExpression((MetaProperty) expression),
  113. Nodes.ChainExpression => ((ChainExpression) expression).Expression.Type == Nodes.CallExpression
  114. ? new JintCallExpression((CallExpression) ((ChainExpression) expression).Expression)
  115. : new JintMemberExpression((MemberExpression) ((ChainExpression) expression).Expression),
  116. Nodes.AwaitExpression => new JintAwaitExpression((AwaitExpression) expression),
  117. _ => null
  118. };
  119. if (result is null)
  120. {
  121. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(expression), $"unsupported expression type '{expression.Type}'");
  122. }
  123. return result;
  124. }
  125. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  126. protected static JsValue Divide(EvaluationContext context, JsValue left, JsValue right)
  127. {
  128. JsValue result;
  129. if (AreIntegerOperands(left, right))
  130. {
  131. result = DivideInteger(left, right);
  132. }
  133. else if (JintBinaryExpression.AreNonBigIntOperands(left, right))
  134. {
  135. result = DivideComplex(left, right);
  136. }
  137. else
  138. {
  139. JintBinaryExpression.AssertValidBigIntArithmeticOperands(left, right);
  140. var x = TypeConverter.ToBigInt(left);
  141. var y = TypeConverter.ToBigInt(right);
  142. if (y == 0)
  143. {
  144. ExceptionHelper.ThrowRangeError(context.Engine.Realm, "Division by zero");
  145. }
  146. result = JsBigInt.Create(x / y);
  147. }
  148. return result;
  149. }
  150. private static JsValue DivideInteger(JsValue lval, JsValue rval)
  151. {
  152. var lN = lval.AsInteger();
  153. var rN = rval.AsInteger();
  154. if (lN == 0 && rN == 0)
  155. {
  156. return JsNumber.DoubleNaN;
  157. }
  158. if (rN == 0)
  159. {
  160. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  161. }
  162. if (lN % rN == 0 && (lN != 0 || rN > 0))
  163. {
  164. return JsNumber.Create(lN / rN);
  165. }
  166. return (double) lN / rN;
  167. }
  168. private static JsValue DivideComplex(JsValue lval, JsValue rval)
  169. {
  170. if (lval.IsUndefined() || rval.IsUndefined())
  171. {
  172. return JsValue.Undefined;
  173. }
  174. else
  175. {
  176. var lN = TypeConverter.ToNumber(lval);
  177. var rN = TypeConverter.ToNumber(rval);
  178. if (double.IsNaN(rN) || double.IsNaN(lN))
  179. {
  180. return JsNumber.DoubleNaN;
  181. }
  182. if (double.IsInfinity(lN) && double.IsInfinity(rN))
  183. {
  184. return JsNumber.DoubleNaN;
  185. }
  186. if (double.IsInfinity(lN) && rN == 0)
  187. {
  188. if (NumberInstance.IsNegativeZero(rN))
  189. {
  190. return -lN;
  191. }
  192. return lN;
  193. }
  194. if (lN == 0 && rN == 0)
  195. {
  196. return JsNumber.DoubleNaN;
  197. }
  198. if (rN == 0)
  199. {
  200. if (NumberInstance.IsNegativeZero(rN))
  201. {
  202. return lN > 0 ? -double.PositiveInfinity : -double.NegativeInfinity;
  203. }
  204. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  205. }
  206. return lN / rN;
  207. }
  208. }
  209. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  210. protected static JsValue Compare(JsValue x, JsValue y, bool leftFirst = true) =>
  211. x.IsNumber() && y.IsNumber()
  212. ? CompareNumber(x, y, leftFirst)
  213. : CompareComplex(x, y, leftFirst);
  214. private static JsValue CompareNumber(JsValue x, JsValue y, bool leftFirst)
  215. {
  216. double nx, ny;
  217. if (leftFirst)
  218. {
  219. nx = x.AsNumber();
  220. ny = y.AsNumber();
  221. }
  222. else
  223. {
  224. ny = y.AsNumber();
  225. nx = x.AsNumber();
  226. }
  227. if (x.IsInteger() && y.IsInteger())
  228. {
  229. return (int) nx < (int) ny ? JsBoolean.True : JsBoolean.False;
  230. }
  231. if (!double.IsInfinity(nx) && !double.IsInfinity(ny) && !double.IsNaN(nx) && !double.IsNaN(ny))
  232. {
  233. return nx < ny ? JsBoolean.True : JsBoolean.False;
  234. }
  235. return CompareComplex(x, y, leftFirst);
  236. }
  237. private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst)
  238. {
  239. JsValue px, py;
  240. if (leftFirst)
  241. {
  242. px = TypeConverter.ToPrimitive(x, Types.Number);
  243. py = TypeConverter.ToPrimitive(y, Types.Number);
  244. }
  245. else
  246. {
  247. py = TypeConverter.ToPrimitive(y, Types.Number);
  248. px = TypeConverter.ToPrimitive(x, Types.Number);
  249. }
  250. var typea = px.Type;
  251. var typeb = py.Type;
  252. if (typea != Types.String || typeb != Types.String)
  253. {
  254. if (typea == Types.BigInt || typeb == Types.BigInt)
  255. {
  256. if (typea == typeb)
  257. {
  258. return TypeConverter.ToBigInt(px) < TypeConverter.ToBigInt(py) ? JsBoolean.True : JsBoolean.False;
  259. }
  260. if (typea == Types.BigInt)
  261. {
  262. if (py is JsString jsStringY)
  263. {
  264. if (!TypeConverter.TryStringToBigInt(jsStringY.ToString(), out var temp))
  265. {
  266. return JsValue.Undefined;
  267. }
  268. return TypeConverter.ToBigInt(px) < temp ? JsBoolean.True : JsBoolean.False;
  269. }
  270. var numberB = TypeConverter.ToNumber(py);
  271. if (double.IsNaN(numberB))
  272. {
  273. return JsValue.Undefined;
  274. }
  275. if (double.IsPositiveInfinity(numberB))
  276. {
  277. return JsBoolean.True;
  278. }
  279. if (double.IsNegativeInfinity(numberB))
  280. {
  281. return JsBoolean.False;
  282. }
  283. var normalized = new BigInteger(Math.Ceiling(numberB));
  284. return TypeConverter.ToBigInt(px) < normalized ? JsBoolean.True : JsBoolean.False;
  285. }
  286. if (px is JsString jsStringX)
  287. {
  288. if (!TypeConverter.TryStringToBigInt(jsStringX.ToString(), out var temp))
  289. {
  290. return JsValue.Undefined;
  291. }
  292. return temp < TypeConverter.ToBigInt(py) ? JsBoolean.True : JsBoolean.False;
  293. }
  294. var numberA = TypeConverter.ToNumber(px);
  295. if (double.IsNaN(numberA))
  296. {
  297. return JsValue.Undefined;
  298. }
  299. if (double.IsPositiveInfinity(numberA))
  300. {
  301. return JsBoolean.False;
  302. }
  303. if (double.IsNegativeInfinity(numberA))
  304. {
  305. return JsBoolean.True;
  306. }
  307. var normalizedA = new BigInteger(Math.Floor(numberA));
  308. return normalizedA < TypeConverter.ToBigInt(py);
  309. }
  310. var nx = TypeConverter.ToNumber(px);
  311. var ny = TypeConverter.ToNumber(py);
  312. if (double.IsNaN(nx) || double.IsNaN(ny))
  313. {
  314. return JsValue.Undefined;
  315. }
  316. if (nx == ny)
  317. {
  318. return JsBoolean.False;
  319. }
  320. if (double.IsPositiveInfinity(nx))
  321. {
  322. return JsBoolean.False;
  323. }
  324. if (double.IsPositiveInfinity(ny))
  325. {
  326. return JsBoolean.True;
  327. }
  328. if (double.IsNegativeInfinity(ny))
  329. {
  330. return JsBoolean.False;
  331. }
  332. if (double.IsNegativeInfinity(nx))
  333. {
  334. return JsBoolean.True;
  335. }
  336. return nx < ny ? JsBoolean.True : JsBoolean.False;
  337. }
  338. return string.CompareOrdinal(TypeConverter.ToString(x), TypeConverter.ToString(y)) < 0 ? JsBoolean.True : JsBoolean.False;
  339. }
  340. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  341. protected static void BuildArguments(EvaluationContext context, JintExpression[] jintExpressions, JsValue[] targetArray)
  342. {
  343. for (uint i = 0; i < (uint) jintExpressions.Length; i++)
  344. {
  345. targetArray[i] = jintExpressions[i].GetValue(context).Clone();
  346. }
  347. }
  348. protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, JintExpression[] jintExpressions)
  349. {
  350. var args = new List<JsValue>(jintExpressions.Length);
  351. foreach (var jintExpression in jintExpressions)
  352. {
  353. if (jintExpression is JintSpreadExpression jse)
  354. {
  355. jse.GetValueAndCheckIterator(context, out var objectInstance, out var iterator);
  356. // optimize for array unless someone has touched the iterator
  357. if (objectInstance is JsArray { HasOriginalIterator: true } ai)
  358. {
  359. var length = ai.GetLength();
  360. for (uint j = 0; j < length; ++j)
  361. {
  362. ai.TryGetValue(j, out var value);
  363. args.Add(value);
  364. }
  365. }
  366. else
  367. {
  368. var protocol = new ArraySpreadProtocol(context.Engine, args, iterator!);
  369. protocol.Execute();
  370. }
  371. }
  372. else
  373. {
  374. args.Add(jintExpression.GetValue(context).Clone());
  375. }
  376. }
  377. return args.ToArray();
  378. }
  379. private sealed class ArraySpreadProtocol : IteratorProtocol
  380. {
  381. private readonly List<JsValue> _instance;
  382. public ArraySpreadProtocol(
  383. Engine engine,
  384. List<JsValue> instance,
  385. IteratorInstance iterator) : base(engine, iterator, 0)
  386. {
  387. _instance = instance;
  388. }
  389. protected override void ProcessItem(JsValue[] arguments, JsValue currentValue)
  390. {
  391. _instance.Add(currentValue);
  392. }
  393. }
  394. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  395. protected static bool AreIntegerOperands(JsValue left, JsValue right)
  396. {
  397. return left._type == right._type && left._type == InternalTypes.Integer;
  398. }
  399. }
  400. }