forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonType.cs
More file actions
3468 lines (2860 loc) · 132 KB
/
PythonType.cs
File metadata and controls
3468 lines (2860 loc) · 132 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.Linq.Expressions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime.Types {
/// <summary>
/// Represents a PythonType. Instances of PythonType are created via PythonTypeBuilder.
/// </summary>
[DebuggerDisplay("PythonType: {Name}"), DebuggerTypeProxy(typeof(PythonType.DebugProxy))]
[PythonType("type")]
[Documentation(@"type(object) -> gets the type of the object
type(name, bases, dict) -> creates a new type instance with the given name, base classes, and members from the dictionary")]
public partial class PythonType : IPythonMembersList, IDynamicMetaObjectProvider, IWeakReferenceable, IWeakReferenceableByProxy, ICodeFormattable, IFastGettable, IFastSettable, IFastInvokable {
private Type/*!*/ _underlyingSystemType; // the underlying CLI system type for this type
private string _name; // the name of the type
private Dictionary<string, PythonTypeSlot> _dict; // type-level slots & attributes
private PythonTypeAttributes _attrs; // attributes of the type
private int _flags; // CPython-like flags on the type
private int _version = GetNextVersion(); // version of the type
private List<WeakReference> _subtypes; // all of the subtypes of the PythonType
private PythonContext _pythonContext; // the context the type was created from, or null for system types.
private bool? _objectNew, _objectInit; // true if the type doesn't override __new__ / __init__ from object.
internal Dictionary<CachedGetKey, FastGetBase> _cachedGets; // cached gets on user defined type instances
internal Dictionary<CachedGetKey, FastGetBase> _cachedTryGets; // cached try gets on used defined type instances
internal Dictionary<SetMemberKey, FastSetBase> _cachedSets; // cached sets on user defined instances
internal Dictionary<string, TypeGetBase> _cachedTypeGets; // cached gets on types (system and user types)
internal Dictionary<string, TypeGetBase> _cachedTypeTryGets; // cached gets on types (system and user types)
// commonly calculatable
private List<PythonType> _resolutionOrder; // the search order for methods in the type
private PythonType/*!*/[]/*!*/ _bases; // the base classes of the type
private BuiltinFunction _ctor; // the built-in function which allocates an instance - a .NET ctor
private Type _finalSystemType; // base .NET type if we're inherited from another Python-like type.
// fields that frequently remain null
private WeakRefTracker _weakrefTracker; // storage for Python style weak references
private WeakReference _weakRef; // single weak ref instance used for all user PythonTypes.
private string[] _slots; // the slots when the class was created
private int _originalSlotCount; // the number of slots when the type was created
private InstanceCreator _instanceCtor; // creates instances
private CallSite<Func<CallSite, object, int>> _hashSite;
private CallSite<Func<CallSite, object, object, bool>> _eqSite;
private CallSite<Func<CallSite, object, object, int>> _compareSite;
private Dictionary<CallSignature, LateBoundInitBinder> _lateBoundInitBinders;
private string[] _optimizedInstanceNames; // optimized names stored in a custom dictionary
private int _optimizedInstanceVersion;
private Dictionary<string, List<MethodInfo>> _extensionMethods; // extension methods defined on the type
private PythonSiteCache _siteCache = new PythonSiteCache();
private PythonTypeSlot _lenSlot; // cached length slot, cleared when the type is mutated
internal Func<string, Exception, Exception> _makeException = DefaultMakeException;
[MultiRuntimeAware]
private static int MasterVersion = 1;
private static readonly CommonDictionaryStorage _pythonTypes = new CommonDictionaryStorage();
internal static readonly PythonType _pythonTypeType = DynamicHelpers.GetPythonTypeFromType(typeof(PythonType));
private static readonly WeakReference[] _emptyWeakRef = new WeakReference[0];
private static object _subtypesLock = new object();
internal static readonly Func<string, Exception, Exception> DefaultMakeException = (message, innerException) => new Exception(message, innerException);
internal static readonly Func<string, Exception> DefaultMakeExceptionNoInnerException = (message) => new Exception(message);
/// <summary>
/// Provides delegates that will invoke a parameterless type ctor. The first key provides
/// the dictionary for a specific type, the 2nd key provides the delegate for a specific
/// call site type used in conjunction w/ our IFastInvokable implementation.
/// </summary>
private static Dictionary<Type, Dictionary<Type, Delegate>> _fastBindCtors = new Dictionary<Type, Dictionary<Type, Delegate>>();
/// <summary>
/// Shared built-in functions for creating instances of user defined types. Because all
/// types w/ the same UnderlyingSystemType share the same constructors these can be
/// shared across multiple types.
/// </summary>
private static Dictionary<Type, BuiltinFunction> _userTypeCtors = new Dictionary<Type, BuiltinFunction>();
/// <summary>
/// Creates a new type for a user defined type. The name, base classes (a tuple of type
/// objects), and a dictionary of members is provided.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PythonType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict)
: this(context, name, bases, dict, String.Empty) {
}
/// <summary>
/// Creates a new type for a user defined type. The name, base classes (a tuple of type
/// objects), and a dictionary of members is provided.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal PythonType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict, string selfNames) {
InitializeUserType(context, name, bases, dict, selfNames);
}
internal PythonType() {
}
/// <summary>
/// Creates a new PythonType object which is backed by the specified .NET type for
/// storage. The type is considered a system type which can not be modified
/// by the user.
/// </summary>
/// <param name="underlyingSystemType"></param>
internal PythonType(Type underlyingSystemType) {
_underlyingSystemType = underlyingSystemType;
InitializeSystemType();
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonType.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonType baseType, string name, Func<string, Exception, Exception> exceptionMaker) {
_underlyingSystemType = baseType.UnderlyingSystemType;
IsSystemType = baseType.IsSystemType;
IsPythonType = baseType.IsPythonType;
Name = name;
_bases = new PythonType[] { baseType };
ResolutionOrder = Mro.Calculate(this, _bases);
_attrs |= PythonTypeAttributes.HasDictionary;
_makeException = exceptionMaker;
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonTypes.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonType[] baseTypes, string name) {
bool isSystemType = false;
bool isPythonType = false;
foreach (PythonType baseType in baseTypes) {
isSystemType |= baseType.IsSystemType;
isPythonType |= baseType.IsPythonType;
}
IsSystemType = isSystemType;
IsPythonType = isPythonType;
Name = name;
_bases = baseTypes;
ResolutionOrder = Mro.Calculate(this, _bases);
_attrs |= PythonTypeAttributes.HasDictionary;
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonTypes.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonType[] baseTypes, Type underlyingType, string name, Func<string, Exception, Exception> exceptionMaker)
: this(baseTypes, name) {
_underlyingSystemType = underlyingType;
_makeException = exceptionMaker;
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonType.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonContext context, PythonType baseType, string name, string module, string doc, Func<string, Exception, Exception> exceptionMaker)
: this(baseType, name, exceptionMaker) {
EnsureDict();
_dict["__doc__"] = new PythonTypeUserDescriptorSlot(doc, true);
_dict["__module__"] = new PythonTypeUserDescriptorSlot(module, true);
IsSystemType = false;
IsPythonType = false;
_pythonContext = context;
_attrs |= PythonTypeAttributes.HasDictionary;
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonTypes.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonContext context, PythonType[] baseTypes, string name, string module, string doc)
: this(baseTypes, name) {
EnsureDict();
_dict["__doc__"] = new PythonTypeUserDescriptorSlot(doc, true);
_dict["__module__"] = new PythonTypeUserDescriptorSlot(module, true);
_pythonContext = context;
_attrs |= PythonTypeAttributes.HasDictionary;
}
/// <summary>
/// Creates a new PythonType which is a subclass of the specified PythonTypes.
///
/// Used for runtime defined new-style classes which require multiple inheritance. The
/// primary example of this is the exception system.
/// </summary>
internal PythonType(PythonContext context, PythonType[] baseTypes, Type underlyingType, string name, string module, string doc, Func<string, Exception, Exception> exceptionMaker)
: this(baseTypes, underlyingType, name, exceptionMaker) {
EnsureDict();
_dict["__doc__"] = new PythonTypeUserDescriptorSlot(doc, true);
_dict["__module__"] = new PythonTypeUserDescriptorSlot(module, true);
IsSystemType = false;
IsPythonType = false;
_pythonContext = context;
_attrs |= PythonTypeAttributes.HasDictionary;
}
internal BuiltinFunction Ctor {
get {
EnsureConstructor();
return _ctor;
}
}
#region Public API
public static object __new__(CodeContext/*!*/ context, PythonType cls, string name, PythonTuple bases, PythonDictionary dict) {
return __new__(context, cls, name, bases, dict, String.Empty);
}
internal static object __new__(CodeContext/*!*/ context, PythonType cls, string name, PythonTuple bases, PythonDictionary dict, string selfNames) {
if (name == null) {
throw PythonOps.TypeError("type() argument 1 must be string, not None");
}
if (bases == null) {
throw PythonOps.TypeError("type() argument 2 must be tuple, not None");
}
if (dict == null) {
throw PythonOps.TypeError("TypeError: type() argument 3 must be dict, not None");
}
EnsureModule(context, dict);
PythonType meta = FindMetaClass(cls, bases);
if (meta != TypeCache.PythonType) {
object classdict = PythonOps.CallPrepare(context, meta, name, bases, dict);
if (meta != cls) {
// the user has a custom __new__ which picked the wrong meta class, call the correct metaclass
return PythonCalls.Call(context, meta, name, bases, classdict);
}
// we have the right user __new__, call our ctor method which will do the actual
// creation.
return meta.CreateInstance(context, name, bases, classdict);
}
// no custom user type for __new__
return new PythonType(context, name, bases, dict, selfNames);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __init__(string name, PythonTuple bases, PythonDictionary dict) {
}
internal static PythonType FindMetaClass(PythonType cls, PythonTuple bases) {
PythonType meta = cls;
foreach (object dt in bases) {
PythonType metaCls = DynamicHelpers.GetPythonType(dt);
if (meta.IsSubclassOf(metaCls)) continue;
if (metaCls.IsSubclassOf(meta)) {
meta = metaCls;
continue;
}
throw PythonOps.TypeError("metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases");
}
return meta;
}
public static object __new__(CodeContext/*!*/ context, object cls, object o) {
return DynamicHelpers.GetPythonType(o);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __init__(object o) {
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static PythonTuple Get__bases__(CodeContext/*!*/ context, PythonType/*!*/ type) {
return type.GetBasesTuple();
}
private PythonTuple GetBasesTuple() {
object[] res = new object[BaseTypes.Count];
IList<PythonType> bases = BaseTypes;
for (int i = 0; i < bases.Count; i++) {
PythonType baseType = bases[i];
res[i] = baseType;
}
return PythonTuple.MakeTuple(res);
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static PythonType Get__base__(CodeContext/*!*/ context, PythonType/*!*/ type) {
foreach (object typeObj in Get__bases__(context, type)) {
if (typeObj is PythonType pt) {
return pt;
}
}
return null;
}
/// <summary>
/// Used in copyreg which is the only consumer of __flags__ in the standard library.
///
/// Set if the type is user defined
/// </summary>
private const int TypeFlagHeapType = 0x00000200;
/// <summary>
/// Set if the type has __abstractmethods__ defined
/// </summary>
private const int TypeFlagAbstractMethodsDefined = 0x00080000;
private const int TypeFlagAbstractMethodsNonEmpty = 0x00100000;
private bool SetAbstractMethodFlags(string name, object value) {
if (name != "__abstractmethods__") {
return false;
}
int res = _flags | TypeFlagAbstractMethodsDefined;
IEnumerator enumerator;
if (value == null ||
!PythonOps.TryGetEnumerator(DefaultContext.Default, value, out enumerator) ||
!enumerator.MoveNext()) {
// CPython treats None, non-iterables, and empty iterables as empty sets
// of abstract methods, and sets this flag accordingly
res &= ~(TypeFlagAbstractMethodsNonEmpty);
} else {
res |= TypeFlagAbstractMethodsNonEmpty;
}
_flags = res;
return true;
}
/// <summary>
/// Check whether the current type is iterable
/// </summary>
/// <param name="context"></param>
/// <returns>True if it is iterable</returns>
internal bool IsIterable(CodeContext context) {
object _dummy = null;
if (PythonOps.TryGetBoundAttr(context, this, "__iter__", out _dummy) &&
!Object.ReferenceEquals(_dummy, NotImplementedType.Value)
&& PythonOps.TryGetBoundAttr(context, this, "__next__", out _dummy) &&
!Object.ReferenceEquals(_dummy, NotImplementedType.Value))
{
return true;
}
return false;
}
private void ClearAbstractMethodFlags(string name) {
if (name == "__abstractmethods__") {
_flags &= ~(TypeFlagAbstractMethodsDefined | TypeFlagAbstractMethodsNonEmpty);
}
}
internal bool HasAbstractMethods(CodeContext/*!*/ context) {
object abstractMethods;
IEnumerator en;
return (_flags & TypeFlagAbstractMethodsNonEmpty) != 0 &&
TryGetBoundCustomMember(context, "__abstractmethods__", out abstractMethods) &&
PythonOps.TryGetEnumerator(context, abstractMethods, out en) &&
en.MoveNext();
}
internal string GetAbstractErrorMessage(CodeContext/*!*/ context) {
if ((_flags & TypeFlagAbstractMethodsNonEmpty) == 0) {
return null;
}
object abstractMethods;
IEnumerator en;
if (!TryGetBoundCustomMember(context, "__abstractmethods__", out abstractMethods) ||
!PythonOps.TryGetEnumerator(context, abstractMethods, out en) ||
!en.MoveNext()) {
return null;
}
string comma = "";
StringBuilder error = new StringBuilder("Can't instantiate abstract class ");
error.Append(Name);
error.Append(" with abstract methods ");
int i = 0;
do {
string s = en.Current as string;
if (s == null) {
if (en.Current is Extensible<string> es) {
s = es.Value;
}
}
if (s == null) {
return string.Format(
"sequence item {0}: expected string, {1} found",
i, PythonTypeOps.GetName(en.Current)
);
}
error.Append(comma);
error.Append(en.Current);
comma = ", ";
i++;
} while (en.MoveNext());
return error.ToString();
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static int Get__flags__(CodeContext/*!*/ context, PythonType/*!*/ type) {
int res = type._flags;
if (type.IsSystemType) {
res |= TypeFlagHeapType;
}
return res;
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static void Set__bases__(CodeContext/*!*/ context, PythonType/*!*/ type, object value) {
// validate we got a tuple...
if (!(value is PythonTuple t)) throw PythonOps.TypeError("expected tuple of types or old-classes, got '{0}'", PythonTypeOps.GetName(value));
List<PythonType> ldt = new List<PythonType>();
foreach (object o in t) {
// gather all the type objects...
if (!(o is PythonType adt)) {
throw PythonOps.TypeError("expected tuple of types, got '{0}'", PythonTypeOps.GetName(o));
}
ldt.Add(adt);
}
#if FEATURE_REFEMIT
// Ensure that we are not switching the CLI type
Type newType = NewTypeMaker.GetNewType(type.Name, t);
if (type.UnderlyingSystemType != newType)
throw PythonOps.TypeErrorForIncompatibleObjectLayout("__bases__ assignment", type, newType);
#endif
// set bases & the new resolution order
List<PythonType> mro = CalculateMro(type, ldt);
type.BaseTypes = ldt;
type._resolutionOrder = mro;
}
private static List<PythonType> CalculateMro(PythonType type, IList<PythonType> ldt) {
return Mro.Calculate(type, ldt);
}
private static bool TryReplaceExtensibleWithBase(Type curType, out Type newType) {
if (curType.IsGenericType &&
curType.GetGenericTypeDefinition() == typeof(Extensible<>)) {
newType = curType.GetGenericArguments()[0];
return true;
}
newType = null;
return false;
}
public object __call__(CodeContext context, params object[] args) {
return PythonTypeOps.CallParams(context, this, args);
}
public object __call__(CodeContext context, [ParamDictionary]IDictionary<string, object> kwArgs, params object[] args) {
return PythonTypeOps.CallWorker(context, this, kwArgs, args);
}
public int __cmp__([NotNull]PythonType other) {
if (other != this) {
int res = Name.CompareTo(other.Name);
if (res == 0) {
long thisId = IdDispenser.GetId(this);
long otherId = IdDispenser.GetId(other);
if (thisId > otherId) {
return 1;
}
return -1;
}
return res;
}
return 0;
}
// Do not override == and != because it causes lots of spurious warnings
// TODO Replace those warnings with .ReferenceEquals calls & overload ==/!=
public bool __eq__([NotNull]PythonType other) {
return __cmp__(other) == 0;
}
public bool __ne__([NotNull]PythonType other) {
return this.__cmp__(other) != 0;
}
[Python3Warning("type inequality comparisons not supported in 3.x")]
public static bool operator >(PythonType self, PythonType other) {
return self.__cmp__(other) > 0;
}
[Python3Warning("type inequality comparisons not supported in 3.x")]
public static bool operator <(PythonType self, PythonType other) {
return self.__cmp__(other) < 0;
}
[Python3Warning("type inequality comparisons not supported in 3.x")]
public static bool operator >=(PythonType self, PythonType other) {
return self.__cmp__(other) >= 0;
}
[Python3Warning("type inequality comparisons not supported in 3.x")]
public static bool operator <=(PythonType self, PythonType other) {
return self.__cmp__(other) <= 0;
}
public void __delattr__(CodeContext/*!*/ context, string name) {
DeleteCustomMember(context, name);
}
[SlotField]
public static PythonTypeSlot __dict__ = new PythonTypeDictSlot(_pythonTypeType);
[SpecialName, PropertyMethod, WrapperDescriptor]
public static object Get__doc__(CodeContext/*!*/ context, PythonType self) {
PythonTypeSlot pts;
object res;
if (self.TryLookupSlot(context, "__doc__", out pts) &&
pts.TryGetValue(context, null, self, out res)) {
return res;
} else if (self.IsSystemType) {
return PythonTypeOps.GetDocumentation(self.UnderlyingSystemType);
}
return null;
}
public object __getattribute__(CodeContext/*!*/ context, string name) {
object value;
if (TryGetBoundCustomMember(context, name, out value)) {
return value;
}
throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'", Name, name);
}
public PythonType this[params Type[] args] {
get {
if (UnderlyingSystemType == typeof(Array)) {
if (args.Length == 1) {
return DynamicHelpers.GetPythonTypeFromType(args[0].MakeArrayType());
}
throw PythonOps.TypeError("expected one argument to make array type, got {0}", args.Length);
}
if (!UnderlyingSystemType.IsGenericTypeDefinition) {
throw new InvalidOperationException("MakeGenericType on non-generic type");
}
return DynamicHelpers.GetPythonTypeFromType(UnderlyingSystemType.MakeGenericType(args));
}
}
public object this[string member] {
get {
if (!UnderlyingSystemType.IsEnum) {
throw PythonOps.TypeError("'type' object is not subscriptable");
}
if (member == null) {
throw PythonOps.KeyError(member);
}
try {
return Enum.Parse(UnderlyingSystemType, member);
} catch (ArgumentException) {
throw PythonOps.KeyError(member);
}
}
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static object Get__module__(CodeContext/*!*/ context, PythonType self) {
PythonTypeSlot pts;
object res;
if (self._dict != null &&
self._dict.TryGetValue("__module__", out pts) &&
pts.TryGetValue(context, self, DynamicHelpers.GetPythonType(self), out res)) {
return res;
}
return PythonTypeOps.GetModuleName(context, self.UnderlyingSystemType);
}
[SpecialName, PropertyMethod, WrapperDescriptor, PythonHidden]
public static string Get__clr_assembly__(PythonType self) {
return self.UnderlyingSystemType.Namespace + " in " + self.UnderlyingSystemType.Assembly.FullName;
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static void Set__module__(CodeContext/*!*/ context, PythonType self, object value) {
if (self.IsSystemType) {
throw PythonOps.TypeError("can't set {0}.__module__", self.Name);
}
Debug.Assert(self._dict != null);
self._dict["__module__"] = new PythonTypeUserDescriptorSlot(value);
self.UpdateVersion();
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static void Delete__module__(CodeContext/*!*/ context, PythonType self) {
throw PythonOps.TypeError("can't delete {0}.__module__", self.Name);
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static PythonTuple Get__mro__(PythonType type) {
return PythonTypeOps.MroToPython(type.ResolutionOrder);
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static string Get__name__(PythonType type) {
return type.Name;
}
[SpecialName, PropertyMethod, WrapperDescriptor]
public static void Set__name__(PythonType type, string name) {
if (type.IsSystemType) {
throw PythonOps.TypeError("can't set attributes of built-in/extension type '{0}'", type.Name);
}
type.Name = name;
}
public string/*!*/ __repr__(CodeContext/*!*/ context) {
string name = Name;
if (IsSystemType) {
if (PythonTypeOps.IsRuntimeAssembly(UnderlyingSystemType.Assembly) || IsPythonType) {
object module = Get__module__(context, this);
if (!module.Equals("builtins")) {
return string.Format("<class '{0}.{1}'>", module, Name);
}
}
return string.Format("<class '{0}'>", Name);
} else {
PythonTypeSlot dts;
string module = "unknown";
object modObj;
if (TryLookupSlot(context, "__module__", out dts) &&
dts.TryGetValue(context, this, this, out modObj)) {
module = modObj as string;
}
return string.Format("<class '{0}.{1}'>", module, name);
}
}
internal string/*!*/ GetTypeDebuggerDisplay() {
PythonTypeSlot dts;
string module = "unknown";
object modObj;
if (TryLookupSlot(Context.SharedContext, "__module__", out dts) &&
dts.TryGetValue(Context.SharedContext, this, this, out modObj)) {
module = modObj as string;
}
return string.Format("{0}.{1} instance", module, Name);
}
public void __setattr__(CodeContext/*!*/ context, string name, object value) {
SetCustomMember(context, name, value);
}
public PythonList __subclasses__(CodeContext/*!*/ context) {
PythonList ret = new PythonList();
IList<WeakReference> subtypes = SubTypes;
if (subtypes != null) {
PythonContext pc = context.LanguageContext;
foreach (WeakReference wr in subtypes) {
if (wr.IsAlive) {
PythonType pt = (PythonType)wr.Target;
if (pt.PythonContext == null || pt.PythonContext == pc) {
ret.AddNoLock(wr.Target);
}
}
}
}
return ret;
}
public virtual PythonList mro() {
return new PythonList(Get__mro__(this));
}
/// <summary>
/// Returns true if the specified object is an instance of this type.
/// </summary>
public virtual bool __instancecheck__(object instance) {
return SubclassImpl(DynamicHelpers.GetPythonType(instance));
}
public virtual bool __subclasscheck__(PythonType sub) {
return SubclassImpl(sub);
}
private bool SubclassImpl(PythonType sub) {
if (UnderlyingSystemType.IsInterface) {
// interfaces aren't in bases, and therefore IsSubclassOf doesn't do this check.
if (UnderlyingSystemType.IsAssignableFrom(sub.UnderlyingSystemType)) {
return true;
}
}
return sub.IsSubclassOf(this);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")]
public static implicit operator Type(PythonType self) {
return self.UnderlyingSystemType;
}
public static implicit operator TypeTracker(PythonType self) {
return TypeTracker.GetTypeTracker(self.UnderlyingSystemType);
}
#endregion
#region Internal API
internal int SlotCount {
get {
return _originalSlotCount;
}
}
/// <summary>
/// Gets the name of the dynamic type
/// </summary>
internal string Name {
get {
return _name;
}
set {
_name = value;
}
}
internal int Version {
get {
return _version;
}
}
internal bool IsNull {
get {
return UnderlyingSystemType == typeof(DynamicNull);
}
}
/// <summary>
/// Gets the resolution order used for attribute lookup
/// </summary>
internal IList<PythonType> ResolutionOrder {
get {
return _resolutionOrder;
}
set {
lock (SyncRoot) {
_resolutionOrder = new List<PythonType>(value);
}
}
}
/// <summary>
/// Gets the dynamic type that corresponds with the provided static type.
///
/// Returns null if no type is available. TODO: In the future this will
/// always return a PythonType created by the DLR.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal static PythonType/*!*/ GetPythonType(Type type) {
object res;
if (!_pythonTypes.TryGetValue(type, out res)) {
lock (_pythonTypes) {
if (!_pythonTypes.TryGetValue(type, out res)) {
res = new PythonType(type);
_pythonTypes.Add(type, res);
}
}
}
return (PythonType)res;
}
/// <summary>
/// Sets the python type that corresponds with the provided static type.
///
/// This is used for built-in types which have a metaclass. Currently
/// only used by ctypes.
/// </summary>
internal static PythonType SetPythonType(Type type, PythonType pyType) {
lock (_pythonTypes) {
Debug.Assert(!_pythonTypes.Contains(type));
Debug.Assert(pyType.GetType() != typeof(PythonType));
_pythonTypes.Add(type, pyType);
}
return pyType;
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext/*!*/ context) {
EnsureInstanceCtor();
return _instanceCtor.CreateInstance(context);
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext/*!*/ context, object arg0) {
EnsureInstanceCtor();
return _instanceCtor.CreateInstance(context, arg0);
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1) {
EnsureInstanceCtor();
return _instanceCtor.CreateInstance(context, arg0, arg1);
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1, object arg2) {
EnsureInstanceCtor();
return _instanceCtor.CreateInstance(context, arg0, arg1, arg2);
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext context, params object[] args) {
Assert.NotNull(args);
EnsureInstanceCtor();
// unpack args for common cases so we don't generate code to do it...
switch (args.Length) {
case 0: return _instanceCtor.CreateInstance(context);
case 1: return _instanceCtor.CreateInstance(context, args[0]);
case 2: return _instanceCtor.CreateInstance(context, args[0], args[1]);
case 3: return _instanceCtor.CreateInstance(context, args[0], args[1], args[2]);
default:
return _instanceCtor.CreateInstance(context, args);
}
}
/// <summary>
/// Allocates the storage for the instance running the .NET constructor. This provides
/// the creation functionality for __new__ implementations.
/// </summary>
internal object CreateInstance(CodeContext context, object[] args, string[] names) {
Assert.NotNull(args, "args");
Assert.NotNull(names, "names");
EnsureInstanceCtor();
return _instanceCtor.CreateInstance(context, args, names);
}
internal int Hash(object o) {
EnsureHashSite();
return _hashSite.Target(_hashSite, o);
}
internal bool TryGetLength(CodeContext context, object o, out int length) {
CallSite<Func<CallSite, CodeContext, object, object>> lenSite;
if (IsSystemType) {
lenSite = context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetLenSite(context);
} else {
lenSite = _siteCache.GetLenSite(context);
}
PythonTypeSlot lenSlot = _lenSlot;
if (lenSlot == null && !PythonOps.TryResolveTypeSlot(context, this, "__len__", out lenSlot)) {
length = 0;
return false;
}
object func;
if (!lenSlot.TryGetValue(context, o, this, out func)) {
length = 0;
return false;
}
object res = lenSite.Target(lenSite, context, func);
if (!(res is int)) {
throw PythonOps.ValueError("__len__ must return int");
}
length = (int)res;
return true;
}
internal bool EqualRetBool(object self, object other) {
if (_eqSite == null) {
Interlocked.CompareExchange(
ref _eqSite,
Context.CreateComparisonSite(PythonOperationKind.Equal),
null
);
}
return _eqSite.Target(_eqSite, self, other);
}
internal int Compare(object self, object other) {
if (_compareSite == null) {
Interlocked.CompareExchange(
ref _compareSite,
Context.MakeSortCompareSite(),
null
);
}
return _compareSite.Target(_compareSite, self, other);
}
internal bool TryGetBoundAttr(CodeContext context, object o, string name, out object ret) {
CallSite<Func<CallSite, object, CodeContext, object>> site;
if (IsSystemType) {
site = context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetTryGetMemberSite(context, name);
} else {
site = _siteCache.GetTryGetMemberSite(context, name);
}
try {