compiler: allow init statement in if

This commit is contained in:
Evgenii Stratonikov 2020-08-21 11:41:10 +03:00
parent d73f3cd24c
commit 84c36326f5
2 changed files with 33 additions and 0 deletions

View file

@ -565,6 +565,9 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
lElse := c.newLabel()
lElseEnd := c.newLabel()
if n.Init != nil {
ast.Walk(c, n.Init)
}
if n.Cond != nil {
c.emitBoolExpr(n.Cond, true, false, lElse)
}

View file

@ -1,6 +1,7 @@
package compiler_test
import (
"fmt"
"math/big"
"testing"
)
@ -91,3 +92,32 @@ func TestNestedIF(t *testing.T) {
`
eval(t, src, big.NewInt(0))
}
func TestInitIF(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
src := `package foo
func Main() int {
if a := 42; true {
return a
}
return 0
}`
eval(t, src, big.NewInt(42))
})
t.Run("Shadow", func(t *testing.T) {
srcTmpl := `package foo
func Main() int {
a := 11
if a := 42; %v {
return a
}
return a
}`
t.Run("True", func(t *testing.T) {
eval(t, fmt.Sprintf(srcTmpl, true), big.NewInt(42))
})
t.Run("False", func(t *testing.T) {
eval(t, fmt.Sprintf(srcTmpl, false), big.NewInt(11))
})
})
}