diff --git a/compiler/compiler.go b/compiler/compiler.go index 69e7fe0..4b57e2e 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -207,22 +207,27 @@ func (c *Compiler) Compile(node ast.Node) error { return err } - // second jump placeholder - jumpPos2 := c.emit(OpJump, 0) - - // update first jump offset - curPos := len(c.currentInstructions()) - c.changeOperand(jumpPos1, curPos) - if node.Else != nil { + // second jump placeholder + jumpPos2 := c.emit(OpJump, 0) + + // update first jump offset + curPos := len(c.currentInstructions()) + c.changeOperand(jumpPos1, curPos) + if err := c.Compile(node.Else); err != nil { return err } + + // update second jump offset + curPos = len(c.currentInstructions()) + c.changeOperand(jumpPos2, curPos) + } else { + // update first jump offset + curPos := len(c.currentInstructions()) + c.changeOperand(jumpPos1, curPos) } - // update second jump offset - curPos = len(c.currentInstructions()) - c.changeOperand(jumpPos2, curPos) case *ast.ForStmt: return c.compileForStmt(node) case *ast.ForInStmt: diff --git a/compiler/compiler_test.go b/compiler/compiler_test.go index f05b977..c3ba2fc 100644 --- a/compiler/compiler_test.go +++ b/compiler/compiler_test.go @@ -165,13 +165,12 @@ func TestCompiler_Compile(t *testing.T) { expect(t, `if true { 10 }; 3333`, bytecode( concat( - compiler.MakeInstruction(compiler.OpTrue), // 0000 - compiler.MakeInstruction(compiler.OpJumpFalsy, 11), // 0001 - compiler.MakeInstruction(compiler.OpConstant, 0), // 0004 - compiler.MakeInstruction(compiler.OpPop), // 0007 - compiler.MakeInstruction(compiler.OpJump, 11), // 0008 - compiler.MakeInstruction(compiler.OpConstant, 1), // 0011 - compiler.MakeInstruction(compiler.OpPop)), // 0014 + compiler.MakeInstruction(compiler.OpTrue), // 0000 + compiler.MakeInstruction(compiler.OpJumpFalsy, 8), // 0001 + compiler.MakeInstruction(compiler.OpConstant, 0), // 0004 + compiler.MakeInstruction(compiler.OpPop), // 0007 + compiler.MakeInstruction(compiler.OpConstant, 1), // 0008 + compiler.MakeInstruction(compiler.OpPop)), // 0011 objectsArray( intObject(10), intObject(3333))))