JintExpression.cs 19 KB

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