Skip to content

Commit

Permalink
Fix ast printing for ?? operator
Browse files Browse the repository at this point in the history
Fixes #442
  • Loading branch information
antonmedv committed Nov 16, 2023
1 parent dbbec97 commit 507d734
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
21 changes: 13 additions & 8 deletions ast/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,18 +58,23 @@ func (n *UnaryNode) String() string {
}

func (n *BinaryNode) String() string {
var left, right string
if b, ok := n.Left.(*BinaryNode); ok && operator.Less(b.Operator, n.Operator) {
left = fmt.Sprintf("(%s)", n.Left.String())
var lhs, rhs string

lb, ok := n.Left.(*BinaryNode)
if ok && (operator.Less(lb.Operator, n.Operator) || lb.Operator == "??") {
lhs = fmt.Sprintf("(%s)", n.Left.String())
} else {
left = n.Left.String()
lhs = n.Left.String()
}
if b, ok := n.Right.(*BinaryNode); ok && operator.Less(b.Operator, n.Operator) {
right = fmt.Sprintf("(%s)", n.Right.String())

rb, ok := n.Right.(*BinaryNode)
if ok && operator.Less(rb.Operator, n.Operator) {
rhs = fmt.Sprintf("(%s)", n.Right.String())
} else {
right = n.Right.String()
rhs = n.Right.String()
}
return fmt.Sprintf("%s %s %s", left, n.Operator, right)

return fmt.Sprintf("%s %s %s", lhs, n.Operator, rhs)
}

func (n *ChainNode) String() string {
Expand Down
6 changes: 4 additions & 2 deletions ast/print_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package ast_test
import (
"testing"

"github.com/antonmedv/expr/ast"
"github.com/antonmedv/expr/parser"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/antonmedv/expr/ast"
"github.com/antonmedv/expr/parser"
)

func TestPrint(t *testing.T) {
Expand Down Expand Up @@ -67,6 +68,7 @@ func TestPrint(t *testing.T) {
{`a[1:]`, `a[1:]`},
{`a[1:]`, `a[1:]`},
{`a[:]`, `a[:]`},
{`(nil ?? 1) > 0`, `(nil ?? 1) > 0`},
}

for _, tt := range tests {
Expand Down

0 comments on commit 507d734

Please sign in to comment.