Improve ast printing for boolean operators

This commit is contained in:
Anton Medvedev
2024-01-17 23:21:11 +01:00
parent 84f18d7e5d
commit 7d4dd1a708
3 changed files with 36 additions and 6 deletions
+30 -4
View File
@@ -58,17 +58,43 @@ func (n *UnaryNode) String() string {
}
func (n *BinaryNode) String() string {
if n.Operator == ".." {
return fmt.Sprintf("%s..%s", n.Left, n.Right)
}
var lhs, rhs string
var lwrap, rwrap bool
lb, ok := n.Left.(*BinaryNode)
if ok && (operator.Less(lb.Operator, n.Operator) || lb.Operator == "??") {
if ok {
if operator.Less(lb.Operator, n.Operator) {
lwrap = true
}
if lb.Operator == "??" {
lwrap = true
}
if operator.IsBoolean(lb.Operator) && n.Operator != lb.Operator {
lwrap = true
}
}
rb, ok := n.Right.(*BinaryNode)
if ok {
if operator.Less(rb.Operator, n.Operator) {
rwrap = true
}
if operator.IsBoolean(rb.Operator) && n.Operator != rb.Operator {
rwrap = true
}
}
if lwrap {
lhs = fmt.Sprintf("(%s)", n.Left.String())
} else {
lhs = n.Left.String()
}
rb, ok := n.Right.(*BinaryNode)
if ok && operator.Less(rb.Operator, n.Operator) {
if rwrap {
rhs = fmt.Sprintf("(%s)", n.Right.String())
} else {
rhs = n.Right.String()
@@ -132,7 +158,7 @@ func (n *ClosureNode) String() string {
}
func (n *PointerNode) String() string {
return "#"
return fmt.Sprintf("#%s", n.Name)
}
func (n *VariableDeclaratorNode) String() string {
+2 -2
View File
@@ -42,8 +42,8 @@ func TestPrint(t *testing.T) {
{`a not in b`, `not (a in b)`},
{`a and b`, `a and b`},
{`a or b`, `a or b`},
{`a or b and c`, `a or b and c`},
{`a or (b and c)`, `a or b and c`},
{`a or b and c`, `a or (b and c)`},
{`a or (b and c)`, `a or (b and c)`},
{`(a or b) and c`, `(a or b) and c`},
{`a ? b : c`, `a ? b : c`},
{`a ? b : c ? d : e`, `a ? b : (c ? d : e)`},
+4
View File
@@ -16,6 +16,10 @@ func Less(a, b string) bool {
return Binary[a].Precedence < Binary[b].Precedence
}
func IsBoolean(op string) bool {
return op == "and" || op == "or" || op == "&&" || op == "||"
}
var Unary = map[string]Operator{
"not": {50, Left},
"!": {50, Left},