diff --git a/interp/interp_test.go b/interp/interp_test.go index 3e60147a..4c1cb3e2 100644 --- a/interp/interp_test.go +++ b/interp/interp_test.go @@ -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", "", ""}, diff --git a/parser/parser.go b/parser/parser.go index 93dc180b..71d16cf3 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -64,7 +64,7 @@ type parser struct { tok Token val string progState progState - inLoop bool + loopCount int inFunction bool arrayParams map[string]bool } @@ -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() @@ -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 }