Skip to content

Commit

Permalink
Handle break and continue properly with nested loops
Browse files Browse the repository at this point in the history
  • Loading branch information
benhoyt committed Aug 21, 2018
1 parent 2f0380f commit 65c6b2c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
21 changes: 21 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ NR==3, NR==5 { print NR }
{`BEGIN { a["x"] = 3; a["y"] = 4; for (k in a) x += a[k]; print x }`, "", "7\n", "", ""},
{`BEGIN { while (i < 5) { print i; i++ } }`, "", "\n1\n2\n3\n4\n", "", ""},
{`BEGIN { do { print i; i++ } while (i < 5) }`, "", "\n1\n2\n3\n4\n", "", ""},
// regression tests for break and continue with nested loops
{`
BEGIN {
for (i = 0; i < 1; i++) {
for (j = 0; j < 1; j++) {
print i, j
}
break
}
}
`, "", "0 0\n", "", ""},
{`
BEGIN {
for (i = 0; i < 1; i++) {
for (j = 0; j < 1; j++) {
print i, j
}
continue
}
}
`, "", "0 0\n", "", ""},

// Arrays, "in", and delete
{`BEGIN { a["x"] = 3; print "x" in a, "y" in a }`, "", "1 0\n", "", ""},
Expand Down
10 changes: 5 additions & 5 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ type parser struct {
tok Token
val string
progState progState
inLoop bool
loopCount int
inFunction bool
arrayParams map[string]bool
}
Expand Down Expand Up @@ -274,13 +274,13 @@ func (p *parser) stmt() Stmt {
p.expect(RPAREN)
s = &DoWhileStmt{body, cond}
case BREAK:
if !p.inLoop {
if p.loopCount == 0 {
panic(p.error("break must be inside a loop body"))
}
p.next()
s = &BreakStmt{}
case CONTINUE:
if !p.inLoop {
if p.loopCount == 0 {
panic(p.error("continue must be inside a loop body"))
}
p.next()
Expand Down Expand Up @@ -318,9 +318,9 @@ func (p *parser) stmt() Stmt {
}

func (p *parser) loopStmts() Stmts {
p.inLoop = true
p.loopCount++
ss := p.stmts()
p.inLoop = false
p.loopCount--
return ss
}

Expand Down

0 comments on commit 65c6b2c

Please sign in to comment.