StatementInterpreter.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using System;
  2. using System.Collections.Generic;
  3. using Esprima.Ast;
  4. using Jint.Native;
  5. using Jint.Runtime.Descriptors;
  6. using Jint.Runtime.Environments;
  7. using Jint.Runtime.References;
  8. namespace Jint.Runtime
  9. {
  10. public class StatementInterpreter
  11. {
  12. private readonly Engine _engine;
  13. public StatementInterpreter(Engine engine)
  14. {
  15. _engine = engine;
  16. }
  17. private Completion ExecuteStatement(Statement statement)
  18. {
  19. return _engine.ExecuteStatement(statement);
  20. }
  21. public Completion ExecuteEmptyStatement(EmptyStatement emptyStatement)
  22. {
  23. return new Completion(CompletionType.Normal, null, null);
  24. }
  25. public Completion ExecuteExpressionStatement(ExpressionStatement expressionStatement)
  26. {
  27. var exprRef = _engine.EvaluateExpression(expressionStatement.Expression);
  28. return new Completion(CompletionType.Normal, _engine.GetValue(exprRef, true), null);
  29. }
  30. public Completion ExecuteIfStatement(IfStatement ifStatement)
  31. {
  32. Completion result;
  33. if (TypeConverter.ToBoolean(_engine.GetValue(_engine.EvaluateExpression(ifStatement.Test), true)))
  34. {
  35. result = ExecuteStatement(ifStatement.Consequent);
  36. }
  37. else if (ifStatement.Alternate != null)
  38. {
  39. result = ExecuteStatement(ifStatement.Alternate);
  40. }
  41. else
  42. {
  43. return new Completion(CompletionType.Normal, null, null);
  44. }
  45. return result;
  46. }
  47. public Completion ExecuteLabeledStatement(LabeledStatement labeledStatement)
  48. {
  49. // TODO: Esprima added Statement.Label, maybe not necessary as this line is finding the
  50. // containing label and could keep a table per program with all the labels
  51. // labeledStatement.Body.LabelSet = labeledStatement.Label;
  52. var result = ExecuteStatement(labeledStatement.Body);
  53. if (result.Type == CompletionType.Break && result.Identifier == labeledStatement.Label.Name)
  54. {
  55. var value = result.Value;
  56. return new Completion(CompletionType.Normal, value, null);
  57. }
  58. return result;
  59. }
  60. /// <summary>
  61. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.1
  62. /// </summary>
  63. /// <param name="doWhileStatement"></param>
  64. /// <returns></returns>
  65. public Completion ExecuteDoWhileStatement(DoWhileStatement doWhileStatement)
  66. {
  67. JsValue v = Undefined.Instance;
  68. bool iterating;
  69. do
  70. {
  71. var stmt = ExecuteStatement(doWhileStatement.Body);
  72. if (!ReferenceEquals(stmt.Value, null))
  73. {
  74. v = stmt.Value;
  75. }
  76. if (stmt.Type != CompletionType.Continue || stmt.Identifier != doWhileStatement?.LabelSet?.Name)
  77. {
  78. if (stmt.Type == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == doWhileStatement?.LabelSet?.Name))
  79. {
  80. return new Completion(CompletionType.Normal, v, null);
  81. }
  82. if (stmt.Type != CompletionType.Normal)
  83. {
  84. return stmt;
  85. }
  86. }
  87. var exprRef = _engine.EvaluateExpression(doWhileStatement.Test);
  88. iterating = TypeConverter.ToBoolean(_engine.GetValue(exprRef, true));
  89. } while (iterating);
  90. return new Completion(CompletionType.Normal, v, null);
  91. }
  92. /// <summary>
  93. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.2
  94. /// </summary>
  95. /// <param name="whileStatement"></param>
  96. /// <returns></returns>
  97. public Completion ExecuteWhileStatement(WhileStatement whileStatement)
  98. {
  99. JsValue v = Undefined.Instance;
  100. while (true)
  101. {
  102. var jsValue = _engine.GetValue(_engine.EvaluateExpression(whileStatement.Test), true);
  103. if (!TypeConverter.ToBoolean(jsValue))
  104. {
  105. return new Completion(CompletionType.Normal, v, null);
  106. }
  107. var stmt = ExecuteStatement(whileStatement.Body);
  108. if (!ReferenceEquals(stmt.Value, null))
  109. {
  110. v = stmt.Value;
  111. }
  112. if (stmt.Type != CompletionType.Continue || stmt.Identifier != whileStatement?.LabelSet?.Name)
  113. {
  114. if (stmt.Type == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == whileStatement?.LabelSet?.Name))
  115. {
  116. return new Completion(CompletionType.Normal, v, null);
  117. }
  118. if (stmt.Type != CompletionType.Normal)
  119. {
  120. return stmt;
  121. }
  122. }
  123. }
  124. }
  125. /// <summary>
  126. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.3
  127. /// </summary>
  128. /// <param name="forStatement"></param>
  129. /// <returns></returns>
  130. public Completion ExecuteForStatement(ForStatement forStatement)
  131. {
  132. var init = forStatement.Init;
  133. if (init != null)
  134. {
  135. if (init.Type == Nodes.VariableDeclaration)
  136. {
  137. var c = ExecuteStatement((Statement) init);
  138. }
  139. else
  140. {
  141. _engine.GetValue(_engine.EvaluateExpression(init), true);
  142. }
  143. }
  144. JsValue v = Undefined.Instance;
  145. while (true)
  146. {
  147. if (forStatement.Test != null)
  148. {
  149. var testExprRef = _engine.EvaluateExpression(forStatement.Test);
  150. if (!TypeConverter.ToBoolean(_engine.GetValue(testExprRef, true)))
  151. {
  152. return new Completion(CompletionType.Normal, v, null);
  153. }
  154. }
  155. var stmt = ExecuteStatement(forStatement.Body);
  156. if (!ReferenceEquals(stmt.Value, null))
  157. {
  158. v = stmt.Value;
  159. }
  160. var stmtType = stmt.Type;
  161. if (stmtType == CompletionType.Break && (stmt.Identifier == null || stmt.Identifier == forStatement?.LabelSet?.Name))
  162. {
  163. return new Completion(CompletionType.Normal, v, null);
  164. }
  165. if (stmtType != CompletionType.Continue || ((stmt.Identifier != null) && stmt.Identifier != forStatement?.LabelSet?.Name))
  166. {
  167. if (stmtType != CompletionType.Normal)
  168. {
  169. return stmt;
  170. }
  171. }
  172. if (forStatement.Update != null)
  173. {
  174. _engine.GetValue(_engine.EvaluateExpression(forStatement.Update), true);
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4
  180. /// </summary>
  181. /// <param name="forInStatement"></param>
  182. /// <returns></returns>
  183. public Completion ExecuteForInStatement(ForInStatement forInStatement)
  184. {
  185. var identifier = forInStatement.Left.Type == Nodes.VariableDeclaration
  186. ? (Identifier) ((VariableDeclaration) forInStatement.Left).Declarations[0].Id
  187. : (Identifier) forInStatement.Left;
  188. var varRef = _engine.EvaluateExpression(identifier) as Reference;
  189. var experValue = _engine.GetValue(_engine.EvaluateExpression(forInStatement.Right), true);
  190. if (experValue.IsUndefined() || experValue.IsNull())
  191. {
  192. return new Completion(CompletionType.Normal, null, null);
  193. }
  194. var obj = TypeConverter.ToObject(_engine, experValue);
  195. JsValue v = Null.Instance;
  196. // keys are constructed using the prototype chain
  197. var cursor = obj;
  198. var processedKeys = new HashSet<string>();
  199. while (!ReferenceEquals(cursor, null))
  200. {
  201. var keys = _engine.Object.GetOwnPropertyNames(Undefined.Instance, Arguments.From(cursor)).AsArray();
  202. for (var i = 0; i < keys.GetLength(); 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 = 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 = ExecuteStatement(withStatement.Body);
  296. }
  297. catch (JavaScriptException e)
  298. {
  299. c = new Completion(CompletionType.Throw, e.Error, null, withStatement.Location);
  300. }
  301. finally
  302. {
  303. _engine.UpdateLexicalEnvironment(oldEnv);
  304. }
  305. return c;
  306. }
  307. /// <summary>
  308. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.11
  309. /// </summary>
  310. /// <param name="switchStatement"></param>
  311. /// <returns></returns>
  312. public Completion ExecuteSwitchStatement(SwitchStatement switchStatement)
  313. {
  314. var jsValue = _engine.GetValue(_engine.EvaluateExpression(switchStatement.Discriminant), true);
  315. var r = ExecuteSwitchBlock(switchStatement.Cases, jsValue);
  316. if (r.Type == CompletionType.Break && r.Identifier == switchStatement.LabelSet?.Name)
  317. {
  318. return new Completion(CompletionType.Normal, r.Value, null);
  319. }
  320. return r;
  321. }
  322. public Completion ExecuteSwitchBlock(List<SwitchCase> switchBlock, JsValue input)
  323. {
  324. JsValue v = Undefined.Instance;
  325. SwitchCase defaultCase = null;
  326. bool hit = false;
  327. var switchBlockCount = switchBlock.Count;
  328. for (var i = 0; i < switchBlockCount; i++)
  329. {
  330. var clause = switchBlock[i];
  331. if (clause.Test == null)
  332. {
  333. defaultCase = clause;
  334. }
  335. else
  336. {
  337. var clauseSelector = _engine.GetValue(_engine.EvaluateExpression(clause.Test), true);
  338. if (ExpressionInterpreter.StrictlyEqual(clauseSelector, input))
  339. {
  340. hit = true;
  341. }
  342. }
  343. if (hit && clause.Consequent != null)
  344. {
  345. var r = ExecuteStatementList(clause.Consequent);
  346. if (r.Type != CompletionType.Normal)
  347. {
  348. return r;
  349. }
  350. v = r.Value ?? Undefined.Instance;
  351. }
  352. }
  353. // do we need to execute the default case ?
  354. if (hit == false && defaultCase != null)
  355. {
  356. var r = ExecuteStatementList(defaultCase.Consequent);
  357. if (r.Type != CompletionType.Normal)
  358. {
  359. return r;
  360. }
  361. v = r.Value ?? Undefined.Instance;
  362. }
  363. return new Completion(CompletionType.Normal, v, null);
  364. }
  365. public Completion ExecuteStatementList(List<StatementListItem> statementList)
  366. {
  367. var c = new Completion(CompletionType.Normal, null, null);
  368. Completion sl = c;
  369. Statement s = null;
  370. try
  371. {
  372. var statementListCount = statementList.Count;
  373. for (var i = 0; i < statementListCount; i++)
  374. {
  375. s = (Statement) statementList[i];
  376. c = ExecuteStatement(s);
  377. if (c.Type != CompletionType.Normal)
  378. {
  379. var executeStatementList = new Completion(
  380. c.Type,
  381. c.Value ?? sl.Value,
  382. c.Identifier,
  383. c.Location);
  384. return executeStatementList;
  385. }
  386. sl = c;
  387. }
  388. }
  389. catch (JavaScriptException v)
  390. {
  391. var completion = new Completion(CompletionType.Throw, v.Error, null, v.Location ?? s.Location);
  392. return completion;
  393. }
  394. return new Completion(c.Type, c.GetValueOrDefault(), c.Identifier);
  395. }
  396. /// <summary>
  397. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.13
  398. /// </summary>
  399. /// <param name="throwStatement"></param>
  400. /// <returns></returns>
  401. public Completion ExecuteThrowStatement(ThrowStatement throwStatement)
  402. {
  403. var jsValue = _engine.GetValue(_engine.EvaluateExpression(throwStatement.Argument), true);
  404. return new Completion(CompletionType.Throw, jsValue, null, throwStatement.Location);
  405. }
  406. /// <summary>
  407. /// http://www.ecma-international.org/ecma-262/5.1/#sec-12.14
  408. /// </summary>
  409. /// <param name="tryStatement"></param>
  410. /// <returns></returns>
  411. public Completion ExecuteTryStatement(TryStatement tryStatement)
  412. {
  413. var b = ExecuteStatement(tryStatement.Block);
  414. if (b.Type == CompletionType.Throw)
  415. {
  416. // execute catch
  417. var catchClause = tryStatement.Handler;
  418. if (catchClause != null)
  419. {
  420. var c = _engine.GetValue(b);
  421. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  422. var catchEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  423. catchEnv.Record.CreateMutableBinding(((Identifier) catchClause.Param).Name, c);
  424. _engine.UpdateLexicalEnvironment(catchEnv);
  425. b = ExecuteStatement(catchClause.Body);
  426. _engine.UpdateLexicalEnvironment(oldEnv);
  427. }
  428. }
  429. if (tryStatement.Finalizer != null)
  430. {
  431. var f = ExecuteStatement(tryStatement.Finalizer);
  432. if (f.Type == CompletionType.Normal)
  433. {
  434. return b;
  435. }
  436. return f;
  437. }
  438. return b;
  439. }
  440. public Completion ExecuteProgram(Program program)
  441. {
  442. return ExecuteStatementList(program.Body);
  443. }
  444. public Completion ExecuteVariableDeclaration(VariableDeclaration statement)
  445. {
  446. var declarationsCount = statement.Declarations.Count;
  447. for (var i = 0; i < declarationsCount; i++)
  448. {
  449. var declaration = statement.Declarations[i];
  450. if (declaration.Init != null)
  451. {
  452. if (!(_engine.EvaluateExpression(declaration.Id) is Reference lhs))
  453. {
  454. throw new ArgumentException();
  455. }
  456. if (lhs.IsStrict()
  457. && lhs.GetBase() is EnvironmentRecord
  458. && (lhs.GetReferencedName() == "eval" || lhs.GetReferencedName() == "arguments"))
  459. {
  460. throw new JavaScriptException(_engine.SyntaxError);
  461. }
  462. var value = _engine.GetValue(_engine.EvaluateExpression(declaration.Init), true);
  463. _engine.PutValue(lhs, value);
  464. _engine.ReferencePool.Return(lhs);
  465. }
  466. }
  467. return new Completion(CompletionType.Normal, Undefined.Instance, null);
  468. }
  469. public Completion ExecuteBlockStatement(BlockStatement blockStatement)
  470. {
  471. return ExecuteStatementList(blockStatement.Body);
  472. }
  473. public Completion ExecuteDebuggerStatement(DebuggerStatement debuggerStatement)
  474. {
  475. if (_engine.Options._IsDebuggerStatementAllowed)
  476. {
  477. if (!System.Diagnostics.Debugger.IsAttached)
  478. {
  479. System.Diagnostics.Debugger.Launch();
  480. }
  481. System.Diagnostics.Debugger.Break();
  482. }
  483. return new Completion(CompletionType.Normal, null, null);
  484. }
  485. }
  486. }