JintExpression.cs 18 KB

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