Skip to content

Commit

Permalink
fix deadcode optimization (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
geseq committed Jun 10, 2022
1 parent f90d433 commit 71459c4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
7 changes: 4 additions & 3 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1220,14 +1220,14 @@ func (c *Compiler) optimizeFunc(node parser.Node) {
iterateInstructions(c.scopes[c.scopeIndex].Instructions,
func(pos int, opcode parser.Opcode, operands []int) bool {
switch {
case dsts[pos]:
dstIdx++
deadCode = false
case opcode == parser.OpReturn:
if deadCode {
return true
}
deadCode = true
case dsts[pos]:
dstIdx++
deadCode = false
case deadCode:
return true
}
Expand All @@ -1242,6 +1242,7 @@ func (c *Compiler) optimizeFunc(node parser.Node) {
var appendReturn bool
endPos := len(c.scopes[c.scopeIndex].Instructions)
newEndPost := len(newInsts)

iterateInstructions(newInsts,
func(pos int, opcode parser.Opcode, operands []int) bool {
switch opcode {
Expand Down
24 changes: 24 additions & 0 deletions compiler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,30 @@ func() {
tengo.MakeInstruction(parser.OpReturn, 1),
tengo.MakeInstruction(parser.OpConstant, 1),
tengo.MakeInstruction(parser.OpReturn, 1)))))

expectCompile(t, `
func() {
if true {
return
}
return
return 123
}`, bytecode(
concatInsts(
tengo.MakeInstruction(parser.OpConstant, 1),
tengo.MakeInstruction(parser.OpPop),
tengo.MakeInstruction(parser.OpSuspend)),
objectsArray(
intObject(123),
compiledFunction(0, 0,
tengo.MakeInstruction(parser.OpTrue),
tengo.MakeInstruction(parser.OpJumpFalsy, 6),
tengo.MakeInstruction(parser.OpReturn, 0),
tengo.MakeInstruction(parser.OpReturn, 0),
tengo.MakeInstruction(parser.OpConstant, 0),
tengo.MakeInstruction(parser.OpReturn, 1)))))
}

func TestCompilerScopes(t *testing.T) {
Expand Down

0 comments on commit 71459c4

Please sign in to comment.