2
0

JintExpression.cs 18 KB

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