-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathrequire.jl
74 lines (62 loc) · 1.64 KB
/
require.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
import Base: require
export @require
isprecompiling() = ccall(:jl_generating_output, Cint, ()) == 1
type Hook end
@init @guard begin
methods(require).mt.cache.sig = Tuple{typeof(require),Symbol,Hook}
function Base.require(mod::Symbol)
eval(:(Base.require))(mod, Main.Requires.Hook())
Main.Requires.loadmod(string(mod))
end
end
loaded(mod) = getthing(Main, mod) != nothing
const modlisteners = Dict{AbstractString,Vector{Function}}()
listenmod(f, mod) =
loaded(mod) ? f() :
modlisteners[mod] = push!(get(modlisteners, mod, Function[]), f)
loadmod(mod) =
map(f->f(), get(modlisteners, mod, []))
importexpr(mod::Symbol) = Expr(:import, mod)
importexpr(mod::Expr) = Expr(:import, map(Symbol, split(string(mod), "."))...)
function withpath(f, path)
tls = task_local_storage()
hassource = haskey(tls, :SOURCE_PATH)
hassource && (path′ = tls[:SOURCE_PATH])
tls[:SOURCE_PATH] = path
try
return f()
finally
hassource ?
(tls[:SOURCE_PATH] = path′) :
delete!(tls, :SOURCE_PATH)
end
end
function err(f, listener, mod)
try
f()
catch e
warn("Error requiring $mod from $listener:")
showerror(STDERR, e, catch_backtrace())
println(STDERR)
end
end
macro require(mod, expr)
ex = quote
listenmod($(string(mod))) do
withpath(@__FILE__) do
err($(current_module()), $(string(mod))) do
$(esc(:(eval($(Expr(:quote, Expr(:block,
importexpr(mod),
expr)))))))
end
end
end
end
quote
if isprecompiling()
@init @guard $(ex)
else
$(ex)
end
end
end