Skip to content

Commit

Permalink
ast/parser: generate new wildcards for else (open-policy-agent#5412)
Browse files Browse the repository at this point in the history
The previous behavior had triggered a check in the formatter for multiple
use of wildcard variables:

     f(_) := true { true }
     else := false

The formatter found `$1`, the `_` argument of f, again in else, and thus
changed it into `_1`:

     f(_1) := true { true }
     else := false

There's no extra meaning to the copied wildcards in `else`; they should not
count as second usage.

Fixes: open-policy-agent#5347

Signed-off-by: Stephan Renatus <[email protected]>
  • Loading branch information
srenatus authored Nov 23, 2022
1 parent 3272e52 commit 280cce6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ast/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,11 @@ func (p *Parser) parseElse(head *Head) *Rule {
rule.SetLoc(p.s.Loc())

rule.Head = head.Copy()
for i := range rule.Head.Args {
if v, ok := rule.Head.Args[i].Value.(Var); ok && v.IsWildcard() {
rule.Head.Args[i].Value = Var(p.genwildcard())
}
}
rule.Head.SetLoc(p.s.Loc())

defer func() {
Expand Down
27 changes: 27 additions & 0 deletions ast/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1634,6 +1634,30 @@ func TestRule(t *testing.T) {
})
assertParseError(t, "invalid rule body no separator", `p { a = "foo"bar }`)
assertParseError(t, "invalid rule body no newline", `p { a b c }`)

assertParseRule(t, "wildcard in else args", `f(_) { true } else := false`, &Rule{
Head: &Head{
Name: "f",
Reference: Ref{VarTerm("f")},
Args: Args{
VarTerm("$0"),
},
Value: BooleanTerm(true),
},
Body: MustParseBody(`true`),
Else: &Rule{
Head: &Head{
Name: "f",
Assign: true,
Reference: Ref{VarTerm("f")},
Args: Args{
VarTerm("$1"),
},
Value: BooleanTerm(false),
},
Body: MustParseBody(`true`),
},
})
}

func TestRuleContains(t *testing.T) {
Expand Down Expand Up @@ -4830,6 +4854,9 @@ func assertParseRule(t *testing.T, msg string, input string, correct *Rule, opts
if !rule.Head.Ref().Equal(correct.Head.Ref()) {
t.Errorf("Error on test \"%s\": rule heads not equal: ref = %v (parsed), ref = %v (correct)", msg, rule.Head.Ref(), correct.Head.Ref())
}
if !rule.Head.Equal(correct.Head) {
t.Errorf("Error on test \"%s\": rule heads not equal: %v (parsed), %v (correct)", msg, rule.Head, correct.Head)
}
if !rule.Equal(correct) {
t.Errorf("Error on test \"%s\": rules not equal: %v (parsed), %v (correct)", msg, rule, correct)
}
Expand Down

0 comments on commit 280cce6

Please sign in to comment.