-
Notifications
You must be signed in to change notification settings - Fork 535
Expand file tree
/
Copy pathpy_import.js
More file actions
1498 lines (1394 loc) · 51.7 KB
/
Copy pathpy_import.js
File metadata and controls
1498 lines (1394 loc) · 51.7 KB
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
// import modules
"use strict";
(function($B){
var _b_ = $B.builtins,
_window = globalThis
// var dbUpdater = new Worker($B.brython_path + 'indexedDBupdater.js')
// Class for modules
var Module = $B.module = $B.make_class("module",
function(name, doc, $package){
return {
$tp_class: Module,
__builtins__: _b_.__builtins__,
__name__: name,
__doc__: doc || _b_.None,
__package__: $package || _b_.None
}
}
)
Module.__dir__ = function(self){
if(self.__dir__){
return $B.$call(self.__dir__)()
}
var res = []
for(var key in self){
if(key.startsWith('$') || key == '__class__'){
continue
}
res[res.length] = key
}
return $B.$list(res.sort())
}
Module.__new__ = function(cls, name, doc, $package){
return {
__class__: cls,
__builtins__: _b_.__builtins__,
__name__: name,
__doc__: doc || _b_.None,
__package__: $package || _b_.None
}
}
Module.__repr__ = Module.__str__ = function(self){
var res = "<module " + self.__name__
res += self.__file__ === undefined ? " (built-in)" :
' at ' + self.__file__
return res + ">"
}
Module.__setattr__ = function(self, attr, value){
if(self.__name__ == '__builtins__'){
// set a Python builtin
$B.builtins[attr] = value
}else if(self.__name__ == 'builtins'){
_b_[attr] = value
}else{
self[attr] = value
}
}
$B.set_func_names(Module, "builtins")
$B.make_import_paths = function(filename){
// Set $B.meta_path, the list of finders to use for imports
//
// The original list in $B.meta_path is made of 3 finders defined in
// py_import.js :
// - finder_VFS : in the Virtual File System : a Javascript object with
// source of the standard distribution
// - finder_static_stlib : use the script stdlib_path.js to identify the
// packages and modules in the standard distribution
// - finder_path : search module at different urls
var filepath = $B.script_domain ? $B.script_domain + '/' + filename : filename
var elts = filepath.split('/')
elts.pop()
var script_dir = elts.join('/'),
path = [$B.brython_path + 'Lib',
$B.brython_path + 'libs',
script_dir,
$B.brython_path + 'Lib/site-packages']
var meta_path = [],
path_hooks = []
// $B.use_VFS is set to true if the script brython_stdlib.js or
// brython_modules.js has been loaded in the page. In this case we use the
// Virtual File System (VFS)
if($B.use_VFS){
meta_path.push($B.finders.VFS)
}
var static_stdlib_import = $B.get_option_from_filename('static_stdlib_import',
filename)
if(static_stdlib_import !== false && $B.protocol != "file"){
// Add finder using static paths
meta_path.push($B.finders.stdlib_static)
// Remove /Lib and /libs in sys.path :
// if we use the static list and the module
// was not find in it, it's no use searching twice in the same place
if(path.length > 3) {
path.shift()
path.shift()
}
}
// If option "pythonpath" is specified, use it instead of the current
// script directory
var pythonpath = $B.get_option_from_filename('pythonpath', filename)
if(pythonpath){
// replace script_dir by paths in pythonpath
var ix = path.indexOf(script_dir)
if(ix === -1){
console.log('bizarre, script_dir', script_dir,
'not in path', path)
}else{
var fullpaths = []
for(var p of pythonpath){
if(p == '.'){
fullpaths.push(script_dir)
}else if(p.startsWith('/')){
// issue 2428
fullpaths.push($B.script_domain + p)
}else if(p.split('://')[0].startsWith('http')){
// absolute path, cf. issue 2480
fullpaths.push(p)
}else if(! p.startsWith($B.script_domain)){
fullpaths.push(script_dir + '/' + p)
}else{
fullpaths.push(p)
}
}
path.splice(ix, 1, ...fullpaths)
}
}
// Use the defaut finder using sys.path if protocol is not file://
if($B.protocol !== "file"){
meta_path.push($B.finders.path)
path_hooks.push($B.url_hook)
}
$B.import_info[filename] = {meta_path, path_hooks, path}
}
function $download_module(mod, url){
var xhr = new XMLHttpRequest(),
fake_qs = "?v=" + (new Date().getTime()),
res = null,
mod_name = mod.__name__
if($B.get_option('cache')){
xhr.open("GET", url, false)
}else{
xhr.open("GET", url + fake_qs, false)
}
var timer = _window.setTimeout(function(){
xhr.abort()
}, 5000)
xhr.send()
if($B.$CORS){
if(xhr.status == 200 || xhr.status == 0){
res = xhr.responseText
}else{
res = _b_.ModuleNotFoundError.$factory("No module named '" +
mod_name + "'")
}
}else{
if(xhr.readyState == 4){
if(xhr.status == 200){
res = xhr.responseText
mod.$last_modified =
xhr.getResponseHeader("Last-Modified")
}else{
// don't throw an exception here, it will not be caught
// (issue #30)
console.info("Trying to import " + mod_name +
", not found at url " + url)
res = _b_.ModuleNotFoundError.$factory("No module named '" +
mod_name + "'")
}
}
}
_window.clearTimeout(timer)
// sometimes chrome doesn't set res correctly, so if res == null,
// assume no module found
if(res == null){
throw _b_.ModuleNotFoundError.$factory("No module named '" +
mod_name + "' (res is null)")
}
if(res.constructor === Error){throw res} // module not found
return res
}
$B.$download_module = $download_module
$B.addToImported = function(name, modobj){
if($B.imported[name]){
for(var attr in $B.imported[name]){
if(! modobj.hasOwnProperty(attr)){
modobj[attr] = $B.imported[name][attr]
}
}
}
$B.imported[name] = modobj
if(modobj === undefined){
throw _b_.ImportError.$factory('imported not set by module')
}
modobj.__class__ = Module
modobj.__name__ = name
for(var attr in modobj){
if(typeof modobj[attr] == "function" && ! modobj[attr].$infos){
if(modobj[attr] === _b_.iter){
console.log('set iter', modobj, name)
}
modobj[attr].$infos = {
__module__: name,
__name__: attr,
__qualname__: attr
}
modobj[attr].$in_js_module = true
}else if($B.$isinstance(modobj[attr], _b_.type) &&
! modobj[attr].hasOwnProperty('__module__')){
modobj[attr].__module__ = name
}
}
}
function run_js(module_contents, path, _module){
try{
new Function(module_contents)()
}catch(err){
throw $B.exception(err)
}
var modobj = $B.imported[_module.__name__]
if(modobj === undefined){
throw _b_.ImportError.$factory('imported not set by module')
}
modobj.__class__ = Module
modobj.__name__ = _module.__name__
for(var attr in modobj){
if(typeof modobj[attr] == "function" && ! modobj[attr].$infos){
modobj[attr].$infos = {
__module__: _module.__name__,
__name__: attr,
__qualname__: attr
}
modobj[attr].$in_js_module = true
}else if($B.$isinstance(modobj[attr], _b_.type) &&
! modobj[attr].hasOwnProperty('__module__')){
modobj[attr].__module__ = _module.__name__
}
}
return true
}
function run_py(module_contents, path, module, compiled) {
// set file cache for path ; used in built-in function open()
var filename = module.__file__
$B.file_cache[filename] = module_contents
$B.url2name[filename] = module.__name__
var root,
js,
mod_name = module.__name__, // might be modified inside module, eg _pydecimal
src
if(! compiled){
src = {
src: module_contents,
filename,
imported: true
}
try{
root = $B.py2js(src, module,
module.__name__, $B.builtins_scope)
}catch(err){
err.$frame_obj = $B.frame_obj
if($B.get_option('debug', err) > 1){
console.log('error in imported module', module)
console.log('stack', $B.make_frames_stack(err.$frame_obj))
}
throw err
}
}
try{
js = compiled ? module_contents : root.to_js()
if($B.get_option('debug') == 10){
console.log("code for module " + module.__name__)
console.log($B.format_indent(js, 0))
}
src = js
js = "var $module = (function(){\n" + js
var prefix = 'locals_'
js += 'return ' + prefix
js += module.__name__.replace(/\./g, "_") + "})(__BRYTHON__)\n" +
"return $module"
var module_id = prefix + module.__name__.replace(/\./g, '_')
//console.log(module.__name__, js.length)
//console.log(js)
var mod = (new Function(module_id, js))(module)
}catch(err){
err.$frame_obj = err.$frame_obj || $B.frame_obj
if($B.get_option('debug', err) > 2){
console.log(err + " for module " + module.__name__)
console.log("module", module)
console.log(root)
// console.log(err)
if($B.get_option('debug', err) > 1){
console.log($B.format_indent(js, 0))
}
for(let attr in err){
console.log(attr, err[attr])
}
console.log("message: " + err.$message)
console.log("filename: " + err.fileName)
console.log("linenum: " + err.lineNumber)
console.log(js.split('\n').slice(err.lineNumber - 3, err.lineNumber + 3).join('\n'))
console.log(err.stack)
}
throw err
}
var imports = Object.keys(root.imports).join(",")
try{
// Apply side-effects upon input module object
for(let attr in mod){
module[attr] = mod[attr]
}
module.__initialized__ = true
// $B.imported[mod.__name__] must be the module object, so that
// setting attributes in a program affects the module namespace
// See issue #7
$B.imported[module.__name__] = module
return {
content: src,
name: mod_name,
imports,
is_package: module.$is_package,
path,
timestamp: $B.timestamp,
source_ts: module.__spec__.loader_state.timestamp
}
}catch(err){
console.log("" + err + " " + " for module " + module.__name__)
for(let attr in err){
console.log(attr + " " + err[attr])
}
if($B.get_option('debug') > 0){
console.log("line info " + __BRYTHON__.line_info)
}
throw err
}
}
$B.run_py = run_py // used in importlib.basehook
$B.run_js = run_js
var ModuleSpec = $B.make_class("ModuleSpec",
function(fields) {
fields.__class__ = ModuleSpec
fields.__dict__ = $B.empty_dict()
return fields
}
)
ModuleSpec.__str__ = ModuleSpec.__repr__ = function(self){
var res = `ModuleSpec(name='${self.name}', ` +
`loader=${_b_.str.$factory(self.loader)}, ` +
`origin='${self.origin}'`
if(self.submodule_search_locations !== _b_.None){
res += `, submodule_search_locations=` +
`${_b_.str.$factory(self.submodule_search_locations)}`
}
return res + ')'
}
$B.set_func_names(ModuleSpec, "builtins")
function parent_package(mod_name) {
// Return a module's parent package
var parts = mod_name.split(".")
parts.pop()
return parts.join(".")
}
// Finder for a Virtual File System.
// Used if brython_stdlib.js or brython_modules.js or a "Brython
// package" is loaded in the page.
var VFSFinder = $B.make_class("VFSFinder",
function(){
return {
__class__: VFSFinder
}
}
)
VFSFinder.find_spec = function(cls, fullname){
var stored,
is_package,
timestamp
if(!$B.use_VFS){return _b_.None}
stored = $B.VFS[fullname]
if(stored === undefined){return _b_.None}
is_package = stored[3] || false
timestamp = stored.timestamp
if(stored){
var is_builtin = $B.builtin_module_names.indexOf(fullname) > -1
return ModuleSpec.$factory({
name : fullname,
loader: VFSLoader.$factory(),
// FIXME : Better origin string.
origin : is_builtin? "built-in" : "brython_stdlib",
// FIXME: Namespace packages ?
submodule_search_locations: is_package? $B.$list([]) : _b_.None,
loader_state: {
stored: stored,
timestamp:timestamp
},
// FIXME : Where exactly compiled module is stored ?
cached: _b_.None,
parent: is_package? fullname : parent_package(fullname),
has_location: _b_.False
})
}
}
$B.set_func_names(VFSFinder, "<import>")
for(let method in VFSFinder){
if(typeof VFSFinder[method] == "function"){
VFSFinder[method] = _b_.classmethod.$factory(
VFSFinder[method])
}
}
// Loader for VFS modules
const VFSLoader = $B.make_class("VFSLoader",
function(){
return {
__class__: VFSLoader
}
}
)
VFSLoader.create_module = function(){
// Fallback to default module creation
return _b_.None
}
VFSLoader.exec_module = function(self, modobj){
// Besides module exection, handles the storage of the module in the
// indexedBD cache
var stored = modobj.__spec__.loader_state.stored,
timestamp = modobj.__spec__.loader_state.timestamp
var ext = stored[0],
module_contents = stored[1],
imports = stored[2]
modobj.$is_package = stored[3] || false
var path = "VFS." + modobj.__name__
path += modobj.$is_package ? "/__init__.py" : ext
modobj.__file__ = path
$B.file_cache[modobj.__file__] = $B.VFS[modobj.__name__][1]
$B.url2name[modobj.__file__] = modobj.__name__
if(ext == '.js'){
run_js(module_contents, modobj.__path__, modobj)
}else if($B.precompiled.hasOwnProperty(modobj.__name__)){
if($B.get_option('debug') > 1){
console.info("load", modobj.__name__, "from precompiled")
}
var parts = modobj.__name__.split(".")
for(var i = 0; i < parts.length; i++){
var parent = parts.slice(0, i + 1).join(".")
if($B.imported.hasOwnProperty(parent) &&
$B.imported[parent].__initialized__){
continue
}
// Initialise $B.imported[parent]
var mod_js = $B.precompiled[parent],
is_package = modobj.$is_package
if(mod_js === undefined){
// Might be the case if the code in package __init__.py
// imports a submodule : the parent of the submodule is not
// yet in precompiled
continue
}
if(Array.isArray(mod_js)){
mod_js = mod_js[0]
}
var mod = $B.imported[parent] = Module.$factory(parent,
undefined, is_package)
mod.__initialized__ = true
mod.__spec__ = modobj.__spec__
if(is_package){
mod.__path__ = "<stdlib>"
mod.__package__ = parent
mod.$is_package = true
}else{
let elts = parent.split(".")
elts.pop()
mod.__package__ = elts.join(".")
}
mod.__file__ = path
try{
var parent_id = parent.replace(/\./g, "_"),
prefix = 'locals_'
mod_js += "return " + prefix + parent_id
var $module = new Function(prefix + parent_id, mod_js)(
mod)
}catch(err){
if($B.get_option('debug') > 1){
console.log('error in module', mod)
console.log(err)
for(var k in err){console.log(k, err[k])}
console.log(Object.keys($B.imported))
console.log(modobj, "mod_js", mod_js)
}
throw err
}
for(var attr in $module){
mod[attr] = $module[attr]
}
$module.__file__ = path
if(i > 0){
// Set attribute of parent module
$B.builtins.setattr(
$B.imported[parts.slice(0, i).join(".")],
parts[i], $module)
}
}
return $module
}else{
var mod_name = modobj.__name__
if($B.get_option('debug') > 1){
console.log("run Python code from VFS", mod_name)
}
var path = $B.brython_path + '/' + modobj.__file__
var record = run_py(module_contents, path, modobj)
record.imports = imports.join(',')
record.is_package = modobj.$is_package
record.timestamp = $B.timestamp
record.source_ts = timestamp
$B.precompiled[mod_name] = record.is_package ? [record.content] :
record.content
let elts = mod_name.split(".")
if(elts.length > 1){
elts.pop()
}
if($B.get_page_option('indexeddb') && $B.indexedDB &&
$B.idb_name){
// Store the compiled Javascript in indexedDB cache
// $B.idb_name may not be defined if we are in a web worker
// and the main script is run without a VFS (cf. issue #1202)
var idb_cx = indexedDB.open($B.idb_name)
idb_cx.onsuccess = function(evt){
var db = evt.target.result,
tx = db.transaction("modules", "readwrite"),
store = tx.objectStore("modules"),
request = store.put(record)
request.onsuccess = function(){
if($B.get_option('debug') > 1){
console.info(modobj.__name__, "stored in db")
}
}
request.onerror = function(){
console.info("could not store " + modobj.__name__)
}
}
}
}
}
$B.set_func_names(VFSLoader, "builtins")
// Finder for modules in the standard library when brython_stdlib.js is
// not included in the page.
var StdlibStaticFinder = $B.make_class("StdlibStaticFinder",
function(){
return {
__class__: StdlibStaticFinder
}
}
)
StdlibStaticFinder.find_spec = function(self, fullname){
// find_spec() relies on $B.stdlib, a precompiled list of the existing
// modules in subdirectories Lib and libs below the directory where
// brython.js stands. This list is in file stdlib_paths.js.
if($B.stdlib && $B.get_option('static_stdlib_import')){
var address = $B.stdlib[fullname]
if(address === undefined){
var elts = fullname.split(".")
if(elts.length > 1){
elts.pop()
var $package = $B.stdlib[elts.join(".")]
if($package && $package[1]){
address = ["py"]
}
}
}
if(address !== undefined){
var ext = address[0],
is_pkg = address[1] !== undefined,
path = $B.brython_path +
((ext == "py")? "Lib/" : "libs/") +
fullname.replace(/\./g, "/"),
metadata = {
ext: ext,
is_package: is_pkg,
path: path + (is_pkg? "/__init__.py" :
((ext == "py")? ".py" : ".js")),
address: address
},
_module = Module.$factory(fullname)
metadata.code = $download_module(_module, metadata.path)
var res = ModuleSpec.$factory({
name : fullname,
loader: PathLoader.$factory(),
// FIXME : Better origin string.
origin : metadata.path,
submodule_search_locations: is_pkg? $B.$list([path]) : _b_.None,
loader_state: metadata,
// FIXME : Where exactly compiled module is stored ?
cached: _b_.None,
parent: is_pkg ? fullname : parent_package(fullname),
has_location: _b_.True
})
return res
}
}
return _b_.None
}
$B.set_func_names(StdlibStaticFinder, "<import>")
for(let method in StdlibStaticFinder){
if(typeof StdlibStaticFinder[method] == "function"){
StdlibStaticFinder[method] = _b_.classmethod.$factory(
StdlibStaticFinder[method])
}
}
StdlibStaticFinder.$factory = function (){
return {__class__: StdlibStaticFinder}
}
// Finder for modules in a list of directories.
// By default, this list has one element, the directory of the current script.
// It can be extended with the option "python_path" passed to brython().
var PathFinder = $B.make_class("PathFinder",
function(){
return {
__class__: PathFinder
}
}
)
PathFinder.find_spec = function(cls, fullname, path){
if($B.VFS && $B.VFS[fullname]){
// If current module is in VFS (ie standard library) it's
// pointless to search in other locations
return _b_.None
}
if($B.is_none(path)){
// [Import spec] Top-level import , use sys.path
path = get_info('path')
}
for(var i = 0, li = path.length; i < li; ++i){
var path_entry = path[i]
if(path_entry[path_entry.length - 1] != "/"){
path_entry += "/"
}
// Try path hooks cache first
var finder = $B.path_importer_cache[path_entry]
if(finder === undefined){
// Use path hooks, a list of callables that return finders.
// By default, the only path hook is function url_hook below,
// which returns PathEntryFinder.
var path_hooks = get_info('path_hooks')
for(var j = 0, lj = path_hooks.length; j < lj; ++j){
var hook = path_hooks[j]
try{
finder = $B.$call(hook)(path_entry)
$B.path_importer_cache[path_entry] = finder
break
}catch(e){
if(e.__class__ !== _b_.ImportError){
throw e
}
}
}
}
// Skip this path entry if finder turns out to be None
if($B.is_none(finder)){
continue
}
// If a finder was found with the path hooks, call its method
// find_spec() to return a ModuleSpec or None.
var find_spec = $B.$getattr(finder, "find_spec"),
spec = $B.$call(find_spec)(fullname)
if(!$B.is_none(spec)){
return spec
}
}
return _b_.None
}
$B.set_func_names(PathFinder, "<import>")
for(let method in PathFinder){
if(typeof PathFinder[method] == "function"){
PathFinder[method] = _b_.classmethod.$factory(
PathFinder[method])
}
}
// Find modules deployed in a hierarchy under a given base URL
var PathEntryFinder = $B.make_class("PathEntryFinder",
function(path_entry, hint){
return {
__class__: PathEntryFinder,
path_entry: path_entry,
hint: hint
}
}
)
PathEntryFinder.find_spec = function(self, fullname){
// Search a module at different locations.
// self has an attribute "path_entry" set to the directory where
// modules should be searched.
// The finder executes Ajax calls at urls <path_entry>/<fullname>.py
// and <path_entry>/<fullname>/__init__.py
var loader_data = {},
notfound = true,
hint = self.hint,
base_path = self.path_entry + fullname.match(/[^.]+$/g)[0],
modpaths = [],
py_ext = $B.get_option('python_extension') // defaults to .py (issue #1748)
var tryall = hint === undefined
if(tryall || hint == 'py'){
// either py or undefined , try py code
modpaths = modpaths.concat([[base_path + py_ext, "py", false],
[base_path + "/__init__" + py_ext, "py", true]])
}
for(var j = 0; notfound && j < modpaths.length; ++j){
try{
var file_info = modpaths[j],
module = {__name__:fullname, $is_package: false}
loader_data.code = $download_module(module, file_info[0],
undefined)
notfound = false
loader_data.ext = file_info[1]
loader_data.is_package = file_info[2]
loader_data.timestamp = Date.parse(module.$last_modified)
if(hint === undefined){
self.hint = file_info[1]
// Top-level import
$B.path_importer_cache[self.path_entry] = self
}
if (loader_data.is_package) {
// Populate cache in advance to speed up submodule imports
$B.path_importer_cache[base_path + '/'] =
$B.$call(url_hook)(base_path + '/', self.hint)
}
loader_data.path = file_info[0]
}catch(err){
if(err.__class__ !== _b_.ModuleNotFoundError){
throw err
}
}
}
if(!notfound){
return ModuleSpec.$factory({
name : fullname,
loader: PathLoader.$factory(),
origin : loader_data.path,
// FIXME: Namespace packages ?
submodule_search_locations: loader_data.is_package?
$B.$list([base_path]): _b_.None,
loader_state: loader_data,
// FIXME : Where exactly compiled module is stored ?
cached: _b_.None,
parent: loader_data.is_package? fullname :
parent_package(fullname),
has_location: _b_.True})
}
return _b_.None
}
$B.set_func_names(PathEntryFinder, "builtins")
// Loader for modules or packages found by StdlibStaticFinder or PathFinder
var PathLoader = $B.make_class("PathLoader",
function(){
return {
__class__: PathLoader
}
}
)
PathLoader.create_module = function(){
// Fallback to default module creation
return _b_.None
}
PathLoader.exec_module = function(self, module){
// The finder (StdlibStaticFinder, or PathFinder through an import hook)
// has set the attributes "code" (the source code), "ext" (file
// extension : "py" or "js"), "path" (the module url) and "is_package" to
// the attribute "loader_state" of the module spec.
var metadata = module.__spec__.loader_state
module.$is_package = metadata.is_package
if(metadata.ext == "py"){
run_py(metadata.code, metadata.path, module)
}else{
run_js(metadata.code, metadata.path, module)
}
}
var url_hook = $B.url_hook = function(path_entry){
// path hook: a function that returns a path entry finder for the
// specified path
path_entry = path_entry.endsWith("/") ? path_entry : path_entry + "/"
return PathEntryFinder.$factory(path_entry)
}
function get_info(info){
var filename = $B.get_filename(),
import_info = $B.import_info[filename]
if(import_info === undefined && info == 'meta_path'){
$B.make_import_paths(filename)
}
return $B.import_info[filename][info]
}
function import_engine(mod_name, _path, from_stdlib){
/*
Main import engine. Uses finders in sys.meta_math.
sys.meta_path is built in function brython(), based on the options
passed to this function.
The available meta paths are :
- VFSFinder : search in the Virtual File System ; used if
brython_stdlib.js or brython_modules.js was loaded in the page
- StdlibStaticFinder : search modules of the stdlib by Ajax calls to
a url stored in a static JS object stored in stdlib_paths.js. This
meta path is used by defaut and disabled if option
static_stdlib_import is set to false
- PathFinder : search modules by Ajax calls to a list of locations
(current directory, site-packages). The search is made on the module
name and if not found on module_name/__init__.py in case the module
is a package
If the protocol is file:, StdlibStaticFinder and PathFinder are not
in sys.meta_path (Ajax calls are not supported in this case)
For each finder, run its method find_spec(mod_name, _path)
If the method returns a ModuleSpec instance, get the loader set as
the attribute "loader" of the spec, run its methods create_module(spec)
and exec_module(module).
If everything is ok, set sys.modules[mod_name] to the module object
and return it.
If no spec was found, raise ModuleNotFoundError.
If one of the methods raise an exception, raise it.
*/
var meta_path = get_info('meta_path').slice(),
_sys_modules = $B.imported,
_loader,
spec
if(from_stdlib){
// When importing from a module in the standard library, remove
// finder_path from the finders : the module can't be in the current
// directory.
var path_ix = meta_path.indexOf($B.finders["path"])
if(path_ix > -1){
meta_path.splice(path_ix, 1)
}
}
for(var i = 0, len = meta_path.length; i < len; i++){
var _finder = meta_path[i],
find_spec = $B.$getattr(_finder, "find_spec", _b_.None)
if(find_spec == _b_.None){
// If find_spec is not defined for the meta path, try the legacy
// method find_module()
var find_module = $B.$getattr(_finder, "find_module", _b_.None)
if(find_module !== _b_.None){
_loader = find_module(mod_name, _path)
if(_loader !== _b_.None){
// The loader has a method load_module()
var load_module = $B.$getattr(_loader, "load_module"),
module = $B.$call(load_module)(mod_name)
_sys_modules[mod_name] = module
return module
}
}
}else{
spec = find_spec(mod_name, _path)
if(!$B.is_none(spec)){
module = $B.imported[spec.name]
if(module !== undefined){
// If module of same name is already in imports, return it
return _sys_modules[spec.name] = module
}
_loader = $B.$getattr(spec, "loader", _b_.None)
break
}
}
}
if(_loader === undefined){
// No import spec found
var message = mod_name
if($B.protocol == "file"){
message += " (warning: cannot import local files with protocol 'file')"
}
var exc = _b_.ModuleNotFoundError.$factory(message)
exc.name = mod_name
throw exc
}
// Import spec represents a match
if($B.is_none(module)){
if(spec === _b_.None){
throw _b_.ModuleNotFoundError.$factory(mod_name)
}
var _spec_name = $B.$getattr(spec, "name")
// Create module object
if(!$B.is_none(_loader)){
var create_module = $B.$getattr(_loader, "create_module", _b_.None)
if(!$B.is_none(create_module)){
module = $B.$call(create_module)(spec)
}
}
if(module === undefined){throw _b_.ImportError.$factory(mod_name)}
if($B.is_none(module)){
// FIXME : Initialize __doc__ and __package__
module = $B.module.$factory(mod_name)
}
}
module.__name__ = _spec_name
module.__loader__ = _loader
module.__package__ = $B.$getattr(spec, "parent", "")
module.__spec__ = spec
var locs = $B.$getattr(spec, "submodule_search_locations")
// Brython-specific var
if(module.$is_package = !$B.is_none(locs)){
module.__path__ = locs
}
if($B.$getattr(spec, "has_location")){
module.__file__ = $B.$getattr(spec, "origin")
}
var cached = $B.$getattr(spec, "cached")
if(! $B.is_none(cached)){
module.__cached__ = cached
}
if($B.is_none(_loader)){
if(!$B.is_none(locs)){
_sys_modules[_spec_name] = module
}else{
throw _b_.ImportError.$factory(mod_name)
}
}else{
var exec_module = $B.$getattr(_loader, "exec_module", _b_.None)
if($B.is_none(exec_module)){
// FIXME : Remove !!! Backwards compat in CPython
module = $B.$getattr(_loader, "load_module")(_spec_name)
}else{
_sys_modules[_spec_name] = module
try{
exec_module(module)
}catch(e){
delete _sys_modules[_spec_name]
throw e
}
}
}
return _sys_modules[_spec_name]
}