JintExpression.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #nullable enable
  2. using System.Runtime.CompilerServices;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Native.Array;
  6. using Jint.Native.Iterator;
  7. using Jint.Native.Number;
  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 readonly Engine _engine;
  15. protected internal readonly Expression _expression;
  16. protected JintExpression(Engine engine, Expression expression)
  17. {
  18. _engine = engine;
  19. _expression = expression;
  20. }
  21. /// <summary>
  22. /// Resolves the underlying value for this expression.
  23. /// By default uses the Engine for resolving.
  24. /// </summary>
  25. /// <seealso cref="JintLiteralExpression"/>
  26. public virtual JsValue GetValue()
  27. {
  28. return _engine.GetValue(Evaluate(), true);
  29. }
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. public object Evaluate()
  32. {
  33. _engine._lastSyntaxNode = _expression;
  34. if (!_initialized)
  35. {
  36. Initialize();
  37. _initialized = true;
  38. }
  39. return EvaluateInternal();
  40. }
  41. /// <summary>
  42. /// Opportunity to build one-time structures and caching based on lexical context.
  43. /// </summary>
  44. protected virtual void Initialize()
  45. {
  46. }
  47. protected abstract object EvaluateInternal();
  48. /// <summary>
  49. /// If we'd get Esprima source, we would just refer to it, but this makes error messages easier to decipher.
  50. /// </summary>
  51. internal string SourceText => ToString(_expression) ?? "*unknown*";
  52. internal static string? ToString(Expression expression)
  53. {
  54. while (true)
  55. {
  56. if (expression is Literal literal)
  57. {
  58. return EsprimaExtensions.LiteralKeyToString(literal);
  59. }
  60. if (expression is Identifier identifier)
  61. {
  62. return identifier.Name;
  63. }
  64. if (expression is MemberExpression memberExpression)
  65. {
  66. return ToString(memberExpression.Object) + "." + ToString(memberExpression.Property);
  67. }
  68. if (expression is CallExpression callExpression)
  69. {
  70. expression = callExpression.Callee;
  71. continue;
  72. }
  73. return null;
  74. }
  75. }
  76. protected internal static JintExpression Build(Engine engine, Expression expression)
  77. {
  78. var result = expression.Type switch
  79. {
  80. Nodes.AssignmentExpression => JintAssignmentExpression.Build(engine, (AssignmentExpression) expression),
  81. Nodes.ArrayExpression => new JintArrayExpression(engine, (ArrayExpression) expression),
  82. Nodes.ArrowFunctionExpression => new JintArrowFunctionExpression(engine, (IFunction) expression),
  83. Nodes.BinaryExpression => JintBinaryExpression.Build(engine, (BinaryExpression) expression),
  84. Nodes.CallExpression => new JintCallExpression(engine, (CallExpression) expression),
  85. Nodes.ConditionalExpression => new JintConditionalExpression(engine, (ConditionalExpression) expression),
  86. Nodes.FunctionExpression => new JintFunctionExpression(engine, (IFunction) expression),
  87. Nodes.Identifier => new JintIdentifierExpression(engine, (Identifier) expression),
  88. Nodes.Literal => JintLiteralExpression.Build(engine, (Literal) expression),
  89. Nodes.LogicalExpression => ((BinaryExpression) expression).Operator switch
  90. {
  91. BinaryOperator.LogicalAnd => new JintLogicalAndExpression(engine, (BinaryExpression) expression),
  92. BinaryOperator.LogicalOr => new JintLogicalOrExpression(engine, (BinaryExpression) expression),
  93. BinaryOperator.NullishCoalescing => new NullishCoalescingExpression(engine, (BinaryExpression) expression),
  94. _ => null
  95. },
  96. Nodes.MemberExpression => new JintMemberExpression(engine, (MemberExpression) expression),
  97. Nodes.NewExpression => new JintNewExpression(engine, (NewExpression) expression),
  98. Nodes.ObjectExpression => new JintObjectExpression(engine, (ObjectExpression) expression),
  99. Nodes.SequenceExpression => new JintSequenceExpression(engine, (SequenceExpression) expression),
  100. Nodes.ThisExpression => new JintThisExpression(engine, (ThisExpression) expression),
  101. Nodes.UpdateExpression => new JintUpdateExpression(engine, (UpdateExpression) expression),
  102. Nodes.UnaryExpression => JintUnaryExpression.Build(engine, (UnaryExpression) expression),
  103. Nodes.SpreadElement => new JintSpreadExpression(engine, (SpreadElement) expression),
  104. Nodes.TemplateLiteral => new JintTemplateLiteralExpression(engine, (TemplateLiteral) expression),
  105. Nodes.TaggedTemplateExpression => new JintTaggedTemplateExpression(engine, (TaggedTemplateExpression) expression),
  106. Nodes.ClassExpression => new JintClassExpression(engine, (ClassExpression) expression),
  107. Nodes.Super => new JintSuperExpression(engine, (Super) expression),
  108. Nodes.MetaProperty => new JintMetaPropertyExpression(engine, (MetaProperty) expression),
  109. Nodes.ChainExpression => ((ChainExpression) expression).Expression.Type == Nodes.CallExpression
  110. ? new JintCallExpression(engine, (CallExpression) ((ChainExpression) expression).Expression)
  111. : new JintMemberExpression(engine, (MemberExpression) ((ChainExpression) expression).Expression),
  112. _ => null
  113. };
  114. if (result is null)
  115. {
  116. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(expression), $"unsupported expression type '{expression.Type}'");
  117. }
  118. return result;
  119. }
  120. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  121. protected static JsValue Divide(JsValue lval, JsValue rval)
  122. {
  123. return AreIntegerOperands(lval, rval)
  124. ? DivideInteger(lval, rval)
  125. : DivideComplex(lval, rval);
  126. }
  127. private static JsValue DivideInteger(JsValue lval, JsValue rval)
  128. {
  129. var lN = lval.AsInteger();
  130. var rN = rval.AsInteger();
  131. if (lN == 0 && rN == 0)
  132. {
  133. return JsNumber.DoubleNaN;
  134. }
  135. if (rN == 0)
  136. {
  137. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  138. }
  139. if (lN % rN == 0)
  140. {
  141. return lN / rN;
  142. }
  143. return (double) lN / rN;
  144. }
  145. private static JsValue DivideComplex(JsValue lval, JsValue rval)
  146. {
  147. if (lval.IsUndefined() || rval.IsUndefined())
  148. {
  149. return Undefined.Instance;
  150. }
  151. else
  152. {
  153. var lN = TypeConverter.ToNumber(lval);
  154. var rN = TypeConverter.ToNumber(rval);
  155. if (double.IsNaN(rN) || double.IsNaN(lN))
  156. {
  157. return JsNumber.DoubleNaN;
  158. }
  159. if (double.IsInfinity(lN) && double.IsInfinity(rN))
  160. {
  161. return JsNumber.DoubleNaN;
  162. }
  163. if (double.IsInfinity(lN) && rN == 0)
  164. {
  165. if (NumberInstance.IsNegativeZero(rN))
  166. {
  167. return -lN;
  168. }
  169. return lN;
  170. }
  171. if (lN == 0 && rN == 0)
  172. {
  173. return JsNumber.DoubleNaN;
  174. }
  175. if (rN == 0)
  176. {
  177. if (NumberInstance.IsNegativeZero(rN))
  178. {
  179. return lN > 0 ? -double.PositiveInfinity : -double.NegativeInfinity;
  180. }
  181. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  182. }
  183. return lN / rN;
  184. }
  185. }
  186. protected static bool Equal(JsValue x, JsValue y)
  187. {
  188. return x.Type == y.Type
  189. ? JintBinaryExpression.StrictlyEqual(x, y)
  190. : EqualUnlikely(x, y);
  191. }
  192. private static bool EqualUnlikely(JsValue x, JsValue y)
  193. {
  194. if (x._type == InternalTypes.Null && y._type == InternalTypes.Undefined)
  195. {
  196. return true;
  197. }
  198. if (x._type == InternalTypes.Undefined && y._type == InternalTypes.Null)
  199. {
  200. return true;
  201. }
  202. if (x.IsNumber() && y.IsString())
  203. {
  204. return Equal(x, TypeConverter.ToNumber(y));
  205. }
  206. if (x.IsString() && y.IsNumber())
  207. {
  208. return Equal(TypeConverter.ToNumber(x), y);
  209. }
  210. if (x.IsBoolean())
  211. {
  212. return Equal(TypeConverter.ToNumber(x), y);
  213. }
  214. if (y.IsBoolean())
  215. {
  216. return Equal(x, TypeConverter.ToNumber(y));
  217. }
  218. const InternalTypes stringOrNumber = InternalTypes.String | InternalTypes.Integer | InternalTypes.Number;
  219. if (y.IsObject() && (x._type & stringOrNumber) != 0)
  220. {
  221. return Equal(x, TypeConverter.ToPrimitive(y));
  222. }
  223. if (x.IsObject() && ((y._type & stringOrNumber) != 0))
  224. {
  225. return Equal(TypeConverter.ToPrimitive(x), y);
  226. }
  227. return false;
  228. }
  229. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  230. protected static JsValue Compare(JsValue x, JsValue y, bool leftFirst = true) =>
  231. x._type == y._type && x._type == InternalTypes.Integer
  232. ? CompareInteger(x, y, leftFirst)
  233. : CompareComplex(x, y, leftFirst);
  234. private static JsValue CompareInteger(JsValue x, JsValue y, bool leftFirst)
  235. {
  236. int nx, ny;
  237. if (leftFirst)
  238. {
  239. nx = x.AsInteger();
  240. ny = y.AsInteger();
  241. }
  242. else
  243. {
  244. ny = y.AsInteger();
  245. nx = x.AsInteger();
  246. }
  247. return nx < ny;
  248. }
  249. private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst)
  250. {
  251. JsValue px, py;
  252. if (leftFirst)
  253. {
  254. px = TypeConverter.ToPrimitive(x, Types.Number);
  255. py = TypeConverter.ToPrimitive(y, Types.Number);
  256. }
  257. else
  258. {
  259. py = TypeConverter.ToPrimitive(y, Types.Number);
  260. px = TypeConverter.ToPrimitive(x, Types.Number);
  261. }
  262. var typea = px.Type;
  263. var typeb = py.Type;
  264. if (typea != Types.String || typeb != Types.String)
  265. {
  266. var nx = TypeConverter.ToNumber(px);
  267. var ny = TypeConverter.ToNumber(py);
  268. if (double.IsNaN(nx) || double.IsNaN(ny))
  269. {
  270. return Undefined.Instance;
  271. }
  272. if (nx == ny)
  273. {
  274. return false;
  275. }
  276. if (double.IsPositiveInfinity(nx))
  277. {
  278. return false;
  279. }
  280. if (double.IsPositiveInfinity(ny))
  281. {
  282. return true;
  283. }
  284. if (double.IsNegativeInfinity(ny))
  285. {
  286. return false;
  287. }
  288. if (double.IsNegativeInfinity(nx))
  289. {
  290. return true;
  291. }
  292. return nx < ny;
  293. }
  294. return string.CompareOrdinal(TypeConverter.ToString(x), TypeConverter.ToString(y)) < 0;
  295. }
  296. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  297. protected static void BuildArguments(JintExpression[] jintExpressions, JsValue[] targetArray)
  298. {
  299. for (var i = 0; i < jintExpressions.Length; i++)
  300. {
  301. targetArray[i] = jintExpressions[i].GetValue().Clone();
  302. }
  303. }
  304. protected JsValue[] BuildArgumentsWithSpreads(JintExpression[] jintExpressions)
  305. {
  306. var args = new System.Collections.Generic.List<JsValue>(jintExpressions.Length);
  307. for (var i = 0; i < jintExpressions.Length; i++)
  308. {
  309. var jintExpression = jintExpressions[i];
  310. if (jintExpression is JintSpreadExpression jse)
  311. {
  312. jse.GetValueAndCheckIterator(out var objectInstance, out var iterator);
  313. // optimize for array unless someone has touched the iterator
  314. if (objectInstance is ArrayInstance ai && ai.HasOriginalIterator)
  315. {
  316. var length = ai.GetLength();
  317. for (uint j = 0; j < length; ++j)
  318. {
  319. if (ai.TryGetValue(j, out var value))
  320. {
  321. args.Add(value);
  322. }
  323. }
  324. }
  325. else
  326. {
  327. var protocol = new ArraySpreadProtocol(_engine, args, iterator);
  328. protocol.Execute();
  329. }
  330. }
  331. else
  332. {
  333. args.Add(jintExpression.GetValue().Clone());
  334. }
  335. }
  336. return args.ToArray();
  337. }
  338. private sealed class ArraySpreadProtocol : IteratorProtocol
  339. {
  340. private readonly System.Collections.Generic.List<JsValue> _instance;
  341. public ArraySpreadProtocol(
  342. Engine engine,
  343. System.Collections.Generic.List<JsValue> instance,
  344. IIterator iterator) : base(engine, iterator, 0)
  345. {
  346. _instance = instance;
  347. }
  348. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  349. {
  350. _instance.Add(currentValue);
  351. }
  352. }
  353. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  354. protected static bool AreIntegerOperands(JsValue left, JsValue right)
  355. {
  356. return left._type == right._type && left._type == InternalTypes.Integer;
  357. }
  358. }
  359. }