Skip to content

Commit 0c841b9

Browse files
committed
Fix printing of binary operators with different precedences
1 parent 80d082a commit 0c841b9

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

parser_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ var parseTests = []parseTest{
4949
"(1 - 2) * 3",
5050
binaryNode{"*", binaryNode{"-", numberNode{1}, numberNode{2}}, numberNode{3}},
5151
},
52+
{
53+
"a or b or c",
54+
binaryNode{"or", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
55+
},
56+
{
57+
"a or b and c",
58+
binaryNode{"or", nameNode{"a"}, binaryNode{"and", nameNode{"b"}, nameNode{"c"}}},
59+
},
60+
{
61+
"(a or b) and c",
62+
binaryNode{"and", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
63+
},
5264
{
5365
"2**4-1",
5466
binaryNode{"-", binaryNode{"**", numberNode{2}, numberNode{4}}, numberNode{1}},

print.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ func (n unaryNode) String() string {
3737
case "!", "not":
3838
return fmt.Sprintf("%v %v", n.operator, n.node)
3939
}
40-
return fmt.Sprintf("%v%v", n.operator, n.node)
40+
return fmt.Sprintf("(%v%v)", n.operator, n.node)
4141
}
4242

4343
func (n binaryNode) String() string {
44-
return fmt.Sprintf("%v %v %v", n.left, n.operator, n.right)
44+
return fmt.Sprintf("(%v %v %v)", n.left, n.operator, n.right)
4545
}
4646

4747
func (n propertyNode) String() string {
@@ -114,7 +114,7 @@ func (n mapNode) String() string {
114114
func (n pairNode) String() string {
115115
switch n.key.(type) {
116116
case binaryNode, unaryNode:
117-
return fmt.Sprintf("(%v): %v", n.key, n.value)
117+
return fmt.Sprintf("%v: %v", n.key, n.value)
118118
}
119119
return fmt.Sprintf("%q: %v", n.key, n.value)
120120
}

print_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,18 @@ var printTests = []printTest{
3131
builtinNode{"len", []Node{identifierNode{"array"}}},
3232
"len(array)",
3333
},
34+
{
35+
binaryNode{"or", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
36+
"((a or b) or c)",
37+
},
38+
{
39+
binaryNode{"or", nameNode{"a"}, binaryNode{"and", nameNode{"b"}, nameNode{"c"}}},
40+
"(a or (b and c))",
41+
},
42+
{
43+
binaryNode{"and", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
44+
"((a or b) and c)",
45+
},
3446
}
3547

3648
func TestPrint(t *testing.T) {

0 commit comments

Comments
 (0)