diff --git a/ast/print.go b/ast/print.go index b79048b2..0fd2fa58 100644 --- a/ast/print.go +++ b/ast/print.go @@ -50,8 +50,13 @@ func (n *UnaryNode) String() string { op = fmt.Sprintf("%s ", n.Operator) } wrap := false - switch n.Node.(type) { - case *BinaryNode, *ConditionalNode: + switch b := n.Node.(type) { + case *BinaryNode: + if operator.Binary[b.Operator].Precedence < + operator.Unary[n.Operator].Precedence { + wrap = true + } + case *ConditionalNode: wrap = true } if wrap { @@ -68,10 +73,21 @@ func (n *BinaryNode) String() string { var lhs, rhs string var lwrap, rwrap bool + if l, ok := n.Left.(*UnaryNode); ok { + if operator.Unary[l.Operator].Precedence < + operator.Binary[n.Operator].Precedence { + lwrap = true + } + } if lb, ok := n.Left.(*BinaryNode); ok { if operator.Less(lb.Operator, n.Operator) { lwrap = true } + if operator.Binary[lb.Operator].Precedence == + operator.Binary[n.Operator].Precedence && + operator.Binary[n.Operator].Associativity == operator.Right { + lwrap = true + } if lb.Operator == "??" { lwrap = true } @@ -83,6 +99,11 @@ func (n *BinaryNode) String() string { if operator.Less(rb.Operator, n.Operator) { rwrap = true } + if operator.Binary[rb.Operator].Precedence == + operator.Binary[n.Operator].Precedence && + operator.Binary[n.Operator].Associativity == operator.Left { + rwrap = true + } if operator.IsBoolean(rb.Operator) && n.Operator != rb.Operator { rwrap = true } diff --git a/ast/print_test.go b/ast/print_test.go index a4b20b0a..8f950e27 100644 --- a/ast/print_test.go +++ b/ast/print_test.go @@ -78,6 +78,11 @@ func TestPrint(t *testing.T) { {`{("a" + "b"): 42}`, `{("a" + "b"): 42}`}, {`(One == 1 ? true : false) && Two == 2`, `(One == 1 ? true : false) && Two == 2`}, {`not (a == 1 ? b > 1 : b < 2)`, `not (a == 1 ? b > 1 : b < 2)`}, + {`(-(1+1)) ** 2`, `(-(1 + 1)) ** 2`}, + {`2 ** (-(1+1))`, `2 ** -(1 + 1)`}, + {`(2 ** 2) ** 3`, `(2 ** 2) ** 3`}, + {`(3 + 5) / (5 % 3)`, `(3 + 5) / (5 % 3)`}, + {`(-(1+1)) == 2`, `-(1 + 1) == 2`}, } for _, tt := range tests {