Skip to content

Commit 9293647

Browse files
authored
Merge pull request #234 from JuliaSymbolics/s/less-parens
Less parens in printing
2 parents ce87b71 + 2d3b138 commit 9293647

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

src/types.jl

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -423,13 +423,18 @@ setargs(t, args) = Term{symtype(t)}(operation(t), args)
423423
cdrargs(args) = setargs(t, cdr(args))
424424

425425
print_arg(io, x::Union{Complex, Rational}) = print(io, "(", x, ")")
426-
print_arg(io, x) = print(io, x)
427-
print_arg(io, f::typeof(^), x) = print_arg(IOContext(io, :paren=>true), x)
426+
function print_arg(io, x; paren=false)
427+
if paren && isbinop(x)
428+
print(io, "(", x, ")")
429+
else
430+
print(io, x)
431+
end
432+
end
428433
print_arg(io, s::String) = show(io, s)
429434
function print_arg(io, f, x)
430435
f !== (*) && return print_arg(io, x)
431-
if istree(x) && Base.isbinaryoperator(nameof(operation(x)))
432-
print_arg(IOContext(io, :paren=>true), x)
436+
if Base.isbinaryoperator(nameof(f)) && isbinop(x)
437+
print_arg(io, x, paren=true)
433438
else
434439
print_arg(io, x)
435440
end
@@ -448,11 +453,20 @@ function show_add(io, args)
448453
print_arg(io, -, t)
449454
else
450455
print(io, " - ")
451-
print_arg(IOContext(io, :paren=>true), +, -t)
456+
print_arg(io, -t, paren=true)
452457
end
453458
end
454459
end
455460

461+
isbinop(f) = istree(f) && Base.isbinaryoperator(nameof(operation(f)))
462+
function show_pow(io, args)
463+
base, ex = args
464+
465+
print_arg(io, base, paren=isbinop(base))
466+
print(io, "^")
467+
print_arg(io, ex, paren=isbinop(base))
468+
end
469+
456470
function show_mul(io, args)
457471
length(args) == 1 && return print_arg(io, *, args[1])
458472

@@ -481,8 +495,8 @@ function show_call(io, f, args)
481495
binary = Base.isbinaryoperator(fname)
482496
if binary
483497
for (i, t) in enumerate(args)
484-
i != 1 && print(io, fname == :^ ? fname : " $fname ")
485-
print_arg(io, (^), t)
498+
i != 1 && print(io, " $fname ")
499+
print_arg(io, t)
486500
end
487501
else
488502
if f isa Sym
@@ -507,15 +521,15 @@ function show_term(io::IO, t)
507521
f = operation(t)
508522
args = arguments(t)
509523

510-
get(io, :paren, false) && print(io, "(")
511524
if f === (+)
512525
show_add(io, args)
513526
elseif f === (*)
514527
show_mul(io, args)
528+
elseif f === (^)
529+
show_pow(io, args)
515530
else
516531
show_call(io, f, args)
517532
end
518-
get(io, :paren, false) && print(io, ")")
519533

520534
return nothing
521535
end

0 commit comments

Comments
 (0)