Skip to content

Commit

Permalink
ast/parser: fresh wildcards for chained function heads (#5426)
Browse files Browse the repository at this point in the history
This is a spiritual follow-up to #5412.

A policy like

    f(_) := 1 { true } { true } { true }

would have been pretty-printed as

    f(_0) := 1
    f(_0) := 1
    f(_0) := 1

because of the duplicated wildcards.

They now get the same treatment as "else" gets: fresh wildcards.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
  • Loading branch information
srenatus committed Nov 29, 2022
1 parent 50b9a9d commit 9354f89
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
9 changes: 6 additions & 3 deletions ast/parser.go
Expand Up @@ -660,9 +660,7 @@ func (p *Parser) parseRules() []*Rule {

rule.Location.Text = p.s.Text(rule.Location.Offset, p.s.lastEnd)

var rules []*Rule

rules = append(rules, &rule)
rules := []*Rule{&rule}

for p.s.tok == tokens.LBrace {

Expand All @@ -688,6 +686,11 @@ func (p *Parser) parseRules() []*Rule {
// rule's head AST but have their location
// set to the rule body.
next.Head = rule.Head.Copy()
for i := range next.Head.Args {
if v, ok := next.Head.Args[i].Value.(Var); ok && v.IsWildcard() {
next.Head.Args[i].Value = Var(p.genwildcard())
}
}
setLocRecursive(next.Head, loc)

rules = append(rules, &next)
Expand Down
20 changes: 20 additions & 0 deletions ast/parser_test.go
Expand Up @@ -1658,6 +1658,26 @@ func TestRule(t *testing.T) {
Body: MustParseBody(`true`),
},
})

name := Var("f")
ref := Ref{VarTerm("f")}
tr := BooleanTerm(true)
head := func(v string) *Head { return &Head{Name: name, Reference: ref, Value: tr, Args: []*Term{VarTerm(v)}} }
assertParseModule(t, "wildcard in chained function heads", `package test
f(_) { true } { true }
`, &Module{
Package: MustParsePackage(`package test`),
Rules: []*Rule{
{
Head: head("$0"),
Body: MustParseBody("true"),
},
{
Head: head("$1"),
Body: MustParseBody("true"),
},
},
})
}

func TestRuleContains(t *testing.T) {
Expand Down

0 comments on commit 9354f89

Please sign in to comment.