JintForInForOfStatement.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. using System.Diagnostics.CodeAnalysis;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. using Jint.Native.Iterator;
  5. using Jint.Runtime.Environments;
  6. using Jint.Runtime.Interpreter.Expressions;
  7. using Jint.Runtime.References;
  8. using Environment = Jint.Runtime.Environments.Environment;
  9. namespace Jint.Runtime.Interpreter.Statements
  10. {
  11. /// <summary>
  12. /// https://tc39.es/ecma262/#sec-for-in-and-for-of-statements
  13. /// </summary>
  14. internal sealed class JintForInForOfStatement : JintStatement<Statement>
  15. {
  16. private readonly Node _leftNode;
  17. private readonly Statement _forBody;
  18. private readonly Expression _rightExpression;
  19. private readonly IterationKind _iterationKind;
  20. private ProbablyBlockStatement _body;
  21. private JintExpression? _expr;
  22. private BindingPattern? _assignmentPattern;
  23. private JintExpression _right = null!;
  24. private List<Key>? _tdzNames;
  25. private bool _destructuring;
  26. private LhsKind _lhsKind;
  27. public JintForInForOfStatement(ForInStatement statement) : base(statement)
  28. {
  29. _leftNode = statement.Left;
  30. _rightExpression = statement.Right;
  31. _forBody = statement.Body;
  32. _iterationKind = IterationKind.Enumerate;
  33. }
  34. public JintForInForOfStatement(ForOfStatement statement) : base(statement)
  35. {
  36. _leftNode = statement.Left;
  37. _rightExpression = statement.Right;
  38. _forBody = statement.Body;
  39. _iterationKind = IterationKind.Iterate;
  40. }
  41. protected override void Initialize(EvaluationContext context)
  42. {
  43. _lhsKind = LhsKind.Assignment;
  44. var engine = context.Engine;
  45. if (_leftNode is VariableDeclaration variableDeclaration)
  46. {
  47. _lhsKind = variableDeclaration.Kind == VariableDeclarationKind.Var
  48. ? LhsKind.VarBinding
  49. : LhsKind.LexicalBinding;
  50. var variableDeclarationDeclaration = variableDeclaration.Declarations[0];
  51. var id = variableDeclarationDeclaration.Id;
  52. if (_lhsKind == LhsKind.LexicalBinding)
  53. {
  54. _tdzNames = new List<Key>(1);
  55. id.GetBoundNames(_tdzNames);
  56. }
  57. if (id is BindingPattern bindingPattern)
  58. {
  59. _destructuring = true;
  60. _assignmentPattern = bindingPattern;
  61. }
  62. else
  63. {
  64. var identifier = (Identifier) id;
  65. _expr = new JintIdentifierExpression(identifier);
  66. }
  67. }
  68. else if (_leftNode is BindingPattern bindingPattern)
  69. {
  70. _destructuring = true;
  71. _assignmentPattern = bindingPattern;
  72. }
  73. else if (_leftNode is MemberExpression memberExpression)
  74. {
  75. _expr = new JintMemberExpression(memberExpression);
  76. }
  77. else
  78. {
  79. _expr = new JintIdentifierExpression((Identifier) _leftNode);
  80. }
  81. _body = new ProbablyBlockStatement(_forBody);
  82. _right = JintExpression.Build(_rightExpression);
  83. }
  84. protected override Completion ExecuteInternal(EvaluationContext context)
  85. {
  86. if (!HeadEvaluation(context, out var keyResult))
  87. {
  88. return new Completion(CompletionType.Normal, JsValue.Undefined, _statement);
  89. }
  90. return BodyEvaluation(context, _expr, _body, keyResult, IterationKind.Enumerate, _lhsKind);
  91. }
  92. /// <summary>
  93. /// https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind
  94. /// </summary>
  95. private bool HeadEvaluation(EvaluationContext context, [NotNullWhen(true)] out IteratorInstance? result)
  96. {
  97. var engine = context.Engine;
  98. var oldEnv = engine.ExecutionContext.LexicalEnvironment;
  99. var tdz = JintEnvironment.NewDeclarativeEnvironment(engine, oldEnv);
  100. if (_tdzNames != null)
  101. {
  102. var TDZEnvRec = tdz;
  103. foreach (var name in _tdzNames)
  104. {
  105. TDZEnvRec.CreateMutableBinding(name);
  106. }
  107. }
  108. engine.UpdateLexicalEnvironment(tdz);
  109. var exprValue = _right.GetValue(context);
  110. engine.UpdateLexicalEnvironment(oldEnv);
  111. if (_iterationKind == IterationKind.Enumerate)
  112. {
  113. if (exprValue.IsNullOrUndefined())
  114. {
  115. result = null;
  116. return false;
  117. }
  118. var obj = TypeConverter.ToObject(engine.Realm, exprValue);
  119. result = new IteratorInstance.EnumerableIterator(engine, obj.GetKeys());
  120. }
  121. else
  122. {
  123. result = exprValue as IteratorInstance ?? exprValue.GetIterator(engine.Realm);
  124. }
  125. return true;
  126. }
  127. /// <summary>
  128. /// https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  129. /// </summary>
  130. private Completion BodyEvaluation(
  131. EvaluationContext context,
  132. JintExpression? lhs,
  133. in ProbablyBlockStatement stmt,
  134. IteratorInstance iteratorRecord,
  135. IterationKind iterationKind,
  136. LhsKind lhsKind,
  137. IteratorKind iteratorKind = IteratorKind.Sync)
  138. {
  139. var engine = context.Engine;
  140. var oldEnv = engine.ExecutionContext.LexicalEnvironment;
  141. var v = JsValue.Undefined;
  142. var destructuring = _destructuring;
  143. string? lhsName = null;
  144. var completionType = CompletionType.Normal;
  145. var close = false;
  146. try
  147. {
  148. while (true)
  149. {
  150. Environment? iterationEnv = null;
  151. if (!iteratorRecord.TryIteratorStep(out var nextResult))
  152. {
  153. close = true;
  154. return new Completion(CompletionType.Normal, v, _statement!);
  155. }
  156. if (iteratorKind == IteratorKind.Async)
  157. {
  158. // nextResult = await nextResult;
  159. ExceptionHelper.ThrowNotImplementedException("await");
  160. }
  161. var nextValue = nextResult.Get(CommonProperties.Value);
  162. close = true;
  163. object lhsRef = null!;
  164. if (lhsKind != LhsKind.LexicalBinding)
  165. {
  166. if (!destructuring)
  167. {
  168. lhsRef = lhs!.Evaluate(context);
  169. }
  170. }
  171. else
  172. {
  173. iterationEnv = JintEnvironment.NewDeclarativeEnvironment(engine, oldEnv);
  174. if (_tdzNames != null)
  175. {
  176. BindingInstantiation(iterationEnv);
  177. }
  178. engine.UpdateLexicalEnvironment(iterationEnv);
  179. if (!destructuring)
  180. {
  181. var identifier = (Identifier) ((VariableDeclaration) _leftNode).Declarations[0].Id;
  182. lhsName ??= identifier.Name;
  183. lhsRef = engine.ResolveBinding(lhsName);
  184. }
  185. }
  186. if (context.DebugMode)
  187. {
  188. context.Engine.Debugger.OnStep(_leftNode);
  189. }
  190. var status = CompletionType.Normal;
  191. if (!destructuring)
  192. {
  193. if (context.IsAbrupt())
  194. {
  195. close = true;
  196. status = context.Completion;
  197. }
  198. else
  199. {
  200. var reference = (Reference) lhsRef;
  201. if (lhsKind == LhsKind.LexicalBinding || _leftNode.Type == Nodes.Identifier && !reference.IsUnresolvableReference)
  202. {
  203. reference.InitializeReferencedBinding(nextValue);
  204. }
  205. else
  206. {
  207. engine.PutValue(reference, nextValue);
  208. }
  209. }
  210. }
  211. else
  212. {
  213. nextValue = BindingPatternAssignmentExpression.ProcessPatterns(
  214. context,
  215. _assignmentPattern!,
  216. nextValue,
  217. iterationEnv,
  218. checkPatternPropertyReference: _lhsKind != LhsKind.VarBinding);
  219. status = context.Completion;
  220. if (lhsKind == LhsKind.Assignment)
  221. {
  222. // DestructuringAssignmentEvaluation of assignmentPattern using nextValue as the argument.
  223. }
  224. #pragma warning disable MA0140
  225. else if (lhsKind == LhsKind.VarBinding)
  226. {
  227. // BindingInitialization for lhs passing nextValue and undefined as the arguments.
  228. }
  229. else
  230. {
  231. // BindingInitialization for lhs passing nextValue and iterationEnv as arguments
  232. }
  233. #pragma warning restore MA0140
  234. }
  235. if (status != CompletionType.Normal)
  236. {
  237. engine.UpdateLexicalEnvironment(oldEnv);
  238. if (_iterationKind == IterationKind.AsyncIterate)
  239. {
  240. iteratorRecord.Close(status);
  241. return new Completion(status, nextValue, context.LastSyntaxElement);
  242. }
  243. if (iterationKind == IterationKind.Enumerate)
  244. {
  245. return new Completion(status, nextValue, context.LastSyntaxElement);
  246. }
  247. iteratorRecord.Close(status);
  248. return new Completion(status, nextValue, context.LastSyntaxElement);
  249. }
  250. var result = stmt.Execute(context);
  251. engine.UpdateLexicalEnvironment(oldEnv);
  252. if (!result.Value.IsEmpty)
  253. {
  254. v = result.Value;
  255. }
  256. if (result.Type == CompletionType.Break && (context.Target == null || string.Equals(context.Target, _statement?.LabelSet?.Name, StringComparison.Ordinal)))
  257. {
  258. completionType = CompletionType.Normal;
  259. return new Completion(CompletionType.Normal, v, _statement!);
  260. }
  261. if (result.Type != CompletionType.Continue || (context.Target != null && !string.Equals(context.Target, _statement?.LabelSet?.Name, StringComparison.Ordinal)))
  262. {
  263. completionType = result.Type;
  264. if (result.IsAbrupt())
  265. {
  266. close = true;
  267. return result;
  268. }
  269. }
  270. }
  271. }
  272. catch
  273. {
  274. completionType = CompletionType.Throw;
  275. throw;
  276. }
  277. finally
  278. {
  279. if (close)
  280. {
  281. try
  282. {
  283. iteratorRecord.Close(completionType);
  284. }
  285. catch
  286. {
  287. // if we already have and exception, use it
  288. if (completionType != CompletionType.Throw)
  289. {
  290. #pragma warning disable CA2219
  291. #pragma warning disable MA0072
  292. throw;
  293. #pragma warning restore MA0072
  294. #pragma warning restore CA2219
  295. }
  296. }
  297. }
  298. engine.UpdateLexicalEnvironment(oldEnv);
  299. }
  300. }
  301. private void BindingInstantiation(Environment environment)
  302. {
  303. var envRec = (DeclarativeEnvironment) environment;
  304. var variableDeclaration = (VariableDeclaration) _leftNode;
  305. var boundNames = new List<Key>();
  306. variableDeclaration.GetBoundNames(boundNames);
  307. for (var i = 0; i < boundNames.Count; i++)
  308. {
  309. var name = boundNames[i];
  310. if (variableDeclaration.Kind == VariableDeclarationKind.Const)
  311. {
  312. envRec.CreateImmutableBinding(name, strict: true);
  313. }
  314. else
  315. {
  316. envRec.CreateMutableBinding(name, canBeDeleted: false);
  317. }
  318. }
  319. }
  320. private enum LhsKind
  321. {
  322. Assignment,
  323. VarBinding,
  324. LexicalBinding
  325. }
  326. private enum IteratorKind
  327. {
  328. Sync,
  329. Async
  330. }
  331. private enum IterationKind
  332. {
  333. Enumerate,
  334. Iterate,
  335. AsyncIterate
  336. }
  337. }
  338. }