Skip to content

Commit 2e84bf2

Browse files
committed
Make 'deparse' function correctly handle parentheses
1 parent bd42628 commit 2e84bf2

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/deparse.jl

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
1+
const infix_ops = [:+, :-, :*, :/, :^]
2+
const op_priority = {:+ => 1, :- => 1, :* => 2, :/ => 2, :^ => 3}
3+
4+
isinfix(ex::Expr) = ex.head == :call && ex.args[1] in infix_ops
5+
isinfix(other) = false
6+
17
function deparse(ex::Expr)
28
if ex.head != :call
39
return string(ex)
4-
else
5-
if ex.args[1] in [:+, :-, :*, :/, :^]
6-
if length(ex.args) == 2
7-
return string(ex.args[1], deparse(ex.args[2]))
8-
else
9-
return join(map(x -> deparse(x), ex.args[2:end]),
10-
string(" ", string(ex.args[1]), " "))
11-
end
10+
end
11+
op = ex.args[1]
12+
args = ex.args[2:end]
13+
if !(op in infix_ops)
14+
return string(op, "(", join(map(x -> deparse(x), args), ", "), ")")
15+
end
16+
if length(args) == 1
17+
return string(op, deparse(args[1]))
18+
end
19+
str = {}
20+
for subexpr in args
21+
if isinfix(subexpr) && op_priority[subexpr.args[1]] <= op_priority[op]
22+
push!(str, string("(", deparse(subexpr), ")"))
1223
else
13-
return string(ex.args[1],
14-
"(",
15-
join(map(x -> deparse(x), ex.args[2:end]), ", "),
16-
")")
24+
push!(str, deparse(subexpr))
1725
end
1826
end
27+
return join(str, string(" ", string(op), " "))
1928
end
20-
deparse(other::Any) = string(other)
2129

22-
# TODO: Examine string contents of inputs, insert parentheses if added:
23-
# + (CONTAINS * OR /)
24-
# - (CONTAINS * OR /)
30+
deparse(other) = string(other)

0 commit comments

Comments
 (0)