Skip to content

Commit

Permalink
Fix printing of binary operators with different precedences
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 2, 2018
1 parent 80d082a commit 0c841b9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
12 changes: 12 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ var parseTests = []parseTest{
"(1 - 2) * 3",
binaryNode{"*", binaryNode{"-", numberNode{1}, numberNode{2}}, numberNode{3}},
},
{
"a or b or c",
binaryNode{"or", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
},
{
"a or b and c",
binaryNode{"or", nameNode{"a"}, binaryNode{"and", nameNode{"b"}, nameNode{"c"}}},
},
{
"(a or b) and c",
binaryNode{"and", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
},
{
"2**4-1",
binaryNode{"-", binaryNode{"**", numberNode{2}, numberNode{4}}, numberNode{1}},
Expand Down
6 changes: 3 additions & 3 deletions print.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ func (n unaryNode) String() string {
case "!", "not":
return fmt.Sprintf("%v %v", n.operator, n.node)
}
return fmt.Sprintf("%v%v", n.operator, n.node)
return fmt.Sprintf("(%v%v)", n.operator, n.node)
}

func (n binaryNode) String() string {
return fmt.Sprintf("%v %v %v", n.left, n.operator, n.right)
return fmt.Sprintf("(%v %v %v)", n.left, n.operator, n.right)
}

func (n propertyNode) String() string {
Expand Down Expand Up @@ -114,7 +114,7 @@ func (n mapNode) String() string {
func (n pairNode) String() string {
switch n.key.(type) {
case binaryNode, unaryNode:
return fmt.Sprintf("(%v): %v", n.key, n.value)
return fmt.Sprintf("%v: %v", n.key, n.value)
}
return fmt.Sprintf("%q: %v", n.key, n.value)
}
12 changes: 12 additions & 0 deletions print_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ var printTests = []printTest{
builtinNode{"len", []Node{identifierNode{"array"}}},
"len(array)",
},
{
binaryNode{"or", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
"((a or b) or c)",
},
{
binaryNode{"or", nameNode{"a"}, binaryNode{"and", nameNode{"b"}, nameNode{"c"}}},
"(a or (b and c))",
},
{
binaryNode{"and", binaryNode{"or", nameNode{"a"}, nameNode{"b"}}, nameNode{"c"}},
"((a or b) and c)",
},
}

func TestPrint(t *testing.T) {
Expand Down

0 comments on commit 0c841b9

Please sign in to comment.