Skip to content

Commit af32277

Browse files
zhuliquanantonmedv
andauthored
Fix print with precedence (#678)
* feat: extract code for compiling equal operator * fix: fix unary and binary node print consider the precedence of operators and their associative law when printing unary and binary nodes --------- Co-authored-by: Anton Medvedev <anton@medv.io>
1 parent 156e73d commit af32277

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

Diff for: ast/print.go

+23-2
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,13 @@ func (n *UnaryNode) String() string {
5050
op = fmt.Sprintf("%s ", n.Operator)
5151
}
5252
wrap := false
53-
switch n.Node.(type) {
54-
case *BinaryNode, *ConditionalNode:
53+
switch b := n.Node.(type) {
54+
case *BinaryNode:
55+
if operator.Binary[b.Operator].Precedence <
56+
operator.Unary[n.Operator].Precedence {
57+
wrap = true
58+
}
59+
case *ConditionalNode:
5560
wrap = true
5661
}
5762
if wrap {
@@ -68,10 +73,21 @@ func (n *BinaryNode) String() string {
6873
var lhs, rhs string
6974
var lwrap, rwrap bool
7075

76+
if l, ok := n.Left.(*UnaryNode); ok {
77+
if operator.Unary[l.Operator].Precedence <
78+
operator.Binary[n.Operator].Precedence {
79+
lwrap = true
80+
}
81+
}
7182
if lb, ok := n.Left.(*BinaryNode); ok {
7283
if operator.Less(lb.Operator, n.Operator) {
7384
lwrap = true
7485
}
86+
if operator.Binary[lb.Operator].Precedence ==
87+
operator.Binary[n.Operator].Precedence &&
88+
operator.Binary[n.Operator].Associativity == operator.Right {
89+
lwrap = true
90+
}
7591
if lb.Operator == "??" {
7692
lwrap = true
7793
}
@@ -83,6 +99,11 @@ func (n *BinaryNode) String() string {
8399
if operator.Less(rb.Operator, n.Operator) {
84100
rwrap = true
85101
}
102+
if operator.Binary[rb.Operator].Precedence ==
103+
operator.Binary[n.Operator].Precedence &&
104+
operator.Binary[n.Operator].Associativity == operator.Left {
105+
rwrap = true
106+
}
86107
if operator.IsBoolean(rb.Operator) && n.Operator != rb.Operator {
87108
rwrap = true
88109
}

Diff for: ast/print_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ func TestPrint(t *testing.T) {
7878
{`{("a" + "b"): 42}`, `{("a" + "b"): 42}`},
7979
{`(One == 1 ? true : false) && Two == 2`, `(One == 1 ? true : false) && Two == 2`},
8080
{`not (a == 1 ? b > 1 : b < 2)`, `not (a == 1 ? b > 1 : b < 2)`},
81+
{`(-(1+1)) ** 2`, `(-(1 + 1)) ** 2`},
82+
{`2 ** (-(1+1))`, `2 ** -(1 + 1)`},
83+
{`(2 ** 2) ** 3`, `(2 ** 2) ** 3`},
84+
{`(3 + 5) / (5 % 3)`, `(3 + 5) / (5 % 3)`},
85+
{`(-(1+1)) == 2`, `-(1 + 1) == 2`},
8186
}
8287

8388
for _, tt := range tests {

0 commit comments

Comments
 (0)