fix deadcode optimization (#378)

This commit is contained in:
E Sequeira 2022-06-10 06:45:34 +01:00 committed by GitHub
parent f90d433d21
commit 71459c44f6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 3 deletions

View file

@ -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
}
@ -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 {

View file

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