JintForInForOfStatement.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using System.Diagnostics.CodeAnalysis;
  2. using Jint.Native;
  3. using Jint.Native.Iterator;
  4. using Jint.Runtime.Environments;
  5. using Jint.Runtime.Interpreter.Expressions;
  6. using Environment = Jint.Runtime.Environments.Environment;
  7. namespace Jint.Runtime.Interpreter.Statements;
  8. /// <summary>
  9. /// https://tc39.es/ecma262/#sec-for-in-and-for-of-statements
  10. /// </summary>
  11. internal sealed class JintForInForOfStatement : JintStatement<Statement>
  12. {
  13. private readonly Node _leftNode;
  14. private readonly Statement _forBody;
  15. private readonly Expression _rightExpression;
  16. private readonly IterationKind _iterationKind;
  17. private ProbablyBlockStatement _body;
  18. private JintExpression? _expr;
  19. private DestructuringPattern? _assignmentPattern;
  20. private JintExpression _right = null!;
  21. private List<Key>? _tdzNames;
  22. private bool _destructuring;
  23. private LhsKind _lhsKind;
  24. private DisposeHint _disposeHint;
  25. public JintForInForOfStatement(ForInStatement statement) : base(statement)
  26. {
  27. _leftNode = statement.Left;
  28. _rightExpression = statement.Right;
  29. _forBody = statement.Body;
  30. _iterationKind = IterationKind.Enumerate;
  31. }
  32. public JintForInForOfStatement(ForOfStatement statement) : base(statement)
  33. {
  34. _leftNode = statement.Left;
  35. _rightExpression = statement.Right;
  36. _forBody = statement.Body;
  37. _iterationKind = IterationKind.Iterate;
  38. }
  39. protected override void Initialize(EvaluationContext context2)
  40. {
  41. _lhsKind = LhsKind.Assignment;
  42. _disposeHint = DisposeHint.Normal;
  43. switch (_leftNode)
  44. {
  45. case VariableDeclaration variableDeclaration:
  46. {
  47. _lhsKind = variableDeclaration.Kind == VariableDeclarationKind.Var
  48. ? LhsKind.VarBinding
  49. : LhsKind.LexicalBinding;
  50. _disposeHint = variableDeclaration.Kind.GetDisposeHint();
  51. var variableDeclarationDeclaration = variableDeclaration.Declarations[0];
  52. var id = variableDeclarationDeclaration.Id;
  53. if (_lhsKind == LhsKind.LexicalBinding)
  54. {
  55. _tdzNames = new List<Key>(1);
  56. id.GetBoundNames(_tdzNames);
  57. }
  58. if (id is DestructuringPattern pattern)
  59. {
  60. _destructuring = true;
  61. _assignmentPattern = pattern;
  62. }
  63. else
  64. {
  65. var identifier = (Identifier) id;
  66. _expr = new JintIdentifierExpression(identifier);
  67. }
  68. break;
  69. }
  70. case DestructuringPattern pattern:
  71. _destructuring = true;
  72. _assignmentPattern = pattern;
  73. break;
  74. case MemberExpression memberExpression:
  75. _expr = new JintMemberExpression(memberExpression);
  76. break;
  77. default:
  78. _expr = new JintIdentifierExpression((Identifier) _leftNode);
  79. break;
  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. DeclarativeEnvironment? 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 == NodeType.Identifier && !reference.IsUnresolvableReference)
  202. {
  203. reference.InitializeReferencedBinding(nextValue, _disposeHint);
  204. }
  205. else
  206. {
  207. engine.PutValue(reference, nextValue);
  208. }
  209. }
  210. }
  211. else
  212. {
  213. nextValue = DestructuringPatternAssignmentExpression.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. result = iterationEnv?.DisposeResources(result) ?? result;
  252. engine.UpdateLexicalEnvironment(oldEnv);
  253. if (!result.Value.IsEmpty)
  254. {
  255. v = result.Value;
  256. }
  257. if (result.Type == CompletionType.Break && (context.Target == null || string.Equals(context.Target, _statement?.LabelSet?.Name, StringComparison.Ordinal)))
  258. {
  259. completionType = CompletionType.Normal;
  260. return new Completion(CompletionType.Normal, v, _statement!);
  261. }
  262. if (result.Type != CompletionType.Continue || (context.Target != null && !string.Equals(context.Target, _statement?.LabelSet?.Name, StringComparison.Ordinal)))
  263. {
  264. completionType = result.Type;
  265. if (iterationKind == IterationKind.Enumerate)
  266. {
  267. // TODO es6-generators make sure we can start from where we left off
  268. //return result;
  269. }
  270. if (result.IsAbrupt())
  271. {
  272. close = true;
  273. return result;
  274. }
  275. }
  276. }
  277. }
  278. catch
  279. {
  280. completionType = CompletionType.Throw;
  281. throw;
  282. }
  283. finally
  284. {
  285. if (close)
  286. {
  287. try
  288. {
  289. iteratorRecord.Close(completionType);
  290. }
  291. catch
  292. {
  293. // if we already have and exception, use it
  294. if (completionType != CompletionType.Throw)
  295. {
  296. #pragma warning disable CA2219
  297. #pragma warning disable MA0072
  298. throw;
  299. #pragma warning restore MA0072
  300. #pragma warning restore CA2219
  301. }
  302. }
  303. }
  304. engine.UpdateLexicalEnvironment(oldEnv);
  305. }
  306. }
  307. private void BindingInstantiation(Environment environment)
  308. {
  309. var envRec = (DeclarativeEnvironment) environment;
  310. var variableDeclaration = (VariableDeclaration) _leftNode;
  311. var boundNames = new List<Key>();
  312. variableDeclaration.GetBoundNames(boundNames);
  313. for (var i = 0; i < boundNames.Count; i++)
  314. {
  315. var name = boundNames[i];
  316. if (variableDeclaration.Kind == VariableDeclarationKind.Const)
  317. {
  318. envRec.CreateImmutableBinding(name, strict: true);
  319. }
  320. else
  321. {
  322. envRec.CreateMutableBinding(name, canBeDeleted: false);
  323. }
  324. }
  325. }
  326. private enum LhsKind
  327. {
  328. Assignment,
  329. VarBinding,
  330. LexicalBinding
  331. }
  332. private enum IteratorKind
  333. {
  334. Sync,
  335. Async
  336. }
  337. private enum IterationKind
  338. {
  339. Enumerate,
  340. Iterate,
  341. AsyncIterate
  342. }
  343. }