2
0

JintExpression.cs 17 KB

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