JintExpression.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. using System.Diagnostics;
  2. using System.Numerics;
  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.Import => new JintImportExpression((Import) expression),
  172. Nodes.Super => new JintSuperExpression((Super) expression),
  173. Nodes.MetaProperty => new JintMetaPropertyExpression((MetaProperty) expression),
  174. Nodes.ChainExpression => ((ChainExpression) expression).Expression.Type == Nodes.CallExpression
  175. ? new JintCallExpression((CallExpression) ((ChainExpression) expression).Expression)
  176. : new JintMemberExpression((MemberExpression) ((ChainExpression) expression).Expression),
  177. _ => null
  178. };
  179. if (result is null)
  180. {
  181. ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(expression), $"unsupported expression type '{expression.Type}'");
  182. }
  183. return result;
  184. }
  185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  186. protected static JsValue Divide(EvaluationContext context, JsValue left, JsValue right)
  187. {
  188. JsValue result;
  189. if (AreIntegerOperands(left, right))
  190. {
  191. result = DivideInteger(left, right);
  192. }
  193. else if (JintBinaryExpression.AreNonBigIntOperands(left, right))
  194. {
  195. result = DivideComplex(left, right);
  196. }
  197. else
  198. {
  199. JintBinaryExpression.AssertValidBigIntArithmeticOperands(context, left, right);
  200. var x = TypeConverter.ToBigInt(left);
  201. var y = TypeConverter.ToBigInt(right);
  202. if (y == 0)
  203. {
  204. ExceptionHelper.ThrowRangeError(context.Engine.Realm, "Division by zero");
  205. }
  206. result = JsBigInt.Create(x / y);
  207. }
  208. return result;
  209. }
  210. private static JsValue DivideInteger(JsValue lval, JsValue rval)
  211. {
  212. var lN = lval.AsInteger();
  213. var rN = rval.AsInteger();
  214. if (lN == 0 && rN == 0)
  215. {
  216. return JsNumber.DoubleNaN;
  217. }
  218. if (rN == 0)
  219. {
  220. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  221. }
  222. if (lN % rN == 0)
  223. {
  224. return lN / rN;
  225. }
  226. return (double) lN / rN;
  227. }
  228. private static JsValue DivideComplex(JsValue lval, JsValue rval)
  229. {
  230. if (lval.IsUndefined() || rval.IsUndefined())
  231. {
  232. return Undefined.Instance;
  233. }
  234. else
  235. {
  236. var lN = TypeConverter.ToNumber(lval);
  237. var rN = TypeConverter.ToNumber(rval);
  238. if (double.IsNaN(rN) || double.IsNaN(lN))
  239. {
  240. return JsNumber.DoubleNaN;
  241. }
  242. if (double.IsInfinity(lN) && double.IsInfinity(rN))
  243. {
  244. return JsNumber.DoubleNaN;
  245. }
  246. if (double.IsInfinity(lN) && rN == 0)
  247. {
  248. if (NumberInstance.IsNegativeZero(rN))
  249. {
  250. return -lN;
  251. }
  252. return lN;
  253. }
  254. if (lN == 0 && rN == 0)
  255. {
  256. return JsNumber.DoubleNaN;
  257. }
  258. if (rN == 0)
  259. {
  260. if (NumberInstance.IsNegativeZero(rN))
  261. {
  262. return lN > 0 ? -double.PositiveInfinity : -double.NegativeInfinity;
  263. }
  264. return lN > 0 ? double.PositiveInfinity : double.NegativeInfinity;
  265. }
  266. return lN / rN;
  267. }
  268. }
  269. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  270. protected static JsValue Compare(JsValue x, JsValue y, bool leftFirst = true) =>
  271. x._type == y._type && x._type == InternalTypes.Integer
  272. ? CompareInteger(x, y, leftFirst)
  273. : CompareComplex(x, y, leftFirst);
  274. private static JsValue CompareInteger(JsValue x, JsValue y, bool leftFirst)
  275. {
  276. int nx, ny;
  277. if (leftFirst)
  278. {
  279. nx = x.AsInteger();
  280. ny = y.AsInteger();
  281. }
  282. else
  283. {
  284. ny = y.AsInteger();
  285. nx = x.AsInteger();
  286. }
  287. return nx < ny;
  288. }
  289. private static JsValue CompareComplex(JsValue x, JsValue y, bool leftFirst)
  290. {
  291. JsValue px, py;
  292. if (leftFirst)
  293. {
  294. px = TypeConverter.ToPrimitive(x, Types.Number);
  295. py = TypeConverter.ToPrimitive(y, Types.Number);
  296. }
  297. else
  298. {
  299. py = TypeConverter.ToPrimitive(y, Types.Number);
  300. px = TypeConverter.ToPrimitive(x, Types.Number);
  301. }
  302. var typea = px.Type;
  303. var typeb = py.Type;
  304. if (typea != Types.String || typeb != Types.String)
  305. {
  306. if (typea == Types.BigInt || typeb == Types.BigInt)
  307. {
  308. if (typea == typeb)
  309. {
  310. return TypeConverter.ToBigInt(px) < TypeConverter.ToBigInt(py);
  311. }
  312. if (typea == Types.BigInt)
  313. {
  314. if (py is JsString jsStringY)
  315. {
  316. if (!TypeConverter.TryStringToBigInt(jsStringY.ToString(), out var temp))
  317. {
  318. return JsValue.Undefined;
  319. }
  320. return TypeConverter.ToBigInt(px) < temp;
  321. }
  322. var numberB = TypeConverter.ToNumber(py);
  323. if (double.IsNaN(numberB))
  324. {
  325. return JsValue.Undefined;
  326. }
  327. if (double.IsPositiveInfinity(numberB))
  328. {
  329. return true;
  330. }
  331. if (double.IsNegativeInfinity(numberB))
  332. {
  333. return false;
  334. }
  335. var normalized = new BigInteger(Math.Ceiling(numberB));
  336. return TypeConverter.ToBigInt(px) < normalized;
  337. }
  338. if (px is JsString jsStringX)
  339. {
  340. if (!TypeConverter.TryStringToBigInt(jsStringX.ToString(), out var temp))
  341. {
  342. return JsValue.Undefined;
  343. }
  344. return temp < TypeConverter.ToBigInt(py);
  345. }
  346. var numberA = TypeConverter.ToNumber(px);
  347. if (double.IsNaN(numberA))
  348. {
  349. return JsValue.Undefined;
  350. }
  351. if (double.IsPositiveInfinity(numberA))
  352. {
  353. return false;
  354. }
  355. if (double.IsNegativeInfinity(numberA))
  356. {
  357. return true;
  358. }
  359. var normalizedA = new BigInteger(Math.Floor(numberA));
  360. return normalizedA < TypeConverter.ToBigInt(py);
  361. }
  362. var nx = TypeConverter.ToNumber(px);
  363. var ny = TypeConverter.ToNumber(py);
  364. if (double.IsNaN(nx) || double.IsNaN(ny))
  365. {
  366. return Undefined.Instance;
  367. }
  368. if (nx == ny)
  369. {
  370. return false;
  371. }
  372. if (double.IsPositiveInfinity(nx))
  373. {
  374. return false;
  375. }
  376. if (double.IsPositiveInfinity(ny))
  377. {
  378. return true;
  379. }
  380. if (double.IsNegativeInfinity(ny))
  381. {
  382. return false;
  383. }
  384. if (double.IsNegativeInfinity(nx))
  385. {
  386. return true;
  387. }
  388. return nx < ny;
  389. }
  390. return string.CompareOrdinal(TypeConverter.ToString(x), TypeConverter.ToString(y)) < 0;
  391. }
  392. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  393. protected static void BuildArguments(EvaluationContext context, JintExpression[] jintExpressions, JsValue[] targetArray)
  394. {
  395. for (var i = 0; i < jintExpressions.Length; i++)
  396. {
  397. var completion = jintExpressions[i].GetValue(context);
  398. targetArray[i] = completion.Value.Clone();
  399. }
  400. }
  401. protected static JsValue[] BuildArgumentsWithSpreads(EvaluationContext context, JintExpression[] jintExpressions)
  402. {
  403. var args = new List<JsValue>(jintExpressions.Length);
  404. for (var i = 0; i < jintExpressions.Length; i++)
  405. {
  406. var jintExpression = jintExpressions[i];
  407. if (jintExpression is JintSpreadExpression jse)
  408. {
  409. jse.GetValueAndCheckIterator(context, out var objectInstance, out var iterator);
  410. // optimize for array unless someone has touched the iterator
  411. if (objectInstance is ArrayInstance ai && ai.HasOriginalIterator)
  412. {
  413. var length = ai.GetLength();
  414. for (uint j = 0; j < length; ++j)
  415. {
  416. if (ai.TryGetValue(j, out var value))
  417. {
  418. args.Add(value);
  419. }
  420. }
  421. }
  422. else
  423. {
  424. var protocol = new ArraySpreadProtocol(context.Engine, args, iterator!);
  425. protocol.Execute();
  426. }
  427. }
  428. else
  429. {
  430. var completion = jintExpression.GetValue(context);
  431. args.Add(completion.Value.Clone());
  432. }
  433. }
  434. return args.ToArray();
  435. }
  436. private sealed class ArraySpreadProtocol : IteratorProtocol
  437. {
  438. private readonly List<JsValue> _instance;
  439. public ArraySpreadProtocol(
  440. Engine engine,
  441. List<JsValue> instance,
  442. IteratorInstance iterator) : base(engine, iterator, 0)
  443. {
  444. _instance = instance;
  445. }
  446. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  447. {
  448. _instance.Add(currentValue);
  449. }
  450. }
  451. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  452. protected static bool AreIntegerOperands(JsValue left, JsValue right)
  453. {
  454. return left._type == right._type && left._type == InternalTypes.Integer;
  455. }
  456. }
  457. }