JintForInForOfStatement.cs 14 KB

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