forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImporter.cs
More file actions
933 lines (794 loc) · 40.4 KB
/
Copy pathImporter.cs
File metadata and controls
933 lines (794 loc) · 40.4 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Importer class - used for importing modules. Used by Ops and __builtin__
/// Singleton living on Python engine.
/// </summary>
public static class Importer {
internal const string ModuleReloadMethod = "PerformModuleReload";
#region Internal API Surface
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module.
/// </summary>
public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
if (level < 0) throw new ArgumentException("level must be >= 0", nameof(level));
return LightExceptions.CheckAndThrow(ImportLightThrow(context, fullName, from, level));
}
/// <summary>
/// Gateway into importing ... called from Ops. Performs the initial import of
/// a module and returns the module. This version returns light exceptions instead of throwing.
/// </summary>
[LightThrowing]
internal static object ImportLightThrow(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) {
Debug.Assert(level >= 0);
PythonContext pc = context.LanguageContext;
var site = pc.ImportSite;
return site.Target(
site,
context,
FindImportFunction(context),
fullName,
Builtin.globals(context),
context.Dict,
from,
level
);
}
/// <summary>
/// Gateway into importing ... called from Ops. This is called after
/// importing the module and is used to return individual items from
/// the module. The outer modules dictionary is then updated with the
/// result.
/// </summary>
public static object ImportFrom(CodeContext/*!*/ context, object from, string name) {
if (from is PythonModule scope) {
object ret;
if (scope.GetType() == typeof(PythonModule)) {
if (scope.__dict__.TryGetValue(name, out ret)) {
return ret;
}
} else {
// subclass of module, it could have overridden __getattr__ or __getattribute__
if (PythonOps.TryGetBoundAttr(context, scope, name, out ret)) {
return ret;
}
}
if (scope.__dict__._storage.TryGetPath(out object path)) {
if (path is PythonList listPath) {
return ImportNestedModule(context, scope, new ArraySegment<string>(new[] { name }), listPath, scope.GetName());
}
if (path is string stringPath) {
return ImportNestedModule(context, scope, new ArraySegment<string>(new[] { name }), PythonList.FromArrayNoCopy(stringPath), scope.GetName());
}
}
} else if (from is PythonType pt) {
if (pt.TryResolveSlot(context, name, out PythonTypeSlot pts) &&
pts.TryGetValue(context, null, pt, out object res)) {
return res;
}
} else if (from is NamespaceTracker nt) {
object res = NamespaceTrackerOps.GetCustomMember(context, nt, name);
if (res != OperationFailed.Value) {
return res;
}
} else {
// This is too lax, for example it allows from module.class import member
if (PythonOps.TryGetBoundAttr(context, from, name, out object ret)) {
return ret;
}
}
throw PythonOps.ImportError("Cannot import name {0}", name);
}
private static object ImportModuleFrom(CodeContext/*!*/ context, object from, ArraySegment<string> parts, object root) {
if (from is PythonModule scope) {
if (scope.__dict__._storage.TryGetPath(out object path) || DynamicHelpers.GetPythonType(scope).TryGetMember(context, scope, "__path__", out path)) {
if (path is PythonList listPath) {
return ImportNestedModule(context, scope, parts, listPath, (root as PythonModule)?.GetName());
}
if (path is string stringPath) {
return ImportNestedModule(context, scope, parts, PythonList.FromArrayNoCopy(stringPath), (root as PythonModule)?.GetName());
}
}
}
string name = parts.Array[parts.Offset + parts.Count - 1];
if (from is NamespaceTracker ns) {
if (ns.TryGetValue(name, out object val)) {
object ret = MemberTrackerToPython(context, val);
if (ret != null && val is NamespaceTracker retns && !context.LanguageContext.SystemStateModules.ContainsKey(retns.Name)) {
context.LanguageContext.SystemStateModules[retns.Name] = ret;
}
return ret;
}
}
throw PythonOps.ImportError("No module named {0}", name);
}
/// <summary>
/// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py)
///
/// level indiciates whether to perform absolute or relative imports.
/// 0 indicates only absolute imports should be performed
/// Positive numbers indicate the # of parent directories to search relative to the calling module
/// </summary>
public static object ImportModule(CodeContext/*!*/ context, object globals, string/*!*/ modName, bool bottom, int level) {
if (level < 0) throw PythonOps.ValueError("level must be >= 0");
if (modName.Contains(Path.DirectorySeparatorChar)) {
throw PythonOps.ImportError("Import by filename is not supported.");
}
string package = null;
if (globals is PythonDictionary pyGlobals) {
if (pyGlobals._storage.TryGetPackage(out object attribute)) {
package = attribute as string;
if (package == null && attribute != null) {
throw PythonOps.ValueError("__package__ set to non-string");
}
} else {
package = null;
if (level > 0) {
// explicit relative import, calculate and store __package__
object pathAttr, nameAttr;
if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) {
if (pyGlobals._storage.TryGetPath(out pathAttr)) {
pyGlobals["__package__"] = nameAttr;
} else {
pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0];
}
}
}
}
}
object newmod = null;
string firstName;
int firstDot = modName.IndexOf('.');
if (firstDot == -1) {
firstName = modName;
} else {
firstName = modName.Substring(0, firstDot);
}
string finalName = null;
if (level > 0) {
// try a relative import
// if importing a.b.c, import "a" first and then import b.c from a
string name; // name of the module we are to import in relation to the current module
PythonModule parentModule;
PythonList path; // path to search
if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) {
finalName = name;
var existingOrMetaPathModule = false;
// import relative
if (TryGetExistingModule(context, name, out newmod)) {
existingOrMetaPathModule = true;
} else if (TryLoadMetaPathModule(context, name, path, out newmod)) {
existingOrMetaPathModule = true;
if (parentModule != null && !string.IsNullOrEmpty(firstName)) {
parentModule.__dict__[firstName] = newmod;
}
} else {
newmod = ImportFromPath(context, firstName, name, path);
if (newmod == null) {
// add an indirection entry saying this module does not exist
// see http://www.python.org/doc/essays/packages.html "Dummy Entries"
context.LanguageContext.SystemStateModules[name] = null;
} else if (parentModule != null) {
parentModule.__dict__[firstName] = newmod;
}
}
if (existingOrMetaPathModule && firstDot == -1) {
// if we imported before having the assembly
// loaded and then loaded the assembly we want
// to make the assembly available now.
if (newmod is NamespaceTracker) {
context.ShowCls = true;
}
}
}
}
if (level == 0) {
// try an absolute import
if (newmod == null) {
object parentPkg;
if (!String.IsNullOrEmpty(package) && !context.LanguageContext.SystemStateModules.TryGetValue(package, out parentPkg)) {
PythonModule warnModule = new PythonModule();
warnModule.__dict__["__file__"] = package;
warnModule.__dict__["__name__"] = package;
ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext);
PythonOps.Warn(
modContext.GlobalContext,
PythonExceptions.RuntimeWarning,
"Parent module '{0}' not found while handling absolute import",
package);
}
newmod = ImportTopAbsolute(context, firstName);
finalName = firstName;
if (newmod == null) {
return null;
}
}
}
// now import the a.b.c etc. a needs to be included here
// because the process of importing could have modified
// sys.modules.
string[] parts = modName.Split('.');
object next = newmod;
string curName = null;
for (int i = 0; i < parts.Length; i++) {
curName = i == 0 ? finalName : curName + "." + parts[i];
object tmpNext;
if (TryGetExistingModule(context, curName, out tmpNext)) {
next = tmpNext;
if (i == 0) {
// need to update newmod if we pulled it out of sys.modules
// just in case we're in bottom mode.
newmod = next;
}
} else if (i != 0) {
// child module isn't loaded yet, import it.
next = ImportModuleFrom(context, next, new ArraySegment<string>(parts, 1, i), newmod);
} else {
// top-level module doesn't exist in sys.modules, probably
// came from some weird meta path hook.
newmod = next;
}
}
return bottom ? next : newmod;
}
/// <summary>
/// Interrogates the importing module for __name__ and __path__, which determine
/// whether the imported module (whose name is 'name') is being imported as nested
/// module (__path__ is present) or as sibling.
///
/// For sibling import, the full name of the imported module is parent.sibling
/// For nested import, the full name of the imported module is parent.module.nested
/// where parent.module is the mod.__name__
/// </summary>
/// <param name="context"></param>
/// <param name="globals">the globals dictionary</param>
/// <param name="name">Name of the module to be imported</param>
/// <param name="full">Output - full name of the module being imported</param>
/// <param name="path">Path to use to search for "full"</param>
/// <param name="level">the import level for relaive imports</param>
/// <param name="parentMod">the parent module</param>
/// <param name="package">the global __package__ value</param>
/// <returns></returns>
private static bool TryGetNameAndPath(CodeContext/*!*/ context, object globals, string name, int level, string package, out string full, out PythonList path, out PythonModule parentMod) {
Debug.Assert(level > 0); // shouldn't be here for absolute imports
// Unless we can find enough information to perform relative import,
// we are going to import the module whose name we got
full = name;
path = null;
parentMod = null;
// We need to get __name__ to find the name of the imported module.
// If absent, fall back to absolute import
object attribute;
if (!(globals is PythonDictionary pyGlobals) || !pyGlobals._storage.TryGetName(out attribute)) {
return false;
}
// And the __name__ needs to be string
if (!(attribute is string modName)) {
return false;
}
string pn;
if (package == null) {
// If the module has __path__ (and __path__ is list), nested module is being imported
// otherwise, importing sibling to the importing module
if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as PythonList) != null) {
// found __path__, importing nested module. The actual name of the nested module
// is the name of the mod plus the name of the imported module
if (String.IsNullOrEmpty(name)) {
// relative import of ancestor
full = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
} else {
// relative import of some ancestors child
string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string);
full = parentName + "." + name;
object parentModule;
if (context.LanguageContext.SystemStateModules.TryGetValue(parentName, out parentModule)) {
parentMod = parentModule as PythonModule;
}
}
return true;
}
// importing sibling. The name of the imported module replaces
// the last element in the importing module name
int lastDot = modName.LastIndexOf('.');
if (lastDot == -1) {
// name doesn't include dot, only absolute import possible
if (level > 0) {
throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", string.Empty);
}
return false;
}
// need to remove more than one name
int tmpLevel = level;
while (tmpLevel > 1 && lastDot != -1) {
lastDot = modName.LastIndexOf('.', lastDot - 1);
tmpLevel--;
}
if (lastDot == -1) {
pn = modName;
} else {
pn = modName.Substring(0, lastDot);
}
} else {
// __package__ doesn't include module name, so level is - 1.
pn = GetParentPackageName(level - 1, package.Split('.'));
}
path = GetParentPathAndModule(context, pn, out parentMod);
if (path != null) {
if (String.IsNullOrEmpty(name)) {
full = pn;
} else {
full = pn + "." + name;
}
return true;
}
if (level > 0) {
throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn);
}
// not enough information - absolute import
return false;
}
private static string GetParentPackageName(int level, string[] names) {
Debug.Assert(level >= 0);
StringBuilder parentName = new StringBuilder(names[0]);
for (int i = 1; i < names.Length - level; i++) {
parentName.Append('.');
parentName.Append(names[i]);
}
return parentName.ToString();
}
public static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
PythonContext pc = context.LanguageContext;
// We created the module and it only contains Python code. If the user changes
// __file__ we'll reload from that file.
// built-in module:
if (!(module.GetFile() is string fileName)) {
ReloadBuiltinModule(context, module);
return module;
}
string name = module.GetName();
if (name != null) {
PythonList path = null;
// find the parent module and get it's __path__ property
int dotIndex = name.LastIndexOf('.');
if (dotIndex != -1) {
PythonModule parentModule;
path = GetParentPathAndModule(context, name.Substring(0, dotIndex), out parentModule);
}
object reloaded;
if (TryLoadMetaPathModule(context, module.GetName() as string, path, out reloaded) && reloaded != null) {
return module;
}
PythonList sysPath;
if (context.LanguageContext.TryGetSystemPath(out sysPath)) {
object ret = ImportFromPathHook(context, name, name, sysPath, null);
if (ret != null) {
return ret;
}
}
}
if (!pc.DomainManager.Platform.FileExists(fileName)) {
throw PythonOps.SystemError("module source file not found");
}
var sourceUnit = pc.CreateFileUnit(fileName, pc.DefaultEncoding, SourceCodeKind.File);
pc.GetScriptCode(sourceUnit, name, ModuleOptions.None, Compiler.CompilationMode.Lookup).Run(module.Scope);
return module;
}
/// <summary>
/// Given the parent module name looks up the __path__ property.
/// </summary>
private static PythonList GetParentPathAndModule(CodeContext/*!*/ context, string/*!*/ parentModuleName, out PythonModule parentModule) {
PythonList path = null;
object parentModuleObj;
parentModule = null;
// Try lookup parent module in the sys.modules
if (context.LanguageContext.SystemStateModules.TryGetValue(parentModuleName, out parentModuleObj)) {
// see if it's a module
parentModule = parentModuleObj as PythonModule;
if (parentModule != null) {
object objPath;
// get its path as a List if it's there
if (parentModule.__dict__._storage.TryGetPath(out objPath)) {
path = objPath as PythonList;
}
}
}
return path;
}
private static void ReloadBuiltinModule(CodeContext/*!*/ context, PythonModule/*!*/ module) {
Assert.NotNull(module);
Debug.Assert(module.GetName() is string, "Module is reloadable only if its name is a non-null string");
Type type;
string name = module.GetName();
PythonContext pc = context.LanguageContext;
if (!pc.BuiltinModules.TryGetValue(name, out type)) {
throw PythonOps.ImportError("no module named {0}", module.GetName());
}
// should be a built-in module which we can reload.
Debug.Assert(((PythonDictionary)module.__dict__)._storage is ModuleDictionaryStorage);
((ModuleDictionaryStorage)module.__dict__._storage).Reload();
}
/// <summary>
/// Trys to get an existing module and if that fails fall backs to searching
/// </summary>
private static bool TryGetExistingOrMetaPathModule(CodeContext/*!*/ context, string fullName, PythonList path, out object ret) {
if (TryGetExistingModule(context, fullName, out ret)) {
return true;
}
return TryLoadMetaPathModule(context, fullName, path, out ret);
}
/// <summary>
/// Attempts to load a module from sys.meta_path as defined in PEP 302.
///
/// The meta_path provides a list of importer objects which can be used to load modules before
/// searching sys.path but after searching built-in modules.
/// </summary>
private static bool TryLoadMetaPathModule(CodeContext/*!*/ context, string fullName, PythonList path, out object ret) {
if (context.LanguageContext.GetSystemStateValue("meta_path") is PythonList metaPath) {
foreach (object importer in (IEnumerable)metaPath) {
if (FindAndLoadModuleFromImporter(context, importer, fullName, path, out ret)) {
return true;
}
}
}
ret = null;
return false;
}
/// <summary>
/// Given a user defined importer object as defined in PEP 302 tries to load a module.
///
/// First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked
/// </summary>
private static bool FindAndLoadModuleFromImporter(CodeContext/*!*/ context, object importer, string fullName, PythonList path, out object ret) {
object find_module = PythonOps.GetBoundAttr(context, importer, "find_module");
PythonContext pycontext = context.LanguageContext;
object loader = path == null ? pycontext.Call(context, find_module, fullName) : pycontext.Call(context, find_module, fullName, path);
if (loader != null) {
object findMod = PythonOps.GetBoundAttr(context, loader, "load_module");
ret = pycontext.Call(context, findMod, fullName);
return ret != null;
}
ret = null;
return false;
}
internal static bool TryGetExistingModule(CodeContext/*!*/ context, string/*!*/ fullName, out object ret) {
if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out ret)) {
return true;
}
return false;
}
#endregion
#region Private Implementation Details
private static object ImportTopAbsolute(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
if (TryGetExistingModule(context, name, out ret)) {
if (IsReflected(ret)) {
// Even though we found something in sys.modules, we need to check if a
// clr.AddReference has invalidated it. So try ImportReflected again.
ret = ImportReflected(context, name) ?? ret;
}
if (ret is NamespaceTracker rp || ret == context.LanguageContext.ClrModule) {
context.ShowCls = true;
}
return ret;
}
if (TryLoadMetaPathModule(context, name, null, out ret)) {
return ret;
}
ret = ImportBuiltin(context, name);
if (ret != null) return ret;
PythonList path;
if (context.LanguageContext.TryGetSystemPath(out path)) {
ret = ImportFromPath(context, name, name, path);
if (ret != null) return ret;
}
ret = ImportReflected(context, name);
return ret;
}
private static string [] SubArray(string[] t, int len) {
var ret = new string[len];
Array.Copy(t, ret, len);
return ret;
}
private static bool TryGetNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ scope,
string[]/*!*/ parts, int current, out object nested) {
string name = parts[current];
Assert.NotNull(context, scope, name);
if (scope.__dict__.TryGetValue(name, out nested)) {
if (nested is PythonModule pm) {
var fullPath = string.Join(".", SubArray(parts, current));
// double check, some packages mess with package namespace
// see cp35116
if (pm.GetName() == fullPath) {
return true;
}
}
// This allows from System.Math import *
if (nested is PythonType dt && dt.IsSystemType) {
return true;
}
}
return false;
}
private static object ImportNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ module,
ArraySegment<string> parts, PythonList/*!*/ path, string scopeModuleName) {
Debug.Assert(parts.Array is not null);
Debug.Assert(parts.Count > 0);
object ret;
int current = parts.Offset + parts.Count - 1;
string name = parts.Array[current];
string fullName = CreateFullName(scopeModuleName, parts);
if (TryGetExistingOrMetaPathModule(context, fullName, path, out ret)) {
module.__dict__[name] = ret;
return ret;
}
if (TryGetNestedModule(context, module, parts.Array, current, out ret)) {
return ret;
}
ImportFromPath(context, name, fullName, path);
object importedModule;
if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out importedModule)) {
module.__dict__[name] = importedModule;
return importedModule;
}
throw PythonOps.ImportError("cannot import {0} from {1}", name, module.GetName());
}
private static object FindImportFunction(CodeContext/*!*/ context) {
PythonDictionary builtins = context.GetBuiltinsDict() ?? context.LanguageContext.BuiltinModuleDict;
object import;
if (builtins._storage.TryGetImport(out import)) {
return import;
}
throw PythonOps.ImportError("cannot find __import__");
}
internal static object ImportBuiltin(CodeContext/*!*/ context, string/*!*/ name) {
Assert.NotNull(context, name);
PythonContext pc = context.LanguageContext;
if (name == "sys") {
return pc.SystemState;
} else if (name == "clr") {
context.ShowCls = true;
pc.SystemStateModules["clr"] = pc.ClrModule;
return pc.ClrModule;
}
return pc.GetBuiltinModule(name);
}
private static object ImportReflected(CodeContext/*!*/ context, string/*!*/ name) {
object ret;
PythonContext pc = context.LanguageContext;
if (!PythonOps.ScopeTryGetMember(context, pc.DomainManager.Globals, name, out ret) &&
(ret = pc.TopNamespace.TryGetPackageAny(name)) == null) {
ret = TryImportSourceFile(pc, name);
}
ret = MemberTrackerToPython(context, ret);
if (ret != null) {
context.LanguageContext.SystemStateModules[name] = ret;
}
return ret;
}
internal static object MemberTrackerToPython(CodeContext/*!*/ context, object ret) {
if (ret is MemberTracker res) {
context.ShowCls = true;
object realRes = res;
switch (res.MemberType) {
case TrackerTypes.Type: realRes = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)res).Type); break;
case TrackerTypes.Field: realRes = PythonTypeOps.GetReflectedField(((FieldTracker)res).Field); break;
case TrackerTypes.Event: realRes = PythonTypeOps.GetReflectedEvent((EventTracker)res); break;
case TrackerTypes.Method:
MethodTracker mt = res as MethodTracker;
realRes = PythonTypeOps.GetBuiltinFunction(mt.DeclaringType, mt.Name, new MemberInfo[] { mt.Method });
break;
}
ret = realRes;
}
return ret;
}
internal static PythonModule TryImportSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
var sourceUnit = TryFindSourceFile(context, name);
PlatformAdaptationLayer pal = context.DomainManager.Platform;
if (sourceUnit == null ||
GetFullPathAndValidateCase(context, pal.CombinePaths(pal.GetDirectoryName(sourceUnit.Path), name + pal.GetExtension(sourceUnit.Path)), false) == null) {
return null;
}
var scope = ExecuteSourceUnit(context, sourceUnit);
if (sourceUnit.LanguageContext != context) {
// foreign language, we should publish in sys.modules too
context.SystemStateModules[name] = scope;
}
PythonOps.ScopeSetMember(context.SharedContext, sourceUnit.LanguageContext.DomainManager.Globals, name, scope);
return scope;
}
internal static PythonModule ExecuteSourceUnit(PythonContext context, SourceUnit/*!*/ sourceUnit) {
ScriptCode compiledCode = sourceUnit.Compile();
Scope scope = compiledCode.CreateScope();
PythonModule res = ((PythonScopeExtension)context.EnsureScopeExtension(scope)).Module;
compiledCode.Run(scope);
return res;
}
internal static SourceUnit TryFindSourceFile(PythonContext/*!*/ context, string/*!*/ name) {
PythonList paths;
if (!context.TryGetSystemPath(out paths)) {
return null;
}
foreach (object dirObj in paths) {
if (!(dirObj is string directory)) continue; // skip invalid entries
string candidatePath = null;
LanguageContext candidateLanguage = null;
foreach (string extension in context.DomainManager.Configuration.GetFileExtensions()) {
string fullPath;
try {
fullPath = context.DomainManager.Platform.CombinePaths(directory, name + extension);
} catch (ArgumentException) {
// skip invalid paths
continue;
}
if (context.DomainManager.Platform.FileExists(fullPath)) {
if (candidatePath != null) {
throw PythonOps.ImportError("Found multiple modules of the same name '{0}': '{1}' and '{2}'",
name, candidatePath, fullPath);
}
candidatePath = fullPath;
candidateLanguage = context.DomainManager.GetLanguageByExtension(extension);
}
}
if (candidatePath != null) {
return candidateLanguage.CreateFileUnit(candidatePath);
}
}
return null;
}
private static bool IsReflected(object module) {
// corresponds to the list of types that can be returned by ImportReflected
return module is MemberTracker
|| module is PythonType
|| module is ReflectedEvent
|| module is ReflectedField
|| module is BuiltinFunction;
}
private static string CreateFullName(string/*!*/ baseName, ArraySegment<string> parts) {
if (baseName == null || baseName.Length == 0 || baseName == "__main__") {
return string.Join(".", (IEnumerable<string>)parts);
}
return baseName + "." + string.Join(".", (IEnumerable<string>)parts);
}
#endregion
private static object ImportFromPath(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, PythonList/*!*/ path) {
return ImportFromPathHook(context, name, fullName, path, LoadFromDisk);
}
private static object ImportFromPathHook(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, PythonList/*!*/ path, Func<CodeContext, string, string, string, object> defaultLoader) {
Assert.NotNull(context, name, fullName, path);
if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) {
return null;
}
foreach (object dirname in path) {
string str = dirname as string;
if (str != null || (Converter.TryConvertToString(dirname, out str) && str != null)) { // ignore non-string
object importer;
if (!importCache.TryGetValue(str, out importer)) {
importCache[str] = importer = FindImporterForPath(context, str);
}
if (importer != null) {
// user defined importer object, get the loader and use it.
object ret;
if (FindAndLoadModuleFromImporter(context, importer, fullName, null, out ret)) {
return ret;
}
} else if (defaultLoader != null) {
object res = defaultLoader(context, name, fullName, str);
if (res != null) {
return res;
}
}
}
}
return null;
}
internal static bool TryImportMainFromZip(CodeContext/*!*/ context, string/*!*/ path, out object importer) {
Assert.NotNull(context, path);
if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) {
importer = null;
return false;
}
importCache[path] = importer = FindImporterForPath(context, path);
if (importer is null || importer is PythonImport.NullImporter) {
return false;
}
// for consistency with cpython, insert zip as a first entry into sys.path
var syspath = context.LanguageContext.GetSystemStateValue("path") as PythonList;
syspath?.Insert(0, path);
return FindAndLoadModuleFromImporter(context, importer, "__main__", null, out _);
}
private static object LoadFromDisk(CodeContext context, string name, string fullName, string str) {
// default behavior
string pathname = context.LanguageContext.DomainManager.Platform.CombinePaths(str, name);
PythonModule module = LoadPackageFromSource(context, fullName, pathname);
if (module != null) {
return module;
}
string filename = pathname + ".py";
module = LoadModuleFromSource(context, fullName, filename);
if (module != null) {
return module;
}
return null;
}
/// <summary>
/// Finds a user defined importer for the given path or returns null if no importer
/// handles this path.
/// </summary>
private static object FindImporterForPath(CodeContext/*!*/ context, string dirname) {
PythonList pathHooks = context.LanguageContext.GetSystemStateValue("path_hooks") as PythonList;
foreach (object hook in pathHooks) {
try {
return PythonCalls.Call(context, hook, dirname);
} catch (ImportException) {
// we can't handle the path
}
}
if (!context.LanguageContext.DomainManager.Platform.DirectoryExists(dirname)) {
return new PythonImport.NullImporter(dirname);
}
return null;
}
private static PythonModule LoadModuleFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
PythonContext pc = context.LanguageContext;
string fullPath = GetFullPathAndValidateCase(pc, path, false);
if (fullPath == null || !pc.DomainManager.Platform.FileExists(fullPath)) {
return null;
}
SourceUnit sourceUnit = pc.CreateFileUnit(fullPath, pc.DefaultEncoding, SourceCodeKind.File);
return LoadFromSourceUnit(context, sourceUnit, name, sourceUnit.Path);
}
private static string GetFullPathAndValidateCase(LanguageContext/*!*/ context, string path, bool isDir) {
// Check for a match in the case of the filename.
PlatformAdaptationLayer pal = context.DomainManager.Platform;
string dir = pal.GetDirectoryName(path);
if (!pal.DirectoryExists(dir)) {
return null;
}
try {
string file = pal.GetFileName(path);
string[] files = pal.GetFileSystemEntries(dir, file, !isDir, isDir);
if (files.Length != 1 || pal.GetFileName(files[0]) != file) {
return null;
}
return pal.GetFullPath(files[0]);
} catch (IOException) {
return null;
}
}
internal static PythonModule LoadPackageFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(context, name, path);
path = GetFullPathAndValidateCase(context.LanguageContext, path, true);
if (path == null) {
return null;
}
if(context.LanguageContext.DomainManager.Platform.DirectoryExists(path) && !context.LanguageContext.DomainManager.Platform.FileExists(context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"))) {
PythonOps.Warn(context, PythonExceptions.ImportWarning, "Not importing directory '{0}': missing __init__.py", path);
}
return LoadModuleFromSource(context, name, context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"));
}
private static PythonModule/*!*/ LoadFromSourceUnit(CodeContext/*!*/ context, SourceUnit/*!*/ sourceCode, string/*!*/ name, string/*!*/ path) {
Assert.NotNull(sourceCode, name, path);
return context.LanguageContext.CompileModule(path, name, sourceCode, ModuleOptions.Initialize | ModuleOptions.Optimized);
}
}
}