StatementInterpreter.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. using System.Collections.Generic;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. using Jint.Runtime.Descriptors;
  5. using Jint.Runtime.Environments;
  6. using Jint.Runtime.References;
  7. namespace Jint.Runtime
  8. {
  9. public sealed class StatementInterpreter
  10. {
  11. private readonly Engine _engine;
  12. public StatementInterpreter(Engine engine)
  13. {
  14. _engine = engine;
  15. }
  16. private Completion ExecuteStatement(Statement statement)
  17. {
  18. return _engine.ExecuteStatement(statement);
  19. }
  20. public Completion ExecuteEmptyStatement(EmptyStatement emptyStatement)
  21. {
  22. return new Completion(CompletionType.Normal, null, null);
  23. }
  24. public Completion ExecuteExpressionStatement(ExpressionStatement expressionStatement)
  25. {
  26. var exprRef = _engine.EvaluateExpression(expressionStatement.Expression);
  27. return new Completion(CompletionType.Normal, _engine.GetValue(exprRef, true), null);
  28. }
  29. public Completion ExecuteIfStatement(IfStatement ifStatement)
  30. {
  31. Completion result;
  32. if (TypeConverter.ToBoolean(_engine.GetValue(_engine.EvaluateExpression(ifStatement.Test), true)))
  33. {
  34. result = _engine.ExecuteStatement(ifStatement.Consequent);
  35. }
  36. else if (ifStatement.Alternate != null)
  37. {
  38. result = _engine.ExecuteStatement(ifStatement.Alternate);
  39. }
  40. else
  41. {
  42. return new Completion(CompletionType.Normal, null, null);
  43. }
  44. return result;
  45. }
  46. public Completion ExecuteLabeledStatement(LabeledStatement labeledStatement)
  47. {
  48. // TODO: Esprima added Statement.Label, maybe not necessary as this line is finding the
  49. // containing label and could keep a table per program with all the labels
  50. // labeledStatement.Body.LabelSet = labeledStatement.Label;
  51. var result = _engine.ExecuteStatement(labeledStatement.Body);
  52. if (result.Type == CompletionType.Break && result.Identifier == labeledStatement.Label.Name)
  53. {
  54. var value = result.Value;
  55. return new Completion(CompletionType.Normal, value, null);
  56. }
  57. return result;
  58. }
  59. /// <summary>
  60. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.1
  61. /// </summary>
  62. /// <param name="doWhileStatement"></param>
  63. /// <returns></returns>
  64. public Completion ExecuteDoWhileStatement(DoWhileStatement doWhileStatement)
  65. {
  66. JsValue v = Undefined.Instance;
  67. bool iterating;
  68. do
  69. {
  70. var stmt = _engine.ExecuteStatement(doWhileStatement.Body);
  71. if (!ReferenceEquals(stmt.Value, null))
  72. {
  73. v = stmt.Value;
  74. }
  75. if (stmt.Type != CompletionType.Continue || stmt.Identifier != doWhileStatement?.LabelSet?.Name)
  76. {
  77. if (stmt.Type == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == doWhileStatement?.LabelSet?.Name))
  78. {
  79. return new Completion(CompletionType.Normal, v, null);
  80. }
  81. if (stmt.Type != CompletionType.Normal)
  82. {
  83. return stmt;
  84. }
  85. }
  86. var exprRef = _engine.EvaluateExpression(doWhileStatement.Test);
  87. iterating = TypeConverter.ToBoolean(_engine.GetValue(exprRef, true));
  88. } while (iterating);
  89. return new Completion(CompletionType.Normal, v, null);
  90. }
  91. /// <summary>
  92. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.2
  93. /// </summary>
  94. /// <param name="whileStatement"></param>
  95. /// <returns></returns>
  96. public Completion ExecuteWhileStatement(WhileStatement whileStatement)
  97. {
  98. JsValue v = Undefined.Instance;
  99. while (true)
  100. {
  101. var jsValue = _engine.GetValue(_engine.EvaluateExpression(whileStatement.Test), true);
  102. if (!TypeConverter.ToBoolean(jsValue))
  103. {
  104. return new Completion(CompletionType.Normal, v, null);
  105. }
  106. var stmt = _engine.ExecuteStatement(whileStatement.Body);
  107. if (!ReferenceEquals(stmt.Value, null))
  108. {
  109. v = stmt.Value;
  110. }
  111. if (stmt.Type != CompletionType.Continue || stmt.Identifier != whileStatement?.LabelSet?.Name)
  112. {
  113. if (stmt.Type == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == whileStatement?.LabelSet?.Name))
  114. {
  115. return new Completion(CompletionType.Normal, v, null);
  116. }
  117. if (stmt.Type != CompletionType.Normal)
  118. {
  119. return stmt;
  120. }
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.3
  126. /// </summary>
  127. /// <param name="forStatement"></param>
  128. /// <returns></returns>
  129. public Completion ExecuteForStatement(ForStatement forStatement)
  130. {
  131. var init = forStatement.Init;
  132. if (init != null)
  133. {
  134. if (init.Type == Nodes.VariableDeclaration)
  135. {
  136. var c = _engine.ExecuteStatement((Statement) init);
  137. }
  138. else
  139. {
  140. _engine.GetValue(_engine.EvaluateExpression(init), true);
  141. }
  142. }
  143. JsValue v = Undefined.Instance;
  144. while (true)
  145. {
  146. if (forStatement.Test != null)
  147. {
  148. var testExprRef = _engine.EvaluateExpression(forStatement.Test);
  149. if (!TypeConverter.ToBoolean(_engine.GetValue(testExprRef, true)))
  150. {
  151. return new Completion(CompletionType.Normal, v, null);
  152. }
  153. }
  154. var stmt = _engine.ExecuteStatement(forStatement.Body);
  155. if (!ReferenceEquals(stmt.Value, null))
  156. {
  157. v = stmt.Value;
  158. }
  159. var stmtType = stmt.Type;
  160. if (stmtType == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == forStatement?.LabelSet?.Name))
  161. {
  162. return new Completion(CompletionType.Normal, v, null);
  163. }
  164. if (stmtType != CompletionType.Continue || ((stmt.Identifier != null) && stmt.Identifier != forStatement?.LabelSet?.Name))
  165. {
  166. if (stmtType != CompletionType.Normal)
  167. {
  168. return stmt;
  169. }
  170. }
  171. if (forStatement.Update != null)
  172. {
  173. _engine.GetValue(_engine.EvaluateExpression(forStatement.Update), true);
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4
  179. /// </summary>
  180. /// <param name="forInStatement"></param>
  181. /// <returns></returns>
  182. public Completion ExecuteForInStatement(ForInStatement forInStatement)
  183. {
  184. var identifier = forInStatement.Left.Type == Nodes.VariableDeclaration
  185. ? (Identifier) ((VariableDeclaration) forInStatement.Left).Declarations[0].Id
  186. : (Identifier) forInStatement.Left;
  187. var varRef = _engine.EvaluateExpression(identifier) as Reference;
  188. var experValue = _engine.GetValue(_engine.EvaluateExpression(forInStatement.Right), true);
  189. if (experValue.IsNullOrUndefined())
  190. {
  191. return new Completion(CompletionType.Normal, null, null);
  192. }
  193. var obj = TypeConverter.ToObject(_engine, experValue);
  194. JsValue v = Null.Instance;
  195. // keys are constructed using the prototype chain
  196. var cursor = obj;
  197. var processedKeys = new HashSet<string>();
  198. while (!ReferenceEquals(cursor, null))
  199. {
  200. var keys = _engine.Object.GetOwnPropertyNames(Undefined.Instance, Arguments.From(cursor)).AsArray();
  201. var length = keys.GetLength();
  202. for (var i = 0; i < length; i++)
  203. {
  204. var p = keys.GetOwnProperty(TypeConverter.ToString(i)).Value.AsStringWithoutTypeCheck();
  205. if (processedKeys.Contains(p))
  206. {
  207. continue;
  208. }
  209. processedKeys.Add(p);
  210. // collection might be modified by inner statement
  211. if (cursor.GetOwnProperty(p) == PropertyDescriptor.Undefined)
  212. {
  213. continue;
  214. }
  215. var value = cursor.GetOwnProperty(p);
  216. if (!value.Enumerable)
  217. {
  218. continue;
  219. }
  220. _engine.PutValue(varRef, p);
  221. var stmt = _engine.ExecuteStatement(forInStatement.Body);
  222. if (!ReferenceEquals(stmt.Value, null))
  223. {
  224. v = stmt.Value;
  225. }
  226. if (stmt.Type == CompletionType.Break)
  227. {
  228. return new Completion(CompletionType.Normal, v, null);
  229. }
  230. if (stmt.Type != CompletionType.Continue)
  231. {
  232. if (stmt.Type != CompletionType.Normal)
  233. {
  234. return stmt;
  235. }
  236. }
  237. }
  238. cursor = cursor.Prototype;
  239. }
  240. return new Completion(CompletionType.Normal, v, null);
  241. }
  242. /// <summary>
  243. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.7
  244. /// </summary>
  245. /// <param name="continueStatement"></param>
  246. /// <returns></returns>
  247. public Completion ExecuteContinueStatement(ContinueStatement continueStatement)
  248. {
  249. return new Completion(
  250. CompletionType.Continue,
  251. null,
  252. continueStatement.Label?.Name);
  253. }
  254. /// <summary>
  255. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.8
  256. /// </summary>
  257. /// <param name="breakStatement"></param>
  258. /// <returns></returns>
  259. public Completion ExecuteBreakStatement(BreakStatement breakStatement)
  260. {
  261. return new Completion(
  262. CompletionType.Break,
  263. null,
  264. breakStatement.Label?.Name);
  265. }
  266. /// <summary>
  267. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.9
  268. /// </summary>
  269. /// <param name="statement"></param>
  270. /// <returns></returns>
  271. public Completion ExecuteReturnStatement(ReturnStatement statement)
  272. {
  273. if (statement.Argument == null)
  274. {
  275. return new Completion(CompletionType.Return, Undefined.Instance, null);
  276. }
  277. var jsValue = _engine.GetValue(_engine.EvaluateExpression(statement.Argument), true);
  278. return new Completion(CompletionType.Return, jsValue, null);
  279. }
  280. /// <summary>
  281. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.10
  282. /// </summary>
  283. /// <param name="withStatement"></param>
  284. /// <returns></returns>
  285. public Completion ExecuteWithStatement(WithStatement withStatement)
  286. {
  287. var jsValue = _engine.GetValue(_engine.EvaluateExpression(withStatement.Object), true);
  288. var obj = TypeConverter.ToObject(_engine, jsValue);
  289. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  290. var newEnv = LexicalEnvironment.NewObjectEnvironment(_engine, obj, oldEnv, true);
  291. _engine.UpdateLexicalEnvironment(newEnv);
  292. Completion c;
  293. try
  294. {
  295. c = _engine.ExecuteStatement(withStatement.Body);
  296. }
  297. catch (JavaScriptException e)
  298. {
  299. c = new Completion(CompletionType.Throw, e.Error, null, withStatement.Location);
  300. }
  301. catch (TypeErrorException e)
  302. {
  303. var error = _engine.TypeError.Construct(new JsValue[] {e.Message});
  304. c = new Completion(CompletionType.Throw, error, null, withStatement.Location);
  305. }
  306. finally
  307. {
  308. _engine.UpdateLexicalEnvironment(oldEnv);
  309. }
  310. return c;
  311. }
  312. /// <summary>
  313. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.11
  314. /// </summary>
  315. /// <param name="switchStatement"></param>
  316. /// <returns></returns>
  317. public Completion ExecuteSwitchStatement(SwitchStatement switchStatement)
  318. {
  319. var jsValue = _engine.GetValue(_engine.EvaluateExpression(switchStatement.Discriminant), true);
  320. var r = ExecuteSwitchBlock(switchStatement.Cases, jsValue);
  321. if (r.Type == CompletionType.Break && r.Identifier == switchStatement.LabelSet?.Name)
  322. {
  323. return new Completion(CompletionType.Normal, r.Value, null);
  324. }
  325. return r;
  326. }
  327. public Completion ExecuteSwitchBlock(List<SwitchCase> switchBlock, JsValue input)
  328. {
  329. JsValue v = Undefined.Instance;
  330. SwitchCase defaultCase = null;
  331. bool hit = false;
  332. var switchBlockCount = switchBlock.Count;
  333. for (var i = 0; i < switchBlockCount; i++)
  334. {
  335. var clause = switchBlock[i];
  336. if (clause.Test == null)
  337. {
  338. defaultCase = clause;
  339. }
  340. else
  341. {
  342. var clauseSelector = _engine.GetValue(_engine.EvaluateExpression(clause.Test), true);
  343. if (ExpressionInterpreter.StrictlyEqual(clauseSelector, input))
  344. {
  345. hit = true;
  346. }
  347. }
  348. if (hit && clause.Consequent != null)
  349. {
  350. var r = ExecuteStatementList(clause.Consequent);
  351. if (r.Type != CompletionType.Normal)
  352. {
  353. return r;
  354. }
  355. v = r.Value ?? Undefined.Instance;
  356. }
  357. }
  358. // do we need to execute the default case ?
  359. if (hit == false && defaultCase != null)
  360. {
  361. var r = ExecuteStatementList(defaultCase.Consequent);
  362. if (r.Type != CompletionType.Normal)
  363. {
  364. return r;
  365. }
  366. v = r.Value ?? Undefined.Instance;
  367. }
  368. return new Completion(CompletionType.Normal, v, null);
  369. }
  370. public Completion ExecuteStatementList(List<StatementListItem> statementList)
  371. {
  372. // optimize common case without loop
  373. return statementList.Count == 1
  374. ? ExecuteSingleStatement((Statement) statementList[0])
  375. : ExecuteMultipleStatements(statementList);
  376. }
  377. private Completion ExecuteMultipleStatements(List<StatementListItem> statementList)
  378. {
  379. Statement s = null;
  380. var c = new Completion(CompletionType.Normal, null, null);
  381. Completion sl = c;
  382. try
  383. {
  384. var statementListCount = statementList.Count;
  385. for (var i = 0; i < statementListCount; i++)
  386. {
  387. s = (Statement) statementList[i];
  388. c = _engine.ExecuteStatement(s);
  389. if (c.Type != CompletionType.Normal)
  390. {
  391. var executeStatementList = new Completion(
  392. c.Type,
  393. c.Value ?? sl.Value,
  394. c.Identifier,
  395. c.Location);
  396. return executeStatementList;
  397. }
  398. sl = c;
  399. }
  400. }
  401. catch (JavaScriptException v)
  402. {
  403. var completion = new Completion(CompletionType.Throw, v.Error, null, v.Location ?? s?.Location);
  404. return completion;
  405. }
  406. catch (TypeErrorException e)
  407. {
  408. var error = _engine.TypeError.Construct(new JsValue[] {e.Message});
  409. c = new Completion(CompletionType.Throw, error, null, s?.Location);
  410. }
  411. return new Completion(c.Type, c.GetValueOrDefault(), c.Identifier);
  412. }
  413. private Completion ExecuteSingleStatement(Statement s)
  414. {
  415. try
  416. {
  417. var c = _engine.ExecuteStatement(s);
  418. if (c.Type != CompletionType.Normal)
  419. {
  420. var completion = new Completion(
  421. c.Type,
  422. c.Value,
  423. c.Identifier,
  424. c.Location);
  425. return completion;
  426. }
  427. return new Completion(c.Type, c.GetValueOrDefault(), c.Identifier);
  428. }
  429. catch (JavaScriptException v)
  430. {
  431. return new Completion(CompletionType.Throw, v.Error, null, v.Location ?? s?.Location);
  432. }
  433. catch (TypeErrorException e)
  434. {
  435. var error = _engine.TypeError.Construct(new JsValue[] {e.Message});
  436. return new Completion(CompletionType.Throw, error, null, s?.Location);
  437. }
  438. }
  439. /// <summary>
  440. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.13
  441. /// </summary>
  442. /// <param name="throwStatement"></param>
  443. /// <returns></returns>
  444. public Completion ExecuteThrowStatement(ThrowStatement throwStatement)
  445. {
  446. var jsValue = _engine.GetValue(_engine.EvaluateExpression(throwStatement.Argument), true);
  447. return new Completion(CompletionType.Throw, jsValue, null, throwStatement.Location);
  448. }
  449. /// <summary>
  450. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.14
  451. /// </summary>
  452. /// <param name="tryStatement"></param>
  453. /// <returns></returns>
  454. public Completion ExecuteTryStatement(TryStatement tryStatement)
  455. {
  456. var b = _engine.ExecuteStatement(tryStatement.Block);
  457. if (b.Type == CompletionType.Throw)
  458. {
  459. // execute catch
  460. var catchClause = tryStatement.Handler;
  461. if (catchClause != null)
  462. {
  463. var c = b.Value;
  464. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  465. var catchEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  466. catchEnv._record.CreateMutableBinding(((Identifier) catchClause.Param).Name, c);
  467. _engine.UpdateLexicalEnvironment(catchEnv);
  468. b = _engine.ExecuteStatement(catchClause.Body);
  469. _engine.UpdateLexicalEnvironment(oldEnv);
  470. }
  471. }
  472. if (tryStatement.Finalizer != null)
  473. {
  474. var f = _engine.ExecuteStatement(tryStatement.Finalizer);
  475. if (f.Type == CompletionType.Normal)
  476. {
  477. return b;
  478. }
  479. return f;
  480. }
  481. return b;
  482. }
  483. public Completion ExecuteProgram(Program program)
  484. {
  485. return ExecuteStatementList(program.Body);
  486. }
  487. public Completion ExecuteVariableDeclaration(VariableDeclaration statement)
  488. {
  489. var declarationsCount = statement.Declarations.Count;
  490. for (var i = 0; i < declarationsCount; i++)
  491. {
  492. var declaration = statement.Declarations[i];
  493. if (declaration.Init != null)
  494. {
  495. var lhs = (Reference) _engine.EvaluateExpression(declaration.Id);
  496. lhs.AssertValid(_engine);
  497. var value = _engine.GetValue(_engine.EvaluateExpression(declaration.Init), true);
  498. _engine.PutValue(lhs, value);
  499. _engine._referencePool.Return(lhs);
  500. }
  501. }
  502. return new Completion(CompletionType.Normal, Undefined.Instance, null);
  503. }
  504. public Completion ExecuteBlockStatement(BlockStatement blockStatement)
  505. {
  506. return ExecuteStatementList(blockStatement.Body);
  507. }
  508. public Completion ExecuteDebuggerStatement(DebuggerStatement debuggerStatement)
  509. {
  510. if (_engine.Options._IsDebuggerStatementAllowed)
  511. {
  512. if (!System.Diagnostics.Debugger.IsAttached)
  513. {
  514. System.Diagnostics.Debugger.Launch();
  515. }
  516. System.Diagnostics.Debugger.Break();
  517. }
  518. return new Completion(CompletionType.Normal, null, null);
  519. }
  520. }
  521. }