Skip to content

Commit

Permalink
fmt: don't add virtual = true value unless provided (#6323)
Browse files Browse the repository at this point in the history
This is especially nice for functions doing pattern matching on
equality in its arguments.

Previously, we'd rewrite:

```rego
f(1)
```

into

```rego
f(1) = true
```

Now, we'll leave the shorter form alone, while still respecting
explicit assignment, using either `=` or `:=`.

Signed-off-by: Anders Eknert <anders@eknert.com>
  • Loading branch information
anderseknert authored Oct 17, 2023
1 parent 98031ac commit 0cad9f9
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
13 changes: 12 additions & 1 deletion format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,17 @@ func (w *writer) writeHead(head *ast.Head, isDefault, isExpandedConst bool, o fm
w.write("]")
}
}
if head.Value != nil && (head.Key != nil || ast.Compare(head.Value, ast.BooleanTerm(true)) != 0 || isExpandedConst || isDefault) {

if head.Value != nil &&
(head.Key != nil || ast.Compare(head.Value, ast.BooleanTerm(true)) != 0 || isExpandedConst || isDefault) {

if head.Location == head.Value.Location && head.Name != "else" {
// If the value location is the same as the location of the head,
// we know that the value is generated, i.e. f(1)
// Don't print the value (` = true`) as it is implied.
return comments
}

if head.Assign {
w.write(" := ")
} else {
Expand Down Expand Up @@ -820,6 +830,7 @@ func (w *writer) writeCall(parens bool, x ast.Call, loc *ast.Location, comments
}

func (w *writer) writeInOperator(parens bool, operands []*ast.Term, comments []*ast.Comment, loc *ast.Location, f *types.Function) []*ast.Comment {

if len(operands) != len(f.Args()) {
// The number of operands does not math the arity of the `in` operator
operator := ast.Member.Name
Expand Down
27 changes: 27 additions & 0 deletions format/testfiles/test_functions.rego
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package p

f1(x) = x

f2(x) := x

f3(1)

f4(1) {
true
}

f5(1) := x {
x := 5
}

f6(x) {
true
} else := false

f7(x) := 1 {
x.key1
} else := false {
x.key2
} else {
false
}
25 changes: 25 additions & 0 deletions format/testfiles/test_functions.rego.formatted
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package p

f1(x) = x

f2(x) := x

f3(1)

f4(1) = true

f5(1) := x {
x := 5
}

f6(x) {
true
} else := false

f7(x) := 1 {
x.key1
} else := false {
x.key2
} else {
false
}

0 comments on commit 0cad9f9

Please sign in to comment.