JintForInForOfStatement.cs 14 KB

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