JintExpression.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. using System.Numerics;
  2. using System.Runtime.CompilerServices;
  3. using Jint.Native;
  4. using Jint.Native.Iterator;
  5. using Jint.Native.Number;
  6. namespace Jint.Runtime.Interpreter.Expressions
  7. {
  8. internal abstract class JintExpression
  9. {
  10. protected internal readonly Expression _expression;
  11. protected JintExpression(Expression expression)
  12. {
  13. _expression = expression;
  14. }
  15. /// <summary>
  16. /// Resolves the underlying value for this expression.
  17. /// By default uses the Engine for resolving.
  18. /// </summary>
  19. /// <param name="context"></param>
  20. /// <seealso cref="JintLiteralExpression"/>
  21. public virtual JsValue GetValue(EvaluationContext context)
  22. {
  23. var result = Evaluate(context);
  24. if (result is not Reference reference)
  25. {
  26. return (JsValue) result;
  27. }
  28. return context.Engine.GetValue(reference, returnReferenceToPool: true);
  29. }
  30. [MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions) 512)]
  31. public object Evaluate(EvaluationContext context)
  32. {
  33. var oldSyntaxElement = context.LastSyntaxElement;
  34. context.PrepareFor(_expression);
  35. var result = EvaluateInternal(context);
  36. context.LastSyntaxElement = oldSyntaxElement;
  37. return result;
  38. }
  39. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  40. internal object EvaluateWithoutNodeTracking(EvaluationContext context)
  41. {
  42. return EvaluateInternal(context);
  43. }
  44. protected abstract object EvaluateInternal(EvaluationContext context);
  45. /// <summary>
  46. /// If we'd get Esprima source, we would just refer to it, but this makes error messages easier to decipher.
  47. /// </summary>
  48. internal string SourceText => ToString(_expression) ?? "*unknown*";
  49. internal static string? ToString(Expression expression)
  50. {
  51. while (true)
  52. {
  53. if (expression is Literal literal)
  54. {
  55. return EsprimaExtensions.LiteralKeyToString(literal);
  56. }
  57. if (expression is Identifier identifier)
  58. {
  59. return identifier.Name;
  60. }
  61. if (expression is MemberExpression memberExpression)
  62. {
  63. return ToString(memberExpression.Object) + "." + ToString(memberExpression.Property);
  64. }
  65. if (expression is CallExpression callExpression)
  66. {
  67. expression = callExpression.Callee;
  68. continue;
  69. }
  70. return null;
  71. }
  72. }
  73. protected internal static JintExpression Build(Expression expression)
  74. {
  75. if (expression.AssociatedData is JintExpression preparedExpression)
  76. {
  77. return preparedExpression;
  78. }
  79. var result = expression.Type switch
  80. {
  81. NodeType.AssignmentExpression => JintAssignmentExpression.Build((AssignmentExpression) expression),
  82. NodeType.ArrayExpression => JintArrayExpression.Build((ArrayExpression) expression),
  83. NodeType.ArrowFunctionExpression => new JintArrowFunctionExpression((ArrowFunctionExpression) expression),
  84. NodeType.BinaryExpression => JintBinaryExpression.Build((BinaryExpression) expression),
  85. NodeType.CallExpression => new JintCallExpression((CallExpression) expression),
  86. NodeType.ConditionalExpression => new JintConditionalExpression((ConditionalExpression) expression),
  87. NodeType.FunctionExpression => new JintFunctionExpression((FunctionExpression) expression),
  88. NodeType.Identifier => new JintIdentifierExpression((Identifier) expression),
  89. NodeType.PrivateIdentifier => new JintPrivateIdentifierExpression((PrivateIdentifier) expression),
  90. NodeType.Literal => JintLiteralExpression.Build((Literal) expression),
  91. NodeType.LogicalExpression => ((BinaryExpression) expression).Operator switch
  92. {
  93. BinaryOperator.LogicalAnd => new JintLogicalAndExpression((BinaryExpression) expression),
  94. BinaryOperator.LogicalOr => new JintLogicalOrExpression((BinaryExpression) expression),
  95. BinaryOperator.NullishCoalescing => new NullishCoalescingExpression((BinaryExpression) expression),
  96. _ => null
  97. },
  98. NodeType.MemberExpression => new JintMemberExpression((MemberExpression) expression),
  99. NodeType.NewExpression => new JintNewExpression((NewExpression) expression),
  100. NodeType.ObjectExpression => JintObjectExpression.Build((ObjectExpression) expression),
  101. NodeType.SequenceExpression => new JintSequenceExpression((SequenceExpression) expression),
  102. NodeType.ThisExpression => new JintThisExpression((ThisExpression) expression),
  103. NodeType.UpdateExpression => new JintUpdateExpression((UpdateExpression) expression),
  104. NodeType.UnaryExpression => JintUnaryExpression.Build((UnaryExpression) expression),
  105. NodeType.SpreadElement => new JintSpreadExpression((SpreadElement) expression),
  106. NodeType.TemplateLiteral => new JintTemplateLiteralExpression((TemplateLiteral) expression),
  107. NodeType.TaggedTemplateExpression => new JintTaggedTemplateExpression((TaggedTemplateExpression) expression),
  108. NodeType.ClassExpression => new JintClassExpression((ClassExpression) expression),
  109. NodeType.ImportExpression => new JintImportExpression((ImportExpression) expression),
  110. NodeType.Super => new JintSuperExpression((Super) expression),
  111. NodeType.MetaProperty => new JintMetaPropertyExpression((MetaProperty) expression),
  112. NodeType.ChainExpression => ((ChainExpression) expression).Expression.Type == NodeType.CallExpression
  113. ? new JintCallExpression((CallExpression) ((ChainExpression) expression).Expression)
  114. : new JintMemberExpression((MemberExpression) ((ChainExpression) expression).Expression),
  115. NodeType.AwaitExpression => new JintAwaitExpression((AwaitExpression) expression),
  116. NodeType.YieldExpression => new JintYieldExpression((YieldExpression) 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. }