-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
show.jl
1775 lines (1610 loc) · 60.6 KB
/
show.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: http://julialang.org/license
print(io::IO, s::Symbol) = (write(io,s); nothing)
"""
IOContext
`IOContext` provides a mechanism for passing output configuration settings among [`show`](@ref) methods.
In short, it is an immutable dictionary that is a subclass of `IO`. It supports standard
dictionary operations such as [`getindex`](@ref), and can also be used as an I/O stream.
"""
immutable IOContext{IO_t <: IO} <: AbstractPipe
io::IO_t
dict::ImmutableDict{Symbol, Any}
function IOContext(io::IO_t, dict::ImmutableDict{Symbol, Any})
assert(!(IO_t <: IOContext))
return new(io, dict)
end
end
"""
IOContext(io::IO; properties...)
The same as `IOContext(io::IO, KV::Pair)`, but accepting properties as keyword arguments.
"""
IOContext(io::IO; kws...) = IOContext(IOContext(io, ImmutableDict{Symbol,Any}()); kws...)
function IOContext(io::IOContext; kws...)
for (k, v) in kws
io = IOContext(io, k, v)
end
io
end
IOContext(io::IOContext, dict::ImmutableDict) = typeof(io)(io.io, dict)
IOContext(io::IO, dict::ImmutableDict) = IOContext{typeof(io)}(io, dict)
IOContext(io::IO, key, value) = IOContext(io, ImmutableDict{Symbol, Any}(key, value))
IOContext(io::IOContext, key, value) = IOContext(io, ImmutableDict{Symbol, Any}(io.dict, key, value))
IOContext(io::IO, context::IO) = IOContext(io)
"""
IOContext(io::IO, context::IOContext)
Create an `IOContext` that wraps an alternate `IO` but inherits the properties of `context`.
"""
IOContext(io::IO, context::IOContext) = IOContext(io, context.dict)
"""
IOContext(io::IO, KV::Pair)
Create an `IOContext` that wraps a given stream, adding the specified `key=>value` pair to
the properties of that stream (note that `io` can itself be an `IOContext`).
- use `(key => value) in dict` to see if this particular combination is in the properties set
- use `get(dict, key, default)` to retrieve the most recent value for a particular key
The following properties are in common use:
- `:compact`: Boolean specifying that small values should be printed more compactly, e.g.
that numbers should be printed with fewer digits. This is set when printing array
elements.
- `:limit`: Boolean specifying that containers should be truncated, e.g. showing `…` in
place of most elements.
- `:displaysize`: A `Tuple{Int,Int}` giving the size in rows and columns to use for text
output. This can be used to override the display size for called functions, but to
get the size of the screen use the `displaysize` function.
"""
IOContext(io::IO, KV::Pair) = IOContext(io, KV[1], KV[2])
show(io::IO, ctx::IOContext) = (print(io, "IOContext("); show(io, ctx.io); print(io, ")"))
pipe_reader(io::IOContext) = io.io
pipe_writer(io::IOContext) = io.io
lock(io::IOContext) = lock(io.io)
unlock(io::IOContext) = unlock(io.io)
in(key_value::Pair, io::IOContext) = in(key_value, io.dict, ===)
in(key_value::Pair, io::IO) = false
haskey(io::IOContext, key) = haskey(io.dict, key)
haskey(io::IO, key) = false
getindex(io::IOContext, key) = getindex(io.dict, key)
getindex(io::IO, key) = throw(KeyError(key))
_limit_output = nothing # TODO: delete with with_output_limit deprecation
function get(io::IOContext, key, default)
if key === :limit && _limit_output !== nothing
default = _limit_output::Bool
end
get(io.dict, key, default)
end
function get(io::IO, key, default)
if key === :limit && _limit_output !== nothing
return _limit_output::Bool
end
default
end
displaysize(io::IOContext) = haskey(io, :displaysize) ? io[:displaysize] : displaysize(io.io)
show_circular(io::IO, x::ANY) = false
function show_circular(io::IOContext, x::ANY)
d = 1
for (k, v) in io.dict
if k === :SHOWN_SET
if v === x
print(io, "#= circular reference @-$d =#")
return true
end
d += 1
end
end
return false
end
show(io::IO, x::ANY) = show_default(io, x)
function show_default(io::IO, x::ANY)
t = typeof(x)::DataType
show(io, t)
print(io, '(')
nf = nfields(t)
nb = sizeof(x)
if nf != 0 || nb==0
if !show_circular(io, x)
recur_io = IOContext(io, :SHOWN_SET => x)
for i=1:nf
f = fieldname(t, i)
if !isdefined(x, f)
print(io, undef_ref_str)
else
show(recur_io, getfield(x, f))
end
if i < nf
print(io, ',')
end
end
end
else
print(io, "0x")
p = data_pointer_from_objref(x)
for i=nb-1:-1:0
print(io, hex(unsafe_load(convert(Ptr{UInt8}, p+i)), 2))
end
end
print(io,')')
end
# Check if a particular symbol is exported from a standard library module
function is_exported_from_stdlib(name::Symbol, mod::Module)
!isdefined(mod, name) && return false
orig = getfield(mod, name)
while !(mod === Base || mod === Core)
parent = module_parent(mod)
if mod === Main || mod === parent || parent === Main
return false
end
mod = parent
end
return isexported(mod, name) && isdefined(mod, name) && !isdeprecated(mod, name) && getfield(mod, name) === orig
end
function show(io::IO, f::Function)
ft = typeof(f)
mt = ft.name.mt
if !isdefined(mt, :module) || is_exported_from_stdlib(mt.name, mt.module) || mt.module === Main
print(io, mt.name)
else
print(io, mt.module, ".", mt.name)
end
end
function show(io::IO, x::Core.IntrinsicFunction)
name = ccall(:jl_intrinsic_name, Cstring, (Core.IntrinsicFunction,), x)
print(io, unsafe_string(name))
end
show(io::IO, ::Core.BottomType) = print(io, "Union{}")
function show(io::IO, x::Union)
print(io, "Union")
sorted_types = sort!(uniontypes(x); by=string)
show_comma_array(io, sorted_types, '{', '}')
end
function print_without_params(x::ANY)
if isa(x,UnionAll)
b = unwrap_unionall(x)
return isa(b,DataType) && b.name.wrapper === x
end
return false
end
function show(io::IO, x::UnionAll)
if print_without_params(x)
return show(io, unwrap_unionall(x).name)
end
tvar_env = get(io, :tvar_env, false)
if tvar_env !== false && isa(tvar_env, AbstractVector)
tvar_env = Any[tvar_env..., x.var]
else
tvar_env = Any[x.var]
end
show(IOContext(io, tvar_env = tvar_env), x.body)
print(io, " where ")
show(io, x.var)
end
function show_type_parameter(io::IO, p::ANY, has_tvar_env::Bool)
if has_tvar_env
show(io, p)
else
show(IOContext(io, :tvar_env, true), p)
end
end
show(io::IO, x::DataType) = show_datatype(io, x)
function show_datatype(io::IO, x::DataType)
# tvar_env is a `::Vector{Any}` when we are printing a method signature
# and `true` if we are printing type parameters outside a method signature.
has_tvar_env = get(io, :tvar_env, false) !== false
if (!isempty(x.parameters) || x.name === Tuple.name) && x !== Tuple
n = length(x.parameters)
# Print homogeneous tuples with more than 3 elements compactly as NTuple{N, T}
if n > 3 && all(i -> (x.parameters[1] === i), x.parameters)
print(io, "NTuple{", n, ',', x.parameters[1], "}")
else
show(io, x.name)
# Do not print the type parameters for the primary type if we are
# printing a method signature or type parameter.
# Always print the type parameter if we are printing the type directly
# since this information is still useful.
print(io, '{')
for (i, p) in enumerate(x.parameters)
show_type_parameter(io, p, has_tvar_env)
i < n && print(io, ',')
end
print(io, '}')
end
else
show(io, x.name)
end
end
macro show(exs...)
blk = Expr(:block)
for ex in exs
push!(blk.args, :(println($(sprint(show_unquoted,ex)*" = "),
repr(begin value=$(esc(ex)) end))))
end
if !isempty(exs); push!(blk.args, :value); end
return blk
end
function show(io::IO, tn::TypeName)
if is_exported_from_stdlib(tn.name, tn.module) || tn.module === Main
print(io, tn.name)
else
print(io, tn.module, '.', tn.name)
end
end
show(io::IO, ::Void) = print(io, "nothing")
show(io::IO, b::Bool) = print(io, b ? "true" : "false")
show(io::IO, n::Signed) = (write(io, dec(n)); nothing)
show(io::IO, n::Unsigned) = print(io, "0x", hex(n,sizeof(n)<<1))
print(io::IO, n::Unsigned) = print(io, dec(n))
show{T}(io::IO, p::Ptr{T}) = print(io, typeof(p), " @0x$(hex(UInt(p), Sys.WORD_SIZE>>2))")
function show(io::IO, p::Pair)
if typeof(p.first) != typeof(p).parameters[1] ||
typeof(p.second) != typeof(p).parameters[2]
return show_default(io, p)
end
isa(p.first,Pair) && print(io, "(")
show(io, p.first)
isa(p.first,Pair) && print(io, ")")
print(io, "=>")
isa(p.second,Pair) && print(io, "(")
show(io, p.second)
isa(p.second,Pair) && print(io, ")")
nothing
end
function show(io::IO, m::Module)
if m === Main
print(io, "Main")
else
print(io, join(fullname(m),"."))
end
end
function sourceinfo_slotnames(src::CodeInfo)
slotnames = src.slotnames
isa(slotnames, Array) || return String[]
names = Dict{String,Int}()
printnames = Vector{String}(length(slotnames))
for i in eachindex(slotnames)
name = string(slotnames[i])
idx = get!(names, name, i)
if idx != i
printname = "$name@_$i"
idx > 0 && (printnames[idx] = "$name@_$idx")
names[name] = 0
else
printname = name
end
printnames[i] = printname
end
return printnames
end
function show(io::IO, l::Core.MethodInstance)
if isdefined(l, :def)
if l.def.isstaged && l === l.def.generator
print(io, "MethodInstance generator for ")
show(io, l.def)
else
print(io, "MethodInstance for ")
show_lambda_types(io, l)
end
else
print(io, "Toplevel MethodInstance thunk")
end
end
function show(io::IO, src::CodeInfo)
# Fix slot names and types in function body
print(io, "CodeInfo(")
if isa(src.code, Array{Any,1})
lambda_io = IOContext(io, :SOURCEINFO => src)
if src.slotnames !== nothing
lambda_io = IOContext(lambda_io, :SOURCE_SLOTNAMES => sourceinfo_slotnames(src))
end
body = Expr(:body)
body.args = src.code
show(lambda_io, body)
else
print(io, "<compressed>")
end
print(io, ")")
end
function show_delim_array(io::IO, itr::Union{AbstractArray,SimpleVector}, op, delim, cl,
delim_one, i1=first(linearindices(itr)), l=last(linearindices(itr)))
print(io, op)
if !show_circular(io, itr)
recur_io = IOContext(io, :SHOWN_SET => itr)
if !haskey(io, :compact)
recur_io = IOContext(recur_io, :compact => true)
end
newline = true
first = true
i = i1
if l >= i1
while true
if !isassigned(itr, i)
print(io, undef_ref_str)
multiline = false
else
x = itr[i]
multiline = isa(x,AbstractArray) && ndims(x)>1 && !isempty(x)
newline && multiline && println(io)
show(recur_io, x)
end
i += 1
if i > l
delim_one && first && print(io, delim)
break
end
first = false
print(io, delim)
if multiline
println(io); println(io)
newline = false
else
newline = true
end
end
end
end
print(io, cl)
end
function show_delim_array(io::IO, itr, op, delim, cl, delim_one, i1=1, n=typemax(Int))
print(io, op)
if !show_circular(io, itr)
recur_io = IOContext(io, :SHOWN_SET => itr)
state = start(itr)
newline = true
first = true
while i1 > 1 && !done(itr,state)
_, state = next(itr, state)
i1 -= 1
end
if !done(itr,state)
while true
x, state = next(itr,state)
multiline = isa(x,AbstractArray) && ndims(x)>1 && !isempty(x)
newline && multiline && println(io)
show(recur_io, x)
i1 += 1
if done(itr,state) || i1 > n
delim_one && first && print(io, delim)
break
end
first = false
print(io, delim)
if multiline
println(io); println(io)
newline = false
else
newline = true
end
end
end
end
print(io, cl)
end
show_comma_array(io::IO, itr, o, c) = show_delim_array(io, itr, o, ',', c, false)
show(io::IO, t::Tuple) = show_delim_array(io, t, '(', ',', ')', true)
show(io::IO, v::SimpleVector) = show_delim_array(io, v, "svec(", ',', ')', false)
show(io::IO, s::Symbol) = show_unquoted_quote_expr(io, s, 0, 0)
## Abstract Syntax Tree (AST) printing ##
# Summary:
# print(io, ex) defers to show_unquoted(io, ex)
# show(io, ex) defers to show_unquoted(io, QuoteNode(ex))
# show_unquoted(io, ex) does the heavy lifting
#
# AST printing should follow two rules:
# 1. parse(string(ex)) == ex
# 2. eval(parse(repr(ex))) == ex
#
# Rule 1 means that printing an expression should generate Julia code which
# could be reparsed to obtain the original expression. This code should be
# unambiguous and as readable as possible.
#
# Rule 2 means that showing an expression should generate a quoted version of
# print’s output. Parsing and then evaling this output should return the
# original expression.
#
# This is consistent with many other show methods, i.e.:
# show(Set([1,2,3])) # ==> "Set{Int64}([2,3,1])"
# eval(parse("Set{Int64}([2,3,1])”) # ==> An actual set
# While this isn’t true of ALL show methods, it is of all ASTs.
typealias ExprNode Union{Expr, QuoteNode, Slot, LineNumberNode,
LabelNode, GotoNode, GlobalRef}
# Operators have precedence levels from 1-N, and show_unquoted defaults to a
# precedence level of 0 (the fourth argument). The top-level print and show
# methods use a precedence of -1 to specially allow space-separated macro syntax
print( io::IO, ex::ExprNode) = (show_unquoted(io, ex, 0, -1); nothing)
show( io::IO, ex::ExprNode) = show_unquoted_quote_expr(io, ex, 0, -1)
show_unquoted(io::IO, ex) = show_unquoted(io, ex, 0, 0)
show_unquoted(io::IO, ex, indent::Int) = show_unquoted(io, ex, indent, 0)
show_unquoted(io::IO, ex, ::Int,::Int) = show(io, ex)
## AST printing constants ##
const indent_width = 4
const quoted_syms = Set{Symbol}([:(:),:(::),:(:=),:(=),:(==),:(!=),:(===),:(!==),:(=>),:(>=),:(<=)])
const uni_ops = Set{Symbol}([:(+), :(-), :(!), :(¬), :(~), :(<:), :(>:), :(√), :(∛), :(∜)])
const expr_infix_wide = Set{Symbol}([
:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(^=), :(&=), :(|=), :(÷=), :(%=), :(>>>=), :(>>=), :(<<=),
:(.=), :(.+=), :(.-=), :(.*=), :(./=), :(.\=), :(.^=), :(.&=), :(.|=), :(.÷=), :(.%=), :(.>>>=), :(.>>=), :(.<<=),
:(&&), :(||), :(<:), :(=>), :($=), :(⊻=)]) # `$=` should be removed after deprecation is removed, issue #18977
const expr_infix = Set{Symbol}([:(:), :(->), Symbol("::")])
const expr_infix_any = union(expr_infix, expr_infix_wide)
const all_ops = union(quoted_syms, uni_ops, expr_infix_any)
const expr_calls = Dict(:call => ('(',')'), :calldecl => ('(',')'),
:ref => ('[',']'), :curly => ('{','}'), :(.) => ('(',')'))
const expr_parens = Dict(:tuple=>('(',')'), :vcat=>('[',']'),
:hcat =>('[',']'), :row =>('[',']'), :vect=>('[',']'))
## AST decoding helpers ##
is_id_start_char(c::Char) = ccall(:jl_id_start_char, Cint, (UInt32,), c) != 0
is_id_char(c::Char) = ccall(:jl_id_char, Cint, (UInt32,), c) != 0
function isidentifier(s::AbstractString)
i = start(s)
done(s, i) && return false
(c, i) = next(s, i)
is_id_start_char(c) || return false
while !done(s, i)
(c, i) = next(s, i)
is_id_char(c) || return false
end
return true
end
isidentifier(s::Symbol) = isidentifier(string(s))
isoperator(s::Symbol) = ccall(:jl_is_operator, Cint, (Cstring,), s) != 0
operator_precedence(s::Symbol) = Int(ccall(:jl_operator_precedence, Cint, (Cstring,), s))
operator_precedence(x::Any) = 0 # fallback for generic expression nodes
const prec_power = operator_precedence(:(^))
const prec_decl = operator_precedence(:(::))
is_expr(ex, head::Symbol) = (isa(ex, Expr) && (ex.head == head))
is_expr(ex, head::Symbol, n::Int) = is_expr(ex, head) && length(ex.args) == n
is_linenumber(ex::LineNumberNode) = true
is_linenumber(ex::Expr) = (ex.head == :line)
is_linenumber(ex) = false
is_quoted(ex) = false
is_quoted(ex::QuoteNode) = true
is_quoted(ex::Expr) = is_expr(ex, :quote, 1) || is_expr(ex, :inert, 1)
unquoted(ex::QuoteNode) = ex.value
unquoted(ex::Expr) = ex.args[1]
## AST printing helpers ##
typeemphasize(io::IO) = get(io, :TYPEEMPHASIZE, false) === true
const indent_width = 4
function show_expr_type(io::IO, ty, emph)
if ty === Function
print(io, "::F")
elseif ty === Core.IntrinsicFunction
print(io, "::I")
else
if emph && (!isleaftype(ty) || ty == Core.Box)
emphasize(io, "::$ty")
else
print(io, "::$ty")
end
end
end
emphasize(io, str::AbstractString) = have_color ? print_with_color(Base.error_color(), io, str; bold = true) : print(io, uppercase(str))
show_linenumber(io::IO, line) = print(io," # line ",line,':')
show_linenumber(io::IO, line, file) = print(io," # ", file,", line ",line,':')
# show a block, e g if/for/etc
function show_block(io::IO, head, args::Vector, body, indent::Int)
print(io, head, ' ')
show_list(io, args, ", ", indent)
ind = head === :module || head === :baremodule ? indent : indent + indent_width
exs = (is_expr(body, :block) || is_expr(body, :body)) ? body.args : Any[body]
for ex in exs
if !is_linenumber(ex); print(io, '\n', " "^ind); end
show_unquoted(io, ex, ind, -1)
end
print(io, '\n', " "^indent)
end
show_block(io::IO,head, block,i::Int) = show_block(io,head, [], block,i)
function show_block(io::IO, head, arg, block, i::Int)
if is_expr(arg, :block)
show_block(io, head, arg.args, block, i)
else
show_block(io, head, Any[arg], block, i)
end
end
# show an indented list
function show_list(io::IO, items, sep, indent::Int, prec::Int=0, enclose_operators::Bool=false)
n = length(items)
if n == 0; return end
indent += indent_width
first = true
for item in items
!first && print(io, sep)
parens = enclose_operators && isa(item,Symbol) && isoperator(item)
parens && print(io, '(')
show_unquoted(io, item, indent, prec)
parens && print(io, ')')
first = false
end
end
# show an indented list inside the parens (op, cl)
function show_enclosed_list(io::IO, op, items, sep, cl, indent, prec=0, encl_ops=false)
print(io, op); show_list(io, items, sep, indent, prec, encl_ops); print(io, cl)
end
# show a normal (non-operator) function call, e.g. f(x,y) or A[z]
function show_call(io::IO, head, func, func_args, indent)
op, cl = expr_calls[head]
if isa(func, Symbol) || (isa(func, Expr) &&
(func.head == :. || func.head == :curly))
show_unquoted(io, func, indent)
else
print(io, '(')
show_unquoted(io, func, indent)
print(io, ')')
end
if head == :(.)
print(io, '.')
end
if !isempty(func_args) && isa(func_args[1], Expr) && func_args[1].head === :parameters
print(io, op)
show_list(io, func_args[2:end], ',', indent)
print(io, "; ")
show_list(io, func_args[1].args, ',', indent)
print(io, cl)
else
show_enclosed_list(io, op, func_args, ",", cl, indent)
end
end
## AST printing ##
show_unquoted(io::IO, sym::Symbol, ::Int, ::Int) = print(io, sym)
show_unquoted(io::IO, ex::LineNumberNode, ::Int, ::Int) = show_linenumber(io, ex.line)
show_unquoted(io::IO, ex::LabelNode, ::Int, ::Int) = print(io, ex.label, ": ")
show_unquoted(io::IO, ex::GotoNode, ::Int, ::Int) = print(io, "goto ", ex.label)
show_unquoted(io::IO, ex::GlobalRef, ::Int, ::Int) = print(io, ex.mod, '.', ex.name)
function show_unquoted(io::IO, ex::Slot, ::Int, ::Int)
typ = isa(ex,TypedSlot) ? ex.typ : Any
slotid = ex.id
src = get(io, :SOURCEINFO, false)
if isa(src, CodeInfo)
slottypes = (src::CodeInfo).slottypes
if isa(slottypes, Array) && slotid <= length(slottypes::Array)
slottype = slottypes[slotid]
# The Slot in assignment can somehow have an Any type
if slottype <: typ
typ = slottype
end
end
end
slotnames = get(io, :SOURCE_SLOTNAMES, false)
if (isa(slotnames, Vector{String}) &&
slotid <= length(slotnames::Vector{String}))
print(io, (slotnames::Vector{String})[slotid])
else
print(io, "_", slotid)
end
emphstate = typeemphasize(io)
if emphstate || (typ !== Any && isa(ex,TypedSlot))
show_expr_type(io, typ, emphstate)
end
end
function show_unquoted(io::IO, ex::QuoteNode, indent::Int, prec::Int)
if isa(ex.value, Symbol)
show_unquoted_quote_expr(io, ex.value, indent, prec)
else
print(io, "\$(QuoteNode(")
show(io, ex.value)
print(io, "))")
end
end
function show_unquoted_quote_expr(io::IO, value, indent::Int, prec::Int)
if isa(value, Symbol) && !(value in quoted_syms)
s = string(value)
if isidentifier(s) || isoperator(value)
print(io, ":")
print(io, value)
else
print(io, "Symbol(\"", escape_string(s), "\")")
end
else
if isa(value,Expr) && value.head === :block
show_block(io, "quote", value, indent)
print(io, "end")
else
print(io, ":(")
show_unquoted(io, value, indent+indent_width, -1)
print(io, ")")
end
end
end
function show_generator(io, ex, indent)
if ex.head === :flatten
fg = ex
ranges = Any[]
while isa(fg, Expr) && fg.head === :flatten
push!(ranges, fg.args[1].args[2])
fg = fg.args[1].args[1]
end
push!(ranges, fg.args[2])
show_unquoted(io, fg.args[1], indent)
for r in ranges
print(io, " for ")
show_unquoted(io, r, indent)
end
else
show_unquoted(io, ex.args[1], indent)
print(io, " for ")
show_unquoted(io, ex.args[2], indent)
for i = 3:length(ex.args)
print(io, ", ")
show_unquoted(io, ex.args[i], indent)
end
end
end
# TODO: implement interpolated strings
function show_unquoted(io::IO, ex::Expr, indent::Int, prec::Int)
head, args, nargs = ex.head, ex.args, length(ex.args)
emphstate = typeemphasize(io)
show_type = true
if (ex.head == :(=) || ex.head == :line ||
ex.head == :boundscheck ||
ex.head == :gotoifnot ||
ex.head == :return)
show_type = false
end
if !emphstate && ex.typ === Any
show_type = false
end
# dot (i.e. "x.y"), but not compact broadcast exps
if head === :(.) && !is_expr(args[2], :tuple)
show_unquoted(io, args[1], indent + indent_width)
print(io, '.')
if is_quoted(args[2])
show_unquoted(io, unquoted(args[2]), indent + indent_width)
else
print(io, '(')
show_unquoted(io, args[2], indent + indent_width)
print(io, ')')
end
# infix (i.e. "x<:y" or "x = y")
elseif (head in expr_infix_any && nargs==2) || (head === :(:) && nargs==3)
func_prec = operator_precedence(head)
head_ = head in expr_infix_wide ? " $head " : head
if func_prec <= prec
show_enclosed_list(io, '(', args, head_, ')', indent, func_prec, true)
else
show_list(io, args, head_, indent, func_prec, true)
end
# list (i.e. "(1,2,3)" or "[1,2,3]")
elseif haskey(expr_parens, head) # :tuple/:vcat
op, cl = expr_parens[head]
if head === :vcat
sep = ";"
elseif head === :hcat || head === :row
sep = " "
else
sep = ","
end
head !== :row && print(io, op)
show_list(io, args, sep, indent)
if (head === :tuple || head === :vcat) && nargs == 1
print(io, sep)
end
head !== :row && print(io, cl)
# function call
elseif head === :call && nargs >= 1
func = args[1]
fname = isa(func,GlobalRef) ? func.name : func
func_prec = operator_precedence(fname)
if func_prec > 0 || fname in uni_ops
func = fname
end
func_args = args[2:end]
if (in(ex.args[1], (GlobalRef(Base, :bitcast), :throw)) ||
ismodulecall(ex))
show_type = false
end
if show_type
prec = prec_decl
end
# scalar multiplication (i.e. "100x")
if (func === :* &&
length(func_args)==2 && isa(func_args[1], Real) && isa(func_args[2], Symbol))
if func_prec <= prec
show_enclosed_list(io, '(', func_args, "", ')', indent, func_prec)
else
show_list(io, func_args, "", indent, func_prec)
end
# unary operator (i.e. "!z")
elseif isa(func,Symbol) && func in uni_ops && length(func_args) == 1
show_unquoted(io, func, indent)
if isa(func_args[1], Expr) || func_args[1] in all_ops
show_enclosed_list(io, '(', func_args, ",", ')', indent, func_prec)
else
show_unquoted(io, func_args[1])
end
# binary operator (i.e. "x + y")
elseif func_prec > 0 # is a binary operator
na = length(func_args)
if (na == 2 || (na > 2 && func in (:+, :++, :*))) &&
all(!isa(a, Expr) || a.head !== :... for a in func_args)
sep = " $func "
if func_prec <= prec
show_enclosed_list(io, '(', func_args, sep, ')', indent, func_prec, true)
else
show_list(io, func_args, sep, indent, func_prec, true)
end
elseif na == 1
# 1-argument call to normally-binary operator
op, cl = expr_calls[head]
print(io, "(")
show_unquoted(io, func, indent)
print(io, ")")
show_enclosed_list(io, op, func_args, ",", cl, indent)
else
show_call(io, head, func, func_args, indent)
end
# normal function (i.e. "f(x,y)")
else
show_call(io, head, func, func_args, indent)
end
# other call-like expressions ("A[1,2]", "T{X,Y}", "f.(X,Y)")
elseif haskey(expr_calls, head) && nargs >= 1 # :ref/:curly/:calldecl/:(.)
funcargslike = head == :(.) ? ex.args[2].args : ex.args[2:end]
show_call(io, head, ex.args[1], funcargslike, indent)
# comprehensions
elseif (head === :typed_comprehension || head === :typed_dict_comprehension) && length(args) == 2
isdict = (head === :typed_dict_comprehension)
isdict && print(io, '(')
show_unquoted(io, args[1], indent)
isdict && print(io, ')')
print(io, '[')
show_generator(io, args[2], indent)
print(io, ']')
elseif (head === :comprehension || head === :dict_comprehension) && length(args) == 1
print(io, '[')
show_generator(io, args[1], indent)
print(io, ']')
elseif (head === :generator && length(args) >= 2) || (head === :flatten && length(args) == 1)
print(io, '(')
show_generator(io, ex, indent)
print(io, ')')
elseif head === :filter && length(args) == 2
show_unquoted(io, args[2], indent)
print(io, " if ")
show_unquoted(io, args[1], indent)
# comparison (i.e. "x < y < z")
elseif head === :comparison && nargs >= 3 && (nargs&1==1)
comp_prec = minimum(operator_precedence, args[2:2:end])
if comp_prec <= prec
show_enclosed_list(io, '(', args, " ", ')', indent, comp_prec)
else
show_list(io, args, " ", indent, comp_prec)
end
# function calls need to transform the function from :call to :calldecl
# so that operators are printed correctly
elseif head === :function && nargs==2 && is_expr(args[1], :call)
show_block(io, head, Expr(:calldecl, args[1].args...), args[2], indent)
print(io, "end")
elseif head === :function && nargs == 1
print(io, "function ", args[1], " end")
# block with argument
elseif head in (:for,:while,:function,:if) && nargs==2
show_block(io, head, args[1], args[2], indent)
print(io, "end")
elseif head === :module && nargs==3 && isa(args[1],Bool)
show_block(io, args[1] ? :module : :baremodule, args[2], args[3], indent)
print(io, "end")
# type declaration
elseif head === :type && nargs==3
show_block(io, args[1] ? :type : :immutable, args[2], args[3], indent)
print(io, "end")
elseif head === :bitstype && nargs == 2
print(io, "bitstype ")
show_list(io, args, ' ', indent)
# empty return (i.e. "function f() return end")
elseif head === :return && nargs == 1 && args[1] === nothing
print(io, head)
# type annotation (i.e. "::Int")
elseif head === Symbol("::") && nargs == 1
print(io, "::")
show_unquoted(io, args[1], indent)
# var-arg declaration or expansion
# (i.e. "function f(L...) end" or "f(B...)")
elseif head === :(...) && nargs == 1
show_unquoted(io, args[1], indent)
print(io, "...")
elseif (nargs == 0 && head in (:break, :continue))
print(io, head)
elseif (nargs == 1 && head in (:return, :abstract, :const)) ||
head in (:local, :global, :export)
print(io, head, ' ')
show_list(io, args, ", ", indent)
elseif head === :macrocall && nargs >= 1
# Use the functional syntax unless specifically designated with prec=-1
if prec >= 0
show_call(io, :call, ex.args[1], ex.args[2:end], indent)
else
show_list(io, args, ' ', indent)
end
elseif head === :typealias && nargs == 2
print(io, "typealias ")
show_list(io, args, ' ', indent)
elseif head === :line && 1 <= nargs <= 2
show_linenumber(io, args...)
elseif head === :if && nargs == 3 # if/else
show_block(io, "if", args[1], args[2], indent)
show_block(io, "else", args[3], indent)
print(io, "end")
elseif head === :try && 3 <= nargs <= 4
show_block(io, "try", args[1], indent)
if is_expr(args[3], :block)
show_block(io, "catch", args[2] === false ? Any[] : args[2], args[3], indent)
end
if nargs >= 4 && is_expr(args[4], :block)
show_block(io, "finally", Any[], args[4], indent)
end
print(io, "end")
elseif head === :let && nargs >= 1
show_block(io, "let", args[2:end], args[1], indent); print(io, "end")
elseif head === :block || head === :body
show_block(io, "begin", ex, indent); print(io, "end")
elseif head === :quote && nargs == 1 && isa(args[1],Symbol)
show_unquoted_quote_expr(io, args[1], indent, 0)
elseif head === :gotoifnot && nargs == 2
print(io, "unless ")
show_list(io, args, " goto ", indent)
elseif head === :string && nargs == 1 && isa(args[1], AbstractString)
show(io, args[1])
elseif head === :null
print(io, "nothing")
elseif head === :kw && length(args)==2
show_unquoted(io, args[1], indent+indent_width)
print(io, '=')
show_unquoted(io, args[2], indent+indent_width)
elseif head === :string
print(io, '"')
for x in args
if !isa(x,AbstractString)
print(io, "\$(")
if isa(x,Symbol) && !(x in quoted_syms)
print(io, x)
else
show_unquoted(io, x)
end
print(io, ")")
else
escape_string(io, x, "\"\$")
end
end
print(io, '"')
elseif (head === :&#= || head === :$=#) && length(args) == 1
print(io, head)
a1 = args[1]
parens = (isa(a1,Expr) && a1.head !== :tuple) || (isa(a1,Symbol) && isoperator(a1))
parens && print(io, "(")
show_unquoted(io, a1)
parens && print(io, ")")
# transpose
elseif (head === Symbol('\'') || head === Symbol(".'")) && length(args) == 1
if isa(args[1], Symbol)
show_unquoted(io, args[1])
else
print(io, "(")
show_unquoted(io, args[1])
print(io, ")")
end
print(io, head)
# `where` syntax
elseif head === :where && length(args) == 2
parens = 1 <= prec