JintForInForOfStatement.cs 13 KB

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