JintForInForOfStatement.cs 14 KB

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