From 84c36326f552c4cba97f1604361ba24f5bede81b Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Fri, 21 Aug 2020 11:41:10 +0300 Subject: [PATCH] compiler: allow init statement in if --- pkg/compiler/codegen.go | 3 +++ pkg/compiler/if_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 90f4d62c9..93ee4c711 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -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) } diff --git a/pkg/compiler/if_test.go b/pkg/compiler/if_test.go index 23077ecf9..038c8fe92 100644 --- a/pkg/compiler/if_test.go +++ b/pkg/compiler/if_test.go @@ -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)) + }) + }) +}