forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClrModule.cs
More file actions
1234 lines (1040 loc) · 50.6 KB
/
ClrModule.cs
File metadata and controls
1234 lines (1040 loc) · 50.6 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
// 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.
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization.Formatters.Binary;
#endif
#if !FEATURE_REMOTING
using MarshalByRefObject = System.Object;
#endif
#if FEATURE_COM
using ComTypeLibInfo = Microsoft.Scripting.ComInterop.ComTypeLibInfo;
using ComTypeLibDesc = Microsoft.Scripting.ComInterop.ComTypeLibDesc;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("clr", typeof(IronPython.Runtime.ClrModule))]
namespace IronPython.Runtime {
/// <summary>
/// this class contains objecs and static methods used for
/// .NET/CLS interop with Python.
/// </summary>
public static class ClrModule {
#if NETCOREAPP
public static readonly bool IsNetCoreApp = true;
#elif NETFRAMEWORK
public static readonly bool IsNetCoreApp = false;
#else
public static readonly bool IsNetCoreApp = FrameworkDescription.StartsWith(".NET", StringComparison.Ordinal) && !FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal);
#endif
public static string TargetFramework => typeof(ClrModule).Assembly.GetCustomAttribute<TargetFrameworkAttribute>()?.FrameworkName;
internal static string FileVersion => typeof(ClrModule).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version;
#if DEBUG
public static readonly bool IsDebug = true;
#else
public static readonly bool IsDebug = false;
#endif
public static string FrameworkDescription {
get {
#if FEATURE_RUNTIMEINFORMATION
var frameworkDescription = RuntimeInformation.FrameworkDescription;
if (frameworkDescription.StartsWith(".NET Core 4.6.", StringComparison.OrdinalIgnoreCase)) {
return $".NET Core 2.x ({frameworkDescription.Substring(10)})";
}
return frameworkDescription;
#else
// try reflection since we're probably running on a newer runtime anyway
if (typeof(void).Assembly.GetType("System.Runtime.InteropServices.RuntimeInformation")?.GetProperty("FrameworkDescription")?.GetValue(null) is string frameworkDescription) {
return frameworkDescription;
}
return (IsMono ? "Mono " : ".NET Framework ") + Environment.Version.ToString();
#endif
}
}
private static int _isMono = -1;
public static bool IsMono {
get {
if (_isMono == -1) {
_isMono = Type.GetType("Mono.Runtime") != null ? 1 : 0;
}
return _isMono == 1;
}
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
if (!dict.ContainsKey("References")) {
dict["References"] = context.ReferencedAssemblies;
}
}
#region Public methods
/// <summary>
/// Gets the current ScriptDomainManager that IronPython is loaded into. The
/// ScriptDomainManager can then be used to work with the language portion of the
/// DLR hosting APIs.
/// </summary>
public static ScriptDomainManager/*!*/ GetCurrentRuntime(CodeContext/*!*/ context) {
return context.LanguageContext.DomainManager;
}
[Documentation(@"Adds a reference to a .NET assembly. Parameters can be an already loaded
Assembly object, a full assembly name, or a partial assembly name. After the
load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReference(CodeContext/*!*/ context, params object[] references) {
if (references == null) throw new TypeErrorException("Expected string or Assembly, got NoneType");
if (references.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, nameof(context));
foreach (object reference in references) {
AddReference(context, reference);
}
}
[Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
be provided. The assembly is searched for in the directories specified in
sys.path and dependencies will be loaded from sys.path as well. The assembly
name should be the filename on disk without a directory specifier and
optionally including the .EXE or .DLL extension. After the load the assemblies
namespaces and top-level types will be available via import Namespace.")]
public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] files) {
if (files == null) throw new TypeErrorException("Expected string, got NoneType");
if (files.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, nameof(context));
foreach (string file in files) {
AddReferenceToFile(context, file);
}
}
[Documentation(@"Adds a reference to a .NET assembly. Parameters are an assembly name.
After the load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceByName(CodeContext/*!*/ context, params string[] names) {
if (names == null) throw new TypeErrorException("Expected string, got NoneType");
if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, nameof(context));
foreach (string name in names) {
AddReferenceByName(context, name);
}
}
[Documentation(@"Adds a reference to a .NET assembly. Parameters are a partial assembly name.
After the load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceByPartialName(CodeContext/*!*/ context, params string[] names) {
if (names == null) throw new TypeErrorException("Expected string, got NoneType");
if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none");
ContractUtils.RequiresNotNull(context, nameof(context));
foreach (string name in names) {
AddReferenceByPartialName(context, name);
}
}
#if FEATURE_FILESYSTEM
[Documentation(@"Adds a reference to a .NET assembly. Parameters are a full path to an.
assembly on disk. After the load the assemblies namespaces and top-level types
will be available via import Namespace.")]
public static Assembly/*!*/ LoadAssemblyFromFileWithPath(CodeContext/*!*/ context, string/*!*/ file) {
if (file == null) throw new TypeErrorException("LoadAssemblyFromFileWithPath: arg 1 must be a string.");
Assembly res;
if (!context.LanguageContext.TryLoadAssemblyFromFileWithPath(file, out res)) {
if (!Path.IsPathRooted(file)) {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: path must be rooted");
} else if (!File.Exists(file)) {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: file not found");
} else {
throw new ValueErrorException("LoadAssemblyFromFileWithPath: error loading assembly");
}
}
return res;
}
[Documentation(@"Loads an assembly from the specified filename and returns the assembly
object. Namespaces or types in the assembly can be accessed directly from
the assembly object.")]
public static Assembly/*!*/ LoadAssemblyFromFile(CodeContext/*!*/ context, string/*!*/ file) {
if (file == null) throw new TypeErrorException("Expected string, got NoneType");
if (file.Length == 0) throw new ValueErrorException("assembly name must not be empty string");
ContractUtils.RequiresNotNull(context, nameof(context));
if (file.IndexOf(Path.DirectorySeparatorChar) != -1) {
throw new ValueErrorException("filenames must not contain full paths, first add the path to sys.path");
}
return context.LanguageContext.LoadAssemblyFromFile(file);
}
#endif
#if FEATURE_LOADWITHPARTIALNAME
[Documentation(@"Loads an assembly from the specified partial assembly name and returns the
assembly object. Namespaces or types in the assembly can be accessed directly
from the assembly object.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")]
public static Assembly/*!*/ LoadAssemblyByPartialName(string/*!*/ name) {
if (name == null) {
throw new TypeErrorException("LoadAssemblyByPartialName: arg 1 must be a string");
}
#pragma warning disable 618, 612 // csc
return Assembly.LoadWithPartialName(name);
#pragma warning restore 618, 612
}
#endif
[Documentation(@"Loads an assembly from the specified assembly name and returns the assembly
object. Namespaces or types in the assembly can be accessed directly from
the assembly object.")]
public static Assembly/*!*/ LoadAssemblyByName(CodeContext/*!*/ context, string/*!*/ name) {
if (name == null) {
throw new TypeErrorException("LoadAssemblyByName: arg 1 must be a string");
}
return context.LanguageContext.DomainManager.Platform.LoadAssembly(name);
}
/// <summary>
/// Use(name) -> module
///
/// Attempts to load the specified module searching all languages in the loaded ScriptRuntime.
/// </summary>
public static object Use(CodeContext/*!*/ context, string/*!*/ name) {
ContractUtils.RequiresNotNull(context, nameof(context));
if (name == null) {
throw new TypeErrorException("Use: arg 1 must be a string");
}
var scope = Importer.TryImportSourceFile(context.LanguageContext, name);
if (scope == null) {
throw new ValueErrorException(String.Format("couldn't find module {0} to use", name));
}
return scope;
}
[Documentation("Converts an array of bytes to a string.")]
public static string GetString(byte[] bytes) {
return GetString(bytes, bytes.Length);
}
[Documentation("Converts maxCount of an array of bytes to a string")]
public static string GetString(byte[] bytes, int maxCount) {
int bytesToCopy = Math.Min(bytes.Length, maxCount);
return Encoding.GetEncoding("iso-8859-1").GetString(bytes, 0, bytesToCopy);
}
[Documentation("Converts a string to an array of bytes")]
public static byte[] GetBytes(string s) {
return GetBytes(s, s.Length);
}
[Documentation("Converts maxCount of a string to an array of bytes")]
public static byte[] GetBytes(string s, int maxCount) {
int charsToCopy = Math.Min(s.Length, maxCount);
byte[] ret = new byte[charsToCopy];
Encoding.GetEncoding("iso-8859-1").GetBytes(s, 0, charsToCopy, ret, 0);
return ret;
}
/// <summary>
/// Use(path, language) -> module
///
/// Attempts to load the specified module belonging to a specific language loaded into the
/// current ScriptRuntime.
/// </summary>
public static object/*!*/ Use(CodeContext/*!*/ context, string/*!*/ path, string/*!*/ language) {
ContractUtils.RequiresNotNull(context, nameof(context));
if (path == null) {
throw new TypeErrorException("Use: arg 1 must be a string");
}
if (language == null) {
throw new TypeErrorException("Use: arg 2 must be a string");
}
var manager = context.LanguageContext.DomainManager;
if (!manager.Platform.FileExists(path)) {
throw new ValueErrorException(String.Format("couldn't load module at path '{0}' in language '{1}'", path, language));
}
var sourceUnit = manager.GetLanguageByName(language).CreateFileUnit(path);
return Importer.ExecuteSourceUnit(context.LanguageContext, sourceUnit);
}
/// <summary>
/// SetCommandDispatcher(commandDispatcher)
///
/// Sets the current command dispatcher for the Python command line.
///
/// The command dispatcher will be called with a delegate to be executed. The command dispatcher
/// should invoke the target delegate in the desired context.
///
/// A common use for this is to enable running all REPL commands on the UI thread while the REPL
/// continues to run on a non-UI thread.
/// </summary>
public static Action<Action> SetCommandDispatcher(CodeContext/*!*/ context, Action<Action> dispatcher) {
ContractUtils.RequiresNotNull(context, nameof(context));
return ((PythonContext)context.LanguageContext).GetSetCommandDispatcher(dispatcher);
}
public static void ImportExtensions(CodeContext/*!*/ context, PythonType type) {
if (type == null) {
throw PythonOps.TypeError("type must not be None");
} else if (!type.IsSystemType) {
throw PythonOps.ValueError("type must be .NET type");
}
lock (context.ModuleContext) {
context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddType(context.LanguageContext, context.ModuleContext.ExtensionMethods, type);
}
}
public static void ImportExtensions(CodeContext/*!*/ context, [NotNone] NamespaceTracker @namespace) {
lock (context.ModuleContext) {
context.ModuleContext.ExtensionMethods = ExtensionMethodSet.AddNamespace(context.LanguageContext, context.ModuleContext.ExtensionMethods, @namespace);
}
}
#if FEATURE_COM
/// <summary>
/// LoadTypeLibrary(rcw) -> type lib desc
///
/// Gets an ITypeLib object from OLE Automation compatible RCW ,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates an object that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, object rcw) {
return ComTypeLibDesc.CreateFromObject(rcw);
}
/// <summary>
/// LoadTypeLibrary(guid) -> type lib desc
///
/// Reads the latest registered type library for the corresponding GUID,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
public static ComTypeLibInfo LoadTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
return ComTypeLibDesc.CreateFromGuid(typeLibGuid);
}
/// <summary>
/// AddReferenceToTypeLibrary(rcw) -> None
///
/// Makes the type lib desc available for importing. See also LoadTypeLibrary.
/// </summary>
public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, object rcw) {
ComTypeLibInfo typeLibInfo = ComTypeLibDesc.CreateFromObject(rcw);
PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
}
/// <summary>
/// AddReferenceToTypeLibrary(guid) -> None
///
/// Makes the type lib desc available for importing. See also LoadTypeLibrary.
/// </summary>
public static void AddReferenceToTypeLibrary(CodeContext/*!*/ context, Guid typeLibGuid) {
ComTypeLibInfo typeLibInfo = ComTypeLibDesc.CreateFromGuid(typeLibGuid);
PublishTypeLibDesc(context, typeLibInfo.TypeLibDesc);
}
private static void PublishTypeLibDesc(CodeContext context, ComTypeLibDesc typeLibDesc) {
PythonOps.ScopeSetMember(context, context.LanguageContext.DomainManager.Globals, typeLibDesc.Name, typeLibDesc);
}
#endif
#endregion
#region Private implementation methods
private static void AddReference(CodeContext/*!*/ context, object reference) {
Assembly asmRef = reference as Assembly;
if (asmRef != null) {
AddReference(context, asmRef);
return;
}
if (reference is string strRef) {
AddReference(context, strRef);
return;
}
throw new TypeErrorException(String.Format("Invalid assembly type. Expected string or Assembly, got {0}.", reference));
}
private static void AddReference(CodeContext/*!*/ context, Assembly assembly) {
context.LanguageContext.DomainManager.LoadAssembly(assembly);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // TODO: fix
private static void AddReference(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
Assembly asm = null;
try {
asm = LoadAssemblyByName(context, name);
} catch { }
// note we don't explicit call to get the file version
// here because the assembly resolve event will do it for us.
#if FEATURE_LOADWITHPARTIALNAME
if (asm == null) {
asm = LoadAssemblyByPartialName(name);
}
#endif
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
private static void AddReferenceToFile(CodeContext/*!*/ context, string file) {
if (file == null) throw new TypeErrorException("Expected string, got NoneType");
#if !FEATURE_FILESYSTEM
Assembly asm = context.LanguageContext.DomainManager.Platform.LoadAssemblyFromPath(file);
#else
Assembly asm = LoadAssemblyFromFile(context, file);
#endif
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", file));
}
AddReference(context, asm);
}
#if FEATURE_LOADWITHPARTIALNAME
private static void AddReferenceByPartialName(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
ContractUtils.RequiresNotNull(context, nameof(context));
Assembly asm = LoadAssemblyByPartialName(name);
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
#endif
private static void AddReferenceByName(CodeContext/*!*/ context, string name) {
if (name == null) throw new TypeErrorException("Expected string, got NoneType");
Assembly asm = LoadAssemblyByName(context, name);
if (asm == null) {
throw new IOException(String.Format("Could not add reference to assembly {0}", name));
}
AddReference(context, asm);
}
#endregion
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix
public sealed class ReferencesList : List<Assembly>, ICodeFormattable {
public new void Add(Assembly other) {
base.Add(other);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), SpecialName]
public ClrModule.ReferencesList Add(object other) {
IEnumerator ie = PythonOps.GetEnumerator(other);
while (ie.MoveNext()) {
Assembly cur = ie.Current as Assembly;
if (cur == null) throw PythonOps.TypeError("non-assembly added to references list");
base.Add(cur);
}
return this;
}
public string/*!*/ __repr__(CodeContext/*!*/ context) {
StringBuilder res = new StringBuilder("(");
string comma = "";
foreach (Assembly asm in this) {
res.Append(comma);
res.Append('<');
res.Append(asm.FullName);
res.Append('>');
comma = "," + Environment.NewLine;
}
res.AppendLine(")");
return res.ToString();
}
}
private static PythonType _strongBoxType;
#region Runtime Type Checking support
#if FEATURE_FILESYSTEM
[Documentation(@"Adds a reference to a .NET assembly. One or more assembly names can
be provided which are fully qualified names to the file on disk. The
directory is added to sys.path and AddReferenceToFile is then called. After the
load the assemblies namespaces and top-level types will be available via
import Namespace.")]
public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, params string[] files) {
if (files == null) throw new TypeErrorException("Expected string, got NoneType");
ContractUtils.RequiresNotNull(context, nameof(context));
foreach (string file in files) {
AddReferenceToFileAndPath(context, file);
}
}
private static void AddReferenceToFileAndPath(CodeContext/*!*/ context, string file) {
if (file == null) throw PythonOps.TypeError("Expected string, got NoneType");
// update our path w/ the path of this file...
string path = System.IO.Path.GetDirectoryName(Path.GetFullPath(file));
PythonList list;
PythonContext pc = context.LanguageContext;
if (!pc.TryGetSystemPath(out list)) {
throw PythonOps.TypeError("cannot update path, it is not a list");
}
list.append(path);
Assembly asm = pc.LoadAssemblyFromFile(file);
if (asm == null) throw PythonOps.IOError("file does not exist: {0}", file);
AddReference(context, asm);
}
#endif
/// <summary>
/// Gets the CLR Type object from a given Python type object.
/// </summary>
public static Type GetClrType(Type type) {
return type;
}
/// <summary>
/// Gets the Python type object from a given CLR Type object.
/// </summary>
public static PythonType GetPythonType(Type t) {
return DynamicHelpers.GetPythonTypeFromType(t);
}
/// <summary>
/// OBSOLETE: Gets the Python type object from a given CLR Type object.
///
/// Use clr.GetPythonType instead.
/// </summary>
[Obsolete("Call clr.GetPythonType instead")]
public static PythonType GetDynamicType(Type t) {
return DynamicHelpers.GetPythonTypeFromType(t);
}
public static PythonType Reference {
get {
return StrongBox;
}
}
public static PythonType StrongBox {
get {
if (_strongBoxType == null) {
_strongBoxType = DynamicHelpers.GetPythonTypeFromType(typeof(StrongBox<>));
}
return _strongBoxType;
}
}
/// <summary>
/// accepts(*types) -> ArgChecker
///
/// Decorator that returns a new callable object which will validate the arguments are of the specified types.
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
public static object accepts([NotNone] params object[] types) {
return new ArgChecker(types);
}
/// <summary>
/// returns(type) -> ReturnChecker
///
/// Returns a new callable object which will validate the return type is of the specified type.
/// </summary>
public static object returns(object type) {
return new ReturnChecker(type);
}
public static object Self() {
return null;
}
#endregion
/// <summary>
/// Decorator for verifying the arguments to a function are of a specified type.
/// </summary>
public class ArgChecker {
private readonly PythonType[] expected;
public ArgChecker([NotNone] object[] types) {
expected = types.Select(t => t.ToPythonType()).ToArray();
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, object func) {
// expect only to receive the function we'll call here.
return new RuntimeArgChecker(func, expected);
}
#endregion
}
/// <summary>
/// Returned value when using clr.accepts/ArgChecker. Validates the argument types and
/// then calls the original function.
/// </summary>
public class RuntimeArgChecker : PythonTypeSlot {
private readonly PythonType[] _expected;
private readonly object _func;
private readonly object _inst;
public RuntimeArgChecker([NotNone] object function, [NotNone] PythonType[] expectedArgs) {
_expected = expectedArgs;
_func = function;
}
public RuntimeArgChecker(object instance, [NotNone] object function, [NotNone] PythonType[] expectedArgs)
: this(function, expectedArgs) {
_inst = instance;
}
private void ValidateArgs(object[] args) {
int start = 0;
if (_inst != null) {
start = 1;
}
// no need to validate self... the method should handle it.
for (int i = start; i < args.Length + start; i++) {
object arg = args[i - start];
PythonType expct = _expected[i];
if (!IsInstanceOf(arg, expct)) {
throw PythonOps.AssertionError(
"argument {0} has bad value (expected {1}, got {2})",
i, expct.Name, PythonOps.GetPythonTypeName(arg));
}
}
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, params object[] args) {
ValidateArgs(args);
if (_inst != null) {
return PythonOps.CallWithContext(context, _func, ArrayUtils.Insert(_inst, args));
} else {
return PythonOps.CallWithContext(context, _func, args);
}
}
#endregion
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
value = new RuntimeArgChecker(instance, _func, _expected);
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
#region IFancyCallable Members
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
ValidateArgs(args);
if (_inst != null) {
return PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
} else {
return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
}
}
#endregion
}
/// <summary>
/// Decorator for verifying the return type of functions.
/// </summary>
public class ReturnChecker {
public PythonType retType;
public ReturnChecker(object returnType) {
retType = returnType.ToPythonType();
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, object func) {
// expect only to receive the function we'll call here.
return new RuntimeReturnChecker(func, retType);
}
#endregion
}
/// <summary>
/// Returned value when using clr.returns/ReturnChecker. Calls the original function and
/// validates the return type is of a specified type.
/// </summary>
public class RuntimeReturnChecker : PythonTypeSlot {
private readonly PythonType _retType;
private readonly object _func;
private readonly object _inst;
public RuntimeReturnChecker([NotNone] object function, [NotNone] PythonType expectedReturn) {
_retType = expectedReturn;
_func = function;
}
public RuntimeReturnChecker(object instance, [NotNone] object function, [NotNone] PythonType expectedReturn)
: this(function, expectedReturn) {
_inst = instance;
}
private void ValidateReturn(object ret) {
if (!IsInstanceOf(ret, _retType)) {
throw PythonOps.AssertionError(
"bad return value returned (expected {0}, got {1})",
_retType.Name, PythonOps.GetPythonTypeName(ret));
}
}
#region ICallableWithCodeContext Members
[SpecialName]
public object Call(CodeContext context, params object[] args) {
object ret = PythonOps.CallWithContext(
context,
_func,
_inst != null ? ArrayUtils.Insert(_inst, args) : args);
ValidateReturn(ret);
return ret;
}
#endregion
#region IDescriptor Members
public object GetAttribute(object instance, object owner) {
return new RuntimeReturnChecker(instance, _func, _retType);
}
#endregion
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) {
value = GetAttribute(instance, owner);
return true;
}
internal override bool GetAlwaysSucceeds {
get {
return true;
}
}
#region IFancyCallable Members
[SpecialName]
public object Call(CodeContext context, [ParamDictionary]IDictionary<object, object> dict, params object[] args) {
object ret;
if (_inst != null) {
ret = PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict);
} else {
return PythonCalls.CallWithKeywordArgs(context, _func, args, dict);
}
ValidateReturn(ret);
return ret;
}
#endregion
}
private static PythonType ToPythonType(this object obj) {
return obj switch {
PythonType pt => pt,
Type t => DynamicHelpers.GetPythonTypeFromType(t),
null => TypeCache.Null,
_ => throw PythonOps.TypeErrorForTypeMismatch("type", obj)
};
}
private static bool IsInstanceOf(object obj, PythonType pt) {
// See also PythonOps.IsInstance
var objType = DynamicHelpers.GetPythonType(obj);
if (objType == pt) {
return true;
}
// PEP 237: int/long unification
// https://github.com/IronLanguages/ironpython3/issues/52
if (pt == TypeCache.BigInteger && obj is int) {
return true;
}
return pt.__subclasscheck__(objType);
}
/// <summary>
/// returns the result of dir(o) as-if "import clr" has not been performed.
/// </summary>
public static PythonList Dir(CodeContext context, object o) {
IList<object> ret = PythonOps.GetAttrNames(DefaultContext.Default, o);
PythonList lret = new PythonList(context, ret);
lret.Sort(DefaultContext.Default);
return lret;
}
/// <summary>
/// Returns the result of dir(o) as-if "import clr" has been performed.
/// </summary>
public static PythonList DirClr(CodeContext context, object o) {
IList<object> ret = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, o);
PythonList lret = new PythonList(context, ret);
lret.Sort(DefaultContext.DefaultCLS);
return lret;
}
/// <summary>
/// Attempts to convert the provided object to the specified type. Conversions that
/// will be attempted include standard Python conversions as well as .NET implicit
/// and explicit conversions.
///
/// If the conversion cannot be performed a TypeError will be raised.
/// </summary>
public static object Convert(CodeContext/*!*/ context, object o, Type toType) {
return Converter.Convert(o, toType);
}
#if FEATURE_FILESYSTEM && FEATURE_REFEMIT
/// <summary>
/// Provides a helper for compiling a group of modules into a single assembly. The assembly can later be
/// reloaded using the clr.AddReference API.
/// </summary>
public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary]IDictionary<string, object> kwArgs, params string/*!*/[]/*!*/ filenames) {
ContractUtils.RequiresNotNull(assemblyName, nameof(assemblyName));
ContractUtils.RequiresNotNullItems(filenames, nameof(filenames));
PythonContext pc = context.LanguageContext;
for (int i = 0; i < filenames.Length; i++) {
filenames[i] = Path.GetFullPath(filenames[i]);
}
Dictionary<string, string> packageMap = BuildPackageMap(filenames);
List<SavableScriptCode> code = new List<SavableScriptCode>();
foreach (string filename in filenames) {
if (!pc.DomainManager.Platform.FileExists(filename)) {
throw PythonOps.IOError($"Couldn't find file for compilation: {filename}");
}
ScriptCode sc;
string modName;
string dname = Path.GetDirectoryName(filename);
string outFilename = "";
if (Path.GetFileName(filename) == "__init__.py") {
// remove __init__.py to get package name
dname = Path.GetDirectoryName(dname);
if (String.IsNullOrEmpty(dname)) {
modName = Path.GetDirectoryName(filename);
} else {
modName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(filename));
}
outFilename = Path.DirectorySeparatorChar + "__init__.py";
} else {
modName = Path.GetFileNameWithoutExtension(filename);
}
// see if we have a parent package, if so incorporate it into
// our name
if (packageMap.TryGetValue(dname, out string parentPackage)) {
modName = parentPackage + "." + modName;
}
outFilename = modName.Replace('.', Path.DirectorySeparatorChar) + outFilename;
SourceUnit su = pc.CreateSourceUnit(
new FileStreamContentProvider(
context.LanguageContext.DomainManager.Platform,
filename
),
outFilename,
pc.DefaultEncoding,
SourceCodeKind.File
);
sc = context.LanguageContext.GetScriptCode(su, modName, ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk);
code.Add((SavableScriptCode)sc);
}
if (kwArgs != null && kwArgs.TryGetValue("mainModule", out object mainModule)) {
if (mainModule is string strModule) {
if (!pc.DomainManager.Platform.FileExists(strModule)) {
throw PythonOps.IOError("Couldn't find main file for compilation: {0}", strModule);
}
SourceUnit su = pc.CreateFileUnit(strModule, pc.DefaultEncoding, SourceCodeKind.File);
code.Add((SavableScriptCode)context.LanguageContext.GetScriptCode(su, "__main__", ModuleOptions.Initialize, Compiler.CompilationMode.ToDisk));
}
}
SavableScriptCode.SaveToAssembly(assemblyName, kwArgs, code.ToArray());
}
#endif
#if FEATURE_REFEMIT
/// <summary>
/// clr.CompileSubclassTypes(assemblyName, *typeDescription)
///
/// Provides a helper for creating an assembly which contains pre-generated .NET
/// base types for new-style types.
///
/// This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached
/// types will be used instead of generating the types at runtime.
///
/// This function takes the name of the assembly to save to and then an arbitrary
/// number of parameters describing the types to be created. Each of those
/// parameter can either be a plain type or a sequence of base types.
///
/// clr.CompileSubclassTypes(object) -> create a base type for object
/// clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create
/// base types for both object and ArrayList.
///
/// clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for
/// object and an object which implements IComparable.
///
/// </summary>
public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[] newTypes) {
if (assemblyName == null) {
throw PythonOps.TypeError("CompileTypes expected str for assemblyName, got NoneType");
}
var typesToCreate = new List<PythonTuple>();
foreach (object o in newTypes) {
if (o is PythonType) {
typesToCreate.Add(PythonTuple.MakeTuple(o));
} else {
typesToCreate.Add(PythonTuple.Make(o));
}
}
NewTypeMaker.SaveNewTypes(assemblyName, typesToCreate);
}
#endif
/// <summary>
/// clr.GetSubclassedTypes() -> tuple
///
/// Returns a tuple of information about the types which have been subclassed.
///
/// This tuple can be passed to clr.CompileSubclassTypes to cache these
/// types on disk such as:
///
/// clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes())
/// </summary>
public static PythonTuple GetSubclassedTypes() {
List<object> res = new List<object>();
foreach (NewTypeInfo info in NewTypeMaker._newTypes.Keys) {