-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
show.jl
3340 lines (3020 loc) · 116 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
using Core.Compiler: has_typevar
function show(io::IO, ::MIME"text/plain", u::UndefInitializer)
show(io, u)
get(io, :compact, false)::Bool && 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", r::LogRange) # display LogRange like LinRange
isempty(r) && return show(io, r)
summary(io, r)
println(io, ":")
print_range(io, r, " ", ", ", "", " \u2026 ")
end
function _isself(ft::DataType)
ftname = ft.name
isdefined(ftname, :mt) || return false
name = ftname.mt.name
mod = parentmodule(ft) # NOTE: not necessarily the same as ft.name.mt.module
return isdefined(mod, name) && ft == typeof(getfield(mod, name))
end
function show(io::IO, ::MIME"text/plain", f::Function)
get(io, :compact, false)::Bool && return show(io, f)
ft = typeof(f)
name = ft.name.mt.name
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, name, " (built-in function)")
else
n = length(methods(f))
m = n==1 ? "method" : "methods"
sname = string(name)
ns = (_isself(ft) || '#' in sname) ? sname : string("(::", ft, ")")
what = startswith(ns, '@') ? "macro" : "generic function"
print(io, ns, " (", what, " with $n $m)")
end
end
show(io::IO, ::MIME"text/plain", c::ComposedFunction) = show(io, c)
show(io::IO, ::MIME"text/plain", c::Returns) = show(io, c)
show(io::IO, ::MIME"text/plain", s::Splat) = show(io, s)
const ansi_regex = r"(?s)(?:\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))|."
# Pseudo-character representing an ANSI delimiter
struct ANSIDelimiter
del::SubString{String}
end
ncodeunits(c::ANSIDelimiter) = ncodeunits(c.del)
textwidth(::ANSIDelimiter) = 0
# An iterator similar to `pairs(::String)` but whose values are Char or ANSIDelimiter
struct ANSIIterator
captures::RegexMatchIterator
end
ANSIIterator(s::AbstractString) = ANSIIterator(eachmatch(ansi_regex, s))
IteratorSize(::Type{ANSIIterator}) = SizeUnknown()
eltype(::Type{ANSIIterator}) = Pair{Int, Union{Char,ANSIDelimiter}}
function iterate(I::ANSIIterator, (i, m_st)=(1, iterate(I.captures)))
m_st === nothing && return nothing
m, (j, new_m_st) = m_st
c = lastindex(m.match) == 1 ? only(m.match) : ANSIDelimiter(m.match)
return (i => c, (j, iterate(I.captures, (j, new_m_st))))
end
textwidth(I::ANSIIterator) = mapreduce(textwidth∘last, +, I; init=0)
function _truncate_at_width_or_chars(ignore_ANSI::Bool, str::AbstractString, width::Int, rpad::Bool=false, chars="\r\n", truncmark="…")
truncwidth = textwidth(truncmark)
(width <= 0 || width < truncwidth) && return ""
wid = truncidx = lastidx = 0
# if str needs to be truncated, truncidx is the index of truncation.
stop = false # once set, only ANSI delimiters will be kept as new characters.
needANSIend = false # set if the last ANSI delimiter before truncidx is not "\033[0m".
I = ignore_ANSI ? ANSIIterator(str) : pairs(str)
for (i, c) in I
if c isa ANSIDelimiter
truncidx == 0 && (needANSIend = c != "\033[0m")
lastidx = i + ncodeunits(c) - 1
else
stop && break
wid += textwidth(c)
truncidx == 0 && wid > (width - truncwidth) && (truncidx = lastidx)
lastidx = i
c in chars && break
stop = wid >= width
end
end
lastidx == 0 && return rpad ? ' '^width : ""
str[lastidx] in chars && (lastidx = prevind(str, lastidx))
ANSIend = needANSIend ? "\033[0m" : ""
pad = rpad ? repeat(' ', max(0, width-wid)) : ""
truncidx == 0 && (truncidx = lastidx)
if lastidx < lastindex(str)
return string(SubString(str, 1, truncidx), ANSIend, truncmark, pad)
else
return string(str, ANSIend, pad)
end
end
function show(io::IO, ::MIME"text/plain", iter::Union{KeySet,ValueIterator})
isempty(iter) && get(io, :compact, false)::Bool && return show(io, iter)
summary(io, iter)
isempty(iter) && return
print(io, ". ", isa(iter,KeySet) ? "Keys" : "Values", ":")
limit = get(io, :limit, false)::Bool
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(get(io, :color, false)::Bool, str, cols)
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 = get(io, :limit, false)::Bool
if !haskey(io, :compact)
recur_io = IOContext(recur_io, :compact => true)
end
recur_io_k = IOContext(recur_io, :typeinfo=>keytype(t))
recur_io_v = IOContext(recur_io, :typeinfo=>valtype(t))
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
hascolor = get(recur_io, :color, false)
ks = Vector{String}(undef, min(rows, length(t)))
vs = Vector{String}(undef, min(rows, length(t)))
keywidth = 0
valwidth = 0
for (i, (k, v)) in enumerate(t)
i > rows && break
ks[i] = sprint(show, k, context=recur_io_k, sizehint=0)
vs[i] = sprint(show, v, context=recur_io_v, sizehint=0)
keywidth = clamp(hascolor ? textwidth(ANSIIterator(ks[i])) : textwidth(ks[i]), keywidth, cols)
valwidth = clamp(hascolor ? textwidth(ANSIIterator(vs[i])) : textwidth(vs[i]), valwidth, cols)
end
if keywidth > max(div(cols, 2), cols - valwidth)
keywidth = max(cld(cols, 3), cols - valwidth)
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("⋮", keywidth), " => ⋮")
break
end
if limit
key = _truncate_at_width_or_chars(hascolor, ks[i], keywidth, true)
else
key = sprint(show, k, context=recur_io_k, sizehint=0)
end
print(recur_io, key)
print(io, " => ")
if limit
val = _truncate_at_width_or_chars(hascolor, vs[i], cols - keywidth)
print(io, val)
else
show(recur_io_v, 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 = get(io, :limit, false)::Bool
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(get(io, :color, false)::Bool, str, cols))
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 istaskfailed(t)
println(io)
show_task_exception(io, t, indent = false)
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
io isa IOContext && (io = io.io) # implicitly unwrap, since the io.dict field is not useful anymore, and could confuse pipe_reader consumers
return new(io, dict)
end
end
# (Note that TTY and TTYTerminal io types have an implied :color property.)
ioproperties(io::IO) = get(io, :color, false) ? ImmutableDict{Symbol,Any}(:color, true) : ImmutableDict{Symbol,Any}()
ioproperties(io::IOContext) = io.dict
# these can probably be deprecated, but there is a use in the ecosystem for them
unwrapcontext(io::IO) = (io,)
unwrapcontext(io::IOContext) = (io.io,)
function IOContext(io::IO, dict::ImmutableDict{Symbol, Any})
return IOContext{typeof(io)}(io, dict)
end
function IOContext(io::IOContext, dict::ImmutableDict{Symbol, Any})
return typeof(io)(io.io, dict)
end
convert(::Type{IOContext}, io::IOContext) = io
convert(::Type{IOContext}, io::IO) = IOContext(io, ioproperties(io))::IOContext
IOContext(io::IO) = convert(IOContext, io)
function IOContext(io::IO, KV::Pair)
d = ioproperties(io)
return IOContext(io, 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(io, ioproperties(context))
"""
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
keys(io::IOContext) = keys(io.dict)
keys(io::IO) = keys(ImmutableDict{Symbol,Any}())
displaysize(io::IOContext) = haskey(io, :displaysize) ? io[:displaysize]::Tuple{Int,Int} : 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.
For a more verbose human-readable text output for objects of type `T`, define
`show(io::IO, ::MIME"text/plain", ::T)` in addition. Checking the `:compact`
[`IOContext`](@ref) key (often checked as `get(io, :compact, false)::Bool`)
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, 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)::DataType)
print(io, '(')
nf = nfields(x)
nb = sizeof(x)::Int
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{Any}(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
function active_module()
if ccall(:jl_is_in_pure_context, Bool, ())
error("active_module() should not be called from a pure context")
end
if !@isdefined(active_repl) || active_repl === nothing
return Main
end
return invokelatest(active_module, active_repl)::Module
end
module UsesCoreAndBaseOnly
end
function show_function(io::IO, f::Function, compact::Bool, fallback::Function)
ft = typeof(f)
mt = ft.name.mt
if mt === Symbol.name.mt
# uses shared method table
fallback(io, f)
elseif compact
print(io, mt.name)
elseif isdefined(mt, :module) && isdefined(mt.module, mt.name) &&
getfield(mt.module, mt.name) === f
# this used to call the removed internal function `is_exported_from_stdlib`, which effectively
# just checked for exports from Core and Base.
mod = get(io, :module, UsesCoreAndBaseOnly)
if !(isvisible(mt.name, mt.module, mod) || mt.module === mod)
print(io, mt.module, ".")
end
show_sym(io, mt.name)
else
fallback(io, f)
end
end
show(io::IO, f::Function) = show_function(io, f, get(io, :compact, false)::Bool, show_default)
print(io::IO, f::Function) = show_function(io, f, true, show)
function show(io::IO, f::Core.IntrinsicFunction)
if !(get(io, :compact, false)::Bool)
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))
b = unwrap_unionall(x)
return isa(b, DataType) && b.name.wrapper === x
end
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
modulesof!(s::Set{Module}, x::TypeVar) = modulesof!(s, x.ub)
function modulesof!(s::Set{Module}, x::Type)
x = unwrap_unionall(x)
if x isa DataType
push!(s, parentmodule(x))
elseif x isa Union
modulesof!(s, x.a)
modulesof!(s, x.b)
end
s
end
# given an IO context for printing a type, reconstruct the proper type that
# we're attempting to represent.
# Union{T} where T is a degenerate case and is equal to T.ub, but we don't want
# to print them that way, so filter those out from our aliases completely.
function makeproper(io::IO, @nospecialize(x::Type))
if io isa IOContext
for (key, val) in io.dict
if key === :unionall_env && val isa TypeVar
x = UnionAll(val, x)
end
end
end
has_free_typevars(x) && return Any
return x
end
function make_typealias(@nospecialize(x::Type))
Any === x && return nothing
x <: Tuple && return nothing
mods = modulesof!(Set{Module}(), x)
Core in mods && push!(mods, Base)
aliases = Tuple{GlobalRef,SimpleVector}[]
xenv = UnionAll[]
for p in uniontypes(unwrap_unionall(x))
p isa UnionAll && push!(xenv, p)
end
x isa UnionAll && push!(xenv, x)
for mod in mods
for name in unsorted_names(mod)
if isdefined(mod, name) && !isdeprecated(mod, name) && isconst(mod, name)
alias = getfield(mod, name)
if alias isa Type && !has_free_typevars(alias) && !print_without_params(alias) && x <: alias
if alias isa UnionAll
(ti, env) = ccall(:jl_type_intersection_with_env, Any, (Any, Any), x, alias)::SimpleVector
# ti === Union{} && continue # impossible, since we already checked that x <: alias
env = env::SimpleVector
# TODO: In some cases (such as the following), the `env` is over-approximated.
# We'd like to disable `fix_inferred_var_bound` since we'll already do that fix-up here.
# (or detect and reverse the computation of it here).
# T = Array{Array{T,1}, 1} where T
# (ti, env) = ccall(:jl_type_intersection_with_env, Any, (Any, Any), T, Vector)
# env[1].ub.var == T.var
applied = try
# this can fail if `x` contains a covariant
# union, and the non-matching branch of the
# union has additional restrictions on the
# bounds of the environment that are not met by
# the instantiation found above
alias{env...}
catch ex
ex isa TypeError || rethrow()
continue
end
for p in xenv
applied = rewrap_unionall(applied, p)
end
has_free_typevars(applied) && continue
applied === x || continue # it couldn't figure out the parameter matching
elseif alias === x
env = Core.svec()
else
continue # not a complete match
end
push!(aliases, (GlobalRef(mod, name), env))
end
end
end
end
if length(aliases) == 1 # TODO: select the type with the "best" (shortest?) environment
return aliases[1]
end
end
isgensym(s::Symbol) = '#' in string(s)
function show_can_elide(p::TypeVar, wheres::Vector, elide::Int, env::SimpleVector, skip::Int)
elide == 0 && return false
wheres[elide] === p || return false
for i = (elide + 1):length(wheres)
v = wheres[i]::TypeVar
has_typevar(v.lb, p) && return false
has_typevar(v.ub, p) && return false
end
for i = eachindex(env)
i == skip && continue
has_typevar(env[i], p) && return false
end
return true
end
function show_typeparams(io::IO, env::SimpleVector, orig::SimpleVector, wheres::Vector)
n = length(env)
elide = length(wheres)
function egal_var(p::TypeVar, @nospecialize o)
return o isa TypeVar &&
ccall(:jl_types_egal, Cint, (Any, Any), p.ub, o.ub) != 0 &&
ccall(:jl_types_egal, Cint, (Any, Any), p.lb, o.lb) != 0
end
for i = n:-1:1
p = env[i]
if p isa TypeVar
if i == n && egal_var(p, orig[i]) && show_can_elide(p, wheres, elide, env, i)
n -= 1
elide -= 1
elseif p.lb === Union{} && isgensym(p.name) && show_can_elide(p, wheres, elide, env, i)
elide -= 1
elseif p.ub === Any && isgensym(p.name) && show_can_elide(p, wheres, elide, env, i)
elide -= 1
end
end
end
if n > 0
print(io, "{")
for i = 1:n
p = env[i]
if p isa TypeVar
if p.lb === Union{} && something(findfirst(@nospecialize(w) -> w === p, wheres), 0) > elide
print(io, "<:")
show(io, p.ub)
elseif p.ub === Any && something(findfirst(@nospecialize(w) -> w === p, wheres), 0) > elide
print(io, ">:")
show(io, p.lb)
else
show(io, p)
end
else
show(io, p)
end
i < n && print(io, ", ")
end
print(io, "}")
end
resize!(wheres, elide)
nothing
end
function show_typealias(io::IO, name::GlobalRef, x::Type, env::SimpleVector, wheres::Vector)
if !(get(io, :compact, false)::Bool)
# Print module prefix unless alias 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 (from === nothing || !isvisible(name.name, name.mod, from))
show(io, name.mod)
print(io, ".")
end
end
print(io, name.name)
isempty(env) && return
io = IOContext(io)
for p in wheres
io = IOContext(io, :unionall_env => p)
end
orig = getfield(name.mod, name.name)
vars = TypeVar[]
while orig isa UnionAll
push!(vars, orig.var)
orig = orig.body
end
show_typeparams(io, env, Core.svec(vars...), wheres)
nothing
end
function make_wheres(io::IO, env::SimpleVector, @nospecialize(x::Type))
seen = IdSet()
wheres = TypeVar[]
# record things printed by the context
if io isa IOContext
for (key, val) in io.dict
if key === :unionall_env && val isa TypeVar && has_typevar(x, val)
push!(seen, val)
end
end
end
# record things in x to print outermost
while x isa UnionAll
if !(x.var in seen)
push!(seen, x.var)
push!(wheres, x.var)
end
x = x.body
end
# record remaining things in env to print innermost
for i = length(env):-1:1
p = env[i]
if p isa TypeVar && !(p in seen)
push!(seen, p)
pushfirst!(wheres, p)
end
end
return wheres
end
function show_wheres(io::IO, wheres::Vector{TypeVar})
isempty(wheres) && return
io = IOContext(io)
n = length(wheres)
for i = 1:n
p = wheres[i]
print(io, n == 1 ? " where " : i == 1 ? " where {" : ", ")
show(io, p)
io = IOContext(io, :unionall_env => p)
end
n > 1 && print(io, "}")
nothing
end
function show_typealias(io::IO, @nospecialize(x::Type))
properx = makeproper(io, x)
alias = make_typealias(properx)
alias === nothing && return false
wheres = make_wheres(io, alias[2], x)
show_typealias(io, alias[1], x, alias[2], wheres)
show_wheres(io, wheres)
return true
end
function make_typealiases(@nospecialize(x::Type))
aliases = SimpleVector[]
Any === x && return aliases, Union{}
x <: Tuple && return aliases, Union{}
mods = modulesof!(Set{Module}(), x)
Core in mods && push!(mods, Base)
vars = Dict{Symbol,TypeVar}()
xenv = UnionAll[]
each = Any[]
for p in uniontypes(unwrap_unionall(x))
p isa UnionAll && push!(xenv, p)
push!(each, rewrap_unionall(p, x))
end
x isa UnionAll && push!(xenv, x)
for mod in mods
for name in unsorted_names(mod)
if isdefined(mod, name) && !isdeprecated(mod, name) && isconst(mod, name)
alias = getfield(mod, name)
if alias isa Type && !has_free_typevars(alias) && !print_without_params(alias) && !(alias <: Tuple)
(ti, env) = ccall(:jl_type_intersection_with_env, Any, (Any, Any), x, alias)::SimpleVector
ti === Union{} && continue
# make sure this alias wasn't from an unrelated part of the Union
mod2 = modulesof!(Set{Module}(), alias)
mod in mod2 || (mod === Base && Core in mods) || continue
env = env::SimpleVector
applied = alias
if !isempty(env)
applied = try
# this can fail if `x` contains a covariant
# union, and the non-matching branch of the
# union has additional restrictions on the
# bounds of the environment that are not met by
# the instantiation found above
alias{env...}
catch ex
ex isa TypeError || rethrow()
continue
end
end
ul = unionlen(applied)
for p in xenv
applied = rewrap_unionall(applied, p)
end
has_free_typevars(applied) && continue
applied <: x || continue # parameter matching didn't make a subtype
print_without_params(x) && (env = Core.svec())
for typ in each # check that the alias also fully subsumes at least component of the input
if typ <: applied
push!(aliases, Core.svec(GlobalRef(mod, name), env, applied, (ul, -length(env))))
break
end
end
end
end
end
end
if isempty(aliases)
return aliases, Union{}
end
sort!(aliases, by = x -> x[4]::Tuple{Int,Int}, rev = true) # heuristic sort by "best" environment
let applied = Union{}
applied1 = Union{}
keep = SimpleVector[]
prev = (0, 0)
for alias in aliases
alias4 = alias[4]::Tuple{Int,Int}
if alias4[1] < 2
if !(alias[3] <: applied)
applied1 = Union{applied1, alias[3]}
push!(keep, alias)
end
elseif alias4 == prev || !(alias[3] <: applied)
applied = applied1 = Union{applied1, alias[3]}
push!(keep, alias)
prev = alias4
end
end
return keep, applied1
end
end
function show_unionaliases(io::IO, x::Union)
properx = makeproper(io, x)
aliases, applied = make_typealiases(properx)
isempty(aliases) && return false
first = true
tvar = false
for typ in uniontypes(x)
if isa(typ, TypeVar)
tvar = true # sort bare TypeVars to the end
continue
elseif rewrap_unionall(typ, properx) <: applied
continue
end
print(io, first ? "Union{" : ", ")
first = false
show(io, typ)
end
if first && !tvar && length(aliases) == 1
alias = aliases[1]
env = alias[2]::SimpleVector
wheres = make_wheres(io, env, x)
show_typealias(io, alias[1], x, env, wheres)
show_wheres(io, wheres)
else
for alias in aliases
print(io, first ? "Union{" : ", ")
first = false
env = alias[2]::SimpleVector
wheres = make_wheres(io, env, x)
show_typealias(io, alias[1], x, env, wheres)
show_wheres(io, wheres)
end
if tvar
for typ in uniontypes(x)
if isa(typ, TypeVar)
print(io, ", ")
show(io, typ)
end
end
end
print(io, "}")
end
return true
end
function show(io::IO, ::MIME"text/plain", @nospecialize(x::Type))
if !print_without_params(x)
properx = makeproper(io, x)
if make_typealias(properx) !== nothing || (unwrap_unionall(x) isa Union && x <: make_typealiases(properx)[2])
show(IOContext(io, :compact => true), x)
if !(get(io, :compact, false)::Bool)
printstyled(io, " (alias for "; color = :light_black)
printstyled(IOContext(io, :compact => false), x, color = :light_black)
printstyled(io, ")"; color = :light_black)
end
return
end
end
show(io, x)
# give a helpful hint for function types
if x isa DataType && x !== UnionAll && !(get(io, :compact, false)::Bool)
tn = x.name::Core.TypeName
globname = isdefined(tn, :mt) ? tn.mt.name : nothing
if is_global_function(tn, globname)
print(io, " (singleton type of function ")
show_sym(io, globname)
print(io, ", subtype of Function)")
end
end
end
show(io::IO, @nospecialize(x::Type)) = _show_type(io, inferencebarrier(x))
function _show_type(io::IO, @nospecialize(x::Type))
if print_without_params(x)
show_type_name(io, (unwrap_unionall(x)::DataType).name)
return
elseif get(io, :compact, true)::Bool && show_typealias(io, x)
return
elseif x isa DataType
show_datatype(io, x)
return
elseif x isa Union
if get(io, :compact, true)::Bool && show_unionaliases(io, x)
return
end
print(io, "Union")
show_delim_array(io, uniontypes(x), '{', ',', '}', false)
return
end
x = x::UnionAll
wheres = TypeVar[]
let io = IOContext(io)
while x isa UnionAll
var = x.var
if var.name === :_ || io_has_tvar_name(io, var.name, x)
counter = 1
while true
newname = Symbol(var.name, counter)
if !io_has_tvar_name(io, newname, x)
var = TypeVar(newname, var.lb, var.ub)
x = x{var}
break
end
counter += 1
end
else
x = x.body
end
push!(wheres, var)