Skip to content

Commit bfa39c0

Browse files
committed
less parens
1 parent ce87b71 commit bfa39c0

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/types.jl

Lines changed: 24 additions & 11 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

@@ -477,12 +491,11 @@ function show_mul(io, args)
477491
end
478492

479493
function show_call(io, f, args)
480-
fname = nameof(f)
481-
binary = Base.isbinaryoperator(fname)
494+
binary = Base.isbinaryoperator(nameof(f))
482495
if binary
483496
for (i, t) in enumerate(args)
484-
i != 1 && print(io, fname == :^ ? fname : " $fname ")
485-
print_arg(io, (^), t)
497+
i != 1 && print(io, " $fname ")
498+
print_arg(io, t)
486499
end
487500
else
488501
if f isa Sym
@@ -507,15 +520,15 @@ function show_term(io::IO, t)
507520
f = operation(t)
508521
args = arguments(t)
509522

510-
get(io, :paren, false) && print(io, "(")
511523
if f === (+)
512524
show_add(io, args)
513525
elseif f === (*)
514526
show_mul(io, args)
527+
elseif f === (^)
528+
show_pow(io, args)
515529
else
516530
show_call(io, f, args)
517531
end
518-
get(io, :paren, false) && print(io, ")")
519532

520533
return nothing
521534
end

0 commit comments

Comments
 (0)