From e5566d0b1071fe7628b6a052223b4bee06f61ff9 Mon Sep 17 00:00:00 2001 From: Anders Eknert Date: Mon, 21 Oct 2024 15:57:34 +0200 Subject: [PATCH] Fix location for multivalue rules with generated bodies Since there is no body, the location of the head is a better option than simply using the fist scanned token for location. Fixes #7128 Signed-off-by: Anders Eknert --- ast/parser.go | 2 ++ ast/parser_test.go | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/ast/parser.go b/ast/parser.go index 1dacbb3b06..09ede2baec 100644 --- a/ast/parser.go +++ b/ast/parser.go @@ -780,6 +780,8 @@ func (p *Parser) parseRules() []*Rule { case usesContains: rule.Body = NewBody(NewExpr(BooleanTerm(true).SetLocation(rule.Location)).SetLocation(rule.Location)) rule.generatedBody = true + rule.Location = rule.Head.Location + return []*Rule{&rule} default: diff --git a/ast/parser_test.go b/ast/parser_test.go index 53d9b4a300..d330bacdac 100644 --- a/ast/parser_test.go +++ b/ast/parser_test.go @@ -4112,6 +4112,29 @@ func TestWildcards(t *testing.T) { }) } +// https://github.com/open-policy-agent/opa/issues/7128 +func TestParseMultiValueRuleGeneratedBodyLocationText(t *testing.T) { + t.Parallel() + + mod := `package test + + import rego.v1 + + foo contains "bar" + ` + + parsed, err := ParseModule("test.rego", mod) + if err != nil { + t.Fatal(err) + } + + text := string(parsed.Rules[0].Location.Text) + + if text != `foo contains "bar"` { + t.Errorf("Expected rule location text to be %q but got %q", `foo contains "bar"`, text) + } +} + func TestRuleFromBodyJSONOptions(t *testing.T) { tests := []string{ `pi = 3.14159`,