Skip to content

Commit 6c94396

Browse files
authored
fix: compile Nop for empty block regardless of pattern (#262)
In PR#230, the fix for #228, I made the wrong fix. It should compile a Nop if action.Stmts is not nil, regardless of pattern. Add a few more test cases too. Fixes #261.
1 parent 6ba8ef3 commit 6c94396

2 files changed

Lines changed: 21 additions & 7 deletions

File tree

internal/compiler/compiler.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -131,17 +131,21 @@ func Compile(resolved *resolver.ResolvedProgram) (compiledProg *Program, err err
131131
pattern = append(pattern, c.finish())
132132
}
133133
var body []Opcode
134-
if len(action.Stmts) > 0 {
135-
c := compiler{resolved: resolved, program: p, indexes: indexes}
136-
c.stmts(action.Stmts)
137-
body = c.finish()
138-
} else if len(action.Pattern) == 0 {
139-
// No action and no pattern (a bare '{}') should have at least one
134+
switch {
135+
case action.Stmts == nil:
136+
// No action block, interpreter will treat this as '{ print $0 }'
137+
case len(action.Stmts) == 0:
138+
// Empty action block (a bare '{}') should have at least one
140139
// opcode, otherwise interpreter will treat it as no action, which
141140
// would be evaluated as '{ print $0 }'.
142141
c := compiler{resolved: resolved, program: p, indexes: indexes}
143142
c.add(Nop)
144143
body = c.finish()
144+
default:
145+
// Regular body such as `{ print $1 }`
146+
c := compiler{resolved: resolved, program: p, indexes: indexes}
147+
c.stmts(action.Stmts)
148+
body = c.finish()
145149
}
146150
p.Actions = append(p.Actions, Action{
147151
Pattern: pattern,

interp/interp_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,17 @@ var interpTests = []interpTest{
5050
{`BEGIN { print "b"} END { print "e" }`, "foo", "b\ne\n", "", ""},
5151
{`BEGIN { print "b"} $0 { print NR } END { print "e" }`, "foo", "b\n1\ne\n", "", ""},
5252
{`BEGIN { printf "x" }; BEGIN { printf "y" }`, "", "xy", "", ""},
53-
{`{}`, "1\n2\n3\n", "", "", ""}, // issue #228
53+
54+
// Presence of patterns and actions
55+
{``, "foo", "", "", ""}, // no pattern, no action
56+
{`0`, "foo", "", "", ""}, // false pattern, no action
57+
{`1`, "foo", "foo\n", "", ""}, // true pattern, no action
58+
{`{}`, "foo", "", "", ""}, // no pattern, empty action (issue #228)
59+
{`0 {}`, "foo", "", "", ""}, // false pattern, empty action
60+
{`1 {}`, "foo", "", "", ""}, // true pattern, empty action (issue #261)
61+
{`{ print $1 }`, "foo", "foo\n", "", ""}, // no pattern, non-empty action
62+
{`0 { print $1 }`, "foo", "", "", ""}, // false pattern, non-empty action
63+
{`1 { print $1 }`, "foo", "foo\n", "", ""}, // true pattern, non-empty action
5464

5565
// Patterns
5666
{`$0`, "foo\n\nbar", "foo\nbar\n", "", ""},

0 commit comments

Comments
 (0)