-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
loading.jl
1398 lines (1262 loc) · 51.8 KB
/
loading.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
# Base.require is the implementation for the `import` statement
# Cross-platform case-sensitive path canonicalization
if Sys.isunix() && !Sys.isapple()
# assume case-sensitive filesystems, don't have to do anything
isfile_casesensitive(path) = isfile(path)
elseif Sys.iswindows()
# GetLongPathName Win32 function returns the case-preserved filename on NTFS.
function isfile_casesensitive(path)
isfile(path) || return false # Fail fast
basename(Filesystem.longpath(path)) == basename(path)
end
elseif Sys.isapple()
# HFS+ filesystem is case-preserving. The getattrlist API returns
# a case-preserved filename. In the rare event that HFS+ is operating
# in case-sensitive mode, this will still work but will be redundant.
# Constants from <sys/attr.h>
const ATRATTR_BIT_MAP_COUNT = 5
const ATTR_CMN_NAME = 1
const BITMAPCOUNT = 1
const COMMONATTR = 5
const FSOPT_NOFOLLOW = 1 # Don't follow symbolic links
const attr_list = zeros(UInt8, 24)
attr_list[BITMAPCOUNT] = ATRATTR_BIT_MAP_COUNT
attr_list[COMMONATTR] = ATTR_CMN_NAME
# This essentially corresponds to the following C code:
# attrlist attr_list;
# memset(&attr_list, 0, sizeof(attr_list));
# attr_list.bitmapcount = ATTR_BIT_MAP_COUNT;
# attr_list.commonattr = ATTR_CMN_NAME;
# struct Buffer {
# u_int32_t total_length;
# u_int32_t filename_offset;
# u_int32_t filename_length;
# char filename[max_filename_length];
# };
# Buffer buf;
# getattrpath(path, &attr_list, &buf, sizeof(buf), FSOPT_NOFOLLOW);
function isfile_casesensitive(path)
isfile(path) || return false
path_basename = String(basename(path))
local casepreserved_basename
header_size = 12
buf = Vector{UInt8}(uninitialized, length(path_basename) + header_size + 1)
while true
ret = ccall(:getattrlist, Cint,
(Cstring, Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Culong),
path, attr_list, buf, sizeof(buf), FSOPT_NOFOLLOW)
systemerror(:getattrlist, ret ≠ 0)
filename_length = GC.@preserve buf unsafe_load(
convert(Ptr{UInt32}, pointer(buf) + 8))
if (filename_length + header_size) > length(buf)
resize!(buf, filename_length + header_size)
continue
end
casepreserved_basename =
view(buf, (header_size+1):(header_size+filename_length-1))
break
end
# Hack to compensate for inability to create a string from a subarray with no allocations.
codeunits(path_basename) == casepreserved_basename && return true
# If there is no match, it's possible that the file does exist but HFS+
# performed unicode normalization. See https://developer.apple.com/library/mac/qa/qa1235/_index.html.
isascii(path_basename) && return false
codeunits(Unicode.normalize(path_basename, :NFD)) == casepreserved_basename
end
else
# Generic fallback that performs a slow directory listing.
function isfile_casesensitive(path)
isfile(path) || return false
dir, filename = splitdir(path)
any(readdir(dir) .== filename)
end
end
## SHA1 ##
struct SHA1
bytes::Vector{UInt8}
function SHA1(bytes::Vector{UInt8})
length(bytes) == 20 ||
throw(ArgumentError("wrong number of bytes for SHA1 hash: $(length(bytes))"))
return new(bytes)
end
end
SHA1(s::Union{String,SubString{String}}) = SHA1(hex2bytes(s))
convert(::Type{String}, hash::SHA1) = bytes2hex(convert(Vector{UInt8}, hash))
convert(::Type{Vector{UInt8}}, hash::SHA1) = hash.bytes
string(hash::SHA1) = String(hash)
show(io::IO, hash::SHA1) = print(io, "SHA1(", convert(String, hash), ")")
isless(a::SHA1, b::SHA1) = lexless(a.bytes, b.bytes)
hash(a::SHA1, h::UInt) = hash((SHA1, a.bytes), h)
==(a::SHA1, b::SHA1) = a.bytes == b.bytes
## package path slugs: turning UUID + SHA1 into a pair of 4-byte "slugs" ##
const SlugInt = UInt32 # max p = 4
const chars = String(['A':'Z'; 'a':'z'; '0':'9'])
const nchars = SlugInt(length(chars))
const max_p = floor(Int, log(nchars, typemax(SlugInt) >>> 8))
function slug(x::SlugInt, p::Int)
1 ≤ p ≤ max_p || # otherwise previous steps are wrong
error("invalid slug size: $p (need 1 ≤ p ≤ $max_p)")
return sprint() do io
for i = 1:p
x, d = divrem(x, nchars)
write(io, chars[1+d])
end
end
end
slug(x::Integer, p::Int) = slug(SlugInt(x), p)
function slug(bytes::Vector{UInt8}, p::Int)
n = nchars^p
x = zero(SlugInt)
for (i, b) in enumerate(bytes)
x = (x + b*powermod(2, 8(i-1), n)) % n
end
slug(x, p)
end
slug(uuid::UUID, p::Int=4) = slug(uuid.value % nchars^p, p)
slug(sha1::SHA1, p::Int=4) = slug(sha1.bytes, p)
version_slug(uuid::UUID, sha1::SHA1) = joinpath(slug(uuid), slug(sha1))
## load path expansion: turn LOAD_PATH entries into concrete paths ##
function find_env(envs::Vector)
for env in envs
path = find_env(env)
path != nothing && return path
end
end
function find_env(env::AbstractString)
path = abspath(env)
if isdir(path)
# directory with a project file?
for name in project_names
file = abspath(path, name)
isfile_casesensitive(file) && return file
end
end
# package dir or path to project file
return path
end
function find_env(env::NamedEnv)
# look for named env in each depot
for depot in DEPOT_PATH
isdir(depot) || continue
file = nothing
for name in project_names
file = abspath(depot, "environments", env.name, name)
isfile_casesensitive(file) && return file
end
file != nothing && env.create && return file
end
end
function find_env(env::CurrentEnv, dir::AbstractString = pwd())
# look for project file in current dir and parents
home = homedir()
while true
for name in project_names
file = joinpath(dir, name)
isfile_casesensitive(file) && return file
end
# bail at home directory or top of git repo
(dir == home || ispath(joinpath(dir, ".git"))) && break
old, dir = dir, dirname(dir)
dir == old && break
end
end
find_env(env::Function) = find_env(env())
load_path() = filter(env -> env ≠ nothing, map(find_env, LOAD_PATH))
## package identification: determine unique identity of package to be loaded ##
find_package(args...) = locate_package(identify_package(args...))
struct PkgId
uuid::Union{UUID,Nothing}
name::String
PkgId(u::UUID, name::AbstractString) = new(UInt128(u) == 0 ? nothing : u, name)
PkgId(::Nothing, name::AbstractString) = new(nothing, name)
end
PkgId(name::AbstractString) = PkgId(nothing, name)
function PkgId(m::Module)
uuid = UUID(ccall(:jl_module_uuid, NTuple{2, UInt64}, (Any,), m))
name = String(nameof(m))
UInt128(uuid) == 0 && return PkgId(name)
return PkgId(uuid, name)
end
==(a::PkgId, b::PkgId) = a.uuid == b.uuid && a.name == b.name
function hash(pkg::PkgId, h::UInt)
h += 0xc9f248583a0ca36c % UInt
h = hash(pkg.uuid, h)
h = hash(pkg.name, h)
return h
end
show(io::IO, pkg::PkgId) =
print(io, pkg.name, " [", pkg.uuid === nothing ? "top-level" : pkg.uuid, "]")
function binpack(pkg::PkgId)
io = IOBuffer()
write(io, UInt8(0))
uuid = pkg.uuid
write(io, uuid === nothing ? UInt128(0) : UInt128(uuid))
write(io, pkg.name)
return String(take!(io))
end
function binunpack(s::String)
io = IOBuffer(s)
@assert read(io, UInt8) === 0x00
uuid = read(io, UInt128)
name = read(io, String)
return PkgId(UUID(uuid), name)
end
function identify_package(where::Module, name::String)::Union{Nothing,PkgId}
identify_package(PkgId(where), name)
end
function identify_package(where::PkgId, name::String)::Union{Nothing,PkgId}
where.uuid === nothing && return identify_package(name)
for env in load_path()
found_or_uuid = manifest_deps_get(env, where, name)
found_or_uuid isa UUID && return PkgId(found_or_uuid, name)
found_or_uuid && return nothing
end
return nothing
end
function identify_package(name::String)::Union{Nothing,PkgId}
for env in load_path()
found_or_uuid = project_deps_get(env, name)
found_or_uuid isa UUID && return PkgId(found_or_uuid, name)
found_or_uuid && return PkgId(name)
end
return nothing
end
function identify_package(name::String, names::String...)
pkg = identify_package(name)
pkg === nothing ? nothing :
pkg.uuid === nothing ? identify_package(names...) :
identify_package(pkg, names...)
end
function identify_package(where::PkgId, name::String, names::String...)
pkg = identify_package(where, name)
pkg === nothing ? nothing :
pkg.uuid === nothing ? identify_package(names...) :
identify_package(pkg, names...)
end
## package location: given a package identity find file to load ##
function locate_package(pkg::PkgId)::Union{Nothing,String}
if pkg.uuid === nothing
for env in load_path()
found_or_uuid = project_deps_get(env, pkg.name)
found_or_uuid isa UUID &&
return locate_package(PkgId(found_or_uuid, pkg.name))
found_or_uuid && return implicit_manifest_uuid_path(env, pkg)
end
else
for env in load_path()
path = manifest_uuid_path(env, pkg)
path != nothing && return entry_path(path, pkg.name)
end
end
end
locate_package(::Nothing) = nothing
## generic project & manifest API ##
const project_names = ("JuliaProject.toml", "Project.toml")
const manifest_names = ("JuliaManifest.toml", "Manifest.toml")
# return means
# - `false`: nothing to see here
# - `true`: `env` is an implicit environment
# - `path`: the path of an explicit project file
function env_project_file(env::String)::Union{Bool,String}
if isdir(env)
for proj in project_names
project_file = joinpath(env, proj)
isfile_casesensitive(project_file) && return project_file
end
return true
elseif basename(env) in project_names && isfile_casesensitive(env)
return env
end
return false
end
function project_deps_get(env::String, name::String)::Union{Bool,UUID}
project_file = env_project_file(env)
if project_file isa String
return explicit_project_deps_get(project_file, name)
end
project_file && implicit_project_deps_get(env, name)
end
function manifest_deps_get(env::String, where::PkgId, name::String)::Union{Bool,UUID}
project_file = env_project_file(env)
if project_file isa String
manifest_file = project_file_manifest_path(project_file)
if isfile_casesensitive(manifest_file)
return explicit_manifest_deps_get(manifest_file, where.uuid, name)
end
end
project_file && implicit_manifest_deps_get(env, where, name)
end
function manifest_uuid_path(env::String, pkg::PkgId)::Union{Nothing,String}
project_file = env_project_file(env)
if project_file isa String
manifest_file = project_file_manifest_path(project_file)
if isfile_casesensitive(manifest_file)
return explicit_manifest_uuid_path(manifest_file, pkg)
end
end
project_file ? implicit_manifest_uuid_path(env, pkg) : nothing
end
# regular expressions for scanning project & manifest files
const re_section = r"^\s*\["
const re_array_of_tables = r"^\s*\[\s*\["
const re_section_deps = r"^\s*\[\s*\"?deps\"?\s*\]\s*(?:#|$)"
const re_section_capture = r"^\s*\[\s*\[\s*\"?(\w+)\"?\s*\]\s*\]\s*(?:#|$)"
const re_subsection_deps = r"^\s*\[\s*\"?(\w+)\"?\s*\.\s*\"?deps\"?\s*\]\s*(?:#|$)"
const re_key_to_string = r"^\s*(\w+)\s*=\s*\"(.*)\"\s*(?:#|$)"
const re_uuid_to_string = r"^\s*uuid\s*=\s*\"(.*)\"\s*(?:#|$)"
const re_path_to_string = r"^\s*path\s*=\s*\"(.*)\"\s*(?:#|$)"
const re_hash_to_string = r"^\s*git-tree-sha1\s*=\s*\"(.*)\"\s*(?:#|$)"
const re_manifest_to_string = r"^\s*manifest\s*=\s*\"(.*)\"\s*(?:#|$)"
const re_deps_to_any = r"^\s*deps\s*=\s*(.*?)\s*(?:#|$)"
# find project file's top-level UUID entry (or nothing)
function project_file_uuid(project_file::String)::Union{Nothing,UUID}
open(project_file) do io
for line in eachline(io)
contains(line, re_section) && break
if (m = match(re_uuid_to_string, line)) != nothing
return UUID(m.captures[1])
end
end
end
end
# find project file's corresponding manifest file
function project_file_manifest_path(project_file::String)::Union{Nothing,String}
open(project_file) do io
dir = abspath(dirname(project_file))
for line in eachline(io)
contains(line, re_section) && break
if (m = match(re_manifest_to_string, line)) != nothing
return normpath(joinpath(dir, m.captures[1]))
end
end
local manifest_file
for mfst in manifest_names
manifest_file = joinpath(dir, mfst)
isfile_casesensitive(manifest_file) && return manifest_file
end
return manifest_file
end
end
# find `name` in a manifest file and return its UUID
function manifest_file_name_uuid(manifest_file::String, name::String, io::IO)::Union{Nothing,UUID}
uuid = name′ = nothing
for line in eachline(io)
if (m = match(re_section_capture, line)) != nothing
name′ == name && break
name′ = String(m.captures[1])
elseif (m = match(re_uuid_to_string, line)) != nothing
uuid = UUID(m.captures[1])
end
end
name′ == name ? uuid : nothing
end
# given package dir and name, find an entry point
# and project file if one exists (or nothing if not)
function entry_point_and_project_file(dir::String, name::String)::Union{Tuple{Nothing,Nothing},Tuple{String,Nothing},Tuple{String,String}}
for entry in ("", joinpath(name, "src"), joinpath("$name.jl", "src"))
path = joinpath(dir, entry, "$name.jl")
isfile_casesensitive(path) || continue
if !isempty(entry)
for proj in project_names
project_file = joinpath(dir, dirname(entry), proj)
isfile_casesensitive(project_file) || continue
return path, project_file
end
end
return path, nothing
end
return nothing, nothing
end
# given a path and a name, return the entry point
function entry_path(path::String, name::String)::Union{Nothing,String}
isfile_casesensitive(path) && return path
path = joinpath(path, "src", "$name.jl")
isfile_casesensitive(path) ? path : nothing
end
entry_path(::Nothing, name::String) = nothing
# given a project path (project directory or entry point)
# return the project file
function package_path_to_project_file(path::String)::Union{Nothing,String}
if !isdir(path)
dir = dirname(path)
basename(dir) == "src" || return nothing
path = dirname(dir)
end
for proj in project_names
project_file = joinpath(path, proj)
isfile_casesensitive(project_file) && return project_file
end
end
## explicit project & manifest API ##
# find project file deps section's `name => uuid` mapping
function explicit_project_deps_get(project_file::String, name::String)::Union{Bool,UUID}
open(project_file) do io
for line in eachline(io)
contains(line, re_section_deps) && break
end
for line in eachline(io)
contains(line, re_section) && break
(m = match(re_key_to_string, line)) == nothing && continue
m.captures[1] == name && return UUID(m.captures[2])
end
return false
end
end
# find `where` stanza and `name` in its deps and return its UUID
# - `false` means: did not find `where`
# - `true` means: found `where` but not `name` in its deps
# - `uuid` means: found `where` and `name` mapped to `uuid` in its deps
function explicit_manifest_deps_get(manifest_file::String, where::UUID, name::String)::Union{Bool,UUID}
uuid = deps = nothing
state = :other
open(manifest_file) do io
for line in eachline(io)
if contains(line, re_array_of_tables)
uuid == where && break
uuid = deps = nothing
state = :stanza
elseif state == :stanza
if (m = match(re_uuid_to_string, line)) != nothing
uuid = UUID(m.captures[1])
elseif (m = match(re_deps_to_any, line)) != nothing
deps = String(m.captures[1])
elseif contains(line, re_subsection_deps)
state = :deps
elseif contains(line, re_section)
state = :other
end
elseif state == :deps && uuid == where
if (m = match(re_key_to_string, line)) != nothing
m.captures[1] == name && return UUID(m.captures[2])
end
end
end
uuid == where || return false
deps == nothing && return true
# TODO: handle inline table syntax
if deps[1] != '[' || deps[end] != ']'
@warn "Unexpected TOML deps format:\n$deps"
return nothing
end
contains(deps, repr(name)) || return true
seekstart(io) # rewind IO handle
manifest_file_name_uuid(manifest_file, name, io)
end
end
# find `uuid` stanza, return the corresponding path
function explicit_manifest_uuid_path(manifest_file::String, pkg::PkgId)::Union{Nothing,String}
open(manifest_file) do io
uuid = name = path = hash = nothing
for line in eachline(io)
if (m = match(re_section_capture, line)) != nothing
uuid == pkg.uuid && break
name = String(m.captures[1])
path = hash = nothing
elseif (m = match(re_uuid_to_string, line)) != nothing
uuid = UUID(m.captures[1])
elseif (m = match(re_path_to_string, line)) != nothing
path = String(m.captures[1])
elseif (m = match(re_hash_to_string, line)) != nothing
hash = SHA1(m.captures[1])
end
end
uuid == pkg.uuid || return nothing
name == pkg.name || return nothing # TODO: allow a mismatch?
if path != nothing
path = normpath(abspath(dirname(manifest_file), path))
return entry_path(path, name)
end
hash == nothing && return nothing
slug = version_slug(uuid, hash)
for depot in DEPOT_PATH
path = abspath(depot, "packages", slug)
ispath(path) && return path
end
end
end
## implicit project & manifest API ##
# look for an entry point for `name`:
# - `false` means: did not find `name`
# - `true` means: found `name` without UUID
# - `uuid` means: found `name` with `uuid` in project file
function implicit_project_deps_get(dir::String, name::String)::Union{Bool,UUID}
path, project_file = entry_point_and_project_file(dir, name)
project_file == nothing && return path != nothing
uuid = project_file_uuid(project_file)
uuid == nothing || uuid
end
# look for an entry-point for `where` by name, check that UUID matches
# if there's a project file, look up `name` in its deps and return that
# if that returns a path to a project, return the UUID of that
# - `false` means: did not find `where`
# - `true` means: found `where` but not `name` in its deps
# - `uuid` means: found `where` and `name` mapped to `uuid` in its deps
function implicit_manifest_deps_get(dir::String, where::PkgId, name::String)::Union{Bool,UUID}
@assert where.uuid !== nothing
path, project_file = entry_point_and_project_file(dir, where.name)
project_file === nothing && return false
uuid = project_file_uuid(project_file)
uuid === where.uuid || return false
uuid_or_path = explicit_project_deps_get(project_file, name)
uuid_or_path === nothing && return true
uuid_or_path isa UUID && return uuid_or_path
# found `name => path`, see if we can figure out its UUID
project_file = package_path_to_project_file(uuid_or_path::String)
uuid = project_file_uuid(project_file)
uuid isa UUID ? uuid : false
end
# look for an entry-point for `pkg` and return its path if UUID matches
function implicit_manifest_uuid_path(dir::String, pkg::PkgId)::Union{Nothing,String}
path, project_file = entry_point_and_project_file(dir, pkg.name)
uuid = project_file == nothing ? nothing : project_file_uuid(project_file)
uuid == pkg.uuid ? path : nothing
end
## other code loading functionality ##
function find_source_file(path::AbstractString)
(isabspath(path) || isfile(path)) && return path
base_path = joinpath(Sys.BINDIR, DATAROOTDIR, "julia", "base", path)
return isfile(base_path) ? base_path : nothing
end
function find_all_in_cache_path(pkg::PkgId)
paths = String[]
suffix = "$(pkg.name).ji"
pkg.uuid !== nothing && (suffix = joinpath(slug(pkg.uuid), suffix))
for prefix in LOAD_CACHE_PATH
path = joinpath(prefix, suffix)
isfile_casesensitive(path) && push!(paths, path)
end
return paths
end
# these return either the array of modules loaded from the path / content given
# or an Exception that describes why it couldn't be loaded
# and it reconnects the Base.Docs.META
function _include_from_serialized(path::String, depmods::Vector{Any})
restored = ccall(:jl_restore_incremental, Any, (Cstring, Any), path, depmods)
if !isa(restored, Exception)
for M in restored::Vector{Any}
M = M::Module
if isdefined(M, Base.Docs.META)
push!(Base.Docs.modules, M)
end
if parentmodule(M) === M
register_root_module(M)
end
end
end
return restored
end
function _tryrequire_from_serialized(modkey::PkgId, build_id::UInt64, modpath::Union{Nothing, String})
if root_module_exists(modkey)
M = root_module(modkey)
if PkgId(M) == modkey && module_build_id(M) === build_id
return M
end
else
if modpath === nothing
modpath = locate_package(modkey)
modpath === nothing && return nothing
end
mod = _require_search_from_serialized(modkey, String(modpath))
if !isa(mod, Bool)
for callback in package_callbacks
invokelatest(callback, modkey)
end
for M in mod::Vector{Any}
if PkgId(M) == modkey && module_build_id(M) === build_id
return M
end
end
end
end
return nothing
end
function _require_from_serialized(path::String)
# loads a precompile cache file, ignoring stale_cachfile tests
# load all of the dependent modules first
local depmodnames
io = open(path, "r")
try
isvalid_cache_header(io) || return ArgumentError("Invalid header in cache file $path.")
depmodnames = parse_cache_header(io)[3]
isvalid_file_crc(io) || return ArgumentError("Invalid checksum in cache file $path.")
finally
close(io)
end
ndeps = length(depmodnames)
depmods = Vector{Any}(uninitialized, ndeps)
for i in 1:ndeps
modkey, build_id = depmodnames[i]
dep = _tryrequire_from_serialized(modkey, build_id, nothing)
dep === nothing && return ErrorException("Required dependency $modkey failed to load from a cache file.")
depmods[i] = dep::Module
end
# then load the file
return _include_from_serialized(path, depmods)
end
# returns `true` if require found a precompile cache for this sourcepath, but couldn't load it
# returns `false` if the module isn't known to be precompilable
# returns the set of modules restored if the cache load succeeded
function _require_search_from_serialized(pkg::PkgId, sourcepath::String)
paths = find_all_in_cache_path(pkg)
for path_to_try in paths::Vector{String}
staledeps = stale_cachefile(sourcepath, path_to_try)
if staledeps === true
continue
end
# finish loading module graph into staledeps
for i in 1:length(staledeps)
dep = staledeps[i]
dep isa Module && continue
modpath, modkey, build_id = dep::Tuple{String, PkgId, UInt64}
dep = _tryrequire_from_serialized(modkey, build_id, modpath)
if dep === nothing
@debug "Required dependency $modname failed to load from cache file for $modpath."
staledeps = true
break
end
staledeps[i] = dep::Module
end
if staledeps === true
continue
end
restored = _include_from_serialized(path_to_try, staledeps)
if isa(restored, Exception)
@debug "Deserialization checks failed while attempting to load cache from $path_to_try" exception=restored
else
return restored
end
end
return !isempty(paths)
end
# to synchronize multiple tasks trying to import/using something
const package_locks = Dict{PkgId,Condition}()
# to notify downstream consumers that a module was successfully loaded
# Callbacks take the form (mod::Base.PkgId) -> nothing.
# WARNING: This is an experimental feature and might change later, without deprecation.
const package_callbacks = Any[]
# to notify downstream consumers that a file has been included into a particular module
# Callbacks take the form (mod::Module, filename::String) -> nothing
# WARNING: This is an experimental feature and might change later, without deprecation.
const include_callbacks = Any[]
# used to optionally track dependencies when requiring a module:
const _concrete_dependencies = Pair{PkgId,UInt64}[] # these dependency versions are "set in stone", and the process should try to avoid invalidating them
const _require_dependencies = Any[] # a list of (mod, path, mtime) tuples that are the file dependencies of the module currently being precompiled
const _track_dependencies = Ref(false) # set this to true to track the list of file dependencies
function _include_dependency(mod::Module, _path::AbstractString)
prev = source_path(nothing)
if prev === nothing
path = abspath(_path)
else
path = joinpath(dirname(prev), _path)
end
if _track_dependencies[]
push!(_require_dependencies, (mod, normpath(path), mtime(path)))
end
return path, prev
end
"""
include_dependency(path::AbstractString)
In a module, declare that the file specified by `path` (relative or absolute) is a
dependency for precompilation; that is, the module will need to be recompiled if this file
changes.
This is only needed if your module depends on a file that is not used via `include`. It has
no effect outside of compilation.
"""
function include_dependency(path::AbstractString)
_include_dependency(Main, path)
return nothing
end
# We throw PrecompilableError(true) when a module wants to be precompiled but isn't,
# and PrecompilableError(false) when a module doesn't want to be precompiled but is
struct PrecompilableError <: Exception
isprecompilable::Bool
end
function show(io::IO, ex::PrecompilableError)
if ex.isprecompilable
print(io, "Declaring __precompile__(true) is only allowed in module files being imported.")
else
print(io, "Declaring __precompile__(false) is not allowed in files that are being precompiled.")
end
end
precompilableerror(ex::PrecompilableError, c) = ex.isprecompilable == c
precompilableerror(ex::WrappedException, c) = precompilableerror(ex.error, c)
precompilableerror(ex, c) = false
# Call __precompile__ at the top of a file to force it to be precompiled (true), or
# to be prevent it from being precompiled (false). __precompile__(true) is
# ignored except within "require" call.
"""
__precompile__(isprecompilable::Bool=true)
Specify whether the file calling this function is precompilable. If `isprecompilable` is
`true`, then `__precompile__` throws an exception when the file is loaded by
`using`/`import`/`require` *unless* the file is being precompiled, and in a module file it
causes the module to be automatically precompiled when it is imported. Typically,
`__precompile__()` should occur before the `module` declaration in the file.
If a module or file is *not* safely precompilable, it should call `__precompile__(false)` in
order to throw an error if Julia attempts to precompile it.
`__precompile__()` should *not* be used in a module unless all of its dependencies are also
using `__precompile__()`. Failure to do so can result in a runtime error when loading the module.
"""
function __precompile__(isprecompilable::Bool=true)
if (JLOptions().use_compiled_modules != 0 &&
isprecompilable != (0 != ccall(:jl_generating_output, Cint, ())) &&
!(isprecompilable && toplevel_load[]))
throw(PrecompilableError(isprecompilable))
end
end
# require always works in Main scope and loads files from node 1
const toplevel_load = Ref(true)
"""
require(module::Symbol)
This function is part of the implementation of `using` / `import`, if a module is not
already defined in `Main`. It can also be called directly to force reloading a module,
regardless of whether it has been loaded before (for example, when interactively developing
libraries).
Loads a source file, in the context of the `Main` module, on every active node, searching
standard locations for files. `require` is considered a top-level operation, so it sets the
current `include` path but does not use it to search for files (see help for `include`).
This function is typically used to load library code, and is implicitly called by `using` to
load packages.
When searching for files, `require` first looks for package code under `Pkg.dir()`,
then tries paths in the global array `LOAD_PATH`. `require` is case-sensitive on
all platforms, including those with case-insensitive filesystems like macOS and
Windows.
"""
function require(into::Module, mod::Symbol)
uuidkey = identify_package(into, String(mod))
uuidkey === nothing &&
throw(ArgumentError("Module $mod not found in current path.\nRun `Pkg.add(\"$mod\")` to install the $mod package."))
if _track_dependencies[]
push!(_require_dependencies, (into, binpack(uuidkey), 0.0))
end
if !root_module_exists(uuidkey)
_require(uuidkey)
# After successfully loading, notify downstream consumers
for callback in package_callbacks
invokelatest(callback, uuidkey)
end
end
return root_module(uuidkey)
end
const loaded_modules = Dict{PkgId,Module}()
const module_keys = IdDict{Module,PkgId}() # the reverse
function register_root_module(m::Module)
key = PkgId(m)
if haskey(loaded_modules, key)
oldm = loaded_modules[key]
if oldm !== m
@warn "Replacing module `$(key.name)`"
end
end
loaded_modules[key] = m
module_keys[m] = key
nothing
end
register_root_module(Core)
register_root_module(Base)
register_root_module(Main)
is_root_module(m::Module) = haskey(module_keys, m)
root_module_key(m::Module) = module_keys[m]
# This is used as the current module when loading top-level modules.
# It has the special behavior that modules evaluated in it get added
# to the loaded_modules table instead of getting bindings.
baremodule __toplevel__
using Base
end
# get a top-level Module from the given key
root_module(key::PkgId) = loaded_modules[key]
root_module(where::Module, name::Symbol) =
root_module(identify_package(where, String(name)))
root_module_exists(key::PkgId) = haskey(loaded_modules, key)
loaded_modules_array() = collect(values(loaded_modules))
function unreference_module(key::PkgId)
if haskey(loaded_modules, key)
m = pop!(loaded_modules, key)
# need to ensure all modules are GC rooted; will still be referenced
# in module_keys
end
end
function _require(pkg::PkgId)
# handle recursive calls to require
loading = get(package_locks, pkg, false)
if loading !== false
# load already in progress for this module
wait(loading)
return
end
package_locks[pkg] = Condition()
last = toplevel_load[]
try
toplevel_load[] = false
# perform the search operation to select the module file require intends to load
name = pkg.name
path = locate_package(pkg)
if path === nothing
throw(ArgumentError("Module $name not found in current path.\nRun `Pkg.add(\"$name\")` to install the $name package."))
end
# attempt to load the module file via the precompile cache locations
doneprecompile = false
if JLOptions().use_compiled_modules != 0
doneprecompile = _require_search_from_serialized(pkg, path)
if !isa(doneprecompile, Bool)
return
end
end
# if the module being required was supposed to have a particular version
# but it was not handled by the precompile loader, complain
for (concrete_pkg, concrete_build_id) in _concrete_dependencies
if pkg == concrete_pkg
@warn """Module $name with build ID $concrete_build_id is missing from the cache.
This may mean module $name does not support precompilation but is imported by a module that does."""
if JLOptions().incremental != 0
# during incremental precompilation, this should be fail-fast
throw(PrecompilableError(false))
end
end
end
if doneprecompile === true || JLOptions().incremental != 0
# spawn off a new incremental pre-compile task for recursive `require` calls
# or if the require search declared it was pre-compiled before (and therefore is expected to still be pre-compilable)
cachefile = compilecache(pkg)
m = _require_from_serialized(cachefile)
if isa(m, Exception)
@warn "The call to compilecache failed to create a usable precompiled cache file for module $name" exception=m
# fall-through, TODO: disable __precompile__(true) error so that the normal include will succeed
else
return
end
end
# just load the file normally via include
# for unknown dependencies
uuid = pkg.uuid
uuid = (uuid === nothing ? (UInt64(0), UInt64(0)) : convert(NTuple{2, UInt64}, uuid))
old_uuid = ccall(:jl_module_uuid, NTuple{2, UInt64}, (Any,), __toplevel__)
if uuid !== old_uuid
ccall(:jl_set_module_uuid, Cvoid, (Any, NTuple{2, UInt64}), __toplevel__, uuid)
end
try
include_relative(__toplevel__, path)
return
catch ex
if uuid !== old_uuid
ccall(:jl_set_module_uuid, Cvoid, (Any, NTuple{2, UInt64}), __toplevel__, old_uuid)
end
if doneprecompile === true || JLOptions().use_compiled_modules == 0 || !precompilableerror(ex, true)
rethrow() # rethrow non-precompilable=true errors
end
# the file requested `__precompile__`, so try to build a cache file and use that
cachefile = compilecache(pkg)
m = _require_from_serialized(cachefile)
if isa(m, Exception)
@warn """Module `$name` declares `__precompile__(true)` but `require` failed
to create a usable precompiled cache file""" exception=m
# TODO: disable __precompile__(true) error and do normal include instead of error
error("Module $name declares __precompile__(true) but require failed to create a usable precompiled cache file.")
end
end
if uuid !== old_uuid
ccall(:jl_set_module_uuid, Cvoid, (Any, NTuple{2, UInt64}), __toplevel__, old_uuid)
end
finally
toplevel_load[] = last
loading = pop!(package_locks, pkg)
notify(loading, all=true)
end
nothing
end
# relative-path load
"""
include_string(m::Module, code::AbstractString, filename::AbstractString="string")
Like `include`, except reads code from the given string rather than from a file.
"""
include_string(m::Module, txt::String, fname::String) =
ccall(:jl_load_file_string, Any, (Ptr{UInt8}, Csize_t, Cstring, Any),
txt, sizeof(txt), fname, m)
include_string(m::Module, txt::AbstractString, fname::AbstractString="string") =
include_string(m, String(txt), String(fname))
function source_path(default::Union{AbstractString,Nothing}="")
t = current_task()
while true
s = t.storage
if s !== nothing && haskey(s, :SOURCE_PATH)
return s[:SOURCE_PATH]
end
if t === t.parent
return default
end
t = t.parent
end
end
function source_dir()
p = source_path(nothing)
p === nothing ? pwd() : dirname(p)
end