Skip to content

Commit 507d734

Browse files
committed
Fix ast printing for ?? operator
Fixes #442
1 parent dbbec97 commit 507d734

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

ast/print.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,23 @@ func (n *UnaryNode) String() string {
5858
}
5959

6060
func (n *BinaryNode) String() string {
61-
var left, right string
62-
if b, ok := n.Left.(*BinaryNode); ok && operator.Less(b.Operator, n.Operator) {
63-
left = fmt.Sprintf("(%s)", n.Left.String())
61+
var lhs, rhs string
62+
63+
lb, ok := n.Left.(*BinaryNode)
64+
if ok && (operator.Less(lb.Operator, n.Operator) || lb.Operator == "??") {
65+
lhs = fmt.Sprintf("(%s)", n.Left.String())
6466
} else {
65-
left = n.Left.String()
67+
lhs = n.Left.String()
6668
}
67-
if b, ok := n.Right.(*BinaryNode); ok && operator.Less(b.Operator, n.Operator) {
68-
right = fmt.Sprintf("(%s)", n.Right.String())
69+
70+
rb, ok := n.Right.(*BinaryNode)
71+
if ok && operator.Less(rb.Operator, n.Operator) {
72+
rhs = fmt.Sprintf("(%s)", n.Right.String())
6973
} else {
70-
right = n.Right.String()
74+
rhs = n.Right.String()
7175
}
72-
return fmt.Sprintf("%s %s %s", left, n.Operator, right)
76+
77+
return fmt.Sprintf("%s %s %s", lhs, n.Operator, rhs)
7378
}
7479

7580
func (n *ChainNode) String() string {

ast/print_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ package ast_test
33
import (
44
"testing"
55

6-
"github.com/antonmedv/expr/ast"
7-
"github.com/antonmedv/expr/parser"
86
"github.com/stretchr/testify/assert"
97
"github.com/stretchr/testify/require"
8+
9+
"github.com/antonmedv/expr/ast"
10+
"github.com/antonmedv/expr/parser"
1011
)
1112

1213
func TestPrint(t *testing.T) {
@@ -67,6 +68,7 @@ func TestPrint(t *testing.T) {
6768
{`a[1:]`, `a[1:]`},
6869
{`a[1:]`, `a[1:]`},
6970
{`a[:]`, `a[:]`},
71+
{`(nil ?? 1) > 0`, `(nil ?? 1) > 0`},
7072
}
7173

7274
for _, tt := range tests {

0 commit comments

Comments
 (0)