JintExpression.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. Nodes.YieldExpression => new JintYieldExpression((YieldExpression) expression),
  118. _ => null
  119. };
  120. if (result is null)
  121. {
  122. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(expression), $"unsupported expression type '{expression.Type}'");
  123. }
  124. return result;
  125. }
  126. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  127. protected static JsValue Divide(EvaluationContext context, JsValue left, JsValue right)
  128. {
  129. JsValue result;
  130. if (AreIntegerOperands(left, right))
  131. {
  132. result = DivideInteger(left, right);
  133. }
  134. else if (JintBinaryExpression.AreNonBigIntOperands(left, right))
  135. {
  136. result = DivideComplex(left, right);
  137. }
  138. else
  139. {
  140. JintBinaryExpression.AssertValidBigIntArithmeticOperands(left, right);
  141. var x = TypeConverter.ToBigInt(left);
  142. var y = TypeConverter.ToBigInt(right);
  143. if (y == 0)
  144. {
  145. ExceptionHelper.ThrowRangeError(context.Engine.Realm, "Division by zero");
  146. }
  147. result = JsBigInt.Create(x / y);
  148. }
  149. return result;
  150. }
  151. private static JsValue DivideInteger(JsValue lval, JsValue rval)
  152. {
  153. var lN = lval.AsInteger();
  154. var rN = rval.AsInteger();
  155. if (lN == 0 && rN == 0)
  156. {
  157. return JsNumber.DoubleNaN;
  158. }
  159. if (rN == 0)
  160. {
  161. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  162. }
  163. if (lN % rN == 0 && (lN != 0 || rN > 0))
  164. {
  165. return JsNumber.Create(lN / rN);
  166. }
  167. return (double) lN / rN;
  168. }
  169. private static JsValue DivideComplex(JsValue lval, JsValue rval)
  170. {
  171. if (lval.IsUndefined() || rval.IsUndefined())
  172. {
  173. return JsValue.Undefined;
  174. }
  175. else
  176. {
  177. var lN = TypeConverter.ToNumber(lval);
  178. var rN = TypeConverter.ToNumber(rval);
  179. if (double.IsNaN(rN) || double.IsNaN(lN))
  180. {
  181. return JsNumber.DoubleNaN;
  182. }
  183. if (double.IsInfinity(lN) && double.IsInfinity(rN))
  184. {
  185. return JsNumber.DoubleNaN;
  186. }
  187. if (double.IsInfinity(lN) && rN == 0)
  188. {
  189. if (NumberInstance.IsNegativeZero(rN))
  190. {
  191. return -lN;
  192. }
  193. return lN;
  194. }
  195. if (lN == 0 && rN == 0)
  196. {
  197. return JsNumber.DoubleNaN;
  198. }
  199. if (rN == 0)
  200. {
  201. if (NumberInstance.IsNegativeZero(rN))
  202. {
  203. return lN > 0 ? -double.PositiveInfinity : -double.NegativeInfinity;
  204. }
  205. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  206. }
  207. return lN / rN;
  208. }
  209. }
  210. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  211. protected static JsValue Compare(JsValue x, JsValue y, bool leftFirst = true) =>
  212. x.IsNumber() && y.IsNumber()
  213. ? CompareNumber(x, y, leftFirst)
  214. : CompareComplex(x, y, leftFirst);
  215. private static JsValue CompareNumber(JsValue x, JsValue y, bool leftFirst)
  216. {
  217. double nx, ny;
  218. if (leftFirst)
  219. {
  220. nx = x.AsNumber();
  221. ny = y.AsNumber();
  222. }
  223. else
  224. {
  225. ny = y.AsNumber();
  226. nx = x.AsNumber();
  227. }
  228. if (x.IsInteger() && y.IsInteger())
  229. {
  230. return (int) nx < (int) ny ? JsBoolean.True : JsBoolean.False;
  231. }
  232. if (!double.IsInfinity(nx) && !double.IsInfinity(ny) && !double.IsNaN(nx) && !double.IsNaN(ny))
  233. {
  234. return nx < ny ? JsBoolean.True : JsBoolean.False;
  235. }
  236. return CompareComplex(x, y, leftFirst);
  237. }
  238. private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst)
  239. {
  240. JsValue px, py;
  241. if (leftFirst)
  242. {
  243. px = TypeConverter.ToPrimitive(x, Types.Number);
  244. py = TypeConverter.ToPrimitive(y, Types.Number);
  245. }
  246. else
  247. {
  248. py = TypeConverter.ToPrimitive(y, Types.Number);
  249. px = TypeConverter.ToPrimitive(x, Types.Number);
  250. }
  251. var typea = px.Type;
  252. var typeb = py.Type;
  253. if (typea != Types.String || typeb != Types.String)
  254. {
  255. if (typea == Types.BigInt || typeb == Types.BigInt)
  256. {
  257. if (typea == typeb)
  258. {
  259. return TypeConverter.ToBigInt(px) < TypeConverter.ToBigInt(py) ? JsBoolean.True : JsBoolean.False;
  260. }
  261. if (typea == Types.BigInt)
  262. {
  263. if (py is JsString jsStringY)
  264. {
  265. if (!TypeConverter.TryStringToBigInt(jsStringY.ToString(), out var temp))
  266. {
  267. return JsValue.Undefined;
  268. }
  269. return TypeConverter.ToBigInt(px) < temp ? JsBoolean.True : JsBoolean.False;
  270. }
  271. var numberB = TypeConverter.ToNumber(py);
  272. if (double.IsNaN(numberB))
  273. {
  274. return JsValue.Undefined;
  275. }
  276. if (double.IsPositiveInfinity(numberB))
  277. {
  278. return JsBoolean.True;
  279. }
  280. if (double.IsNegativeInfinity(numberB))
  281. {
  282. return JsBoolean.False;
  283. }
  284. var normalized = new BigInteger(Math.Ceiling(numberB));
  285. return TypeConverter.ToBigInt(px) < normalized ? JsBoolean.True : JsBoolean.False;
  286. }
  287. if (px is JsString jsStringX)
  288. {
  289. if (!TypeConverter.TryStringToBigInt(jsStringX.ToString(), out var temp))
  290. {
  291. return JsValue.Undefined;
  292. }
  293. return temp < TypeConverter.ToBigInt(py) ? JsBoolean.True : JsBoolean.False;
  294. }
  295. var numberA = TypeConverter.ToNumber(px);
  296. if (double.IsNaN(numberA))
  297. {
  298. return JsValue.Undefined;
  299. }
  300. if (double.IsPositiveInfinity(numberA))
  301. {
  302. return JsBoolean.False;
  303. }
  304. if (double.IsNegativeInfinity(numberA))
  305. {
  306. return JsBoolean.True;
  307. }
  308. var normalizedA = new BigInteger(Math.Floor(numberA));
  309. return normalizedA < TypeConverter.ToBigInt(py);
  310. }
  311. var nx = TypeConverter.ToNumber(px);
  312. var ny = TypeConverter.ToNumber(py);
  313. if (double.IsNaN(nx) || double.IsNaN(ny))
  314. {
  315. return JsValue.Undefined;
  316. }
  317. if (nx == ny)
  318. {
  319. return JsBoolean.False;
  320. }
  321. if (double.IsPositiveInfinity(nx))
  322. {
  323. return JsBoolean.False;
  324. }
  325. if (double.IsPositiveInfinity(ny))
  326. {
  327. return JsBoolean.True;
  328. }
  329. if (double.IsNegativeInfinity(ny))
  330. {
  331. return JsBoolean.False;
  332. }
  333. if (double.IsNegativeInfinity(nx))
  334. {
  335. return JsBoolean.True;
  336. }
  337. return nx < ny ? JsBoolean.True : JsBoolean.False;
  338. }
  339. return string.CompareOrdinal(TypeConverter.ToString(x), TypeConverter.ToString(y)) < 0 ? JsBoolean.True : JsBoolean.False;
  340. }
  341. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  342. protected static void BuildArguments(EvaluationContext context, JintExpression[] jintExpressions, JsValue[] targetArray)
  343. {
  344. for (uint i = 0; i < (uint) jintExpressions.Length; i++)
  345. {
  346. targetArray[i] = jintExpressions[i].GetValue(context).Clone();
  347. }
  348. }
  349. protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, JintExpression[] jintExpressions)
  350. {
  351. var args = new List<JsValue>(jintExpressions.Length);
  352. foreach (var jintExpression in jintExpressions)
  353. {
  354. if (jintExpression is JintSpreadExpression jse)
  355. {
  356. jse.GetValueAndCheckIterator(context, out var objectInstance, out var iterator);
  357. // optimize for array unless someone has touched the iterator
  358. if (objectInstance is JsArray { HasOriginalIterator: true } ai)
  359. {
  360. var length = ai.GetLength();
  361. for (uint j = 0; j < length; ++j)
  362. {
  363. ai.TryGetValue(j, out var value);
  364. args.Add(value);
  365. }
  366. }
  367. else
  368. {
  369. var protocol = new ArraySpreadProtocol(context.Engine, args, iterator!);
  370. protocol.Execute();
  371. }
  372. }
  373. else
  374. {
  375. args.Add(jintExpression.GetValue(context).Clone());
  376. }
  377. }
  378. return args.ToArray();
  379. }
  380. private sealed class ArraySpreadProtocol : IteratorProtocol
  381. {
  382. private readonly List<JsValue> _instance;
  383. public ArraySpreadProtocol(
  384. Engine engine,
  385. List<JsValue> instance,
  386. IteratorInstance iterator) : base(engine, iterator, 0)
  387. {
  388. _instance = instance;
  389. }
  390. protected override void ProcessItem(JsValue[] arguments, JsValue currentValue)
  391. {
  392. _instance.Add(currentValue);
  393. }
  394. }
  395. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  396. protected static bool AreIntegerOperands(JsValue left, JsValue right)
  397. {
  398. return left._type == right._type && left._type == InternalTypes.Integer;
  399. }
  400. }
  401. }