Skip to content

Commit 71bc9f9

Browse files
committed
Improve ast printing for boolean operators
1 parent 7cd9fa6 commit 71bc9f9

File tree

3 files changed

+36
-6
lines changed

3 files changed

+36
-6
lines changed

ast/print.go

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,43 @@ func (n *UnaryNode) String() string {
5858
}
5959

6060
func (n *BinaryNode) String() string {
61+
if n.Operator == ".." {
62+
return fmt.Sprintf("%s..%s", n.Left, n.Right)
63+
}
64+
6165
var lhs, rhs string
66+
var lwrap, rwrap bool
6267

6368
lb, ok := n.Left.(*BinaryNode)
64-
if ok && (operator.Less(lb.Operator, n.Operator) || lb.Operator == "??") {
69+
if ok {
70+
if operator.Less(lb.Operator, n.Operator) {
71+
lwrap = true
72+
}
73+
if lb.Operator == "??" {
74+
lwrap = true
75+
}
76+
if operator.IsBoolean(lb.Operator) && n.Operator != lb.Operator {
77+
lwrap = true
78+
}
79+
}
80+
81+
rb, ok := n.Right.(*BinaryNode)
82+
if ok {
83+
if operator.Less(rb.Operator, n.Operator) {
84+
rwrap = true
85+
}
86+
if operator.IsBoolean(rb.Operator) && n.Operator != rb.Operator {
87+
rwrap = true
88+
}
89+
}
90+
91+
if lwrap {
6592
lhs = fmt.Sprintf("(%s)", n.Left.String())
6693
} else {
6794
lhs = n.Left.String()
6895
}
6996

70-
rb, ok := n.Right.(*BinaryNode)
71-
if ok && operator.Less(rb.Operator, n.Operator) {
97+
if rwrap {
7298
rhs = fmt.Sprintf("(%s)", n.Right.String())
7399
} else {
74100
rhs = n.Right.String()
@@ -132,7 +158,7 @@ func (n *ClosureNode) String() string {
132158
}
133159

134160
func (n *PointerNode) String() string {
135-
return "#"
161+
return fmt.Sprintf("#%s", n.Name)
136162
}
137163

138164
func (n *VariableDeclaratorNode) String() string {

ast/print_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ func TestPrint(t *testing.T) {
4242
{`a not in b`, `not (a in b)`},
4343
{`a and b`, `a and b`},
4444
{`a or b`, `a or b`},
45-
{`a or b and c`, `a or b and c`},
46-
{`a or (b and c)`, `a or b and c`},
45+
{`a or b and c`, `a or (b and c)`},
46+
{`a or (b and c)`, `a or (b and c)`},
4747
{`(a or b) and c`, `(a or b) and c`},
4848
{`a ? b : c`, `a ? b : c`},
4949
{`a ? b : c ? d : e`, `a ? b : (c ? d : e)`},

parser/operator/operator.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ func Less(a, b string) bool {
1616
return Binary[a].Precedence < Binary[b].Precedence
1717
}
1818

19+
func IsBoolean(op string) bool {
20+
return op == "and" || op == "or" || op == "&&" || op == "||"
21+
}
22+
1923
var Unary = map[string]Operator{
2024
"not": {50, Left},
2125
"!": {50, Left},

0 commit comments

Comments
 (0)