PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/DICK.B1/IronPython/Runtime/Types/PythonType.cs

https://bitbucket.org/williamybs/uidipythontool
C# | 3232 lines | 2364 code | 557 blank | 311 comment | 676 complexity | 752f5f948f96afb4e8139d82ff0a3283 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Microsoft Public License. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Microsoft Public License, please send an email to
  8. * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Microsoft Public License.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. #if !CLR2
  16. using System.Linq.Expressions;
  17. using System.Numerics;
  18. #else
  19. using Microsoft.Scripting.Ast;
  20. using Microsoft.Scripting.Math;
  21. using Complex = Microsoft.Scripting.Math.Complex64;
  22. #endif
  23. using System;
  24. using System.Collections;
  25. using System.Collections.Generic;
  26. using System.Diagnostics;
  27. using System.Globalization;
  28. using System.Reflection;
  29. using System.Runtime.CompilerServices;
  30. using System.Dynamic;
  31. using System.Threading;
  32. using Microsoft.Scripting;
  33. using Microsoft.Scripting.Actions;
  34. using Microsoft.Scripting.Generation;
  35. using Microsoft.Scripting.Runtime;
  36. using Microsoft.Scripting.Utils;
  37. using IronPython.Runtime.Binding;
  38. using IronPython.Runtime.Operations;
  39. namespace IronPython.Runtime.Types {
  40. /// <summary>
  41. /// Represents a PythonType. Instances of PythonType are created via PythonTypeBuilder.
  42. /// </summary>
  43. [DebuggerDisplay("PythonType: {Name}"), DebuggerTypeProxy(typeof(PythonType.DebugProxy))]
  44. [PythonType("type")]
  45. [Documentation(@"type(object) -> gets the type of the object
  46. type(name, bases, dict) -> creates a new type instance with the given name, base classes, and members from the dictionary")]
  47. public partial class PythonType : IPythonMembersList, IDynamicMetaObjectProvider, IWeakReferenceable, ICodeFormattable, IFastGettable, IFastSettable, IFastInvokable {
  48. private Type/*!*/ _underlyingSystemType; // the underlying CLI system type for this type
  49. private string _name; // the name of the type
  50. private Dictionary<string, PythonTypeSlot> _dict; // type-level slots & attributes
  51. private PythonTypeAttributes _attrs; // attributes of the type
  52. private int _version = GetNextVersion(); // version of the type
  53. private List<WeakReference> _subtypes; // all of the subtypes of the PythonType
  54. private PythonContext _pythonContext; // the context the type was created from, or null for system types.
  55. private bool? _objectNew, _objectInit; // true if the type doesn't override __new__ / __init__ from object.
  56. internal Dictionary<string, FastGetBase> _cachedGets; // cached gets on user defined type instances
  57. internal Dictionary<string, FastGetBase> _cachedTryGets; // cached try gets on used defined type instances
  58. internal Dictionary<SetMemberKey, FastSetBase> _cachedSets; // cached sets on user defined instances
  59. internal Dictionary<string, TypeGetBase> _cachedTypeGets; // cached gets on types (system and user types)
  60. internal Dictionary<string, TypeGetBase> _cachedTypeTryGets; // cached gets on types (system and user types)
  61. // commonly calculatable
  62. private List<PythonType> _resolutionOrder; // the search order for methods in the type
  63. private PythonType/*!*/[]/*!*/ _bases; // the base classes of the type
  64. private BuiltinFunction _ctor; // the built-in function which allocates an instance - a .NET ctor
  65. // fields that frequently remain null
  66. private WeakRefTracker _weakrefTracker; // storage for Python style weak references
  67. private WeakReference _weakRef; // single weak ref instance used for all user PythonTypes.
  68. private string[] _slots; // the slots when the class was created
  69. private OldClass _oldClass; // the associated OldClass or null for new-style types
  70. private int _originalSlotCount; // the number of slots when the type was created
  71. private InstanceCreator _instanceCtor; // creates instances
  72. private CallSite<Func<CallSite, object, int>> _hashSite;
  73. private CallSite<Func<CallSite, object, object, bool>> _eqSite;
  74. private CallSite<Func<CallSite, object, object, int>> _compareSite;
  75. private Dictionary<CallSignature, LateBoundInitBinder> _lateBoundInitBinders;
  76. private string[] _optimizedInstanceNames; // optimized names stored in a custom dictionary
  77. private int _optimizedInstanceVersion;
  78. private PythonSiteCache _siteCache = new PythonSiteCache();
  79. private PythonTypeSlot _lenSlot; // cached length slot, cleared when the type is mutated
  80. [MultiRuntimeAware]
  81. private static int MasterVersion = 1;
  82. private static readonly CommonDictionaryStorage _pythonTypes = new CommonDictionaryStorage();
  83. internal static PythonType _pythonTypeType = DynamicHelpers.GetPythonTypeFromType(typeof(PythonType));
  84. private static readonly WeakReference[] _emptyWeakRef = new WeakReference[0];
  85. private static object _subtypesLock = new object();
  86. /// <summary>
  87. /// Provides delegates that will invoke a parameterless type ctor. The first key provides
  88. /// the dictionary for a specific type, the 2nd key provides the delegate for a specific
  89. /// call site type used in conjunction w/ our IFastInvokable implementation.
  90. /// </summary>
  91. private static Dictionary<Type, Dictionary<Type, Delegate>> _fastBindCtors = new Dictionary<Type, Dictionary<Type, Delegate>>();
  92. /// <summary>
  93. /// Shared built-in functions for creating instances of user defined types. Because all
  94. /// types w/ the same UnderlyingSystemType share the same constructors these can be
  95. /// shared across multiple types.
  96. /// </summary>
  97. private static Dictionary<Type, BuiltinFunction> _userTypeCtors = new Dictionary<Type, BuiltinFunction>();
  98. /// <summary>
  99. /// Creates a new type for a user defined type. The name, base classes (a tuple of type
  100. /// objects), and a dictionary of members is provided.
  101. /// </summary>
  102. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  103. public PythonType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict)
  104. : this(context, name, bases, dict, String.Empty) {
  105. }
  106. /// <summary>
  107. /// Creates a new type for a user defined type. The name, base classes (a tuple of type
  108. /// objects), and a dictionary of members is provided.
  109. /// </summary>
  110. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
  111. internal PythonType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict, string selfNames) {
  112. InitializeUserType(context, name, bases, dict, selfNames);
  113. }
  114. internal PythonType() {
  115. }
  116. /// <summary>
  117. /// Creates a new PythonType object which is backed by the specified .NET type for
  118. /// storage. The type is considered a system type which can not be modified
  119. /// by the user.
  120. /// </summary>
  121. /// <param name="underlyingSystemType"></param>
  122. internal PythonType(Type underlyingSystemType) {
  123. _underlyingSystemType = underlyingSystemType;
  124. InitializeSystemType();
  125. }
  126. /// <summary>
  127. /// Creates a new PythonType which is a subclass of the specified PythonType.
  128. ///
  129. /// Used for runtime defined new-style classes which require multiple inheritance. The
  130. /// primary example of this is the exception system.
  131. /// </summary>
  132. internal PythonType(PythonType baseType, string name) {
  133. _underlyingSystemType = baseType.UnderlyingSystemType;
  134. IsSystemType = baseType.IsSystemType;
  135. IsPythonType = baseType.IsPythonType;
  136. Name = name;
  137. _bases = new PythonType[] { baseType };
  138. ResolutionOrder = Mro.Calculate(this, _bases);
  139. _attrs |= PythonTypeAttributes.HasDictionary;
  140. }
  141. /// <summary>
  142. /// Creates a new PythonType which is a subclass of the specified PythonType.
  143. ///
  144. /// Used for runtime defined new-style classes which require multiple inheritance. The
  145. /// primary example of this is the exception system.
  146. /// </summary>
  147. internal PythonType(PythonContext context, PythonType baseType, string name, string module, string doc)
  148. : this(baseType, name) {
  149. EnsureDict();
  150. _dict["__doc__"] = new PythonTypeUserDescriptorSlot(doc, true);
  151. _dict["__module__"] = new PythonTypeUserDescriptorSlot(module, true);
  152. IsSystemType = false;
  153. IsPythonType = false;
  154. _pythonContext = context;
  155. _attrs |= PythonTypeAttributes.HasDictionary;
  156. }
  157. /// <summary>
  158. /// Creates a new PythonType object which represents an Old-style class.
  159. /// </summary>
  160. internal PythonType(OldClass oc) {
  161. EnsureDict();
  162. _underlyingSystemType = typeof(OldInstance);
  163. Name = oc.Name;
  164. OldClass = oc;
  165. List<PythonType> ocs = new List<PythonType>(oc.BaseClasses.Count);
  166. foreach (OldClass klass in oc.BaseClasses) {
  167. ocs.Add(klass.TypeObject);
  168. }
  169. List<PythonType> mro = new List<PythonType>();
  170. mro.Add(this);
  171. _bases = ocs.ToArray();
  172. _resolutionOrder = mro;
  173. AddSlot("__class__", new PythonTypeUserDescriptorSlot(this, true));
  174. }
  175. internal BuiltinFunction Ctor {
  176. get {
  177. EnsureConstructor();
  178. return _ctor;
  179. }
  180. }
  181. #region Public API
  182. public static object __new__(CodeContext/*!*/ context, PythonType cls, string name, PythonTuple bases, PythonDictionary dict) {
  183. return __new__(context, cls, name, bases, dict, String.Empty);
  184. }
  185. internal static object __new__(CodeContext/*!*/ context, PythonType cls, string name, PythonTuple bases, PythonDictionary dict, string selfNames) {
  186. if (name == null) {
  187. throw PythonOps.TypeError("type() argument 1 must be string, not None");
  188. }
  189. if (bases == null) {
  190. throw PythonOps.TypeError("type() argument 2 must be tuple, not None");
  191. }
  192. if (dict == null) {
  193. throw PythonOps.TypeError("TypeError: type() argument 3 must be dict, not None");
  194. }
  195. EnsureModule(context, dict);
  196. PythonType meta = FindMetaClass(cls, bases);
  197. if (meta != TypeCache.OldInstance && meta != TypeCache.PythonType) {
  198. if (meta != cls) {
  199. // the user has a custom __new__ which picked the wrong meta class, call the correct metaclass
  200. return PythonCalls.Call(context, meta, name, bases, dict);
  201. }
  202. // we have the right user __new__, call our ctor method which will do the actual
  203. // creation.
  204. return meta.CreateInstance(context, name, bases, dict);
  205. }
  206. // no custom user type for __new__
  207. return new PythonType(context, name, bases, dict, selfNames);
  208. }
  209. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
  210. public void __init__(string name, PythonTuple bases, PythonDictionary dict) {
  211. }
  212. internal static PythonType FindMetaClass(PythonType cls, PythonTuple bases) {
  213. PythonType meta = cls;
  214. foreach (object dt in bases) {
  215. PythonType metaCls = DynamicHelpers.GetPythonType(dt);
  216. if (metaCls == TypeCache.OldClass) continue;
  217. if (meta.IsSubclassOf(metaCls)) continue;
  218. if (metaCls.IsSubclassOf(meta)) {
  219. meta = metaCls;
  220. continue;
  221. }
  222. throw PythonOps.TypeError("metaclass conflict {0} and {1}", metaCls.Name, meta.Name);
  223. }
  224. return meta;
  225. }
  226. public static object __new__(CodeContext/*!*/ context, object cls, object o) {
  227. return DynamicHelpers.GetPythonType(o);
  228. }
  229. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
  230. public void __init__(object o) {
  231. }
  232. [SpecialName, PropertyMethod, WrapperDescriptor]
  233. public static PythonTuple Get__bases__(CodeContext/*!*/ context, PythonType/*!*/ type) {
  234. return type.GetBasesTuple();
  235. }
  236. private PythonTuple GetBasesTuple() {
  237. object[] res = new object[BaseTypes.Count];
  238. IList<PythonType> bases = BaseTypes;
  239. for (int i = 0; i < bases.Count; i++) {
  240. PythonType baseType = bases[i];
  241. if (baseType.IsOldClass) {
  242. res[i] = baseType.OldClass;
  243. } else {
  244. res[i] = baseType;
  245. }
  246. }
  247. return PythonTuple.MakeTuple(res);
  248. }
  249. [SpecialName, PropertyMethod, WrapperDescriptor]
  250. public static PythonType Get__base__(CodeContext/*!*/ context, PythonType/*!*/ type) {
  251. foreach (object typeObj in Get__bases__(context, type)) {
  252. PythonType pt = typeObj as PythonType;
  253. if (pt != null) {
  254. return pt;
  255. }
  256. }
  257. return null;
  258. }
  259. /// <summary>
  260. /// Used in copy_reg which is the only consumer of __flags__ in the standard library.
  261. ///
  262. /// Set if the type is user defined
  263. /// </summary>
  264. private const int TypeFlagHeapType = 1 << 9;
  265. [SpecialName, PropertyMethod, WrapperDescriptor]
  266. public static int Get__flags__(CodeContext/*!*/ context, PythonType/*!*/ type) {
  267. if (type.IsSystemType) {
  268. return 0;
  269. }
  270. return TypeFlagHeapType;
  271. }
  272. [SpecialName, PropertyMethod, WrapperDescriptor]
  273. public static void Set__bases__(CodeContext/*!*/ context, PythonType/*!*/ type, object value) {
  274. // validate we got a tuple...
  275. PythonTuple t = value as PythonTuple;
  276. if (t == null) throw PythonOps.TypeError("expected tuple of types or old-classes, got '{0}'", PythonTypeOps.GetName(value));
  277. List<PythonType> ldt = new List<PythonType>();
  278. foreach (object o in t) {
  279. // gather all the type objects...
  280. PythonType adt = o as PythonType;
  281. if (adt == null) {
  282. OldClass oc = o as OldClass;
  283. if (oc == null) {
  284. throw PythonOps.TypeError("expected tuple of types, got '{0}'", PythonTypeOps.GetName(o));
  285. }
  286. adt = oc.TypeObject;
  287. }
  288. ldt.Add(adt);
  289. }
  290. // Ensure that we are not switching the CLI type
  291. Type newType = NewTypeMaker.GetNewType(type.Name, t);
  292. if (type.UnderlyingSystemType != newType)
  293. throw PythonOps.TypeErrorForIncompatibleObjectLayout("__bases__ assignment", type, newType);
  294. // set bases & the new resolution order
  295. List<PythonType> mro = CalculateMro(type, ldt);
  296. type.BaseTypes = ldt;
  297. type._resolutionOrder = mro;
  298. }
  299. private static List<PythonType> CalculateMro(PythonType type, IList<PythonType> ldt) {
  300. return Mro.Calculate(type, ldt);
  301. }
  302. private static bool TryReplaceExtensibleWithBase(Type curType, out Type newType) {
  303. if (curType.IsGenericType &&
  304. curType.GetGenericTypeDefinition() == typeof(Extensible<>)) {
  305. newType = curType.GetGenericArguments()[0];
  306. return true;
  307. }
  308. newType = null;
  309. return false;
  310. }
  311. public object __call__(CodeContext context, params object[] args) {
  312. return PythonTypeOps.CallParams(context, this, args);
  313. }
  314. public object __call__(CodeContext context, [ParamDictionary]IDictionary<string, object> kwArgs, params object[] args) {
  315. return PythonTypeOps.CallWorker(context, this, kwArgs, args);
  316. }
  317. public int __cmp__([NotNull]PythonType other) {
  318. if (other != this) {
  319. int res = Name.CompareTo(other.Name);
  320. if (res == 0) {
  321. long thisId = IdDispenser.GetId(this);
  322. long otherId = IdDispenser.GetId(other);
  323. if (thisId > otherId) {
  324. return 1;
  325. } else {
  326. return -1;
  327. }
  328. }
  329. return res;
  330. }
  331. return 0;
  332. }
  333. [Python3Warning("type inequality comparisons not supported in 3.x")]
  334. public static bool operator >(PythonType self, PythonType other) {
  335. return self.__cmp__(other) > 0;
  336. }
  337. [Python3Warning("type inequality comparisons not supported in 3.x")]
  338. public static bool operator <(PythonType self, PythonType other) {
  339. return self.__cmp__(other) < 0;
  340. }
  341. [Python3Warning("type inequality comparisons not supported in 3.x")]
  342. public static bool operator >=(PythonType self, PythonType other) {
  343. return self.__cmp__(other) >= 0;
  344. }
  345. [Python3Warning("type inequality comparisons not supported in 3.x")]
  346. public static bool operator <=(PythonType self, PythonType other) {
  347. return self.__cmp__(other) <= 0;
  348. }
  349. public void __delattr__(CodeContext/*!*/ context, string name) {
  350. DeleteCustomMember(context, name);
  351. }
  352. [SlotField]
  353. public static PythonTypeSlot __dict__ = new PythonTypeDictSlot(_pythonTypeType);
  354. [SpecialName, PropertyMethod, WrapperDescriptor]
  355. public static object Get__doc__(CodeContext/*!*/ context, PythonType self) {
  356. PythonTypeSlot pts;
  357. object res;
  358. if (self.TryLookupSlot(context, "__doc__", out pts) &&
  359. pts.TryGetValue(context, null, self, out res)) {
  360. return res;
  361. } else if (self.IsSystemType) {
  362. return PythonTypeOps.GetDocumentation(self.UnderlyingSystemType);
  363. }
  364. return null;
  365. }
  366. public object __getattribute__(CodeContext/*!*/ context, string name) {
  367. object value;
  368. if (TryGetBoundCustomMember(context, name, out value)) {
  369. return value;
  370. }
  371. throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'", Name, name);
  372. }
  373. public PythonType this[params Type[] args] {
  374. get {
  375. if (UnderlyingSystemType == typeof(Array)) {
  376. if (args.Length == 1) {
  377. return DynamicHelpers.GetPythonTypeFromType(args[0].MakeArrayType());
  378. }
  379. throw PythonOps.TypeError("expected one argument to make array type, got {0}", args.Length);
  380. }
  381. if (!UnderlyingSystemType.IsGenericTypeDefinition) {
  382. throw new InvalidOperationException("MakeGenericType on non-generic type");
  383. }
  384. return DynamicHelpers.GetPythonTypeFromType(UnderlyingSystemType.MakeGenericType(args));
  385. }
  386. }
  387. [SpecialName, PropertyMethod, WrapperDescriptor]
  388. public static object Get__module__(CodeContext/*!*/ context, PythonType self) {
  389. PythonTypeSlot pts;
  390. object res;
  391. if (self._dict != null &&
  392. self._dict.TryGetValue("__module__", out pts) &&
  393. pts.TryGetValue(context, self, DynamicHelpers.GetPythonType(self), out res)) {
  394. return res;
  395. }
  396. return PythonTypeOps.GetModuleName(context, self.UnderlyingSystemType);
  397. }
  398. [SpecialName, PropertyMethod, WrapperDescriptor]
  399. public static void Set__module__(CodeContext/*!*/ context, PythonType self, object value) {
  400. if (self.IsSystemType) {
  401. throw PythonOps.TypeError("can't set {0}.__module__", self.Name);
  402. }
  403. Debug.Assert(self._dict != null);
  404. self._dict["__module__"] = new PythonTypeUserDescriptorSlot(value);
  405. self.UpdateVersion();
  406. }
  407. [SpecialName, PropertyMethod, WrapperDescriptor]
  408. public static void Delete__module__(CodeContext/*!*/ context, PythonType self) {
  409. throw PythonOps.TypeError("can't delete {0}.__module__", self.Name);
  410. }
  411. [SpecialName, PropertyMethod, WrapperDescriptor]
  412. public static PythonTuple Get__mro__(PythonType type) {
  413. return PythonTypeOps.MroToPython(type.ResolutionOrder);
  414. }
  415. [SpecialName, PropertyMethod, WrapperDescriptor]
  416. public static string Get__name__(PythonType type) {
  417. return type.Name;
  418. }
  419. [SpecialName, PropertyMethod, WrapperDescriptor]
  420. public static void Set__name__(PythonType type, string name) {
  421. if (type.IsSystemType) {
  422. throw PythonOps.TypeError("can't set attributes of built-in/extension type '{0}'", type.Name);
  423. }
  424. type.Name = name;
  425. }
  426. public string/*!*/ __repr__(CodeContext/*!*/ context) {
  427. string name = Name;
  428. if (IsSystemType) {
  429. if (PythonTypeOps.IsRuntimeAssembly(UnderlyingSystemType.Assembly) || IsPythonType) {
  430. object module = Get__module__(context, this);
  431. if (!module.Equals("__builtin__")) {
  432. return string.Format("<type '{0}.{1}'>", module, Name);
  433. }
  434. }
  435. return string.Format("<type '{0}'>", Name);
  436. } else {
  437. PythonTypeSlot dts;
  438. string module = "unknown";
  439. object modObj;
  440. if (TryLookupSlot(context, "__module__", out dts) &&
  441. dts.TryGetValue(context, this, this, out modObj)) {
  442. module = modObj as string;
  443. }
  444. return string.Format("<class '{0}.{1}'>", module, name);
  445. }
  446. }
  447. internal string/*!*/ GetTypeDebuggerDisplay() {
  448. PythonTypeSlot dts;
  449. string module = "unknown";
  450. object modObj;
  451. if (TryLookupSlot(Context.SharedContext, "__module__", out dts) &&
  452. dts.TryGetValue(Context.SharedContext, this, this, out modObj)) {
  453. module = modObj as string;
  454. }
  455. return string.Format("{0}.{1} instance", module, Name);
  456. }
  457. public void __setattr__(CodeContext/*!*/ context, string name, object value) {
  458. SetCustomMember(context, name, value);
  459. }
  460. public List __subclasses__(CodeContext/*!*/ context) {
  461. List ret = new List();
  462. IList<WeakReference> subtypes = SubTypes;
  463. if (subtypes != null) {
  464. PythonContext pc = PythonContext.GetContext(context);
  465. foreach (WeakReference wr in subtypes) {
  466. if (wr.IsAlive) {
  467. PythonType pt = (PythonType)wr.Target;
  468. if (pt.PythonContext == null || pt.PythonContext == pc) {
  469. ret.AddNoLock(wr.Target);
  470. }
  471. }
  472. }
  473. }
  474. return ret;
  475. }
  476. public virtual List mro() {
  477. return new List(Get__mro__(this));
  478. }
  479. /// <summary>
  480. /// Returns true if the specified object is an instance of this type.
  481. /// </summary>
  482. public virtual bool __instancecheck__(object instance) {
  483. return SubclassImpl(DynamicHelpers.GetPythonType(instance));
  484. }
  485. public virtual bool __subclasscheck__(PythonType sub) {
  486. return SubclassImpl(sub);
  487. }
  488. private bool SubclassImpl(PythonType sub) {
  489. if (UnderlyingSystemType.IsInterface) {
  490. // interfaces aren't in bases, and therefore IsSubclassOf doesn't do this check.
  491. if (UnderlyingSystemType.IsAssignableFrom(sub.UnderlyingSystemType)) {
  492. return true;
  493. }
  494. }
  495. return sub.IsSubclassOf(this);
  496. }
  497. public virtual bool __subclasscheck__(OldClass sub) {
  498. return IsSubclassOf(sub.TypeObject);
  499. }
  500. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates")]
  501. public static implicit operator Type(PythonType self) {
  502. return self.UnderlyingSystemType;
  503. }
  504. public static implicit operator TypeTracker(PythonType self) {
  505. return ReflectionCache.GetTypeTracker(self.UnderlyingSystemType);
  506. }
  507. #endregion
  508. #region Internal API
  509. internal bool IsMixedNewStyleOldStyle() {
  510. if (!IsOldClass) {
  511. foreach (PythonType baseType in ResolutionOrder) {
  512. if (baseType.IsOldClass) {
  513. // mixed new-style/old-style class, we can't handle
  514. // __init__ in an old-style class yet (it doesn't show
  515. // up in a slot).
  516. return true;
  517. }
  518. }
  519. }
  520. return false;
  521. }
  522. internal int SlotCount {
  523. get {
  524. return _originalSlotCount;
  525. }
  526. }
  527. /// <summary>
  528. /// Gets the name of the dynamic type
  529. /// </summary>
  530. internal string Name {
  531. get {
  532. return _name;
  533. }
  534. set {
  535. _name = value;
  536. }
  537. }
  538. internal int Version {
  539. get {
  540. return _version;
  541. }
  542. }
  543. internal bool IsNull {
  544. get {
  545. return UnderlyingSystemType == typeof(DynamicNull);
  546. }
  547. }
  548. /// <summary>
  549. /// Gets the resolution order used for attribute lookup
  550. /// </summary>
  551. internal IList<PythonType> ResolutionOrder {
  552. get {
  553. return _resolutionOrder;
  554. }
  555. set {
  556. lock (SyncRoot) {
  557. _resolutionOrder = new List<PythonType>(value);
  558. }
  559. }
  560. }
  561. /// <summary>
  562. /// Gets the dynamic type that corresponds with the provided static type.
  563. ///
  564. /// Returns null if no type is available. TODO: In the future this will
  565. /// always return a PythonType created by the DLR.
  566. /// </summary>
  567. /// <param name="type"></param>
  568. /// <returns></returns>
  569. internal static PythonType/*!*/ GetPythonType(Type type) {
  570. object res;
  571. if (!_pythonTypes.TryGetValue(type, out res)) {
  572. lock (_pythonTypes) {
  573. if (!_pythonTypes.TryGetValue(type, out res)) {
  574. res = new PythonType(type);
  575. _pythonTypes.Add(type, res);
  576. }
  577. }
  578. }
  579. return (PythonType)res;
  580. }
  581. /// <summary>
  582. /// Sets the python type that corresponds with the provided static type.
  583. ///
  584. /// This is used for built-in types which have a metaclass. Currently
  585. /// only used by ctypes.
  586. /// </summary>
  587. internal static PythonType SetPythonType(Type type, PythonType pyType) {
  588. lock (_pythonTypes) {
  589. Debug.Assert(!_pythonTypes.Contains(type));
  590. Debug.Assert(pyType.GetType() != typeof(PythonType));
  591. _pythonTypes.Add(type, pyType);
  592. }
  593. return pyType;
  594. }
  595. /// <summary>
  596. /// Allocates the storage for the instance running the .NET constructor. This provides
  597. /// the creation functionality for __new__ implementations.
  598. /// </summary>
  599. internal object CreateInstance(CodeContext/*!*/ context) {
  600. EnsureInstanceCtor();
  601. return _instanceCtor.CreateInstance(context);
  602. }
  603. /// <summary>
  604. /// Allocates the storage for the instance running the .NET constructor. This provides
  605. /// the creation functionality for __new__ implementations.
  606. /// </summary>
  607. internal object CreateInstance(CodeContext/*!*/ context, object arg0) {
  608. EnsureInstanceCtor();
  609. return _instanceCtor.CreateInstance(context, arg0);
  610. }
  611. /// <summary>
  612. /// Allocates the storage for the instance running the .NET constructor. This provides
  613. /// the creation functionality for __new__ implementations.
  614. /// </summary>
  615. internal object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1) {
  616. EnsureInstanceCtor();
  617. return _instanceCtor.CreateInstance(context, arg0, arg1);
  618. }
  619. /// <summary>
  620. /// Allocates the storage for the instance running the .NET constructor. This provides
  621. /// the creation functionality for __new__ implementations.
  622. /// </summary>
  623. internal object CreateInstance(CodeContext/*!*/ context, object arg0, object arg1, object arg2) {
  624. EnsureInstanceCtor();
  625. return _instanceCtor.CreateInstance(context, arg0, arg1, arg2);
  626. }
  627. /// <summary>
  628. /// Allocates the storage for the instance running the .NET constructor. This provides
  629. /// the creation functionality for __new__ implementations.
  630. /// </summary>
  631. internal object CreateInstance(CodeContext context, params object[] args) {
  632. Assert.NotNull(args);
  633. EnsureInstanceCtor();
  634. // unpack args for common cases so we don't generate code to do it...
  635. switch (args.Length) {
  636. case 0: return _instanceCtor.CreateInstance(context);
  637. case 1: return _instanceCtor.CreateInstance(context, args[0]);
  638. case 2: return _instanceCtor.CreateInstance(context, args[0], args[1]);
  639. case 3: return _instanceCtor.CreateInstance(context, args[0], args[1], args[2]);
  640. default:
  641. return _instanceCtor.CreateInstance(context, args);
  642. }
  643. }
  644. /// <summary>
  645. /// Allocates the storage for the instance running the .NET constructor. This provides
  646. /// the creation functionality for __new__ implementations.
  647. /// </summary>
  648. internal object CreateInstance(CodeContext context, object[] args, string[] names) {
  649. Assert.NotNull(args, "args");
  650. Assert.NotNull(names, "names");
  651. EnsureInstanceCtor();
  652. return _instanceCtor.CreateInstance(context, args, names);
  653. }
  654. internal int Hash(object o) {
  655. EnsureHashSite();
  656. return _hashSite.Target(_hashSite, o);
  657. }
  658. internal bool TryGetLength(CodeContext context, object o, out int length) {
  659. CallSite<Func<CallSite, CodeContext, object, object>> lenSite;
  660. if (IsSystemType) {
  661. lenSite = PythonContext.GetContext(context).GetSiteCacheForSystemType(UnderlyingSystemType).GetLenSite(context);
  662. } else {
  663. lenSite = _siteCache.GetLenSite(context);
  664. }
  665. PythonTypeSlot lenSlot = _lenSlot;
  666. if (lenSlot == null && !PythonOps.TryResolveTypeSlot(context, this, "__len__", out lenSlot)) {
  667. length = 0;
  668. return false;
  669. }
  670. object func;
  671. if (!lenSlot.TryGetValue(context, o, this, out func)) {
  672. length = 0;
  673. return false;
  674. }
  675. object res = lenSite.Target(lenSite, context, func);
  676. if (!(res is int)) {
  677. throw PythonOps.ValueError("__len__ must return int");
  678. }
  679. length = (int)res;
  680. return true;
  681. }
  682. internal bool EqualRetBool(object self, object other) {
  683. if (_eqSite == null) {
  684. Interlocked.CompareExchange(
  685. ref _eqSite,
  686. Context.CreateComparisonSite(PythonOperationKind.Equal),
  687. null
  688. );
  689. }
  690. return _eqSite.Target(_eqSite, self, other);
  691. }
  692. internal int Compare(object self, object other) {
  693. if (_compareSite == null) {
  694. Interlocked.CompareExchange(
  695. ref _compareSite,
  696. Context.MakeSortCompareSite(),
  697. null
  698. );
  699. }
  700. return _compareSite.Target(_compareSite, self, other);
  701. }
  702. internal bool TryGetBoundAttr(CodeContext context, object o, string name, out object ret) {
  703. CallSite<Func<CallSite, object, CodeContext, object>> site;
  704. if (IsSystemType) {
  705. site = PythonContext.GetContext(context).GetSiteCacheForSystemType(UnderlyingSystemType).GetTryGetMemberSite(context, name);
  706. } else {
  707. site = _siteCache.GetTryGetMemberSite(context, name);
  708. }
  709. try {
  710. ret = site.Target(site, o, context);
  711. return ret != OperationFailed.Value;
  712. } catch (MissingMemberException) {
  713. ExceptionHelpers.DynamicStackFrames = null;
  714. ret = null;
  715. return false;
  716. }
  717. }
  718. internal CallSite<Func<CallSite, object, int>> HashSite {
  719. get {
  720. EnsureHashSite();
  721. return _hashSite;
  722. }
  723. }
  724. private void EnsureHashSite() {
  725. if(_hashSite == null) {
  726. Interlocked.CompareExchange(
  727. ref _hashSite,
  728. CallSite<Func<CallSite, object, int>>.Create(
  729. Context.Operation(
  730. PythonOperationKind.Hash
  731. )
  732. ),
  733. null
  734. );
  735. }
  736. }
  737. /// <summary>
  738. /// Gets the underlying system type that is backing this type. All instances of this
  739. /// type are an instance of the underlying system type.
  740. /// </summary>
  741. internal Type/*!*/ UnderlyingSystemType {
  742. get {
  743. return _underlyingSystemType;
  744. }
  745. }
  746. /// <summary>
  747. /// Gets the extension type for this type. The extension type provides
  748. /// a .NET type which can be inherited from to extend sealed classes
  749. /// or value types which Python allows inheritance from.
  750. /// </summary>
  751. internal Type/*!*/ ExtensionType {
  752. get {
  753. if (!_underlyingSystemType.IsEnum) {
  754. switch (Type.GetTypeCode(_underlyingSystemType)) {
  755. case TypeCode.String: return typeof(ExtensibleString);
  756. case TypeCode.Int32: return typeof(Extensible<int>);
  757. case TypeCode.Double: return typeof(Extensible<double>);
  758. case TypeCode.Object:
  759. if (_underlyingSystemType == typeof(BigInteger)) {
  760. return typeof(Extensible<BigInteger>);
  761. } else if (_underlyingSystemType == typeof(Complex)) {
  762. return typeof(ExtensibleComplex);
  763. }
  764. break;
  765. }
  766. }
  767. return _underlyingSystemType;
  768. }
  769. }
  770. /// <summary>
  771. /// Gets the base types from which this type inherits.
  772. /// </summary>
  773. internal IList<PythonType>/*!*/ BaseTypes {
  774. get {
  775. return _bases;
  776. }
  777. set {
  778. // validate input...
  779. foreach (PythonType pt in value) {
  780. if (pt == null) throw new ArgumentNullException("value", "a PythonType was null while assigning base classes");
  781. }
  782. // first update our sub-type list
  783. lock (_bases) {
  784. foreach (PythonType dt in _bases) {
  785. dt.RemoveSubType(this);
  786. }
  787. // set the new bases
  788. List<PythonType> newBases = new List<PythonType>(value);
  789. // add us as subtypes of our new bases
  790. foreach (PythonType dt in newBases) {
  791. dt.AddSubType(this);
  792. }
  793. UpdateVersion();
  794. _bases = newBases.ToArray();
  795. }
  796. }
  797. }
  798. /// <summary>
  799. /// Returns true if this type is a subclass of other
  800. /// </summary>
  801. internal bool IsSubclassOf(PythonType other) {
  802. // check for a type match
  803. if (other == this) {
  804. return true;
  805. }
  806. //Python doesn't have value types inheriting from ValueType, but we fake this for interop
  807. if (other.UnderlyingSystemType == typeof(ValueType) && UnderlyingSystemType.IsValueType) {
  808. return true;
  809. }
  810. return IsSubclassWorker(other);
  811. }
  812. private bool IsSubclassWorker(PythonType other) {
  813. for (int i = 0; i < _bases.Length; i++) {
  814. PythonType baseClass = _bases[i];
  815. if (baseClass == other || baseClass.IsSubclassWorker(other)) {
  816. return true;
  817. }
  818. }
  819. return false;
  820. }
  821. /// <summary>
  822. /// True if the type is a system type. A system type is a type which represents an
  823. /// underlying .NET type and not a subtype of one of these types.
  824. /// </summary>
  825. internal bool IsSystemType {
  826. get {
  827. return (_attrs & PythonTypeAttributes.SystemType) != 0;
  828. }
  829. set {
  830. if (value) _attrs |= PythonTypeAttributes.SystemType;
  831. else _attrs &= (~PythonTypeAttributes.SystemType);
  832. }
  833. }
  834. internal bool IsWeakReferencable {
  835. get {
  836. return (_attrs & PythonTypeAttributes.WeakReferencable) != 0;
  837. }
  838. set {
  839. if (value) _attrs |= PythonTypeAttributes.WeakReferencable;
  840. else _attrs &= (~PythonTypeAttributes.WeakReferencable);
  841. }
  842. }
  843. internal bool HasDictionary {
  844. get {
  845. return (_attrs & PythonTypeAttributes.HasDictionary) != 0;
  846. }
  847. set {
  848. if (value) _attrs |= PythonTypeAttributes.HasDictionary;
  849. else _attrs &= (~PythonTypeAttributes.HasDictionary);
  850. }
  851. }
  852. internal bool HasSystemCtor {
  853. get {
  854. return (_attrs & PythonTypeAttributes.SystemCtor) != 0;
  855. }
  856. }
  857. internal void SetConstructor(BuiltinFunction ctor) {
  858. _ctor = ctor;
  859. }
  860. internal bool IsPythonType {
  861. get {
  862. return (_attrs & PythonTypeAttributes.IsPythonType) != 0;
  863. }
  864. set {
  865. if (value) {
  866. _attrs |= PythonTypeAttributes.IsPythonType;
  867. } else {
  868. _attrs &= ~PythonTypeAttributes.IsPythonType;
  869. }
  870. }
  871. }
  872. internal OldClass OldClass {
  873. get {
  874. return _oldClass;
  875. }
  876. set {
  877. _oldClass = value;
  878. }
  879. }
  880. internal bool IsOldClass {
  881. get {
  882. return _oldClass != null;
  883. }
  884. }
  885. internal PythonContext PythonContext {
  886. get {
  887. return _pythonContext;
  888. }
  889. }
  890. internal PythonContext/*!*/ Context {
  891. get {
  892. return _pythonContext ?? DefaultContext.DefaultPythonContext;
  893. }
  894. }
  895. internal object SyncRoot {
  896. get {
  897. // TODO: This is un-ideal, we should lock on something private.
  898. return this;
  899. }
  900. }
  901. internal bool IsHiddenMember(string name) {
  902. PythonTypeSlot dummySlot;
  903. return !TryResolveSlot(DefaultContext.Default, name, out dummySlot) &&
  904. TryResolveSlot(DefaultContext.DefaultCLS, name, out dummySlot);
  905. }
  906. internal LateBoundInitBinder GetLateBoundInitBinder(CallSignature signature) {
  907. Debug.Assert(!IsSystemType); // going to hold onto a PythonContext, shouldn't ever be a system type
  908. Debug.Assert(_pythonContext != null);
  909. if (_lateBoundInitBinders == null) {
  910. Interlocked.CompareExchange(ref _lateBoundInitBinders, new Dictionary<CallSignature, LateBoundInitBinder>(), null);
  911. }
  912. lock(_lateBoundInitBinders) {
  913. LateBoundInitBinder res;
  914. if (!_lateBoundInitBinders.TryGetValue(signature, out res)) {
  915. _lateBoundInitBinders[signature] = res = new LateBoundInitBinder(this, signature);
  916. }
  917. return res;
  918. }
  919. }
  920. #endregion
  921. #region Type member access
  922. /// <summary>
  923. /// Looks up a slot on the dynamic type
  924. /// </summary>
  925. internal bool TryLookupSlot(CodeContext context, string name, out PythonTypeSlot slot) {
  926. if (IsSystemType) {
  927. return PythonBinder.GetBinder(context).TryLookupSlot(context, this, name, out slot);
  928. }
  929. return _dict.TryGetValue(name, out slot);
  930. }
  931. /// <summary>
  932. /// Searches the resolution order for a slot matching by name
  933. /// </summary>
  934. internal bool TryResolveSlot(CodeContext context, string name, out PythonTypeSlot slot) {
  935. for (int i = 0; i < _resolutionOrder.Count; i++) {
  936. PythonType dt = _resolutionOrder[i];
  937. // don't look at interfaces - users can inherit from them, but we resolve members
  938. // via methods implemented on types and defined by Python.
  939. if (dt.IsSystemType && !dt.UnderlyingSystemType.IsInterface) {
  940. return PythonBinder.GetBinder(context).TryResolveSlot(context, dt, this, name, out slot);
  941. }
  942. if (dt.TryLookupSlot(context, name, out slot)) {
  943. return true;
  944. }
  945. }
  946. if (UnderlyingSystemType.IsInterface) {
  947. return TypeCache.Object.TryResolveSlot(context, name, out slot);
  948. }
  949. slot = null;
  950. return false;
  951. }
  952. /// <summary>
  953. /// Searches the resolution order for a slot matching by name.
  954. ///
  955. /// Includes searching for methods in old-style classes
  956. /// </summary>
  957. internal bool TryResolveMixedSlot(CodeContext context, string name, out PythonTypeSlot slot) {
  958. for (int i = 0; i < _resolutionOrder.Count; i++) {
  959. PythonType dt = _resolutionOrder[i];
  960. if (dt.TryLookupSlot(context, name, out slot)) {
  961. return true;
  962. }
  963. if (dt.OldClass != null) {
  964. object ret;
  965. if (dt.OldClass.TryLookupSlot(name, out ret)) {
  966. slot = ToTypeSlot(ret);
  967. return true;
  968. }
  969. }
  970. }
  971. slot = null;
  972. return false;
  973. }
  974. /// <summary>
  975. /// Internal helper to add a new slot to the type
  976. /// </summary>
  977. /// <param name="name"></param>
  978. /// <param name="slot"></param>
  979. internal void AddSlot(string name, PythonTypeSlot slot) {
  980. Debug.Assert(!IsSystemType);
  981. _dict[name] = slot;
  982. if (name == "__new__") {
  983. _objectNew = null;
  984. ClearObjectNewInSubclasses(this);
  985. } else if (name == "__init__") {
  986. _objectInit = null;
  987. ClearObjectInitInSubclasses(this);
  988. }
  989. }
  990. private void ClearObjectNewInSubclasses(PythonType pt) {
  991. lock (_subtypesLock) {
  992. if (pt._subtypes != null) {
  993. foreach (WeakReference wr in pt._subtypes) {
  994. PythonType type = wr.Target as PythonType;
  995. if (type != null) {
  996. type._objectNew = null;
  997. ClearObjectNewInSubclasses(type);
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. private void ClearObjectInitInSubclasses(PythonType pt) {
  1004. lock (_subtypesLock) {
  1005. if (pt._subtypes != null) {
  1006. foreach (WeakReference wr in pt._subtypes) {
  1007. PythonType type = wr.Target as PythonType;
  1008. if (type != null) {
  1009. type._objectInit = null;
  1010. ClearObjectInitInSubclasses(type);
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. internal bool TryGetCustomSetAttr(CodeContext context, out PythonTypeSlot pts) {
  1017. PythonContext pc = PythonContext.GetContext(context);
  1018. return pc.Binder.TryResolveSlot(
  1019. context,
  1020. DynamicHelpers.GetPythonType(this),
  1021. this,
  1022. "__setattr__",
  1023. out pts) &&
  1024. pts is BuiltinMethodDescriptor &&
  1025. ((BuiltinMethodDescriptor)pts).DeclaringType != typeof(PythonType);
  1026. }
  1027. internal void SetCustomMember(CodeContext/*!*/ context, string name, object value) {
  1028. Debug.Assert(context != null);
  1029. PythonTypeSlot dts;
  1030. if (TryResolveSlot(context, name, out dts)) {
  1031. if (dts.TrySetValue(context, null, this, value))
  1032. return;
  1033. }
  1034. if (PythonType._pythonTypeType.TryResolveSlot(context, name, out dts)) {
  1035. if (dts.TrySetValue(context, this, PythonType._pythonTypeType, value))
  1036. return;
  1037. }
  1038. if (IsSystemType) {
  1039. throw new MissingMemberException(String.Format("'{0}' object has no attribute '{1}'", Name, name));
  1040. }
  1041. PythonTypeSlot curSlot;
  1042. if (!(value is PythonTypeSlot) && _dict.TryGetValue(name, out curSlot) && curSlot is PythonTypeUserDescriptorSlot) {
  1043. ((PythonTypeUserDescriptorSlot)curSlot).Value = value;
  1044. } else {
  1045. AddSlot(name, ToTypeSlot(value));
  1046. UpdateVersion();
  1047. }
  1048. }
  1049. internal static PythonTypeSlot ToTypeSlot(object value) {
  1050. PythonTypeSlot pts = value as PythonTypeSlot;
  1051. if (pts != null) {
  1052. return pts;
  1053. }
  1054. // We could do more checks for things which aren't descriptors
  1055. if (value != null) {
  1056. return new PythonTypeUserDescriptorSlot(value);

Large files files are truncated, but you can click here to view the full file