-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
show.jl
2305 lines (2048 loc) · 79.5 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: https://julialang.org/license
function show(io::IO, ::MIME"text/plain", u::UndefInitializer)
show(io, u)
get(io, :compact, false) && return
print(io, ": array initializer with undefined values")
end
# first a few multiline show functions for types defined before the MIME type:
show(io::IO, ::MIME"text/plain", r::AbstractRange) = show(io, r) # always use the compact form for printing ranges
function show(io::IO, ::MIME"text/plain", r::LinRange)
isempty(r) && return show(io, r)
# show for LinRange, e.g.
# range(1, stop=3, length=7)
# 7-element LinRange{Float64}:
# 1.0,1.33333,1.66667,2.0,2.33333,2.66667,3.0
summary(io, r)
println(io, ":")
print_range(io, r)
end
function show(io::IO, ::MIME"text/plain", f::Function)
get(io, :compact, false) && return show(io, f)
ft = typeof(f)
mt = ft.name.mt
if isa(f, Core.IntrinsicFunction)
print(io, f)
id = Core.Intrinsics.bitcast(Int32, f)
print(io, " (intrinsic function #$id)")
elseif isa(f, Core.Builtin)
print(io, mt.name, " (built-in function)")
else
name = mt.name
isself = isdefined(ft.name.module, name) &&
ft == typeof(getfield(ft.name.module, name))
n = length(methods(f))
m = n==1 ? "method" : "methods"
sname = string(name)
ns = (isself || '#' in sname) ? sname : string("(::", ft, ")")
what = startswith(ns, '@') ? "macro" : "generic function"
print(io, ns, " (", what, " with $n $m)")
end
end
function show(io::IO, ::MIME"text/plain", iter::Union{KeySet,ValueIterator})
isempty(iter) && get(io, :compact, false) && return show(io, iter)
summary(io, iter)
isempty(iter) && return
print(io, ". ", isa(iter,KeySet) ? "Keys" : "Values", ":")
limit::Bool = get(io, :limit, false)
if limit
sz = displaysize(io)
rows, cols = sz[1] - 3, sz[2]
rows < 2 && (print(io, " …"); return)
cols < 4 && (cols = 4)
cols -= 2 # For prefix " "
rows -= 1 # For summary
else
rows = cols = typemax(Int)
end
for (i, v) in enumerate(iter)
print(io, "\n ")
i == rows < length(iter) && (print(io, "⋮"); break)
if limit
str = sprint(show, v, context=io, sizehint=0)
str = _truncate_at_width_or_chars(str, cols, "\r\n")
print(io, str)
else
show(io, v)
end
end
end
function show(io::IO, ::MIME"text/plain", t::AbstractDict{K,V}) where {K,V}
isempty(t) && return show(io, t)
# show more descriptively, with one line per key/value pair
recur_io = IOContext(io, :SHOWN_SET => t)
limit::Bool = get(io, :limit, false)
if !haskey(io, :compact)
recur_io = IOContext(recur_io, :compact => true)
end
summary(io, t)
isempty(t) && return
print(io, ":")
show_circular(io, t) && return
if limit
sz = displaysize(io)
rows, cols = sz[1] - 3, sz[2]
rows < 2 && (print(io, " …"); return)
cols < 12 && (cols = 12) # Minimum widths of 2 for key, 4 for value
cols -= 6 # Subtract the widths of prefix " " separator " => "
rows -= 1 # Subtract the summary
# determine max key width to align the output, caching the strings
ks = Vector{String}(undef, min(rows, length(t)))
vs = Vector{String}(undef, min(rows, length(t)))
keylen = 0
vallen = 0
for (i, (k, v)) in enumerate(t)
i > rows && break
ks[i] = sprint(show, k, context=recur_io, sizehint=0)
vs[i] = sprint(show, v, context=recur_io, sizehint=0)
keylen = clamp(length(ks[i]), keylen, cols)
vallen = clamp(length(vs[i]), vallen, cols)
end
if keylen > max(div(cols, 2), cols - vallen)
keylen = max(cld(cols, 3), cols - vallen)
end
else
rows = cols = typemax(Int)
end
for (i, (k, v)) in enumerate(t)
print(io, "\n ")
if i == rows < length(t)
print(io, rpad("⋮", keylen), " => ⋮")
break
end
if limit
key = rpad(_truncate_at_width_or_chars(ks[i], keylen, "\r\n"), keylen)
else
key = sprint(show, k, context=recur_io, sizehint=0)
end
print(recur_io, key)
print(io, " => ")
if limit
val = _truncate_at_width_or_chars(vs[i], cols - keylen, "\r\n")
print(io, val)
else
show(recur_io, v)
end
end
end
function summary(io::IO, t::AbstractSet)
n = length(t)
showarg(io, t, true)
print(io, " with ", n, (n==1 ? " element" : " elements"))
end
function show(io::IO, ::MIME"text/plain", t::AbstractSet{T}) where T
isempty(t) && return show(io, t)
# show more descriptively, with one line per value
recur_io = IOContext(io, :SHOWN_SET => t)
limit::Bool = get(io, :limit, false)
summary(io, t)
isempty(t) && return
print(io, ":")
show_circular(io, t) && return
if limit
sz = displaysize(io)
rows, cols = sz[1] - 3, sz[2]
rows < 2 && (print(io, " …"); return)
cols -= 2 # Subtract the width of prefix " "
cols < 4 && (cols = 4) # Minimum widths of 4 for value
rows -= 1 # Subtract the summary
else
rows = cols = typemax(Int)
end
for (i, v) in enumerate(t)
print(io, "\n ")
if i == rows < length(t)
print(io, rpad("⋮", 2))
break
end
if limit
str = sprint(show, v, context=recur_io, sizehint=0)
print(io, _truncate_at_width_or_chars(str, cols, "\r\n"))
else
show(recur_io, v)
end
end
end
function show(io::IO, ::MIME"text/plain", opt::JLOptions)
println(io, "JLOptions(")
fields = fieldnames(JLOptions)
nfields = length(fields)
for (i, f) in enumerate(fields)
v = getfield(opt, i)
if isa(v, Ptr{UInt8})
v = (v != C_NULL) ? unsafe_string(v) : ""
elseif isa(v, Ptr{Ptr{UInt8}})
v = unsafe_load_commands(v)
end
println(io, " ", f, " = ", repr(v), i < nfields ? "," : "")
end
print(io, ")")
end
function show(io::IO, ::MIME"text/plain", t::Task)
show(io, t)
if t.state === :failed
println(io)
showerror(io, CapturedException(t.result, t.backtrace))
end
end
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.
"""
struct IOContext{IO_t <: IO} <: AbstractPipe
io::IO_t
dict::ImmutableDict{Symbol, Any}
function IOContext{IO_t}(io::IO_t, dict::ImmutableDict{Symbol, Any}) where IO_t<:IO
@assert !(IO_t <: IOContext) "Cannot create `IOContext` from another `IOContext`."
return new(io, dict)
end
end
# (Note that TTY and TTYTerminal io types have a :color property.)
unwrapcontext(io::IO) = io, get(io,:color,false) ? ImmutableDict{Symbol,Any}(:color, true) : ImmutableDict{Symbol,Any}()
unwrapcontext(io::IOContext) = io.io, io.dict
function IOContext(io::IO, dict::ImmutableDict)
io0 = unwrapcontext(io)[1]
IOContext{typeof(io0)}(io0, dict)
end
convert(::Type{IOContext}, io::IO) = IOContext(unwrapcontext(io)...)
IOContext(io::IO) = convert(IOContext, io)
function IOContext(io::IO, KV::Pair)
io0, d = unwrapcontext(io)
IOContext(io0, ImmutableDict{Symbol,Any}(d, KV[1], KV[2]))
end
"""
IOContext(io::IO, context::IOContext)
Create an `IOContext` that wraps an alternate `IO` but inherits the properties of `context`.
"""
IOContext(io::IO, context::IO) = IOContext(unwrapcontext(io)[1], unwrapcontext(context)[2])
"""
IOContext(io::IO, KV::Pair...)
Create an `IOContext` that wraps a given stream, adding the specified `key=>value` pairs to
the properties of that stream (note that `io` can itself be an `IOContext`).
- use `(key => value) in io` to see if this particular combination is in the properties set
- use `get(io, key, default)` to retrieve the most recent value for a particular key
The following properties are in common use:
- `:compact`: Boolean specifying that values should be printed more compactly, e.g.
that numbers should be printed with fewer digits. This is set when printing array
elements. `:compact` output should not contain line breaks.
- `: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.
- `:typeinfo`: a `Type` characterizing the information already printed
concerning the type of the object about to be displayed. This is mainly useful when
displaying a collection of objects of the same type, so that redundant type information
can be avoided (e.g. `[Float16(0)]` can be shown as "Float16[0.0]" instead
of "Float16[Float16(0.0)]" : while displaying the elements of the array, the `:typeinfo`
property will be set to `Float16`).
- `:color`: Boolean specifying whether ANSI color/escape codes are supported/expected.
By default, this is determined by whether `io` is a compatible terminal and by any
`--color` command-line flag when `julia` was launched.
# Examples
```jldoctest
julia> io = IOBuffer();
julia> printstyled(IOContext(io, :color => true), "string", color=:red)
julia> String(take!(io))
"\\e[31mstring\\e[39m"
julia> printstyled(io, "string", color=:red)
julia> String(take!(io))
"string"
```
```jldoctest
julia> print(IOContext(stdout, :compact => false), 1.12341234)
1.12341234
julia> print(IOContext(stdout, :compact => true), 1.12341234)
1.12341
```
```jldoctest
julia> function f(io::IO)
if get(io, :short, false)
print(io, "short")
else
print(io, "loooooong")
end
end
f (generic function with 1 method)
julia> f(stdout)
loooooong
julia> f(IOContext(stdout, :short => true))
short
```
"""
IOContext(io::IO, KV::Pair, KVs::Pair...) = IOContext(IOContext(io, KV), KVs...)
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))
get(io::IOContext, key, default) = get(io.dict, key, default)
get(io::IO, key, default) = default
displaysize(io::IOContext) = haskey(io, :displaysize) ? io[:displaysize] : displaysize(io.io)
show_circular(io::IO, @nospecialize(x)) = false
function show_circular(io::IOContext, @nospecialize(x))
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 = stdout], x)
Write a text representation of a value `x` to the output stream `io`. New types `T`
should overload `show(io::IO, x::T)`. The representation used by `show` generally
includes Julia-specific formatting and type information, and should be parseable
Julia code when possible.
[`repr`](@ref) returns the output of `show` as a string.
To customize human-readable text output for objects of type `T`, define
`show(io::IO, ::MIME"text/plain", ::T)` instead. Checking the `:compact`
[`IOContext`](@ref) property of `io` in such methods is recommended,
since some containers show their elements by calling this method with
`:compact => true`.
See also [`print`](@ref), which writes un-decorated representations.
# Examples
```jldoctest
julia> show("Hello World!")
"Hello World!"
julia> print("Hello World!")
Hello World!
```
"""
show(io::IO, @nospecialize(x)) = show_default(io, x)
show(x) = show(stdout::IO, x)
# avoid inferring show_default on the type of `x`
show_default(io::IO, @nospecialize(x)) = _show_default(io, inferencebarrier(x))
function _show_default(io::IO, @nospecialize(x))
t = typeof(x)
show(io, inferencebarrier(t))
print(io, '(')
nf = nfields(x)
nb = sizeof(x)
if nf != 0 || nb == 0
if !show_circular(io, x)
recur_io = IOContext(io, Pair{Symbol,Any}(:SHOWN_SET, x),
Pair{Symbol,Any}(:typeinfo, Any))
for i in 1:nf
f = fieldname(t, i)
if !isdefined(x, f)
print(io, undef_ref_str)
else
show(recur_io, getfield(x, i))
end
if i < nf
print(io, ", ")
end
end
end
else
print(io, "0x")
r = Ref(x)
GC.@preserve r begin
p = unsafe_convert(Ptr{Cvoid}, r)
for i in (nb - 1):-1:0
print(io, string(unsafe_load(convert(Ptr{UInt8}, p + i)), base = 16, pad = 2))
end
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 = parentmodule(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_function(io::IO, f::Function, compact::Bool)
ft = typeof(f)
mt = ft.name.mt
if mt === Symbol.name.mt
# uses shared method table
show_default(io, f)
elseif compact
print(io, mt.name)
elseif isdefined(mt, :module) && isdefined(mt.module, mt.name) &&
getfield(mt.module, mt.name) === f
if is_exported_from_stdlib(mt.name, mt.module) || mt.module === Main
print(io, mt.name)
else
print(io, mt.module, ".", mt.name)
end
else
show_default(io, f)
end
end
show(io::IO, f::Function) = show_function(io, f, get(io, :compact, false))
print(io::IO, f::Function) = show_function(io, f, true)
function show(io::IO, f::Core.IntrinsicFunction)
if !get(io, :compact, false)
print(io, "Core.Intrinsics.")
end
print(io, nameof(f))
end
print(io::IO, f::Core.IntrinsicFunction) = print(io, nameof(f))
show(io::IO, ::Core.TypeofBottom) = print(io, "Union{}")
show(io::IO, ::MIME"text/plain", ::Core.TypeofBottom) = print(io, "Union{}")
function print_without_params(@nospecialize(x))
if isa(x,UnionAll)
b = unwrap_unionall(x)
return isa(b,DataType) && b.name.wrapper === x
end
return false
end
has_typevar(@nospecialize(t), v::TypeVar) = ccall(:jl_has_typevar, Cint, (Any, Any), t, v)!=0
function io_has_tvar_name(io::IOContext, name::Symbol, @nospecialize(x))
for (key, val) in io.dict
if key === :unionall_env && val isa TypeVar && val.name === name && has_typevar(x, val)
return true
end
end
return false
end
io_has_tvar_name(io::IO, name::Symbol, @nospecialize(x)) = false
function show(io::IO, @nospecialize(x::Type))
if x isa DataType
show_datatype(io, x)
return
elseif x isa Union
if x.a isa DataType && Core.Compiler.typename(x.a) === Core.Compiler.typename(DenseArray)
T, N = x.a.parameters
if x == StridedArray{T,N}
print(io, "StridedArray")
show_delim_array(io, (T,N), '{', ',', '}', false)
return
elseif x == StridedVecOrMat{T}
print(io, "StridedVecOrMat")
show_delim_array(io, (T,), '{', ',', '}', false)
return
elseif StridedArray{T,N} <: x
print(io, "Union")
show_delim_array(io, vcat(StridedArray{T,N}, uniontypes(Core.Compiler.typesubtract(x, StridedArray{T,N}))), '{', ',', '}', false)
return
end
end
print(io, "Union")
show_delim_array(io, uniontypes(x), '{', ',', '}', false)
return
end
x::UnionAll
if print_without_params(x)
return show(io, unwrap_unionall(x).name)
end
if x.var.name === :_ || io_has_tvar_name(io, x.var.name, x)
counter = 1
while true
newname = Symbol(x.var.name, counter)
if !io_has_tvar_name(io, newname, x)
newtv = TypeVar(newname, x.var.lb, x.var.ub)
x = UnionAll(newtv, x{newtv})
break
end
counter += 1
end
end
show(IOContext(io, :unionall_env => x.var), x.body)
print(io, " where ")
show(io, x.var)
end
# Check whether 'sym' (defined in module 'parent') is visible from module 'from'
# If an object with this name exists in 'from', we need to check that it's the same binding
# and that it's not deprecated.
function isvisible(sym::Symbol, parent::Module, from::Module)
owner = ccall(:jl_binding_owner, Any, (Any, Any), parent, sym)
from_owner = ccall(:jl_binding_owner, Any, (Any, Any), from, sym)
return owner !== nothing && from_owner === owner &&
!isdeprecated(parent, sym) &&
isdefined(from, sym) # if we're going to return true, force binding resolution
end
function show_type_name(io::IO, tn::Core.TypeName)
if tn === UnionAll.name
# by coincidence, `typeof(Type)` is a valid representation of the UnionAll type.
# intercept this case and print `UnionAll` instead.
return print(io, "UnionAll")
end
globname = isdefined(tn, :mt) ? tn.mt.name : nothing
globfunc = false
if globname !== nothing
globname_str = string(globname::Symbol)
if ('#' ∉ globname_str && '@' ∉ globname_str && isdefined(tn, :module) &&
isbindingresolved(tn.module, globname) && isdefined(tn.module, globname) &&
isconcretetype(tn.wrapper) && isa(getfield(tn.module, globname), tn.wrapper))
globfunc = true
end
end
sym = (globfunc ? globname : tn.name)::Symbol
globfunc && print(io, "typeof(")
quo = false
if !get(io, :compact, false)
# Print module prefix unless type is visible from module passed to
# IOContext If :module is not set, default to Main. nothing can be used
# to force printing prefix
from = get(io, :module, Main)
if isdefined(tn, :module) && (from === nothing || !isvisible(sym, tn.module, from))
show(io, tn.module)
print(io, ".")
if globfunc && !is_id_start_char(first(string(sym)))
print(io, ':')
if sym in quoted_syms
print(io, '(')
quo = true
end
end
end
end
show_sym(io, sym)
quo && print(io, ")")
globfunc && print(io, ")")
end
function show_datatype(io::IO, x::DataType)
istuple = x.name === Tuple.name
if (!isempty(x.parameters) || istuple) && x !== Tuple
n = length(x.parameters)::Int
# Print homogeneous tuples with more than 3 elements compactly as NTuple{N, T}
if istuple && n > 3 && all(i -> (x.parameters[1] === i), x.parameters)
print(io, "NTuple{", n, ',', x.parameters[1], "}")
else
show_type_name(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(io, p)
i < n && print(io, ',')
end
print(io, '}')
end
else
show_type_name(io, x.name)
end
end
function show_supertypes(io::IO, typ::DataType)
print(io, typ)
while typ != Any
typ = supertype(typ)
print(io, " <: ", typ)
end
end
show_supertypes(typ::DataType) = show_supertypes(stdout, typ)
"""
@show
Show an expression and result, returning the result. See also [`show`](@ref).
"""
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
isempty(exs) || push!(blk.args, :value)
return blk
end
function show(io::IO, tn::Core.TypeName)
show_type_name(io, tn)
end
show(io::IO, ::Nothing) = print(io, "nothing")
show(io::IO, b::Bool) = print(io, get(io, :typeinfo, Any) === Bool ? (b ? "1" : "0") : (b ? "true" : "false"))
show(io::IO, n::Signed) = (write(io, string(n)); nothing)
show(io::IO, n::Unsigned) = print(io, "0x", string(n, pad = sizeof(n)<<1, base = 16))
print(io::IO, n::Unsigned) = print(io, string(n))
show(io::IO, p::Ptr) = print(io, typeof(p), " @0x$(string(UInt(p), base = 16, pad = Sys.WORD_SIZE>>2))")
has_tight_type(p::Pair) =
typeof(p.first) == typeof(p).parameters[1] &&
typeof(p.second) == typeof(p).parameters[2]
isdelimited(io::IO, x) = true
isdelimited(io::IO, x::Function) = !isoperator(Symbol(x))
# !isdelimited means that the Pair is printed with "=>" (like in "1 => 2"),
# without its explicit type (like in "Pair{Integer,Integer}(1, 2)")
isdelimited(io::IO, p::Pair) = !(has_tight_type(p) || get(io, :typeinfo, Any) == typeof(p))
function gettypeinfos(io::IO, p::Pair)
typeinfo = get(io, :typeinfo, Any)
p isa typeinfo <: Pair ?
fieldtype(typeinfo, 1) => fieldtype(typeinfo, 2) :
Any => Any
end
function show(io::IO, p::Pair)
isdelimited(io, p) && return show_default(io, p)
typeinfos = gettypeinfos(io, p)
for i = (1, 2)
io_i = IOContext(io, :typeinfo => typeinfos[i])
isdelimited(io_i, p[i]) || print(io, "(")
show(io_i, p[i])
isdelimited(io_i, p[i]) || print(io, ")")
i == 1 && print(io, get(io, :compact, false) ? "=>" : " => ")
end
end
function show(io::IO, m::Module)
if is_root_module(m)
print(io, nameof(m))
else
print(io, join(fullname(m),"."))
end
end
function sourceinfo_slotnames(src::CodeInfo)
slotnames = src.slotnames
names = Dict{String,Int}()
printnames = Vector{String}(undef, length(slotnames))
for i in eachindex(slotnames)
name = string(slotnames[i])
idx = get!(names, name, i)
if idx != i || isempty(name)
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)
def = l.def
if isa(def, Method)
if isdefined(def, :generator) && l === def.generator
print(io, "MethodInstance generator for ")
show(io, def)
else
print(io, "MethodInstance for ")
show_tuple_as_call(io, def.name, l.specTypes)
end
else
print(io, "Toplevel MethodInstance thunk")
end
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)
first = true
i = i1
if l >= i1
while true
if !isassigned(itr, i)
print(io, undef_ref_str)
else
x = itr[i]
show(recur_io, x)
end
i += 1
if i > l
delim_one && first && print(io, delim)
break
end
first = false
print(io, delim)
print(io, ' ')
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)
y = iterate(itr)
first = true
i0 = i1-1
while i1 > 1 && y !== nothing
y = iterate(itr, y[2])
i1 -= 1
end
if y !== nothing
typeinfo = get(io, :typeinfo, Any)
while true
x = y[1]
y = iterate(itr, y[2])
show(IOContext(recur_io, :typeinfo => itr isa typeinfo <: Tuple ?
fieldtype(typeinfo, i1+i0) :
typeinfo),
x)
i1 += 1
if y === nothing || i1 > n
delim_one && first && print(io, delim)
break
end
first = false
print(io, delim)
print(io, ' ')
end
end
end
print(io, cl)
end
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, 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. Meta.parse(string(ex)) == ex
# 2. eval(Meta.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(Meta.parse("Set{Int64}([2,3,1])”) # ==> An actual set
# While this isn’t true of ALL show methods, it is of all ASTs.
const ExprNode = Union{Expr, QuoteNode, Slot, LineNumberNode, SSAValue,
GotoNode, GlobalRef, PhiNode, PhiCNode, UpsilonNode,
Core.Compiler.GotoIfNot, Core.Compiler.ReturnNode}
# 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.
# IOContext(io, :unquote_fallback => false) tells show_unquoted to treat any
# Expr whose head is :$ as if it is inside a quote, preventing fallback to the
# "unhandled" case: this is used by print/string to be lawful to Rule 1 above.
# On the countrary, show/repr have to follow Rule 2, requiring any Expr whose
# head is :$ and which is not inside a quote to fallback to the "unhandled" case:
# this is behavior is triggered by IOContext(io, :unquote_fallback => true)
print( io::IO, ex::ExprNode) = (show_unquoted(IOContext(io, :unquote_fallback => false), ex, 0, -1); nothing)
show( io::IO, ex::ExprNode) = show_unquoted_quote_expr(IOContext(io, :unquote_fallback => true), ex, 0, -1, 0)
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)
show_unquoted(io::IO, ex, indent::Int, prec::Int, ::Int) = show_unquoted(io, ex, indent, prec)
## AST printing constants ##
const indent_width = 4
const quoted_syms = Set{Symbol}([:(:),:(::),:(:=),:(=),:(==),:(===),:(=>)])
const uni_syms = Set{Symbol}([:(::), :(<:), :(>:)])
const uni_ops = Set{Symbol}([:(+), :(-), :(!), :(¬), :(~), :(<:), :(>:), :(√), :(∛), :(∜)])
const expr_infix_wide = Set{Symbol}([
:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(^=), :(&=), :(|=), :(÷=), :(%=), :(>>>=), :(>>=), :(<<=),
:(.=), :(.+=), :(.-=), :(.*=), :(./=), :(.\=), :(.^=), :(.&=), :(.|=), :(.÷=), :(.%=), :(.>>>=), :(.>>=), :(.<<=),
:(&&), :(||), :(<:), :($=), :(⊻=), :(>:)])
const expr_infix = Set{Symbol}([:(:), :(->), Symbol("::")])
const expr_infix_any = union(expr_infix, expr_infix_wide)
const expr_calls = Dict(:call => ('(',')'), :calldecl => ('(',')'),
:ref => ('[',']'), :curly => ('{','}'), :(.) => ('(',')'))
const expr_parens = Dict(:tuple=>('(',')'), :vcat=>('[',']'),
:hcat =>('[',']'), :row =>('[',']'), :vect=>('[',']'),
:braces=>('{','}'), :bracescat=>('{','}'))
## AST decoding helpers ##
is_id_start_char(c::AbstractChar) = ccall(:jl_id_start_char, Cint, (UInt32,), c) != 0
is_id_char(c::AbstractChar) = ccall(:jl_id_char, Cint, (UInt32,), c) != 0
function isidentifier(s::AbstractString)
isempty(s) && return false
(s == "true" || s == "false") && return false
c, rest = Iterators.peel(s)
is_id_start_char(c) || return false
return all(is_id_char, rest)
end
isidentifier(s::Symbol) = isidentifier(string(s))
"""
isoperator(s::Symbol)
Return `true` if the symbol can be used as an operator, `false` otherwise.
# Examples
```jldoctest
julia> Base.isoperator(:+), Base.isoperator(:f)
(true, false)
```
"""
isoperator(s::Union{Symbol,AbstractString}) = ccall(:jl_is_operator, Cint, (Cstring,), s) != 0
"""
isunaryoperator(s::Symbol)
Return `true` if the symbol can be used as a unary (prefix) operator, `false` otherwise.
# Examples
```jldoctest
julia> Base.isunaryoperator(:-), Base.isunaryoperator(:√), Base.isunaryoperator(:f)
(true, true, false)
```
"""
isunaryoperator(s::Symbol) = ccall(:jl_is_unary_operator, Cint, (Cstring,), s) != 0
is_unary_and_binary_operator(s::Symbol) = ccall(:jl_is_unary_and_binary_operator, Cint, (Cstring,), s) != 0
"""
isbinaryoperator(s::Symbol)
Return `true` if the symbol can be used as a binary (infix) operator, `false` otherwise.
# Examples
```jldoctest
julia> Base.isbinaryoperator(:-), Base.isbinaryoperator(:√), Base.isbinaryoperator(:f)
(true, false, false)
```
"""
isbinaryoperator(s::Symbol) = isoperator(s) && (!isunaryoperator(s) || is_unary_and_binary_operator(s))
"""
operator_precedence(s::Symbol)
Return an integer representing the precedence of operator `s`, relative to
other operators. Higher-numbered operators take precedence over lower-numbered
operators. Return `0` if `s` is not a valid operator.
# Examples
```jldoctest
julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)
(11, 12, 17)
julia> Base.operator_precedence(:sin), Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`)
(0, 1, 1)
```
"""
operator_precedence(s::Symbol) = Int(ccall(:jl_operator_precedence, Cint, (Cstring,), s))
operator_precedence(x::Any) = 0 # fallback for generic expression nodes
const prec_assignment = operator_precedence(:(=))
const prec_pair = operator_precedence(:(=>))
const prec_control_flow = operator_precedence(:(&&))
const prec_arrow = operator_precedence(:(-->))
const prec_comparison = operator_precedence(:(>))
const prec_power = operator_precedence(:(^))
const prec_decl = operator_precedence(:(::))
"""
operator_associativity(s::Symbol)
Return a symbol representing the associativity of operator `s`. Left- and right-associative
operators return `:left` and `:right`, respectively. Return `:none` if `s` is non-associative
or an invalid operator.
# Examples
```jldoctest
julia> Base.operator_associativity(:-), Base.operator_associativity(:+), Base.operator_associativity(:^)
(:left, :none, :right)
julia> Base.operator_associativity(:⊗), Base.operator_associativity(:sin), Base.operator_associativity(:→)
(:left, :none, :right)
```
"""
function operator_associativity(s::Symbol)
if operator_precedence(s) in (prec_arrow, prec_assignment, prec_control_flow, prec_pair, prec_power) ||
(isunaryoperator(s) && !is_unary_and_binary_operator(s)) || s === :<| || s === :||
return :right
elseif operator_precedence(s) in (0, prec_comparison) || s in (:+, :++, :*)
return :none
end
return :left
end
is_expr(@nospecialize(ex), head::Symbol) = isa(ex, Expr) && (ex.head === head)
is_expr(@nospecialize(ex), head::Symbol, n::Int) = is_expr(ex, head) && length(ex.args) == n
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 ##
function printstyled end
function with_output_color end
const indent_width = 4
is_expected_union(u::Union) = u.a == Nothing || u.b == Nothing || u.a == Missing || u.b == Missing
emphasize(io, str::AbstractString, col = Base.error_color()) = get(io, :color, false) ?
printstyled(io, str; color=col, 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, " =#")
show_linenumber(io::IO, line, file::Nothing) = show_linenumber(io, line)
# show a block, e g if/for/etc
function show_block(io::IO, head, args::Vector, body, indent::Int, quote_level::Int)
print(io, head)
if !isempty(args)
print(io, ' ')
if head === :elseif
show_list(io, args, " ", indent, 0, quote_level)
else
show_list(io, args, ", ", indent, 0, quote_level)