From 94ed7ececc7a2979133853e1e541b7f3382b8ae6 Mon Sep 17 00:00:00 2001 From: Max Kaufmann Date: Tue, 2 Aug 2011 22:38:03 -0700 Subject: [PATCH] else statements --- Lang/Block.cs | 20 +++++++++++++++++++- Lang/InstructionParser.cs | 6 ++++++ Main.cs | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Lang/Block.cs b/Lang/Block.cs index fbb7927..b92d070 100644 --- a/Lang/Block.cs +++ b/Lang/Block.cs @@ -32,14 +32,32 @@ public Block(List buffer) { public class IfBlock : Block { public BranchInstruction branch; public int branchIndex; + public JumpInstruction elseJump = null; public IfBlock(Expression condition, List buffer) : base(buffer) { branchIndex = buffer.Count; branch = new BranchInstruction(condition, branchIndex+1, -1); + buffer.Add(branch); } - override public void End() { + public bool ElseIf(Expression condition) { + return false; + } + + public bool Else() { + if (elseJump != null) { return false; } + elseJump = new JumpInstruction(-1); + buffer.Add(elseJump); branch.indexFalse = buffer.Count; + return true; + } + + override public void End() { + if (elseJump != null) { + elseJump.index = buffer.Count; + } else { + branch.indexFalse = buffer.Count; + } } // todo add elseif, else diff --git a/Lang/InstructionParser.cs b/Lang/InstructionParser.cs index f1ef2da..eb3fe81 100644 --- a/Lang/InstructionParser.cs +++ b/Lang/InstructionParser.cs @@ -97,6 +97,12 @@ State Idle(Token t) { if (mBlock.Count == 0) { return null; } mBlock.Pop().End(); return Idle; + case "else": + if (mBlock.Count == 0) { return null; } + var block = mBlock.Peek() as IfBlock; + if (block == null) { return null; } + if (!block.Else()) { return null; } + return Idle; default: break; } } diff --git a/Main.cs b/Main.cs index 8c62eae..6968009 100644 --- a/Main.cs +++ b/Main.cs @@ -41,6 +41,11 @@ turn left move backward 5 stop stroke end + if 0 + move forward 100 + else + move backward 100 + end "); var interpreter = new Interpreter(program); while(interpreter.ExecuteNextInstruction()) {}