JintExpression.cs 17 KB

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