From f0b6f783aaca838d260192bcbcf2ab3ce6b3ccec Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 26 Mar 2020 14:57:57 +0300 Subject: [PATCH] compiler: allow for loops with empty condition --- pkg/compiler/codegen.go | 8 +++++--- pkg/compiler/for_test.go | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 11538fda1..5761f94f9 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -781,10 +781,12 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { // Set label and walk the condition. c.pushStackLabel(label, 0) c.setLabel(fstart) - ast.Walk(c, n.Cond) + if n.Cond != nil { + ast.Walk(c, n.Cond) - // Jump if the condition is false - emit.Jmp(c.prog.BinWriter, opcode.JMPIFNOT, fend) + // Jump if the condition is false + emit.Jmp(c.prog.BinWriter, opcode.JMPIFNOT, fend) + } // Walk body followed by the iterator (post stmt). ast.Walk(c, n.Body) diff --git a/pkg/compiler/for_test.go b/pkg/compiler/for_test.go index d45618168..34289613e 100644 --- a/pkg/compiler/for_test.go +++ b/pkg/compiler/for_test.go @@ -374,6 +374,23 @@ func TestDec(t *testing.T) { eval(t, src, big.NewInt(1)) } +func TestForLoopEmpty(t *testing.T) { + src := ` + package foo + func Main() int { + x := 0 + for { + x++ + if x == 2 { + break + } + } + return x + } + ` + eval(t, src, big.NewInt(2)) +} + func TestForLoopBigIter(t *testing.T) { src := ` package foo