-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathreplutil.jl
460 lines (425 loc) · 17.1 KB
/
replutil.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
# This file is a part of Julia. License is MIT: http://julialang.org/license
# fallback text/plain representation of any type:
writemime(io::IO, ::MIME"text/plain", x) = showcompact(io, x)
writemime(io::IO, ::MIME"text/plain", x::Number) = show(io, x)
function writemime(io::IO, ::MIME"text/plain", f::Function)
ft = typeof(f)
mt = ft.name.mt
name = mt.name
isself = isdefined(ft.name.module, name) &&
ft == typeof(getfield(ft.name.module, name))
n = length(mt)
m = n==1 ? "method" : "methods"
ns = isself ? string(name) : string("(::", name, ")")
what = startswith(ns, '@') ? "macro" : "generic function"
print(io, ns, " (", what, " with $n $m)")
end
function writemime(io::IO, ::MIME"text/plain", f::Builtin)
print(io, typeof(f).name.mt.name, " (built-in function)")
end
# writemime for ranges, e.g.
# 3-element UnitRange{Int64,Int}
# 1,2,3
# or for more elements than fit on screen:
# 1.0,2.0,3.0,…,6.0,7.0,8.0
function writemime(io::IO, ::MIME"text/plain", r::Range)
print(io, summary(r))
if !isempty(r)
println(io, ":")
print_range(IOContext(io, :limit_output => true), r)
end
end
function writemime(io::IO, ::MIME"text/plain", v::AbstractVector)
print(io, summary(v))
if !isempty(v)
println(io, ":")
print_matrix(IOContext(io, :limit_output => true), v)
end
end
writemime(io::IO, ::MIME"text/plain", v::AbstractArray) =
showarray(IOContext(io, :limit_output => true), v, header=true, repr=false)
function writemime(io::IO, ::MIME"text/plain", v::DataType)
show(io, v)
# TODO: maybe show constructor info?
end
function writemime(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
# showing exception objects as descriptive error messages
showerror(io::IO, ex) = show(io, ex)
function showerror(io::IO, ex::BoundsError)
print(io, "BoundsError")
if isdefined(ex, :a)
print(io, ": attempt to access ")
writemime(io, MIME"text/plain"(), ex.a)
if isdefined(ex, :i)
print(io, "\n at index [")
if isa(ex.i, Range)
print(io, ex.i)
else
print_joined(io, ex.i, ',')
end
print(io, ']')
end
end
end
function showerror(io::IO, ex::TypeError)
print(io, "TypeError: ")
ctx = isempty(ex.context) ? "" : "in $(ex.context), "
if ex.expected === Bool
print(io, "non-boolean ($(typeof(ex.got))) used in boolean context")
else
if isa(ex.got, Type)
tstr = "Type{$(ex.got)}"
else
tstr = string(typeof(ex.got))
end
print(io, "$(ex.func): $(ctx)expected $(ex.expected), got $tstr")
if ex.func === :apply && ex.expected <: Function && isa(ex.got, AbstractArray)
print(io, "\nUse square brackets [] for indexing.")
end
end
end
function showerror(io::IO, ex, bt; backtrace=true)
try
showerror(io, ex)
finally
backtrace && show_backtrace(io, bt)
end
end
function showerror(io::IO, ex::LoadError, bt; backtrace=true)
print(io, "LoadError: ")
showerror(io, ex.error, bt, backtrace=backtrace)
print(io, "\nwhile loading $(ex.file), in expression starting on line $(ex.line)")
end
showerror(io::IO, ex::LoadError) = showerror(io, ex, [])
function showerror(io::IO, ex::InitError, bt; backtrace=true)
print(io, "InitError: ")
showerror(io, ex.error, bt, backtrace=backtrace)
print(io, "\nduring initialization of module $(ex.mod)")
end
showerror(io::IO, ex::InitError) = showerror(io, ex, [])
function showerror(io::IO, ex::DomainError, bt; backtrace=true)
print(io, "DomainError:")
for b in bt
code = StackTraces.lookup(b)
if code !== lookup && code.from_c
if code.func in (:log, :log2, :log10, :sqrt) # TODO add :besselj, :besseli, :bessely, :besselk
print(io,"\n$(code.func) will only return a complex result if called with a complex argument. Try $(code[1])(complex(x)).")
elseif (code.func == :^ && code.file == symbol("intfuncs.jl")) || code.func == :power_by_squaring #3024
print(io, "\nCannot raise an integer x to a negative power -n. \nMake x a float by adding a zero decimal (e.g. 2.0^-n instead of 2^-n), or write 1/x^n, float(x)^-n, or (x//1)^-n.")
elseif code.func == :^ && (code.file == symbol("promotion.jl") || code.file == symbol("math.jl"))
print(io, "\nExponentiation yielding a complex result requires a complex argument.\nReplace x^y with (x+0im)^y, Complex(x)^y, or similar.")
end
break
end
end
backtrace && show_backtrace(io, bt)
nothing
end
function showerror(io::IO, ex::SystemError)
if ex.extrainfo == nothing
print(io, "SystemError: $(ex.prefix): $(Libc.strerror(ex.errnum))")
else
print(io, "SystemError (with $(ex.extrainfo)): $(ex.prefix): $(Libc.strerror(ex.errnum))")
end
end
showerror(io::IO, ::DivideError) = print(io, "DivideError: integer division error")
showerror(io::IO, ::StackOverflowError) = print(io, "StackOverflowError:")
showerror(io::IO, ::UndefRefError) = print(io, "UndefRefError: access to undefined reference")
showerror(io::IO, ex::UndefVarError) = print(io, "UndefVarError: $(ex.var) not defined")
showerror(io::IO, ::EOFError) = print(io, "EOFError: read end of file")
showerror(io::IO, ex::ErrorException) = print(io, ex.msg)
showerror(io::IO, ex::KeyError) = print(io, "KeyError: $(ex.key) not found")
showerror(io::IO, ex::InterruptException) = print(io, "InterruptException:")
showerror(io::IO, ex::ArgumentError) = print(io, "ArgumentError: $(ex.msg)")
showerror(io::IO, ex::AssertionError) = print(io, "AssertionError: $(ex.msg)")
function showerror(io::IO, ex::MethodError)
# ex.args is a tuple type if it was thrown from `invoke` and is
# a tuple of the arguments otherwise.
is_arg_types = isa(ex.args, DataType)
arg_types = is_arg_types ? ex.args : typesof(ex.args...)
arg_types_param::SimpleVector = arg_types.parameters
print(io, "MethodError: ")
f = ex.f
ft = typeof(f)
name = ft.name.mt.name
f_is_function = false
if f == Base.convert && length(arg_types_param) == 2 && !is_arg_types
f_is_function = true
# See #13033
T = striptype(ex.args[1])
if T == nothing
print(io, "First argument to `convert` must be a Type, got ", ex.args[1])
else
print(io, "Cannot `convert` an object of type ", arg_types_param[2], " to an object of type ", T)
end
elseif isempty(methods(f)) && !isa(f, Function)
print(io, "::$ft is not callable")
else
if ft <: Function && isempty(ft.parameters) &&
isdefined(ft.name.module, name) &&
ft == typeof(getfield(ft.name.module, name))
f_is_function = true
print(io, "no method matching ", name)
elseif isa(f, Type)
print(io, "no method matching ", f)
else
print(io, "no method matching (::", ft, ")")
end
print(io, "(")
for (i, typ) in enumerate(arg_types_param)
print(io, "::$typ")
i == length(arg_types_param) || print(io, ", ")
end
print(io, ")")
end
# Check for local functions that shadow methods in Base
if f_is_function && isdefined(Base, name)
basef = getfield(Base, name)
if basef !== ex.f && method_exists(basef, arg_types)
println(io)
print(io, "you may have intended to import Base.", name)
end
end
if !is_arg_types
# Check for row vectors used where a column vector is intended.
vec_args = []
hasrows = false
for arg in ex.args
isrow = isa(arg,Array) && ndims(arg)==2 && size(arg,1)==1
hasrows |= isrow
push!(vec_args, isrow ? vec(arg) : arg)
end
if hasrows && applicable(f, vec_args...)
print(io, "\n\nYou might have used a 2d row vector where a 1d column vector was required.",
"\nNote the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3].",
"\nYou can convert to a column vector with the vec() function.")
end
end
# Give a helpful error message if the user likely called a type constructor
# and sees a no method error for convert
if (f === Base.convert && !isempty(arg_types_param) && !is_arg_types &&
isa(arg_types_param[1], DataType) &&
arg_types_param[1].name === Type.name)
construct_type = arg_types_param[1].parameters[1]
println(io)
print(io, "This may have arisen from a call to the constructor $construct_type(...),",
"\nsince type constructors fall back to convert methods.")
end
try
show_method_candidates(io, ex)
catch
warn(io, "Error showing method candidates, aborted")
end
end
striptype{T}(::Type{T}) = T
striptype(::Any) = nothing
#Show an error by directly calling jl_printf.
#Useful in Base submodule __init__ functions where STDERR isn't defined yet.
function showerror_nostdio(err, msg::AbstractString)
stderr_stream = ccall(:jl_stderr_stream, Ptr{Void}, ())
ccall(:jl_printf, UInt, (Ptr{Void},Cstring), stderr_stream, msg)
ccall(:jl_printf, UInt, (Ptr{Void},Cstring), stderr_stream, ":\n")
ccall(:jl_static_show, UInt, (Ptr{Void},Ptr{Void}), stderr_stream,
pointer_from_objref(err))
ccall(:jl_printf, UInt, (Ptr{Void},Cstring), stderr_stream, "\n")
end
function show_method_candidates(io::IO, ex::MethodError)
is_arg_types = isa(ex.args, DataType)
arg_types = is_arg_types ? ex.args : typesof(ex.args...)
arg_types_param = Any[arg_types.parameters...]
# Displays the closest candidates of the given function by looping over the
# functions methods and counting the number of matching arguments.
if isa(ex.f, Tuple)
f = ex.f[1]
else
f = ex.f
end
lines = []
# These functions are special cased to only show if first argument is matched.
special = f in [convert, getindex, setindex!]
funcs = Any[(Core.Typeof(f),arg_types_param)]
# An incorrect call method produces a MethodError for convert.
# It also happens that users type convert when they mean call. So
# pool MethodErrors for these two functions.
if f === convert && !isempty(arg_types_param)
push!(funcs, (arg_types_param[1],arg_types_param[2:end]))
end
for (func,arg_types_param) in funcs
for method in func.name.mt
buf = IOBuffer()
s1 = method.sig.parameters[1]
sig = method.sig.parameters[2:end]
print(buf, " ")
if !(func <: s1)
# function itself doesn't match
print(buf, "(")
if Base.have_color
Base.with_output_color(:red, buf) do buf
print(buf, "::", s1)
end
else
print(buf, "!Matched::", s1)
end
print(buf, ")")
else
use_constructor_syntax = func.name === Type.name && !isa(func.parameters[1],TypeVar)
print(buf, use_constructor_syntax ? func.parameters[1] : func.name.mt.name)
end
right_matches = 0
tv = method.tvars
if !isa(tv,SimpleVector)
tv = Any[tv]
end
if !isempty(tv)
show_delim_array(buf, tv, '{', ',', '}', false)
end
print(buf, "(")
t_i = copy(arg_types_param)
right_matches = 0
for i = 1 : min(length(t_i), length(sig))
i > 1 && print(buf, ", ")
# If isvarargtype then it checks wether the rest of the input arguements matches
# the varargtype
if Base.isvarargtype(sig[i])
sigstr = string(sig[i].parameters[1], "...")
j = length(t_i)
else
sigstr = string(sig[i])
j = i
end
# Checks if the type of arg 1:i of the input intersects with the current method
t_in = typeintersect(Tuple{sig[1:i]...}, Tuple{t_i[1:j]...})
# If the function is one of the special cased then it should break the loop if
# the type of the first argument is not matched.
t_in === Union{} && special && i == 1 && break
if t_in === Union{}
if Base.have_color
Base.with_output_color(:red, buf) do buf
print(buf, "::$sigstr")
end
else
print(buf, "!Matched::$sigstr")
end
# If there is no typeintersect then the type signature from the method is
# inserted in t_i this ensures if the type at the next i matches the type
# signature then there will be a type intersect
t_i[i] = sig[i]
else
right_matches += j==i ? 1 : 0
print(buf, "::$sigstr")
end
end
special && right_matches==0 && continue
if length(t_i) > length(sig) && !isempty(sig) && Base.isvarargtype(sig[end])
# It ensures that methods like f(a::AbstractString...) gets the correct
# number of right_matches
for t in arg_types_param[length(sig):end]
if t <: sig[end].parameters[1]
right_matches += 1
end
end
end
if right_matches > 0
if length(t_i) < length(sig)
# If the methods args is longer than input then the method
# arguments is printed as not a match
for sigtype in sig[length(t_i)+1:end]
if Base.isvarargtype(sigtype)
sigstr = string(sigtype.parameters[1], "...")
else
sigstr = string(sigtype)
end
print(buf, ", ")
if Base.have_color
Base.with_output_color(:red, buf) do buf
print(buf, "::$sigstr")
end
else
print(buf, "!Matched::$sigstr")
end
end
end
print(buf, ")")
push!(lines, (buf, right_matches))
end
end
end
if !isempty(lines) # Display up to three closest candidates
Base.with_output_color(:normal, io) do io
println(io)
print(io, "Closest candidates are:")
sort!(lines, by = x -> -x[2])
i = 0
for line in lines
println(io)
if i >= 3
print(io, " ...")
break
end
i += 1
print(io, takebuf_string(line[1]))
end
end
end
end
function show_trace_entry(io, frame, n)
print(io, "\n")
show(io, frame, full_path=true)
n > 1 && print(io, " (repeats ", n, " times)")
end
function show_backtrace(io::IO, t, set=1:typemax(Int))
# we may not declare :eval_user_input
# directly so that we get a compile error
# in case its name changes in the future
show_backtrace(io,
try
typeof(eval_user_input).name.mt.name
catch
:(:) #for when client.jl is not yet defined
end, t, set)
end
function show_backtrace(io::IO, top_function::Symbol, t, set)
process_entry(last_frame, n) =
show_trace_entry(io, last_frame, n)
process_backtrace(process_entry, top_function, t, set)
end
function show_backtrace(io::IO, top_function::Symbol, t::Vector{Any}, set)
for entry in t
show_trace_entry(io, entry...)
end
end
# process the backtrace, up to (but not including) top_function
function process_backtrace(process_func::Function, top_function::Symbol, t, set; skipC = true)
n = 0
last_frame = StackTraces.UNKNOWN
count = 0
for i = 1:length(t)
lkup = StackTraces.lookup(t[i])
if lkup === StackTraces.UNKNOWN
continue
end
if lkup.from_c && skipC; continue; end
if i == 1 && lkup.func == :error; continue; end
if lkup.func == top_function; break; end
count += 1
if !in(count, set); continue; end
if lkup.file != last_frame.file || lkup.line != last_frame.line || lkup.func != last_frame.func
if n > 0
process_func(last_frame, n)
end
n = 1
last_frame = lkup
else
n += 1
end
end
if n > 0
process_func(last_frame, n)
end
end