Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format: generated vars may have a proper location #4333

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,10 @@ func groupIterable(elements []interface{}, last *ast.Location) [][]interface{} {
// Those variables, and wildcard variables have the "default location",
// set in `Ast()`). That is no proper file location, and the grouping
// based on source location will yield a bad result.
// Another case is generated variables: they do have proper file locations,
// but their row/col information may no longer match their AST location.
// So, for generated variables, we also don't trust the location, but
// keep them ungrouped.
def := false // default location found?
for _, elem := range elements {
ast.WalkTerms(elem, func(t *ast.Term) bool {
Expand All @@ -913,6 +917,13 @@ func groupIterable(elements []interface{}, last *ast.Location) [][]interface{} {
}
return false
})
ast.WalkVars(elem, func(v ast.Var) bool {
if v.IsGenerated() {
def = true
return true
}
return false
})
if def { // return as-is
return [][]interface{}{elements}
}
Expand Down
17 changes: 17 additions & 0 deletions format/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,23 @@ a[_x[y][[z, w]]]`,
}(),
expected: `["foo", __local1__] = split(input.foo, ":")`,
},
{
note: "expr where generated var has an AST location not matching its source location",
toFmt: func() *ast.Expr {
e := ast.MustParseExpr(`__local0__ = concat(",", [__local1__])`)
ast.WalkTerms(e, func(t *ast.Term) bool {
t.Location.File = "t.rego"
return false
})
// mangling that may happen in PE
return ast.Concat.Expr(
e.Operand(1).Value.(ast.Call)[1],
e.Operand(1).Value.(ast.Call)[2],
e.Operand(0),
).SetLocation(e.Location)
}(),
expected: `concat(",", [__local1__], __local0__)`,
},
}

for _, tc := range cases {
Expand Down