forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonContext.cs
More file actions
3963 lines (3265 loc) · 156 KB
/
PythonContext.cs
File metadata and controls
3963 lines (3265 loc) · 156 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Debugging.CompilerServices;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Hosting;
using IronPython.Modules;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Debugging = Microsoft.Scripting.Debugging;
using PyAst = IronPython.Compiler.Ast;
namespace IronPython.Runtime {
public delegate int HashDelegate(object o, ref HashDelegate dlg);
public sealed partial class PythonContext : LanguageContext {
internal static readonly string/*!*/ IronPythonDisplayName = CurrentVersion.DisplayName;
internal const string/*!*/ IronPythonNames = "IronPython;Python;py";
internal const string/*!*/ IronPythonFileExtensions = ".py";
private static readonly Guid PythonLanguageGuid = new Guid("03ed4b80-d10b-442f-ad9a-47dae85b2051");
private static readonly Guid LanguageVendor_Microsoft = new Guid(-1723120188, -6423, 0x11d2, 0x90, 0x3f, 0, 0xc0, 0x4f, 0xa3, 2, 0xa1);
private readonly Dictionary<string, ModuleGlobalCache>/*!*/ _builtinCache = new Dictionary<string, ModuleGlobalCache>(StringComparer.Ordinal);
#if FEATURE_ASSEMBLY_RESOLVE && FEATURE_FILESYSTEM
private readonly AssemblyResolveHolder _resolveHolder;
private readonly HashSet<Assembly> _loadedAssemblies = new HashSet<Assembly>();
#endif
// conditional variables for silverlight/desktop CLR features
private PythonService _pythonService;
private string _initialExecutable;
// other fields which might only be conditionally used
private string _initialVersionString;
private PythonModule _clrModule;
private PythonFileManager _fileManager;
private Dictionary<string, object> _errorHandlers;
private List<object> _searchFunctions;
private Dictionary<object, object> _moduleState;
/// <summary> stored for copyreg module, used for reduce protocol </summary>
internal BuiltinFunction NewObject;
/// <summary> stored for copyreg module, used for reduce protocol </summary>
internal BuiltinFunction PythonReconstructor;
private Dictionary<Type, object> _genericSiteStorage;
private CallSite<Func<CallSite, CodeContext, object, object>>[] _newUnarySites;
private CallSite<Func<CallSite, CodeContext, object, object, object, object>>[] _newTernarySites;
private CallSite<Func<CallSite, object, object, int>> _compareSite;
private Dictionary<AttrKey, CallSite<Func<CallSite, object, object, object>>> _setAttrSites;
private Dictionary<AttrKey, CallSite<Action<CallSite, object>>> _deleteAttrSites;
private CallSite<Func<CallSite, CodeContext, object, string, PythonTuple, object, object>> _metaClassSite;
private CallSite<Func<CallSite, CodeContext, object, string, object>> _writeSite;
private CallSite<Func<CallSite, object, object, object>> _getIndexSite, _equalSite;
private CallSite<Action<CallSite, object, object>> _delIndexSite;
private CallSite<Func<CallSite, CodeContext, object, object>> _finalizerSite;
private CallSite<Func<CallSite, CodeContext, PythonFunction, object>> _functionCallSite;
private CallSite<Func<CallSite, object, object, bool>> _greaterThanSite, _lessThanSite, _greaterThanEqualSite, _lessThanEqualSite, _containsSite;
private CallSite<Func<CallSite, CodeContext, object, object[], object>> _callSplatSite;
private CallSite<Func<CallSite, CodeContext, object, object[], IDictionary<object, object>, object>> _callDictSite;
private CallSite<Func<CallSite, CodeContext, object, object, object, object>> _callDictSiteLooselyTyped;
private CallSite<Func<CallSite, CodeContext, object, string, PythonDictionary, PythonDictionary, PythonTuple, int, object>> _importSite;
private CallSite<Func<CallSite, object, bool>> _isCallableSite;
private CallSite<Func<CallSite, object, IList<string>>> _getSignaturesSite;
private CallSite<Func<CallSite, object, object, object>> _addSite, _divModSite, _rdivModSite;
private CallSite<Func<CallSite, object, object, object, object>> _setIndexSite, _delSliceSite;
private CallSite<Func<CallSite, object, object, object, object, object>> _setSliceSite;
private CallSite<Func<CallSite, object, string>> _docSite;
// conversion sites
private CallSite<Func<CallSite, object, int>> _intSite;
private CallSite<Func<CallSite, object, string>> _tryStringSite;
private CallSite<Func<CallSite, object, object>> _tryIntSite;
private CallSite<Func<CallSite, object, IEnumerable>> _tryIEnumerableSite;
private Dictionary<Type, CallSite<Func<CallSite, object, object>>> _implicitConvertSites;
private Dictionary<PythonOperationKind, CallSite<Func<CallSite, object, object, object>>> _binarySites;
private Dictionary<Type, DefaultPythonComparer> _defaultComparer;
private Dictionary<Type, DefaultPythonLtComparer> _defaultLtComparer;
private CallSite<Func<CallSite, CodeContext, object, int, object>> _getItemCallSite;
private CallSite<Func<CallSite, CodeContext, object, object, object>> _propGetSite, _propDelSite;
private CallSite<Func<CallSite, CodeContext, object, object, object, object>> _propSetSite;
private CompiledLoader _compiledLoader;
private bool _importWarningThrows;
private bool _importedEncodings;
private Action<Action> _commandDispatcher; // can be null
private ClrModule.ReferencesList _referencesList;
private CultureInfo _collateCulture, _ctypeCulture, _timeCulture, _monetaryCulture, _numericCulture;
private Dictionary<Type, CallSite<Func<CallSite, object, object, bool>>> _equalSites;
private Dictionary<Type, PythonSiteCache> _systemSiteCache;
internal static readonly object _syntaxErrorNoCaret = new object();
// atomized binders
private PythonInvokeBinder _invokeNoArgs, _invokeOneArg;
private Dictionary<CallSignature, PythonInvokeBinder/*!*/> _invokeBinders;
private Dictionary<string/*!*/, PythonGetMemberBinder/*!*/> _getMemberBinders;
private Dictionary<string/*!*/, PythonGetMemberBinder/*!*/> _tryGetMemberBinders;
private Dictionary<string/*!*/, PythonSetMemberBinder/*!*/> _setMemberBinders;
private Dictionary<string/*!*/, PythonDeleteMemberBinder/*!*/> _deleteMemberBinders;
private Dictionary<string/*!*/, CompatibilityGetMember/*!*/> _compatGetMember;
private Dictionary<string/*!*/, CompatibilityGetMember/*!*/> _compatGetMemberNoThrow;
private Dictionary<PythonOperationKind, PythonOperationBinder/*!*/> _operationBinders;
private Dictionary<ExpressionType, PythonUnaryOperationBinder/*!*/> _unaryBinders;
private PythonBinaryOperationBinder[] _binaryBinders;
private Dictionary<OperationRetTypeKey<ExpressionType>, BinaryRetTypeBinder/*!*/> _binaryRetTypeBinders;
private Dictionary<OperationRetTypeKey<PythonOperationKind>, BinaryRetTypeBinder/*!*/> _operationRetTypeBinders;
private Dictionary<Type/*!*/, PythonConversionBinder/*!*/>[] _conversionBinders;
private Dictionary<Type/*!*/, DynamicMetaObjectBinder/*!*/>[] _convertRetObjectBinders;
private Dictionary<CallSignature, CreateFallback/*!*/> _createBinders;
private Dictionary<CallSignature, CompatibilityInvokeBinder/*!*/> _compatInvokeBinders;
private PythonGetSliceBinder _getSlice;
private PythonSetSliceBinder _setSlice;
private PythonDeleteSliceBinder _deleteSlice;
private PythonGetIndexBinder[] _getIndexBinders;
private PythonSetIndexBinder[] _setIndexBinders;
private PythonDeleteIndexBinder[] _deleteIndexBinders;
private static CultureInfo _CCulture;
private DynamicDelegateCreator _delegateCreator;
// tracing / in-proc debugging support
private DebugContext _debugContext;
private Debugging.TracePipeline _tracePipeline;
private readonly Microsoft.Scripting.Utils.ThreadLocal<PythonTracebackListener> _tracebackListeners = new Microsoft.Scripting.Utils.ThreadLocal<PythonTracebackListener>();
private int _tracebackListenersCount;
internal FunctionCode.CodeList _allCodes;
internal readonly object _codeCleanupLock = new object(), _codeUpdateLock = new object();
internal int _codeCount, _nextCodeCleanup = 200;
private int _recursionLimit;
internal readonly List<FunctionStack> _mainThreadFunctionStack;
private CallSite<Func<CallSite, CodeContext, object, object>> _callSite0LightEh;
private List<WeakReference> _weakExtensionMethodSets;
// store the Python types mapping to each .NET type
private readonly CommonDictionaryStorage _systemPythonTypesWeakRefs = new CommonDictionaryStorage();
#region Generated Python Shared Call Sites Storage
// *** BEGIN GENERATED CODE ***
// generated by function: gen_shared_call_sites_storage from: generate_calls.py
private CallSite<Func<CallSite, CodeContext, object, object>> _callSite0;
private CallSite<Func<CallSite, CodeContext, object, object, object>> _callSite1;
private CallSite<Func<CallSite, CodeContext, object, object, object, object>> _callSite2;
private CallSite<Func<CallSite, CodeContext, object, object, object, object, object>> _callSite3;
private CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object>> _callSite4;
private CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object>> _callSite5;
private CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object, object>> _callSite6;
// *** END GENERATED CODE ***
#endregion
/// <summary>
/// Creates a new PythonContext not bound to Engine.
/// </summary>
public PythonContext(ScriptDomainManager/*!*/ manager, IDictionary<string, object> options)
: base(manager) {
PythonOptions = new PythonOptions(options);
BuiltinModules = CreateBuiltinTable();
PythonDictionary defaultScope = new PythonDictionary();
ModuleContext modContext = new ModuleContext(defaultScope, this);
SharedContext = modContext.GlobalContext;
ModuleDictionaryStorage sysStorage = new ModuleDictionaryStorage(typeof(SysModule));
PythonDictionary sysDict = new PythonDictionary(sysStorage);
SystemState = new PythonModule(sysDict);
SystemState.__dict__["__name__"] = "sys";
SystemState.__dict__["__package__"] = null;
PythonBinder binder = new PythonBinder(this, SharedContext);
SharedOverloadResolverFactory = new PythonOverloadResolverFactory(binder, Expression.Constant(SharedContext));
Binder = binder;
CodeContext defaultClsContext = DefaultContext.CreateDefaultCLSContext(this);
SharedClsContext = defaultClsContext;
if (DefaultContext._default == null) {
DefaultContext.InitializeDefaults(SharedContext, defaultClsContext);
}
InitializeBuiltins();
InitializeSystemState();
// sys.argv always includes at least one empty string.
SetSystemStateValue("argv", (PythonOptions.Arguments.Count == 0) ?
new PythonList(new object[] { string.Empty }) :
new PythonList(PythonOptions.Arguments)
);
if (PythonOptions.WarningFilters.Count > 0) {
SystemState.__dict__["warnoptions"] = new PythonList(PythonOptions.WarningFilters);
}
if (PythonOptions.Frames) {
var getFrame = BuiltinFunction.MakeFunction(
"_getframe",
ArrayUtils.ConvertAll(typeof(SysModule).GetMember(nameof(SysModule._getframeImpl)), (x) => (MethodBase)x),
typeof(SysModule)
);
SystemState.__dict__["_getframe"] = getFrame;
}
if (PythonOptions.Tracing) {
EnsureDebugContext();
}
PythonList path = new PythonList(PythonOptions.SearchPaths);
#if FEATURE_ASSEMBLY_RESOLVE && FEATURE_FILESYSTEM
_resolveHolder = new AssemblyResolveHolder(this);
try {
Assembly entryAssembly = Assembly.GetEntryAssembly();
// Can be null if called from unmanaged code (VS integration scenario)
if (entryAssembly != null) {
string entry = Path.GetDirectoryName(entryAssembly.Location);
string lib = Path.Combine(entry, "Lib");
path.append(lib);
// add DLLs directory for user-defined extention modules
path.append(Path.Combine(entry, "DLLs"));
#if DEBUG
// For developer use, add Src/StdLib/Lib
string devStdLib = Path.Combine(entry, @"../../../Src/StdLib/Lib");
if (Directory.Exists(devStdLib))
path.append(devStdLib);
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
var dirs = new string[] { "lib", "DLLs" };
var version = CurrentVersion.ReleaseLevel == "final" ? $"{CurrentVersion.Major}.{CurrentVersion.Minor}.{CurrentVersion.Micro}" : $"{CurrentVersion.Major}.{CurrentVersion.Minor}.{CurrentVersion.Micro}-{CurrentVersion.ReleaseLevel}{CurrentVersion.ReleaseSerial}";
foreach (var dir in dirs) {
var p = $"/Library/Frameworks/IronPython.framework/Versions/{version}/{dir}";
if (Directory.Exists(p)) {
path.append(p);
}
}
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
var version = $"{CurrentVersion.Major}.{CurrentVersion.Minor}";
var dirs = new string[] { $"/usr/lib/ironpython{version}", $"/usr/share/ironpython{version}/DLLs" };
foreach (var dir in dirs) {
if (Directory.Exists(dir)) {
path.append(dir);
}
}
}
#endif
}
} catch (SecurityException) { }
#endif
SystemState.__dict__["path"] = path;
RecursionLimit = PythonOptions.RecursionLimit;
#if FEATURE_ASSEMBLY_RESOLVE && FEATURE_FILESYSTEM
if (options == null ||
!options.TryGetValue("NoAssemblyResolveHook", out object asmResolve) ||
!System.Convert.ToBoolean(asmResolve)) {
try {
HookAssemblyResolve();
} catch (System.Security.SecurityException) {
// We may not have SecurityPermissionFlag.ControlAppDomain.
// If so, we will not look up sys.path for module loads
}
}
#endif
EqualityComparer = new PythonEqualityComparer(this);
EqualityComparerNonGeneric = (IEqualityComparer)EqualityComparer;
InitialHasher = InitialHasherImpl;
IntHasher = IntHasherImpl;
DoubleHasher = DoubleHasherImpl;
StringHasher = StringHasherImpl;
FallbackHasher = FallbackHasherImpl;
TopNamespace = new TopNamespaceTracker(manager);
foreach (Assembly asm in manager.GetLoadedAssemblyList()) {
TopNamespace.LoadAssembly(asm);
}
manager.AssemblyLoaded += new EventHandler<AssemblyLoadedEventArgs>(ManagerAssemblyLoaded);
_mainThreadFunctionStack = PythonOps.GetFunctionStack();
// bootstrap importlib
try {
var sourceUnit = CreateSourceUnit(new BootstrapStreamContentProvider(), null, DefaultEncoding, SourceCodeKind.File);
var moduleOptions = ModuleOptions.Initialize | ModuleOptions.Optimized;
var scriptCode = GetScriptCode(sourceUnit, "_frozen_importlib", moduleOptions);
var scope = scriptCode.CreateScope();
var _frozen_importlib = InitializeModule(null, ((PythonScopeExtension)scope.GetExtension(ContextId)).ModuleContext, scriptCode, moduleOptions);
PythonOps.Invoke(SharedClsContext, _frozen_importlib, "_install", SystemState, GetBuiltinModule("_imp"));
} catch { }
}
private sealed class BootstrapStreamContentProvider : StreamContentProvider {
public override Stream GetStream() {
return typeof(PythonContext).Assembly.GetManifestResourceStream("IronPython.Modules._bootstrap.py");
}
}
private void ManagerAssemblyLoaded(object sender, AssemblyLoadedEventArgs e) {
TopNamespace.LoadAssembly(e.Assembly);
}
/// <summary>
/// Gets or sets the maximum depth of function calls. Equivalent to sys.getrecursionlimit
/// and sys.setrecursionlimit.
/// </summary>
public int RecursionLimit {
get {
return _recursionLimit;
}
set {
if (value < 0) {
throw PythonOps.ValueError("recursion limit must be positive");
}
lock (_codeUpdateLock) {
_recursionLimit = value;
if ((_recursionLimit == int.MaxValue) != (value == int.MaxValue)) {
// recursion setting has changed, we need to update all of our
// function codes to enforce or un-enforce recursion.
FunctionCode.UpdateAllCode(this);
}
}
}
}
internal bool EnableTracing {
get {
return PythonOptions.Tracing || _tracebackListenersCount > 0;
}
}
internal TopNamespaceTracker TopNamespace { get; }
#if FEATURE_THREAD
/// <summary>
/// Gets or sets the main thread which should be interupted by thread.interrupt_main
/// </summary>
public Thread MainThread { get; set; }
#endif
public IEqualityComparer<object>/*!*/ EqualityComparer { get; }
public IEqualityComparer/*!*/ EqualityComparerNonGeneric { get; }
internal sealed class PythonEqualityComparer : IEqualityComparer, IEqualityComparer<object> {
public readonly PythonContext/*!*/ Context;
public PythonEqualityComparer(PythonContext/*!*/ context) {
Assert.NotNull(context);
Context = context;
}
bool IEqualityComparer.Equals(object x, object y) {
return PythonOps.EqualRetBool(Context.SharedContext, x, y);
}
bool IEqualityComparer<object>.Equals(object x, object y) {
return PythonOps.EqualRetBool(Context.SharedContext, x, y);
}
int IEqualityComparer.GetHashCode(object obj) {
return PythonContext.Hash(obj);
}
int IEqualityComparer<object>.GetHashCode(object obj) {
return PythonContext.Hash(obj);
}
}
#region Specialized Hashers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal readonly HashDelegate InitialHasher;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal readonly HashDelegate IntHasher;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal readonly HashDelegate DoubleHasher;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal readonly HashDelegate StringHasher;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
internal readonly HashDelegate FallbackHasher;
private int InitialHasherImpl(object o, ref HashDelegate dlg) {
if (o == null) {
return NoneTypeOps.NoneHashCode;
}
switch (o.GetType().GetTypeCode()) {
case TypeCode.String:
dlg = StringHasher;
return StringHasher(o, ref dlg);
case TypeCode.Int32:
dlg = IntHasher;
return IntHasher(o, ref dlg);
case TypeCode.Double:
dlg = DoubleHasher;
return DoubleHasher(o, ref dlg);
default:
if (o is IPythonObject) {
dlg = new OptimizedUserHasher(this, ((IPythonObject)o).PythonType).Hasher;
} else {
dlg = new OptimizedBuiltinHasher(this, o.GetType()).Hasher;
}
return dlg(o, ref dlg);
}
}
private int IntHasherImpl(object o, ref HashDelegate dlg) {
if (o != null && o.GetType() == typeof(int)) {
return o.GetHashCode();
}
dlg = FallbackHasher;
return FallbackHasher(o, ref dlg);
}
private int DoubleHasherImpl(object o, ref HashDelegate dlg) {
if (o != null && o.GetType() == typeof(double)) {
return DoubleOps.__hash__((double)o);
}
dlg = FallbackHasher;
return FallbackHasher(o, ref dlg);
}
private int StringHasherImpl(object o, ref HashDelegate dlg) {
if (o != null && o.GetType() == typeof(string)) {
return o.GetHashCode();
}
dlg = FallbackHasher;
return FallbackHasher(o, ref dlg);
}
private int FallbackHasherImpl(object o, ref HashDelegate dlg) {
return PythonOps.Hash(SharedContext, o);
}
private sealed class OptimizedUserHasher {
private readonly PythonContext _context;
private readonly PythonType _pt;
public OptimizedUserHasher(PythonContext context, PythonType pt) {
_context = context;
_pt = pt;
}
public int Hasher(object o, ref HashDelegate dlg) {
if (o is IPythonObject ipo && ipo.PythonType == _pt) {
return _pt.Hash(o);
}
dlg = _context.FallbackHasher;
return _context.FallbackHasher(o, ref dlg);
}
}
private sealed class OptimizedBuiltinHasher {
private readonly PythonContext _context;
private readonly Type _type;
private readonly PythonType _pt;
public OptimizedBuiltinHasher(PythonContext context, Type type) {
_context = context;
_type = type;
_pt = DynamicHelpers.GetPythonTypeFromType(type);
}
public int Hasher(object o, ref HashDelegate dlg) {
if (o != null && o.GetType() == _type) {
return _pt.Hash(o);
}
dlg = _context.FallbackHasher;
return _context.FallbackHasher(o, ref dlg);
}
}
#endregion
public override LanguageOptions/*!*/ Options => PythonOptions;
/// <summary>
/// Checks to see if module state has the current value stored already.
/// </summary>
public bool HasModuleState(object key) {
EnsureModuleState();
lock (_moduleState) {
return _moduleState.ContainsKey(key);
}
}
private void EnsureModuleState() {
if (_moduleState == null) {
Interlocked.CompareExchange(ref _moduleState, new Dictionary<object, object>(), null);
}
}
/// <summary>
/// Gets per-runtime state used by a module. The module should have a unique key for
/// each piece of state it needs to store.
/// </summary>
public object GetModuleState(object key) {
EnsureModuleState();
lock (_moduleState) {
Debug.Assert(_moduleState.ContainsKey(key));
return _moduleState[key];
}
}
/// <summary>
/// Sets per-runtime state used by a module. The module should have a unique key for
/// each piece of state it needs to store.
/// </summary>
public void SetModuleState(object key, object value) {
EnsureModuleState();
lock (_moduleState) {
_moduleState[key] = value;
}
}
/// <summary>
/// Sets per-runtime state used by a module and returns the previous value. The module
/// should have a unique key for each piece of state it needs to store.
/// </summary>
public object GetSetModuleState(object key, object value) {
EnsureModuleState();
lock (_moduleState) {
object result;
_moduleState.TryGetValue(key, out result);
_moduleState[key] = value;
return result;
}
}
/// <summary>
/// Sets per-runtime state used by a module and returns the previous value. The module
/// should have a unique key for each piece of state it needs to store.
/// </summary>
public T GetOrCreateModuleState<T>(object key, Func<T> value) where T : class {
EnsureModuleState();
lock (_moduleState) {
object result;
if (!_moduleState.TryGetValue(key, out result)) {
_moduleState[key] = result = value();
}
return (result as T);
}
}
public PythonType EnsureModuleException(object key, PythonDictionary dict, string name, string module) {
return (PythonType)(dict[name] = GetOrCreateModuleState(
key,
() => PythonExceptions.CreateSubType(this, PythonExceptions.Exception, name, module, null, PythonType.DefaultMakeException)
));
}
public PythonType EnsureModuleException(object key, PythonType baseType, PythonDictionary dict, string name, string module) {
return (PythonType)(dict[name] = GetOrCreateModuleState(
key,
() => PythonExceptions.CreateSubType(this, baseType, name, module, null, PythonType.DefaultMakeException)
));
}
public PythonType EnsureModuleException(object key, PythonType baseType, Type underlyingType, PythonDictionary dict, string name, string module, Func<string, Exception, Exception> exceptionMaker) {
return (PythonType)(dict[name] = GetOrCreateModuleState(
key,
() => PythonExceptions.CreateSubType(this, baseType, underlyingType, name, module, null, exceptionMaker)
));
}
public PythonType EnsureModuleException(object key, PythonType baseType, Type underlyingType, PythonDictionary dict, string name, string module, string documentation, Func<string, Exception, Exception> exceptionMaker) {
return (PythonType)(dict[name] = GetOrCreateModuleState(
key,
() => PythonExceptions.CreateSubType(this, baseType, underlyingType, name, module, documentation, exceptionMaker)
));
}
public PythonType EnsureModuleException(object key, PythonType[] baseTypes, Type underlyingType, PythonDictionary dict, string name, string module) {
return (PythonType)(dict[name] = GetOrCreateModuleState(
key,
() => PythonExceptions.CreateSubType(this, baseTypes, underlyingType, name, module, null, PythonType.DefaultMakeException)
));
}
internal PythonOptions/*!*/ PythonOptions { get; }
public override Guid VendorGuid => LanguageVendor_Microsoft;
public override Guid LanguageGuid => PythonLanguageGuid;
public PythonModule/*!*/ SystemState { get; }
public PythonModule/*!*/ ClrModule {
get {
if (_clrModule == null) {
Interlocked.CompareExchange(ref _clrModule, CreateBuiltinModule("clr"), null);
}
return _clrModule;
}
}
internal bool TryGetSystemPath(out PythonList path) {
if (SystemState.__dict__.TryGetValue("path", out object val)) {
path = val as PythonList;
} else {
path = null;
}
return path != null;
}
internal object SystemStandardOut => GetSystemStateValue("stdout");
internal object SystemStandardIn => GetSystemStateValue("stdin");
internal object SystemStandardError => GetSystemStateValue("stderr");
internal IDictionary<object, object>/*!*/ SystemStateModules { get; } = new PythonDictionary();
internal PythonModule GetModuleByName(string/*!*/ name) {
Assert.NotNull(name);
if (SystemStateModules.TryGetValue(name, out object scopeObj) && scopeObj is PythonModule module) {
return module;
}
return null;
}
internal PythonModule GetModuleByPath(string/*!*/ path) {
Assert.NotNull(path);
foreach (object moduleObj in SystemStateModules.Values) {
if (moduleObj is PythonModule module) {
if (DomainManager.Platform.PathComparer.Compare(module.GetFile(), path) == 0) {
return module;
}
}
}
return null;
}
public override Version LanguageVersion => GetPythonVersion();
internal static Version GetPythonVersion()
=> new AssemblyName(typeof(PythonContext).Assembly.FullName).Version;
internal FloatFormat FloatFormat { get; set; }
internal FloatFormat DoubleFormat { get; set; }
/// <summary>
/// Initializes the sys module on startup. Called both to load and reload sys
/// </summary>
private void InitializeSystemState() {
// These fields do not get reset on "reload(sys)", we populate them once on startup
SetSystemStateValue("argv", PythonList.FromArrayNoCopy(new object[] { string.Empty }));
SetSystemStateValue("modules", SystemStateModules);
InitializeSysFlags();
SystemStateModules["sys"] = SystemState;
SetSystemStateValue("path", new PythonList(3));
SetStandardIO();
SysModule.PerformModuleReload(this, SystemState.__dict__);
}
internal bool EmitDebugSymbols(SourceUnit sourceUnit) {
return sourceUnit.EmitDebugSymbols && (PythonOptions.NoDebug == null || !PythonOptions.NoDebug.IsMatch(sourceUnit.Path));
}
private void InitializeSysFlags() {
// sys.flags
SysModule.SysFlags flags = new SysModule.SysFlags();
SetSystemStateValue("flags", flags);
flags.debug = PythonOptions.Debug ? 1 : 0;
flags.inspect = flags.interactive = PythonOptions.Inspect ? 1 : 0;
if (PythonOptions.StripDocStrings) {
flags.optimize = 2;
} else if (PythonOptions.Optimize) {
flags.optimize = 1;
}
flags.dont_write_bytecode = 1;
SetSystemStateValue("dont_write_bytecode", true);
flags.no_user_site = PythonOptions.NoUserSite ? 1 : 0;
flags.no_site = PythonOptions.NoSite ? 1 : 0;
flags.ignore_environment = PythonOptions.IgnoreEnvironment ? 1 : 0;
switch (PythonOptions.IndentationInconsistencySeverity) {
case Severity.Warning:
flags.tabcheck = 1;
break;
case Severity.Error:
flags.tabcheck = 2;
break;
}
flags.verbose = PythonOptions.Verbose ? 1 : 0;
flags.unicode = 1;
flags.bytes_warning = PythonOptions.BytesWarning ? 1 : 0;
flags.quiet = PythonOptions.Quiet ? 1 : 0;
}
internal bool ShouldInterpret(PythonCompilerOptions options, SourceUnit source) {
// We have to turn off adaptive compilation in debug mode to
// support mangaged debuggers. Also turn off in optimized mode.
bool adaptiveCompilation = !PythonOptions.NoAdaptiveCompilation && !EmitDebugSymbols(source);
return options.Interpreted || adaptiveCompilation;
}
private static PyAst.PythonAst ParseAndBindAst(CompilerContext context) {
ScriptCodeParseResult properties = ScriptCodeParseResult.Complete;
bool propertiesSet = false;
int errorCode = 0;
PyAst.PythonAst ast;
using (Parser parser = Parser.CreateParser(context, PythonContext.GetPythonOptions(null))) {
switch (context.SourceUnit.Kind) {
case SourceCodeKind.InteractiveCode:
ast = parser.ParseInteractiveCode(out properties);
propertiesSet = true;
break;
case SourceCodeKind.Expression:
ast = parser.ParseTopExpression();
break;
case SourceCodeKind.SingleStatement:
ast = parser.ParseSingleStatement();
break;
case SourceCodeKind.File:
ast = parser.ParseFile(true, false);
break;
case SourceCodeKind.Statements:
ast = parser.ParseFile(false, false);
break;
default:
case SourceCodeKind.AutoDetect:
ast = parser.ParseFile(true, true);
break;
}
errorCode = parser.ErrorCode;
}
if (!propertiesSet && errorCode != 0) {
properties = ScriptCodeParseResult.Invalid;
}
context.SourceUnit.CodeProperties = properties;
if (errorCode != 0 || properties == ScriptCodeParseResult.Empty) {
return null;
}
ast.Bind();
return ast;
}
internal static ScriptCode CompilePythonCode(SourceUnit/*!*/ sourceUnit, CompilerOptions/*!*/ options, ErrorSink/*!*/ errorSink) {
var pythonOptions = (PythonCompilerOptions)options;
if (sourceUnit.Kind == SourceCodeKind.File) {
pythonOptions.Module |= ModuleOptions.Initialize;
}
CompilerContext context = new CompilerContext(sourceUnit, options, errorSink);
PyAst.PythonAst ast = ParseAndBindAst(context);
if (ast == null) {
return null;
}
return ast.ToScriptCode();
}
public override ScriptCode CompileSourceCode(SourceUnit/*!*/ sourceUnit, CompilerOptions/*!*/ options, ErrorSink/*!*/ errorSink) {
ScriptCode res = CompilePythonCode(sourceUnit, options, errorSink);
if (res != null) {
Scope scope = res.CreateScope();
// if this is an optimized module we need to initialize the optimized scope.
// Optimized scopes come w/ extensions already attached so we use that to know
// if we're optimized or not.
PythonScopeExtension scopeExtension = (PythonScopeExtension)scope.GetExtension(ContextId);
if (scopeExtension != null) {
InitializeModule(sourceUnit.Path, scopeExtension.ModuleContext, res, ModuleOptions.None);
}
}
return res;
}
public override ScriptCode/*!*/ LoadCompiledCode(Delegate/*!*/ method, string path, string customData) {
// allow loading cross-platform (https://github.com/IronLanguages/ironpython2/issues/476)
if (Path.DirectorySeparatorChar != '\\') path = path.Replace('\\', Path.DirectorySeparatorChar);
if (Path.DirectorySeparatorChar != '/') path = path.Replace('/', Path.DirectorySeparatorChar);
SourceUnit su = new SourceUnit(this, NullTextContentProvider.Null, path, SourceCodeKind.File);
return new OnDiskScriptCode((LookupCompilationDelegate)method, su, customData);
}
public override SourceCodeReader/*!*/ GetSourceReader(Stream/*!*/ stream, Encoding/*!*/ defaultEncoding, string path) {
ContractUtils.RequiresNotNull(stream, nameof(stream));
ContractUtils.RequiresNotNull(defaultEncoding, nameof(defaultEncoding));
ContractUtils.Requires(stream.CanSeek && stream.CanRead, nameof(stream), "The stream must support seeking and reading");
stream.Seek(0, SeekOrigin.Begin);
Encoding sourceEncoding = null;
string encodingName = null;
int linesRead = 0;
bool hasBom = false;
// sr is used to detect encoding from BOM
Encoding bootstrapEncoding = Encoding.ASCII;
using (StreamReader sr = new StreamReader(stream, bootstrapEncoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1, leaveOpen: true)) {
sr.Peek(); // will detect BOM
if (!ReferenceEquals(sr.CurrentEncoding, bootstrapEncoding)) {
// stream autodetected a Unicode encoding from BOM
sourceEncoding = bootstrapEncoding = sr.CurrentEncoding;
hasBom = true;
}
}
// back to the begining of text data
stream.Seek(bootstrapEncoding.GetPreamble().Length, SeekOrigin.Begin);
// read the magic comments (PEP-263)
string line;
int maxMagicLineLen = 512;
line = ReadOneLine(stream, maxMagicLineLen);
linesRead++;
// magic encoding must be on line 1 or 2
// if there is any encoding specified on line 1 (even an invalid one), line 2 is ignored
// line 2 is also ignored if there was no EOL within the limit of bytes
if (line != null && (encodingName = Tokenizer.GetEncodingNameFromComment(line)) == null && (line[line.Length - 1] == '\r' || line[line.Length - 1] == '\n')) {
// try the second line
line = ReadOneLine(stream, maxMagicLineLen);
linesRead++;
encodingName = Tokenizer.GetEncodingNameFromComment(line);
}
if (hasBom && sourceEncoding.CodePage == 65001 && encodingName != null && encodingName != "utf-8" && encodingName != "utf-8-sig") {
// we have both a UTF-8 BOM & a declared encoding different than 'utf-8' -> throw an error in accordance with PEP-236
// CPython will accept 'utf-8-sig' as well, which makes sense
throw PythonOps.BadSourceEncodingError(
$"encoding problem: {encodingName} with BOM. Only \"utf-8\" is allowed as the encoding name when a UTF-8 BOM is present (PEP-236)", linesRead, path);
}
if (encodingName != null) {
// we have an encoding declared in the magic comment
if (!StringOps.TryGetEncoding(encodingName, out Encoding declaredEncoding)) {
throw PythonOps.BadSourceEncodingError($"unknown encoding: {encodingName}", linesRead, path);
}
if (sourceEncoding == null) {
// no autodetected encoding, use the one from the explicit declaration
sourceEncoding = declaredEncoding;
}
}
if (sourceEncoding == null) {
// not autodetected and not declared, hence use default
sourceEncoding = defaultEncoding;
} else {
#if FEATURE_ENCODING
sourceEncoding = (Encoding)sourceEncoding.Clone();
sourceEncoding.DecoderFallback = DecoderFallback.ExceptionFallback;
#endif
}
// seek back to the beginning to correctly report invalid bytes, if any
stream.Seek(0, SeekOrigin.Begin);
// re-read w/ the correct encoding type
// disable autodetection so that the strict error handler is intact
// encodings with non-empty preable will skip it over on reading
return new SourceCodeReader(new StreamReader(stream, sourceEncoding, detectEncodingFromByteOrderMarks: false), sourceEncoding);
}
/// <summary>
/// Reads one line up to the given limit of bytes, decoding it using ISO-8859-1.
/// </summary>
/// <returns>
/// Decoded line including the EOL characters, possibly truncated at the limit of bytes.
/// null if EOS.
/// </returns>
private static string ReadOneLine(Stream stream, int maxBytes) {
byte[] buffer = new byte[maxBytes];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) return null; // EOS
int i = 0;
while (i < bytesRead) {
int c = buffer[i++];
if (c == '\r') {
if (i < bytesRead) {
// LF following CR must be included too
if (buffer[i] == '\n') i++;
// seek back to the byte after CR or CRLF
stream.Seek(i - bytesRead, SeekOrigin.Current);
} else {
// the buffer ends on CR, check whether the next byte is LF, if so, it has to be skipped
if ((c = stream.ReadByte()) != -1 && c != '\n') stream.Seek(-1, SeekOrigin.Current);
}
return buffer.MakeString(i);
} else if (c == '\n') {
// seek back to the byte after LF
stream.Seek(i - bytesRead, SeekOrigin.Current);
return buffer.MakeString(i);
}
}
// completing the loop means there was no EOL within the limit
if (i == maxBytes) i--; // CPython behavior
return buffer.MakeString(i);
}
#if FEATURE_CODEDOM
// Convert a CodeDom to source code, and output the generated code and the line number mappings (if any)
public override SourceUnit/*!*/ GenerateSourceCode(System.CodeDom.CodeObject codeDom, string path, SourceCodeKind kind) {
return new IronPython.Hosting.PythonCodeDomCodeGen().GenerateCode((System.CodeDom.CodeMemberMethod)codeDom, this, path, kind);
}
#endif
#region Scopes
public override Scope GetScope(string/*!*/ path)
=> GetModuleByPath(path)?.Scope;
public PythonModule/*!*/ InitializeModule(string fileName, ModuleContext moduleContext, ScriptCode scriptCode, ModuleOptions options) {
if ((options & ModuleOptions.NoBuiltins) == 0) {
moduleContext.InitializeBuiltins((options & ModuleOptions.ModuleBuiltins) != 0);
}
// If the filename is __init__.py then this is the initialization code
// for a package and we need to set the __path__ variable appropriately
if (fileName != null && Path.GetFileName(fileName) == "__init__.py") {
string dirname = Path.GetDirectoryName(fileName);
string dir_path = DomainManager.Platform.GetFullPath(dirname);
moduleContext.Globals["__path__"] = PythonOps.MakeList(dir_path);
}
moduleContext.ShowCls = (options & ModuleOptions.ShowClsMethods) != 0;
moduleContext.Features = options;
if ((options & ModuleOptions.Initialize) != 0) {
scriptCode.Run(moduleContext.GlobalScope);
if (!moduleContext.Globals.ContainsKey("__package__")) {
moduleContext.Globals["__package__"] = null;