remove unnecessary JMP when there's no ELSE block

This commit is contained in:
Daniel Kang 2019-01-13 12:13:15 -08:00
parent 4b370e8623
commit d581cb24e4
2 changed files with 21 additions and 17 deletions

View file

@ -207,6 +207,7 @@ func (c *Compiler) Compile(node ast.Node) error {
return err
}
if node.Else != nil {
// second jump placeholder
jumpPos2 := c.emit(OpJump, 0)
@ -214,15 +215,19 @@ func (c *Compiler) Compile(node ast.Node) error {
curPos := len(c.currentInstructions())
c.changeOperand(jumpPos1, curPos)
if node.Else != nil {
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)
}
case *ast.ForStmt:
return c.compileForStmt(node)
case *ast.ForInStmt:

View file

@ -166,12 +166,11 @@ func TestCompiler_Compile(t *testing.T) {
bytecode(
concat(
compiler.MakeInstruction(compiler.OpTrue), // 0000
compiler.MakeInstruction(compiler.OpJumpFalsy, 11), // 0001
compiler.MakeInstruction(compiler.OpJumpFalsy, 8), // 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.OpConstant, 1), // 0008
compiler.MakeInstruction(compiler.OpPop)), // 0011
objectsArray(
intObject(10),
intObject(3333))))