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,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:

View file

@ -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))))