JintExpression.cs 18 KB

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