Permalink
Browse files

Try/finally in parser with tests

  • Loading branch information...
1 parent 8d6b291 commit c5f3db36e2065218b4d9a0964ef897dec280c318 @ajlopez committed Nov 20, 2012
@@ -1792,6 +1792,45 @@ public void CompileIfCommandWithElifCommand()
Assert.IsNull(parser.CompileCommand());
}
+ [TestMethod]
+ public void CompileSimpleTry()
+ {
+ Parser parser = new Parser("try:\r\n pass");
+
+ ICommand cmd = parser.CompileCommand();
+
+ Assert.IsNotNull(cmd);
+ Assert.IsInstanceOfType(cmd, typeof(TryCommand));
+
+ TryCommand trycmd = (TryCommand)cmd;
+
+ Assert.IsNotNull(trycmd.Command);
+ Assert.IsInstanceOfType(trycmd.Command, typeof(PassCommand));
+
+ Assert.IsNull(trycmd.Finally);
+ }
+
+ [TestMethod]
+ public void CompileSimpleTryWithFinally()
+ {
+ Parser parser = new Parser("try:\r\n pass\r\nfinally:\r\n pass");
+
+ ICommand cmd = parser.CompileCommand();
+
+ Assert.IsNotNull(cmd);
+ Assert.IsInstanceOfType(cmd, typeof(TryCommand));
+
+ TryCommand trycmd = (TryCommand)cmd;
+
+ Assert.IsNotNull(trycmd.Command);
+ Assert.IsInstanceOfType(trycmd.Command, typeof(PassCommand));
+
+ Assert.IsNotNull(trycmd.Finally);
+ Assert.IsInstanceOfType(trycmd.Command, typeof(PassCommand));
+
+ Assert.IsNull(parser.CompileCommand());
+ }
+
private static object CompileAndEvaluateExpression(string text)
{
Machine machine = new Machine();
@@ -19,6 +19,8 @@ public TryCommand(ICommand command)
public ICommand Command { get { return this.command; } }
+ public ICommand Finally { get { return this.finallyCommand; } }
+
public void SetFinally(ICommand finallyCommand)
{
this.finallyCommand = finallyCommand;
@@ -356,6 +356,9 @@ private ICommand CompileSimpleCommand()
if (token.Value == "def")
return this.CompileDefCommand();
+ if (token.Value == "try")
+ return this.CompileTryCommand();
+
if (token.Value == "pass")
{
this.CompileEndOfCommand();
@@ -498,6 +501,29 @@ private ICommand CompileForCommand()
return new ForCommand(name, expression, command);
}
+ private ICommand CompileTryCommand()
+ {
+ ICommand command = this.CompileSuite();
+
+ var trycommand = new TryCommand(command);
+
+ int indent = this.lexer.NextIndent();
+
+ if (indent == this.indent)
+ {
+ if (this.TryCompile(TokenType.Name, "finally"))
+ {
+ ICommand finallycommand = this.CompileSuite();
+ trycommand.SetFinally(finallycommand);
+ return trycommand;
+ }
+ }
+
+ this.lexer.PushIndent(indent);
+
+ return trycommand;
+ }
+
private ICommand CompileIfCommand()
{
IExpression condition = this.CompileExpression();

0 comments on commit c5f3db3

Please sign in to comment.