JintForInForOfStatement.cs 13 KB

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