diff --git a/src/runtime/arrayobject.cs b/src/runtime/arrayobject.cs index 6096706dd..caf40ca50 100644 --- a/src/runtime/arrayobject.cs +++ b/src/runtime/arrayobject.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -22,13 +21,13 @@ internal override bool CanSubclass() public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - ArrayObject self = GetManagedObject(tp) as ArrayObject; + var self = GetManagedObject(tp) as ArrayObject; if (Runtime.PyTuple_Size(args) != 1) { return Exceptions.RaiseTypeError("array expects 1 argument"); } IntPtr op = Runtime.PyTuple_GetItem(args, 0); - Object result; + object result; if (!Converter.ToManaged(op, self.type, out result, true)) { @@ -43,11 +42,11 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) /// public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = obj.inst as Array; + var obj = (CLRObject)GetManagedObject(ob); + var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; - int index = 0; + int index; object value; // Note that CLR 1.0 only supports int indexes - methods to @@ -61,7 +60,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) if (rank == 1) { - index = (int)Runtime.PyInt_AsLong(idx); + index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { @@ -83,7 +82,7 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) return IntPtr.Zero; } - return Converter.ToPython(items.GetValue(index), itemType); + return Converter.ToPython(value, itemType); } // Multi-dimensional arrays can be indexed a la: list[1, 2, 3]. @@ -96,12 +95,12 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) int count = Runtime.PyTuple_Size(idx); - Array args = Array.CreateInstance(typeof(Int32), count); + var args = new int[count]; - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); - index = (int)Runtime.PyInt_AsLong(op); + index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { @@ -135,11 +134,11 @@ public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) /// public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = obj.inst as Array; + var obj = (CLRObject)GetManagedObject(ob); + var items = obj.inst as Array; Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; - int index = 0; + int index; object value; if (items.IsReadOnly) @@ -155,7 +154,7 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) if (rank == 1) { - index = (int)Runtime.PyInt_AsLong(idx); + index = Runtime.PyInt_AsLong(idx); if (Exceptions.ErrorOccurred()) { @@ -188,13 +187,12 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) } int count = Runtime.PyTuple_Size(idx); + var args = new int[count]; - Array args = Array.CreateInstance(typeof(Int32), count); - - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr op = Runtime.PyTuple_GetItem(idx, i); - index = (int)Runtime.PyInt_AsLong(op); + index = Runtime.PyInt_AsLong(op); if (Exceptions.ErrorOccurred()) { @@ -229,9 +227,9 @@ public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) /// public static int sq_contains(IntPtr ob, IntPtr v) { - CLRObject obj = (CLRObject)ManagedType.GetManagedObject(ob); + var obj = (CLRObject)GetManagedObject(ob); Type itemType = obj.inst.GetType().GetElementType(); - IList items = obj.inst as IList; + var items = obj.inst as IList; object value; if (!Converter.ToManaged(v, itemType, out value, false)) @@ -253,8 +251,8 @@ public static int sq_contains(IntPtr ob, IntPtr v) /// public static int mp_length(IntPtr ob) { - CLRObject self = (CLRObject)ManagedType.GetManagedObject(ob); - Array items = self.inst as Array; + var self = (CLRObject)GetManagedObject(ob); + var items = self.inst as Array; return items.Length; } } diff --git a/src/runtime/assemblymanager.cs b/src/runtime/assemblymanager.cs index b98455ec3..29851c32e 100644 --- a/src/runtime/assemblymanager.cs +++ b/src/runtime/assemblymanager.cs @@ -21,8 +21,10 @@ internal class AssemblyManager //static Dictionary> generics; static AssemblyLoadEventHandler lhandler; static ResolveEventHandler rhandler; + // updated only under GIL? static Dictionary probed; + // modified from event handlers below, potentially triggered from different .NET threads static AssemblyList assemblies; internal static List pypath; @@ -53,7 +55,7 @@ internal static void Initialize() domain.AssemblyResolve += rhandler; Assembly[] items = domain.GetAssemblies(); - foreach (var a in items) + foreach (Assembly a in items) { try { @@ -62,7 +64,7 @@ internal static void Initialize() } catch (Exception ex) { - Debug.WriteLine(string.Format("Error scanning assembly {0}. {1}", a, ex)); + Debug.WriteLine("Error scanning assembly {0}. {1}", a, ex); } } } @@ -86,7 +88,7 @@ internal static void Shutdown() /// so that we can know about assemblies that get loaded after the /// Python runtime is initialized. /// - static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) + private static void AssemblyLoadHandler(object ob, AssemblyLoadEventArgs args) { Assembly assembly = args.LoadedAssembly; assemblies.Add(assembly); @@ -101,7 +103,7 @@ static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args) /// for failed loads, because they might be dependencies of something /// we loaded from Python which also needs to be found on PYTHONPATH. /// - static Assembly ResolveHandler(Object ob, ResolveEventArgs args) + private static Assembly ResolveHandler(object ob, ResolveEventArgs args) { string name = args.Name.ToLower(); foreach (Assembly a in assemblies) @@ -135,7 +137,7 @@ internal static void UpdatePath() { pypath.Clear(); probed.Clear(); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr item = Runtime.PyList_GetItem(list, i); string path = Runtime.GetManagedString(item); @@ -159,7 +161,7 @@ public static string FindAssembly(string name) string path; string temp; - for (int i = 0; i < pypath.Count; i++) + for (var i = 0; i < pypath.Count; i++) { string head = pypath[i]; if (head == null || head.Length == 0) @@ -197,7 +199,7 @@ public static Assembly LoadAssembly(string name) { assembly = Assembly.Load(name); } - catch (System.Exception) + catch (Exception) { //if (!(e is System.IO.FileNotFoundException)) //{ @@ -221,7 +223,7 @@ public static Assembly LoadAssemblyPath(string name) { assembly = Assembly.LoadFrom(path); } - catch + catch (Exception) { } } @@ -241,7 +243,9 @@ public static Assembly LoadAssemblyFullPath(string name) if (Path.IsPathRooted(name)) { if (!Path.HasExtension(name)) + { name = name + ".dll"; + } if (File.Exists(name)) { try @@ -287,13 +291,13 @@ public static Assembly FindLoadedAssembly(string name) public static bool LoadImplicit(string name, bool warn = true) { string[] names = name.Split('.'); - bool loaded = false; - string s = ""; + var loaded = false; + var s = ""; Assembly lastAssembly = null; HashSet assembliesSet = null; - for (int i = 0; i < names.Length; i++) + for (var i = 0; i < names.Length; i++) { - s = (i == 0) ? names[0] : s + "." + names[i]; + s = i == 0 ? names[0] : s + "." + names[i]; if (!probed.ContainsKey(s)) { if (assembliesSet == null) @@ -321,7 +325,7 @@ public static bool LoadImplicit(string name, bool warn = true) // Deprecation warning if (warn && loaded) { - string deprWarning = String.Format( + string deprWarning = string.Format( "\nThe module was found, but not in a referenced namespace.\n" + "Implicit loading is deprecated. Please use clr.AddReference(\"{0}\").", Path.GetFileNameWithoutExtension(lastAssembly.Location)); @@ -345,24 +349,23 @@ internal static void ScanAssembly(Assembly assembly) // the assembly. Type[] types = assembly.GetTypes(); - for (int i = 0; i < types.Length; i++) + foreach (Type t in types) { - Type t = types[i]; string ns = t.Namespace ?? ""; if (!namespaces.ContainsKey(ns)) { string[] names = ns.Split('.'); - string s = ""; - for (int n = 0; n < names.Length; n++) + var s = ""; + for (var n = 0; n < names.Length; n++) { - s = (n == 0) ? names[0] : s + "." + names[n]; + s = n == 0 ? names[0] : s + "." + names[n]; namespaces.TryAdd(s, new ConcurrentDictionary()); } } if (ns != null) { - namespaces[ns].TryAdd(assembly, String.Empty); + namespaces[ns].TryAdd(assembly, string.Empty); } if (ns != null && t.IsGenericTypeDefinition) @@ -374,7 +377,7 @@ internal static void ScanAssembly(Assembly assembly) public static AssemblyName[] ListAssemblies() { - List names = new List(assemblies.Count); + var names = new List(assemblies.Count); foreach (Assembly assembly in assemblies) { names.Add(assembly.GetName()); @@ -388,7 +391,7 @@ public static AssemblyName[] ListAssemblies() /// public static bool IsValidNamespace(string name) { - return !String.IsNullOrEmpty(name) && namespaces.ContainsKey(name); + return !string.IsNullOrEmpty(name) && namespaces.ContainsKey(name); } /// @@ -396,10 +399,7 @@ public static bool IsValidNamespace(string name) /// public static IEnumerable GetAssemblies(string nsname) { - if (!namespaces.ContainsKey(nsname)) - return new List(); - - return namespaces[nsname].Keys; + return !namespaces.ContainsKey(nsname) ? new List() : namespaces[nsname].Keys; } /// @@ -408,7 +408,7 @@ public static IEnumerable GetAssemblies(string nsname) public static List GetNames(string nsname) { //Dictionary seen = new Dictionary(); - List names = new List(8); + var names = new List(8); List g = GenericUtil.GetGenericBaseNames(nsname); if (g != null) @@ -424,9 +424,8 @@ public static List GetNames(string nsname) foreach (Assembly a in namespaces[nsname].Keys) { Type[] types = a.GetTypes(); - for (int i = 0; i < types.Length; i++) + foreach (Type t in types) { - Type t = types[i]; if ((t.Namespace ?? "") == nsname) { names.Add(t.Name); diff --git a/src/runtime/classbase.cs b/src/runtime/classbase.cs index 6ed43689b..580fcabe4 100644 --- a/src/runtime/classbase.cs +++ b/src/runtime/classbase.cs @@ -19,7 +19,7 @@ internal class ClassBase : ManagedType internal Indexer indexer; internal Type type; - internal ClassBase(Type tp) : base() + internal ClassBase(Type tp) { indexer = null; type = tp; @@ -97,10 +97,10 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) return pyfalse; } - Object o1 = co1.inst; - Object o2 = co2.inst; + object o1 = co1.inst; + object o2 = co2.inst; - if (Object.Equals(o1, o2)) + if (Equals(o1, o2)) { Runtime.XIncref(pytrue); return pytrue; @@ -121,7 +121,7 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) return Exceptions.RaiseTypeError("Cannot convert object of type " + co1.GetType() + " to IComparable"); try { - var cmp = co1Comp.CompareTo(co2.inst); + int cmp = co1Comp.CompareTo(co2.inst); IntPtr pyCmp; if (cmp < 0) @@ -177,13 +177,13 @@ public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op) /// public static IntPtr tp_iter(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid object"); } - IEnumerable e = co.inst as IEnumerable; + var e = co.inst as IEnumerable; IEnumerator o; if (e != null) @@ -196,7 +196,7 @@ public static IntPtr tp_iter(IntPtr ob) if (o == null) { - string message = "iteration over non-sequence"; + var message = "iteration over non-sequence"; return Exceptions.RaiseTypeError(message); } } @@ -210,7 +210,7 @@ public static IntPtr tp_iter(IntPtr ob) /// public static IntPtr tp_hash(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("unhashable type"); @@ -224,7 +224,7 @@ public static IntPtr tp_hash(IntPtr ob) /// public static IntPtr tp_str(IntPtr ob) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid object"); diff --git a/src/runtime/clrobject.cs b/src/runtime/clrobject.cs index e7bb345f8..472e5dcbb 100644 --- a/src/runtime/clrobject.cs +++ b/src/runtime/clrobject.cs @@ -1,19 +1,17 @@ using System; -using System.Collections; -using System.Reflection; using System.Runtime.InteropServices; namespace Python.Runtime { internal class CLRObject : ManagedType { - internal Object inst; + internal object inst; - internal CLRObject(Object ob, IntPtr tp) : base() + internal CLRObject(object ob, IntPtr tp) { IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Subclass) != 0) { IntPtr dict = Marshal.ReadIntPtr(py, ObjectOffset.DictOffset(tp)); @@ -26,9 +24,9 @@ internal CLRObject(Object ob, IntPtr tp) : base() GCHandle gc = GCHandle.Alloc(this); Marshal.WriteIntPtr(py, ObjectOffset.magic(tp), (IntPtr)gc); - this.tpHandle = tp; - this.pyHandle = py; - this.gcHandle = gc; + tpHandle = tp; + pyHandle = py; + gcHandle = gc; inst = ob; // Fix the BaseException args (and __cause__ in case of Python 3) @@ -37,27 +35,27 @@ internal CLRObject(Object ob, IntPtr tp) : base() } - internal static CLRObject GetInstance(Object ob, IntPtr pyType) + internal static CLRObject GetInstance(object ob, IntPtr pyType) { return new CLRObject(ob, pyType); } - internal static CLRObject GetInstance(Object ob) + internal static CLRObject GetInstance(object ob) { ClassBase cc = ClassManager.GetClass(ob.GetType()); return GetInstance(ob, cc.tpHandle); } - internal static IntPtr GetInstHandle(Object ob, IntPtr pyType) + internal static IntPtr GetInstHandle(object ob, IntPtr pyType) { CLRObject co = GetInstance(ob, pyType); return co.pyHandle; } - internal static IntPtr GetInstHandle(Object ob, Type type) + internal static IntPtr GetInstHandle(object ob, Type type) { ClassBase cc = ClassManager.GetClass(type); CLRObject co = GetInstance(ob, cc.tpHandle); @@ -65,7 +63,7 @@ internal static IntPtr GetInstHandle(Object ob, Type type) } - internal static IntPtr GetInstHandle(Object ob) + internal static IntPtr GetInstHandle(object ob) { CLRObject co = GetInstance(ob); return co.pyHandle; diff --git a/src/runtime/codegenerator.cs b/src/runtime/codegenerator.cs index d592843cb..4620b0f0c 100644 --- a/src/runtime/codegenerator.cs +++ b/src/runtime/codegenerator.cs @@ -1,8 +1,5 @@ using System; using System.Threading; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Collections; using System.Reflection; using System.Reflection.Emit; @@ -21,9 +18,8 @@ internal class CodeGenerator internal CodeGenerator() { - AssemblyName aname = new AssemblyName(); - aname.Name = "__CodeGenerator_Assembly"; - AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run; + var aname = new AssemblyName { Name = "__CodeGenerator_Assembly" }; + var aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); mBuilder = aBuilder.DefineDynamicModule("__CodeGenerator_Module"); @@ -34,7 +30,7 @@ internal CodeGenerator() /// internal TypeBuilder DefineType(string name) { - TypeAttributes attrs = TypeAttributes.Public; + var attrs = TypeAttributes.Public; return mBuilder.DefineType(name, attrs); } @@ -43,7 +39,7 @@ internal TypeBuilder DefineType(string name) /// internal TypeBuilder DefineType(string name, Type basetype) { - TypeAttributes attrs = TypeAttributes.Public; + var attrs = TypeAttributes.Public; return mBuilder.DefineType(name, attrs, basetype); } } diff --git a/src/runtime/constructorbinder.cs b/src/runtime/constructorbinder.cs index 400a0dd54..1fc541920 100644 --- a/src/runtime/constructorbinder.cs +++ b/src/runtime/constructorbinder.cs @@ -12,9 +12,9 @@ namespace Python.Runtime /// internal class ConstructorBinder : MethodBinder { - private Type _containingType = null; + private Type _containingType; - internal ConstructorBinder(Type containingType) : base() + internal ConstructorBinder(Type containingType) { _containingType = containingType; } @@ -29,7 +29,7 @@ internal ConstructorBinder(Type containingType) : base() /// internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) { - return this.InvokeRaw(inst, args, kw, null); + return InvokeRaw(inst, args, kw, null); } /// @@ -49,7 +49,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw) /// internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) { - Object result; + object result; if (_containingType.IsValueType && !_containingType.IsPrimitive && !_containingType.IsEnum && _containingType != typeof(decimal) && @@ -76,7 +76,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) return result; } - Binding binding = this.Bind(inst, args, kw, info); + Binding binding = Bind(inst, args, kw, info); if (binding == null) { @@ -88,7 +88,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) // any extra args are intended for the subclass' __init__. IntPtr eargs = Runtime.PyTuple_New(0); - binding = this.Bind(inst, eargs, kw); + binding = Bind(inst, eargs, kw); Runtime.XDecref(eargs); if (binding == null) @@ -99,7 +99,7 @@ internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info) } // Fire the selected ctor and catch errors... - ConstructorInfo ci = (ConstructorInfo)binding.info; + var ci = (ConstructorInfo)binding.info; // Object construction is presumed to be non-blocking and fast // enough that we shouldn't really need to release the GIL. try diff --git a/src/runtime/debughelper.cs b/src/runtime/debughelper.cs index 94dd026f6..f42ad2e37 100644 --- a/src/runtime/debughelper.cs +++ b/src/runtime/debughelper.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; @@ -20,19 +19,18 @@ public static void Print(string msg, params IntPtr[] args) string result = msg; result += " "; - for (int i = 0; i < args.Length; i++) + foreach (IntPtr t in args) { - if (args[i] == IntPtr.Zero) + if (t == IntPtr.Zero) { Console.WriteLine("null arg to print"); } - IntPtr ob = Runtime.PyObject_Repr(args[i]); + IntPtr ob = Runtime.PyObject_Repr(t); result += Runtime.GetManagedString(ob); Runtime.XDecref(ob); result += " "; } Console.WriteLine(result); - return; } [Conditional("DEBUG")] @@ -50,13 +48,13 @@ internal static void DumpType(IntPtr type) Console.WriteLine("Dump type: {0}", name); op = Marshal.ReadIntPtr(type, TypeOffset.ob_type); - DebugUtil.Print(" type: ", op); + Print(" type: ", op); op = Marshal.ReadIntPtr(type, TypeOffset.tp_base); - DebugUtil.Print(" base: ", op); + Print(" base: ", op); op = Marshal.ReadIntPtr(type, TypeOffset.tp_bases); - DebugUtil.Print(" bases: ", op); + Print(" bases: ", op); //op = Marshal.ReadIntPtr(type, TypeOffset.tp_mro); //DebugUtil.Print(" mro: ", op); @@ -65,7 +63,7 @@ internal static void DumpType(IntPtr type) FieldInfo[] slots = typeof(TypeOffset).GetFields(); int size = IntPtr.Size; - for (int i = 0; i < slots.Length; i++) + for (var i = 0; i < slots.Length; i++) { int offset = i * size; name = slots[i].Name; @@ -83,7 +81,7 @@ internal static void DumpType(IntPtr type) } else { - DebugUtil.Print(" dict: ", op); + Print(" dict: ", op); } } @@ -91,11 +89,11 @@ internal static void DumpType(IntPtr type) internal static void DumpInst(IntPtr ob) { IntPtr tp = Runtime.PyObject_TYPE(ob); - int sz = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_basicsize); + var sz = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_basicsize); - for (int i = 0; i < sz; i += IntPtr.Size) + for (var i = 0; i < sz; i += IntPtr.Size) { - IntPtr pp = new IntPtr(ob.ToInt64() + i); + var pp = new IntPtr(ob.ToInt64() + i); IntPtr v = Marshal.ReadIntPtr(pp); Console.WriteLine("offset {0}: {1}", i, v); } @@ -107,7 +105,7 @@ internal static void DumpInst(IntPtr ob) [Conditional("DEBUG")] internal static void debug(string msg) { - StackTrace st = new StackTrace(1, true); + var st = new StackTrace(1, true); StackFrame sf = st.GetFrame(0); MethodBase mb = sf.GetMethod(); Type mt = mb.DeclaringType; @@ -116,7 +114,6 @@ internal static void debug(string msg) string tid = t.GetHashCode().ToString(); Console.WriteLine("thread {0} : {1}", tid, caller); Console.WriteLine(" {0}", msg); - return; } } } diff --git a/src/runtime/delegateobject.cs b/src/runtime/delegateobject.cs index 2d305e5f2..ff64ff094 100644 --- a/src/runtime/delegateobject.cs +++ b/src/runtime/delegateobject.cs @@ -26,10 +26,10 @@ internal DelegateObject(Type tp) : base(tp) /// private static Delegate GetTrueDelegate(IntPtr op) { - CLRObject o = GetManagedObject(op) as CLRObject; + var o = GetManagedObject(op) as CLRObject; if (o != null) { - Delegate d = o.inst as Delegate; + var d = o.inst as Delegate; return d; } return null; @@ -51,11 +51,11 @@ internal override bool CanSubclass() /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - DelegateObject self = (DelegateObject)GetManagedObject(tp); + var self = (DelegateObject)GetManagedObject(tp); if (Runtime.PyTuple_Size(args) != 1) { - string message = "class takes exactly one argument"; + var message = "class takes exactly one argument"; return Exceptions.RaiseTypeError(message); } @@ -78,15 +78,15 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { // todo: add fast type check! IntPtr pytype = Runtime.PyObject_TYPE(ob); - DelegateObject self = (DelegateObject)GetManagedObject(pytype); - CLRObject o = GetManagedObject(ob) as CLRObject; + var self = (DelegateObject)GetManagedObject(pytype); + var o = GetManagedObject(ob) as CLRObject; if (o == null) { return Exceptions.RaiseTypeError("invalid argument"); } - Delegate d = o.inst as Delegate; + var d = o.inst as Delegate; if (d == null) { diff --git a/src/runtime/extensiontype.cs b/src/runtime/extensiontype.cs index a09f57696..37ab11239 100644 --- a/src/runtime/extensiontype.cs +++ b/src/runtime/extensiontype.cs @@ -1,7 +1,5 @@ using System; using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -12,14 +10,14 @@ namespace Python.Runtime /// internal abstract class ExtensionType : ManagedType { - public ExtensionType() : base() + public ExtensionType() { // Create a new PyObject whose type is a generated type that is // implemented by the particuar concrete ExtensionType subclass. // The Python instance object is related to an instance of a // particular concrete subclass with a hidden CLR gchandle. - IntPtr tp = TypeManager.GetTypeHandle(this.GetType()); + IntPtr tp = TypeManager.GetTypeHandle(GetType()); //int rc = (int)Marshal.ReadIntPtr(tp, TypeOffset.ob_refcnt); //if (rc > 1050) @@ -40,9 +38,9 @@ public ExtensionType() : base() Runtime.PyObject_GC_UnTrack(py); - this.tpHandle = tp; - this.pyHandle = py; - this.gcHandle = gc; + tpHandle = tp; + pyHandle = py; + gcHandle = gc; } @@ -62,7 +60,7 @@ public static void FinalizeObject(ManagedType self) /// public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) { - string message = "type does not support setting attributes"; + var message = "type does not support setting attributes"; if (val == IntPtr.Zero) { message = "readonly attribute"; @@ -78,8 +76,7 @@ public static int tp_setattro(IntPtr ob, IntPtr key, IntPtr val) /// public static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - string message = "attribute is read-only"; - Exceptions.SetError(Exceptions.AttributeError, message); + Exceptions.SetError(Exceptions.AttributeError, "attribute is read-only"); return -1; } diff --git a/src/runtime/fieldobject.cs b/src/runtime/fieldobject.cs index 3d65f5fd3..6eefb5b0a 100644 --- a/src/runtime/fieldobject.cs +++ b/src/runtime/fieldobject.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Reflection; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -12,7 +10,7 @@ internal class FieldObject : ExtensionType { FieldInfo info; - public FieldObject(FieldInfo info) : base() + public FieldObject(FieldInfo info) { this.info = info; } @@ -24,8 +22,8 @@ public FieldObject(FieldInfo info) : base() /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - FieldObject self = (FieldObject)GetManagedObject(ds); - Object result; + var self = (FieldObject)GetManagedObject(ds); + object result; if (self == null) { @@ -34,12 +32,12 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) FieldInfo info = self.info; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { if (!info.IsStatic) { Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be accessed " + "through a class instance"); + "instance attribute must be accessed through a class instance"); return IntPtr.Zero; } try @@ -56,7 +54,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) try { - CLRObject co = (CLRObject)GetManagedObject(ob); + var co = (CLRObject)GetManagedObject(ob); result = info.GetValue(co.inst); return Converter.ToPython(result, info.FieldType); } @@ -72,10 +70,10 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// a field based on the given Python value. The Python value must be /// convertible to the type of the field. /// - public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) + public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - FieldObject self = (FieldObject)GetManagedObject(ds); - Object newval; + var self = (FieldObject)GetManagedObject(ds); + object newval; if (self == null) { @@ -98,12 +96,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) bool is_static = info.IsStatic; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { if (!is_static) { - Exceptions.SetError(Exceptions.TypeError, - "instance attribute must be set " + "through a class instance"); + Exceptions.SetError(Exceptions.TypeError, "instance attribute must be set through a class instance"); return -1; } } @@ -117,7 +114,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { if (!is_static) { - CLRObject co = (CLRObject)GetManagedObject(ob); + var co = (CLRObject)GetManagedObject(ob); info.SetValue(co.inst, newval); } else @@ -138,8 +135,8 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - FieldObject self = (FieldObject)GetManagedObject(ob); - string s = String.Format("", self.info.Name); + var self = (FieldObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/generictype.cs b/src/runtime/generictype.cs index 761efc045..eeae801d2 100644 --- a/src/runtime/generictype.cs +++ b/src/runtime/generictype.cs @@ -1,5 +1,4 @@ using System; -using System.Reflection; namespace Python.Runtime { diff --git a/src/runtime/genericutil.cs b/src/runtime/genericutil.cs index 6568ac438..d1de1c374 100644 --- a/src/runtime/genericutil.cs +++ b/src/runtime/genericutil.cs @@ -30,7 +30,9 @@ static GenericUtil() internal static void Register(Type t) { if (null == t.Namespace || null == t.Name) + { return; + } Dictionary> nsmap = null; mapping.TryGetValue(t.Namespace, out nsmap); @@ -66,7 +68,7 @@ public static List GetGenericBaseNames(string ns) { return null; } - List names = new List(); + var names = new List(); foreach (string key in nsmap.Keys) { names.Add(key); @@ -87,7 +89,9 @@ public static Type GenericByName(string ns, string name, int paramCount) foreach (Type t in GenericsByName(ns, name)) { if (t.GetGenericArguments().Length == paramCount) + { return t; + } } return null; } @@ -119,7 +123,7 @@ public static List GenericsByName(string ns, string basename) return null; } - List result = new List(); + var result = new List(); foreach (string name in names) { string qname = ns + "." + name; diff --git a/src/runtime/importhook.cs b/src/runtime/importhook.cs index e5843d436..96a343773 100644 --- a/src/runtime/importhook.cs +++ b/src/runtime/importhook.cs @@ -59,7 +59,7 @@ internal static void Initialize() Runtime.PyDict_Update(mod_dict, clr_dict); #elif PYTHON2 Runtime.XIncref(root.pyHandle); // we are using the module two times - py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 + py_clr_module = root.pyHandle; // Alias handle for PY2/PY3 #endif Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module); Runtime.PyDict_SetItemString(dict, "clr", py_clr_module); @@ -150,8 +150,8 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // borrowed reference IntPtr py_mod_name = Runtime.PyTuple_GetItem(args, 0); - if ((py_mod_name == IntPtr.Zero) || - (!Runtime.IsStringType(py_mod_name))) + if (py_mod_name == IntPtr.Zero || + !Runtime.IsStringType(py_mod_name)) { return Exceptions.RaiseTypeError("string expected"); } @@ -160,12 +160,12 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // This determines whether we return the head or tail module. IntPtr fromList = IntPtr.Zero; - bool fromlist = false; + var fromlist = false; if (num_args >= 4) { fromList = Runtime.PyTuple_GetItem(args, 3); - if ((fromList != IntPtr.Zero) && - (Runtime.PyObject_IsTrue(fromList) == 1)) + if (fromList != IntPtr.Zero && + Runtime.PyObject_IsTrue(fromList) == 1) { fromlist = true; } @@ -208,7 +208,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) { clr_prefix = "CLR."; // prepend when adding the module to sys.modules realname = mod_name.Substring(4); - string msg = String.Format("Importing from the CLR.* namespace " + + string msg = string.Format("Importing from the CLR.* namespace " + "is deprecated. Please import '{0}' directly.", realname); Exceptions.deprecation(msg); } @@ -301,7 +301,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) // enable preloading in a non-interactive python processing by // setting clr.preload = True - ModuleObject head = (mod_name == realname) ? null : root; + ModuleObject head = mod_name == realname ? null : root; ModuleObject tail = root; root.InitializePreload(); @@ -310,7 +310,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) ManagedType mt = tail.GetAttribute(name, true); if (!(mt is ModuleObject)) { - string error = String.Format("No module named {0}", name); + string error = string.Format("No module named {0}", name); Exceptions.SetError(Exceptions.ImportError, error); return IntPtr.Zero; } @@ -339,7 +339,7 @@ public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw) if (fromlist && Runtime.PySequence_Size(fromList) == 1) { IntPtr fp = Runtime.PySequence_GetItem(fromList, 0); - if ((!CLRModule.preload) && Runtime.GetManagedString(fp) == "*") + if (!CLRModule.preload && Runtime.GetManagedString(fp) == "*") { mod.LoadNames(); } diff --git a/src/runtime/interfaceobject.cs b/src/runtime/interfaceobject.cs index 8e64c24d7..e1c816f01 100644 --- a/src/runtime/interfaceobject.cs +++ b/src/runtime/interfaceobject.cs @@ -16,7 +16,7 @@ internal class InterfaceObject : ClassBase internal InterfaceObject(Type tp) : base(tp) { - CoClassAttribute coclass = (CoClassAttribute)Attribute.GetCustomAttribute(tp, cc_attr); + var coclass = (CoClassAttribute)Attribute.GetCustomAttribute(tp, cc_attr); if (coclass != null) { ctor = coclass.CoClass.GetConstructor(Type.EmptyTypes); @@ -35,17 +35,17 @@ static InterfaceObject() /// public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) { - InterfaceObject self = (InterfaceObject)GetManagedObject(tp); + var self = (InterfaceObject)GetManagedObject(tp); int nargs = Runtime.PyTuple_Size(args); Type type = self.type; - Object obj; + object obj; if (nargs == 1) { IntPtr inst = Runtime.PyTuple_GetItem(args, 0); - CLRObject co = GetManagedObject(inst) as CLRObject; + var co = GetManagedObject(inst) as CLRObject; - if ((co == null) || (!type.IsInstanceOfType(co.inst))) + if (co == null || !type.IsInstanceOfType(co.inst)) { string msg = "object does not implement " + type.Name; Exceptions.SetError(Exceptions.TypeError, msg); @@ -55,7 +55,7 @@ public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) obj = co.inst; } - else if ((nargs == 0) && (self.ctor != null)) + else if (nargs == 0 && self.ctor != null) { obj = self.ctor.Invoke(null); diff --git a/src/runtime/interfaces.cs b/src/runtime/interfaces.cs index d0edfbf9c..5ce319858 100644 --- a/src/runtime/interfaces.cs +++ b/src/runtime/interfaces.cs @@ -1,6 +1,4 @@ using System; -using System.Reflection; -using System.Runtime.InteropServices; namespace Python.Runtime { diff --git a/src/runtime/iterator.cs b/src/runtime/iterator.cs index f2a32deb4..efa49537c 100644 --- a/src/runtime/iterator.cs +++ b/src/runtime/iterator.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -12,9 +11,9 @@ internal class Iterator : ExtensionType { IEnumerator iter; - public Iterator(IEnumerator e) : base() + public Iterator(IEnumerator e) { - this.iter = e; + iter = e; } @@ -23,7 +22,7 @@ public Iterator(IEnumerator e) : base() /// public static IntPtr tp_iternext(IntPtr ob) { - Iterator self = GetManagedObject(ob) as Iterator; + var self = GetManagedObject(ob) as Iterator; if (!self.iter.MoveNext()) { Exceptions.SetError(Exceptions.StopIteration, Runtime.PyNone); diff --git a/src/runtime/managedtype.cs b/src/runtime/managedtype.cs index 0d46f2366..9ee8d223b 100644 --- a/src/runtime/managedtype.cs +++ b/src/runtime/managedtype.cs @@ -1,7 +1,5 @@ using System; using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; namespace Python.Runtime { @@ -30,13 +28,13 @@ internal static ManagedType GetManagedObject(IntPtr ob) tp = ob; } - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Managed) != 0) { - IntPtr op = (tp == ob) + IntPtr op = tp == ob ? Marshal.ReadIntPtr(tp, TypeOffset.magic()) : Marshal.ReadIntPtr(ob, ObjectOffset.magic(ob)); - GCHandle gc = (GCHandle)op; + var gc = (GCHandle)op; return (ManagedType)gc.Target; } } @@ -65,7 +63,7 @@ internal static bool IsManagedType(IntPtr ob) tp = ob; } - int flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); + var flags = (int)Marshal.ReadIntPtr(tp, TypeOffset.tp_flags); if ((flags & TypeFlags.Managed) != 0) { return true; diff --git a/src/runtime/methodwrapper.cs b/src/runtime/methodwrapper.cs index 71932ddd0..2f3ce3ef2 100644 --- a/src/runtime/methodwrapper.cs +++ b/src/runtime/methodwrapper.cs @@ -1,6 +1,4 @@ using System; -using System.Collections; -using System.Runtime.InteropServices; namespace Python.Runtime { diff --git a/src/runtime/modulefunctionobject.cs b/src/runtime/modulefunctionobject.cs index b6f2899d8..aa4c8fb06 100644 --- a/src/runtime/modulefunctionobject.cs +++ b/src/runtime/modulefunctionobject.cs @@ -1,5 +1,5 @@ using System; -using System.Collections; +using System.Linq; using System.Reflection; namespace Python.Runtime @@ -12,13 +12,9 @@ internal class ModuleFunctionObject : MethodObject public ModuleFunctionObject(Type type, string name, MethodInfo[] info, bool allow_threads) : base(type, name, info, allow_threads) { - for (int i = 0; i < info.Length; i++) + if (info.Any(item => !item.IsStatic)) { - MethodInfo item = (MethodInfo)info[i]; - if (!item.IsStatic) - { - throw new Exception("Module function must be static."); - } + throw new Exception("Module function must be static."); } } @@ -27,17 +23,17 @@ public ModuleFunctionObject(Type type, string name, MethodInfo[] info, bool allo /// public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { - ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); + var self = (ModuleFunctionObject)GetManagedObject(ob); return self.Invoke(ob, args, kw); } /// /// __repr__ implementation. /// - public static new IntPtr tp_repr(IntPtr ob) + public new static IntPtr tp_repr(IntPtr ob) { - ModuleFunctionObject self = (ModuleFunctionObject)GetManagedObject(ob); - string s = String.Format("", self.name); + var self = (ModuleFunctionObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/modulepropertyobject.cs b/src/runtime/modulepropertyobject.cs index 7f7841890..8f5edb6ef 100644 --- a/src/runtime/modulepropertyobject.cs +++ b/src/runtime/modulepropertyobject.cs @@ -1,7 +1,5 @@ using System; -using System.Collections; using System.Reflection; -using System.Security.Permissions; namespace Python.Runtime { @@ -10,7 +8,7 @@ namespace Python.Runtime /// internal class ModulePropertyObject : ExtensionType { - public ModulePropertyObject(PropertyInfo md) : base() + public ModulePropertyObject(PropertyInfo md) { throw new NotImplementedException("ModulePropertyObject"); } diff --git a/src/runtime/monosupport.cs b/src/runtime/monosupport.cs index 7ddf9aa1a..fc39f9065 100644 --- a/src/runtime/monosupport.cs +++ b/src/runtime/monosupport.cs @@ -31,10 +31,8 @@ public int GetNativeDataSize() public IntPtr MarshalManagedToNative(object obj) { - string s = obj as string; - if (s == null) - return IntPtr.Zero; - return UnixMarshal.StringToHeap(s, Encoding.UTF32); + var s = obj as string; + return s == null ? IntPtr.Zero : UnixMarshal.StringToHeap(s, Encoding.UTF32); } public object MarshalNativeToManaged(IntPtr pNativeData) diff --git a/src/runtime/nativecall.cs b/src/runtime/nativecall.cs index 7eb8b87c8..f49f08e7b 100644 --- a/src/runtime/nativecall.cs +++ b/src/runtime/nativecall.cs @@ -13,12 +13,10 @@ namespace Python.Runtime /// C API can just be wrapped with p/invoke, but there are some /// situations (specifically, calling functions through Python /// type structures) where we need to call functions indirectly. - /// /// This class uses Reflection.Emit to generate IJW thunks that /// support indirect calls to native code using various common /// call signatures. This is mainly a workaround for the fact /// that you can't spell an indirect call in C# (but can in IL). - /// /// Another approach that would work is for this to be turned /// into a separate utility program that could be run during the /// build process to generate the thunks as a separate assembly @@ -40,14 +38,14 @@ static NativeCall() // interface (defined below) and generate the required thunk // code based on the method signatures. - AssemblyName aname = new AssemblyName(); + var aname = new AssemblyName(); aname.Name = "e__NativeCall_Assembly"; - AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run; + var aa = AssemblyBuilderAccess.Run; aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa); mBuilder = aBuilder.DefineDynamicModule("e__NativeCall_Module"); - TypeAttributes ta = TypeAttributes.Public; + var ta = TypeAttributes.Public; TypeBuilder tBuilder = mBuilder.DefineType("e__NativeCall", ta); Type iType = typeof(INativeCall); @@ -72,8 +70,8 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) int count = pi.Length; int argc = count - 1; - Type[] args = new Type[count]; - for (int i = 0; i < count; i++) + var args = new Type[count]; + for (var i = 0; i < count; i++) { args[i] = pi[i].ParameterType; } @@ -84,16 +82,16 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) MethodAttributes.Virtual, method.ReturnType, args - ); + ); // Build the method signature for the actual native function. // This is essentially the signature of the wrapper method // minus the first argument (the passed in function pointer). - Type[] nargs = new Type[argc]; - for (int i = 1; i < count; i++) + var nargs = new Type[argc]; + for (var i = 1; i < count; i++) { - nargs[(i - 1)] = args[i]; + nargs[i - 1] = args[i]; } // IL generation: the (implicit) first argument of the method @@ -103,9 +101,9 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) ILGenerator il = mb.GetILGenerator(); - for (int i = 0; i < argc; i++) + for (var i = 0; i < argc; i++) { - il.Emit(OpCodes.Ldarg_S, (i + 2)); + il.Emit(OpCodes.Ldarg_S, i + 2); } il.Emit(OpCodes.Ldarg_1); @@ -114,12 +112,11 @@ private static void GenerateThunk(TypeBuilder tb, MethodInfo method) CallingConvention.Cdecl, method.ReturnType, nargs - ); + ); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(mb, method); - return; } diff --git a/src/runtime/overload.cs b/src/runtime/overload.cs index a183863d6..e8f51c01d 100644 --- a/src/runtime/overload.cs +++ b/src/runtime/overload.cs @@ -12,7 +12,7 @@ internal class OverloadMapper : ExtensionType MethodObject m; IntPtr target; - public OverloadMapper(MethodObject m, IntPtr target) : base() + public OverloadMapper(MethodObject m, IntPtr target) { Runtime.XIncref(target); this.target = target; @@ -24,7 +24,7 @@ public OverloadMapper(MethodObject m, IntPtr target) : base() /// public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { - OverloadMapper self = (OverloadMapper)GetManagedObject(tp); + var self = (OverloadMapper)GetManagedObject(tp); // Note: if the type provides a non-generic method with N args // and a generic method that takes N params, then we always @@ -39,12 +39,11 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) MethodInfo mi = MethodBinder.MatchSignature(self.m.info, types); if (mi == null) { - string e = "No match found for signature"; + var e = "No match found for signature"; return Exceptions.RaiseTypeError(e); } - MethodBinding mb = new MethodBinding(self.m, self.target); - mb.info = mi; + var mb = new MethodBinding(self.m, self.target) { info = mi }; Runtime.XIncref(mb.pyHandle); return mb.pyHandle; } @@ -54,7 +53,7 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) /// public static IntPtr tp_repr(IntPtr op) { - OverloadMapper self = (OverloadMapper)GetManagedObject(op); + var self = (OverloadMapper)GetManagedObject(op); IntPtr doc = self.m.GetDocString(); Runtime.XIncref(doc); return doc; @@ -63,11 +62,11 @@ public static IntPtr tp_repr(IntPtr op) /// /// OverloadMapper dealloc implementation. /// - public static new void tp_dealloc(IntPtr ob) + public new static void tp_dealloc(IntPtr ob) { - OverloadMapper self = (OverloadMapper)GetManagedObject(ob); + var self = (OverloadMapper)GetManagedObject(ob); Runtime.XDecref(self.target); - ExtensionType.FinalizeObject(self); + FinalizeObject(self); } } } diff --git a/src/runtime/propertyobject.cs b/src/runtime/propertyobject.cs index ea029cc91..dae47667f 100644 --- a/src/runtime/propertyobject.cs +++ b/src/runtime/propertyobject.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Reflection; using System.Security.Permissions; @@ -14,8 +13,8 @@ internal class PropertyObject : ExtensionType MethodInfo getter; MethodInfo setter; - [StrongNameIdentityPermissionAttribute(SecurityAction.Assert)] - public PropertyObject(PropertyInfo md) : base() + [StrongNameIdentityPermission(SecurityAction.Assert)] + public PropertyObject(PropertyInfo md) { getter = md.GetGetMethod(true); setter = md.GetSetMethod(true); @@ -30,9 +29,9 @@ public PropertyObject(PropertyInfo md) : base() /// public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { - PropertyObject self = (PropertyObject)GetManagedObject(ds); + var self = (PropertyObject)GetManagedObject(ds); MethodInfo getter = self.getter; - Object result; + object result; if (getter == null) @@ -40,12 +39,12 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) return Exceptions.RaiseTypeError("property cannot be read"); } - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { - if (!(getter.IsStatic)) + if (!getter.IsStatic) { Exceptions.SetError(Exceptions.TypeError, - "instance property must be accessed through " + "a class instance"); + "instance property must be accessed through a class instance"); return IntPtr.Zero; } @@ -60,7 +59,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) } } - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { return Exceptions.RaiseTypeError("invalid target"); @@ -88,11 +87,11 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// a property based on the given Python value. The Python value must /// be convertible to the type of the property. /// - public static new int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) + public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val) { - PropertyObject self = (PropertyObject)GetManagedObject(ds); + var self = (PropertyObject)GetManagedObject(ds); MethodInfo setter = self.setter; - Object newval; + object newval; if (val == IntPtr.Zero) { @@ -114,9 +113,9 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) bool is_static = setter.IsStatic; - if ((ob == IntPtr.Zero) || (ob == Runtime.PyNone)) + if (ob == IntPtr.Zero || ob == Runtime.PyNone) { - if (!(is_static)) + if (!is_static) { Exceptions.RaiseTypeError("instance property must be set on an instance"); return -1; @@ -127,7 +126,7 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) { if (!is_static) { - CLRObject co = GetManagedObject(ob) as CLRObject; + var co = GetManagedObject(ob) as CLRObject; if (co == null) { Exceptions.RaiseTypeError("invalid target"); @@ -158,8 +157,8 @@ public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp) /// public static IntPtr tp_repr(IntPtr ob) { - PropertyObject self = (PropertyObject)GetManagedObject(ob); - string s = String.Format("", self.info.Name); + var self = (PropertyObject)GetManagedObject(ob); + string s = $""; return Runtime.PyString_FromStringAndSize(s, s.Length); } } diff --git a/src/runtime/pyansistring.cs b/src/runtime/pyansistring.cs index d15961ee3..4973d8b2a 100644 --- a/src/runtime/pyansistring.cs +++ b/src/runtime/pyansistring.cs @@ -25,7 +25,7 @@ public PyAnsiString(IntPtr ptr) : base(ptr) /// An ArgumentException will be thrown if the given object is not /// a Python string object. /// - public PyAnsiString(PyObject o) : base() + public PyAnsiString(PyObject o) { if (!IsStringType(o)) { @@ -42,7 +42,7 @@ public PyAnsiString(PyObject o) : base() /// /// Creates a Python string from a managed string. /// - public PyAnsiString(string s) : base() + public PyAnsiString(string s) { obj = Runtime.PyString_FromStringAndSize(s, s.Length); if (obj == IntPtr.Zero) diff --git a/src/runtime/pydict.cs b/src/runtime/pydict.cs index 18f0939b2..7237d1990 100644 --- a/src/runtime/pydict.cs +++ b/src/runtime/pydict.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -30,7 +29,7 @@ public PyDict(IntPtr ptr) : base(ptr) /// /// Creates a new Python dictionary object. /// - public PyDict() : base() + public PyDict() { obj = Runtime.PyDict_New(); if (obj == IntPtr.Zero) @@ -48,7 +47,7 @@ public PyDict() : base() /// ArgumentException will be thrown if the given object is not a /// Python dictionary object. /// - public PyDict(PyObject o) : base() + public PyDict(PyObject o) { if (!IsDictType(o)) { @@ -79,7 +78,7 @@ public static bool IsDictType(PyObject value) /// public bool HasKey(PyObject key) { - return (Runtime.PyMapping_HasKey(obj, key.obj) != 0); + return Runtime.PyMapping_HasKey(obj, key.obj) != 0; } @@ -91,8 +90,10 @@ public bool HasKey(PyObject key) /// public bool HasKey(string key) { - using (PyString str = new PyString(key)) + using (var str = new PyString(key)) + { return HasKey(str); + } } diff --git a/src/runtime/pyfloat.cs b/src/runtime/pyfloat.cs index 959657118..cca436def 100644 --- a/src/runtime/pyfloat.cs +++ b/src/runtime/pyfloat.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -32,7 +31,7 @@ public PyFloat(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python float object. /// - public PyFloat(PyObject o) : base() + public PyFloat(PyObject o) { if (!IsFloatType(o)) { @@ -49,7 +48,7 @@ public PyFloat(PyObject o) : base() /// /// Creates a new Python float from a double value. /// - public PyFloat(double value) : base() + public PyFloat(double value) { obj = Runtime.PyFloat_FromDouble(value); if (obj == IntPtr.Zero) @@ -65,9 +64,9 @@ public PyFloat(double value) : base() /// /// Creates a new Python float from a string value. /// - public PyFloat(string value) : base() + public PyFloat(string value) { - using (PyString s = new PyString(value)) + using (var s = new PyString(value)) { obj = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero); if (obj == IntPtr.Zero) diff --git a/src/runtime/pyint.cs b/src/runtime/pyint.cs index e89c1e87e..c84939482 100644 --- a/src/runtime/pyint.cs +++ b/src/runtime/pyint.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices; namespace Python.Runtime { @@ -32,7 +31,7 @@ public PyInt(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python int object. /// - public PyInt(PyObject o) : base() + public PyInt(PyObject o) { if (!IsIntType(o)) { @@ -49,7 +48,7 @@ public PyInt(PyObject o) : base() /// /// Creates a new Python int from an int32 value. /// - public PyInt(int value) : base() + public PyInt(int value) { obj = Runtime.PyInt_FromInt32(value); if (obj == IntPtr.Zero) @@ -68,7 +67,7 @@ public PyInt(int value) : base() [CLSCompliant(false)] public PyInt(uint value) : base(IntPtr.Zero) { - obj = Runtime.PyInt_FromInt64((long)value); + obj = Runtime.PyInt_FromInt64(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -161,7 +160,7 @@ public PyInt(sbyte value) : this((int)value) /// /// Creates a new Python int from a string value. /// - public PyInt(string value) : base() + public PyInt(string value) { obj = Runtime.PyInt_FromString(value, IntPtr.Zero, 0); if (obj == IntPtr.Zero) @@ -210,7 +209,7 @@ public static PyInt AsInt(PyObject value) /// public short ToInt16() { - return System.Convert.ToInt16(this.ToInt32()); + return Convert.ToInt16(ToInt32()); } @@ -234,7 +233,7 @@ public int ToInt32() /// public long ToInt64() { - return System.Convert.ToInt64(this.ToInt32()); + return Convert.ToInt64(ToInt32()); } } } diff --git a/src/runtime/pyiter.cs b/src/runtime/pyiter.cs index c1bab2781..3c9b2a238 100644 --- a/src/runtime/pyiter.cs +++ b/src/runtime/pyiter.cs @@ -11,7 +11,7 @@ namespace Python.Runtime /// public class PyIter : PyObject, IEnumerator { - private PyObject _current = null; + private PyObject _current; /// /// PyIter Constructor @@ -31,11 +31,13 @@ public PyIter(IntPtr ptr) : base(ptr) /// /// Creates a Python iterator from an iterable. Like doing "iter(iterable)" in python. /// - public PyIter(PyObject iterable) : base() + public PyIter(PyObject iterable) { obj = Runtime.PyObject_GetIter(iterable.obj); if (obj == IntPtr.Zero) + { throw new PythonException(); + } } protected override void Dispose(bool disposing) @@ -61,7 +63,9 @@ public bool MoveNext() IntPtr next = Runtime.PyIter_Next(obj); if (next == IntPtr.Zero) + { return false; + } _current = new PyObject(next); return true; diff --git a/src/runtime/pylist.cs b/src/runtime/pylist.cs index 8a369f654..b22d9d51f 100644 --- a/src/runtime/pylist.cs +++ b/src/runtime/pylist.cs @@ -31,7 +31,7 @@ public PyList(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python list object. /// - public PyList(PyObject o) : base() + public PyList(PyObject o) { if (!IsListType(o)) { @@ -48,7 +48,7 @@ public PyList(PyObject o) : base() /// /// Creates a new empty Python list object. /// - public PyList() : base() + public PyList() { obj = Runtime.PyList_New(0); if (obj == IntPtr.Zero) @@ -64,11 +64,11 @@ public PyList() : base() /// /// Creates a new Python list object from an array of PyObjects. /// - public PyList(PyObject[] items) : base() + public PyList(PyObject[] items) { int count = items.Length; obj = Runtime.PyList_New(count); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); diff --git a/src/runtime/pylong.cs b/src/runtime/pylong.cs index 8deac242e..ade7cb42c 100644 --- a/src/runtime/pylong.cs +++ b/src/runtime/pylong.cs @@ -31,7 +31,7 @@ public PyLong(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python long object. /// - public PyLong(PyObject o) : base() + public PyLong(PyObject o) { if (!IsLongType(o)) { @@ -48,9 +48,9 @@ public PyLong(PyObject o) : base() /// /// Creates a new PyLong from an int32 value. /// - public PyLong(int value) : base() + public PyLong(int value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -65,9 +65,9 @@ public PyLong(int value) : base() /// Creates a new PyLong from a uint32 value. /// [CLSCompliant(false)] - public PyLong(uint value) : base() + public PyLong(uint value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -81,7 +81,7 @@ public PyLong(uint value) : base() /// /// Creates a new PyLong from an int64 value. /// - public PyLong(long value) : base() + public PyLong(long value) { obj = Runtime.PyLong_FromLongLong(value); if (obj == IntPtr.Zero) @@ -98,7 +98,7 @@ public PyLong(long value) : base() /// Creates a new PyLong from a uint64 value. /// [CLSCompliant(false)] - public PyLong(ulong value) : base() + public PyLong(ulong value) { obj = Runtime.PyLong_FromUnsignedLongLong(value); if (obj == IntPtr.Zero) @@ -114,9 +114,9 @@ public PyLong(ulong value) : base() /// /// Creates a new PyLong from an int16 value. /// - public PyLong(short value) : base() + public PyLong(short value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -131,9 +131,9 @@ public PyLong(short value) : base() /// Creates a new PyLong from an uint16 value. /// [CLSCompliant(false)] - public PyLong(ushort value) : base() + public PyLong(ushort value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -147,9 +147,9 @@ public PyLong(ushort value) : base() /// /// Creates a new PyLong from a byte value. /// - public PyLong(byte value) : base() + public PyLong(byte value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -164,9 +164,9 @@ public PyLong(byte value) : base() /// Creates a new PyLong from an sbyte value. /// [CLSCompliant(false)] - public PyLong(sbyte value) : base() + public PyLong(sbyte value) { - obj = Runtime.PyLong_FromLong((long)value); + obj = Runtime.PyLong_FromLong(value); if (obj == IntPtr.Zero) { throw new PythonException(); @@ -180,7 +180,7 @@ public PyLong(sbyte value) : base() /// /// Creates a new PyLong from an double value. /// - public PyLong(double value) : base() + public PyLong(double value) { obj = Runtime.PyLong_FromDouble(value); if (obj == IntPtr.Zero) @@ -196,7 +196,7 @@ public PyLong(double value) : base() /// /// Creates a new PyLong from a string value. /// - public PyLong(string value) : base() + public PyLong(string value) { obj = Runtime.PyLong_FromString(value, IntPtr.Zero, 0); if (obj == IntPtr.Zero) @@ -244,7 +244,7 @@ public static PyLong AsLong(PyObject value) /// public short ToInt16() { - return System.Convert.ToInt16(this.ToInt64()); + return Convert.ToInt16(ToInt64()); } @@ -256,7 +256,7 @@ public short ToInt16() /// public int ToInt32() { - return System.Convert.ToInt32(this.ToInt64()); + return Convert.ToInt32(ToInt64()); } diff --git a/src/runtime/pynumber.cs b/src/runtime/pynumber.cs index 73dde6744..371d9f4f6 100644 --- a/src/runtime/pynumber.cs +++ b/src/runtime/pynumber.cs @@ -15,7 +15,7 @@ protected PyNumber(IntPtr ptr) : base(ptr) { } - protected PyNumber() : base() + protected PyNumber() { } diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index d54959599..bfaee79a6 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -16,7 +16,7 @@ protected PySequence(IntPtr ptr) : base(ptr) { } - protected PySequence() : base() + protected PySequence() { } @@ -115,7 +115,7 @@ public bool Contains(PyObject item) { throw new PythonException(); } - return (r != 0); + return r != 0; } diff --git a/src/runtime/pystring.cs b/src/runtime/pystring.cs index 39e7a8f96..3bd99b87c 100644 --- a/src/runtime/pystring.cs +++ b/src/runtime/pystring.cs @@ -34,7 +34,7 @@ public PyString(IntPtr ptr) : base(ptr) /// An ArgumentException will be thrown if the given object is not /// a Python string object. /// - public PyString(PyObject o) : base() + public PyString(PyObject o) { if (!IsStringType(o)) { @@ -51,7 +51,7 @@ public PyString(PyObject o) : base() /// /// Creates a Python string from a managed string. /// - public PyString(string s) : base() + public PyString(string s) { obj = Runtime.PyUnicode_FromUnicode(s, s.Length); if (obj == IntPtr.Zero) diff --git a/src/runtime/pythonexception.cs b/src/runtime/pythonexception.cs index d2475664c..8e2f992f4 100644 --- a/src/runtime/pythonexception.cs +++ b/src/runtime/pythonexception.cs @@ -15,26 +15,26 @@ public class PythonException : System.Exception private string _message = ""; private bool disposed = false; - public PythonException() : base() + public PythonException() { IntPtr gs = PythonEngine.AcquireLock(); Runtime.PyErr_Fetch(ref _pyType, ref _pyValue, ref _pyTB); Runtime.XIncref(_pyType); Runtime.XIncref(_pyValue); Runtime.XIncref(_pyTB); - if ((_pyType != IntPtr.Zero) && (_pyValue != IntPtr.Zero)) + if (_pyType != IntPtr.Zero && _pyValue != IntPtr.Zero) { string type; string message; Runtime.XIncref(_pyType); - using (PyObject pyType = new PyObject(_pyType)) + using (var pyType = new PyObject(_pyType)) using (PyObject pyTypeName = pyType.GetAttr("__name__")) { type = pyTypeName.ToString(); } Runtime.XIncref(_pyValue); - using (PyObject pyValue = new PyObject(_pyValue)) + using (var pyValue = new PyObject(_pyValue)) { message = pyValue.ToString(); } @@ -44,7 +44,7 @@ public PythonException() : base() { PyObject tb_module = PythonEngine.ImportModule("traceback"); Runtime.XIncref(_pyTB); - using (PyObject pyTB = new PyObject(_pyTB)) + using (var pyTB = new PyObject(_pyTB)) { _tb = tb_module.InvokeMethod("format_tb", pyTB).ToString(); } diff --git a/src/runtime/pytuple.cs b/src/runtime/pytuple.cs index 76ca616ae..b3fb95733 100644 --- a/src/runtime/pytuple.cs +++ b/src/runtime/pytuple.cs @@ -31,7 +31,7 @@ public PyTuple(IntPtr ptr) : base(ptr) /// ArgumentException will be thrown if the given object is not a /// Python tuple object. /// - public PyTuple(PyObject o) : base() + public PyTuple(PyObject o) { if (!IsTupleType(o)) { @@ -48,7 +48,7 @@ public PyTuple(PyObject o) : base() /// /// Creates a new empty PyTuple. /// - public PyTuple() : base() + public PyTuple() { obj = Runtime.PyTuple_New(0); if (obj == IntPtr.Zero) @@ -64,11 +64,11 @@ public PyTuple() : base() /// /// Creates a new PyTuple from an array of PyObject instances. /// - public PyTuple(PyObject[] items) : base() + public PyTuple(PyObject[] items) { int count = items.Length; obj = Runtime.PyTuple_New(count); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); diff --git a/src/runtime/typemanager.cs b/src/runtime/typemanager.cs index d85bdf9bb..49c931183 100644 --- a/src/runtime/typemanager.cs +++ b/src/runtime/typemanager.cs @@ -1,10 +1,8 @@ using System; using System.Runtime.InteropServices; -using System.Reflection.Emit; using System.Collections.Generic; using System.Collections; using System.Reflection; -using System.Threading; namespace Python.Runtime { @@ -34,7 +32,7 @@ internal static IntPtr GetTypeHandle(Type type) { // Note that these types are cached with a refcount of 1, so they // effectively exist until the CPython runtime is finalized. - IntPtr handle = IntPtr.Zero; + IntPtr handle; cache.TryGetValue(type, out handle); if (handle != IntPtr.Zero) { @@ -53,7 +51,7 @@ internal static IntPtr GetTypeHandle(Type type) /// internal static IntPtr GetTypeHandle(ManagedType obj, Type type) { - IntPtr handle = IntPtr.Zero; + IntPtr handle; cache.TryGetValue(type, out handle); if (handle != IntPtr.Zero) { @@ -81,7 +79,7 @@ internal static IntPtr CreateType(Type impl) // Set tp_basicsize to the size of our managed instance objects. Marshal.WriteIntPtr(type, TypeOffset.tp_basicsize, (IntPtr)ob_size); - IntPtr offset = (IntPtr)ObjectOffset.DictOffset(type); + var offset = (IntPtr)ObjectOffset.DictOffset(type); Marshal.WriteIntPtr(type, TypeOffset.tp_dictoffset, offset); InitializeSlots(type, impl); @@ -124,13 +122,13 @@ internal static IntPtr CreateType(ManagedType impl, Type clrType) // XXX Hack, use a different base class for System.Exception // Python 2.5+ allows new style class exceptions but they *must* // subclass BaseException (or better Exception). - if (typeof(System.Exception).IsAssignableFrom(clrType)) + if (typeof(Exception).IsAssignableFrom(clrType)) { ob_size = ObjectOffset.Size(Exceptions.Exception); tp_dictoffset = ObjectOffset.DictOffset(Exceptions.Exception); } - if (clrType == typeof(System.Exception)) + if (clrType == typeof(Exception)) { base_ = Exceptions.Exception; } @@ -171,7 +169,7 @@ internal static IntPtr CreateType(ManagedType impl, Type clrType) Runtime.PyType_Ready(type); IntPtr dict = Marshal.ReadIntPtr(type, TypeOffset.tp_dict); - string mn = clrType.Namespace != null ? clrType.Namespace : ""; + string mn = clrType.Namespace ?? ""; IntPtr mod = Runtime.PyString_FromString(mn); Runtime.PyDict_SetItemString(dict, "__module__", mod); @@ -200,37 +198,43 @@ internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr object assembly = null; object namespaceStr = null; - List disposeList = new List(); + var disposeList = new List(); try { - PyObject assemblyKey = new PyObject(Converter.ToPython("__assembly__", typeof(String))); + var assemblyKey = new PyObject(Converter.ToPython("__assembly__", typeof(string))); disposeList.Add(assemblyKey); if (0 != Runtime.PyMapping_HasKey(py_dict, assemblyKey.Handle)) { - PyObject pyAssembly = new PyObject(Runtime.PyDict_GetItem(py_dict, assemblyKey.Handle)); + var pyAssembly = new PyObject(Runtime.PyDict_GetItem(py_dict, assemblyKey.Handle)); disposeList.Add(pyAssembly); - if (!Converter.ToManagedValue(pyAssembly.Handle, typeof(String), out assembly, false)) + if (!Converter.ToManagedValue(pyAssembly.Handle, typeof(string), out assembly, false)) + { throw new InvalidCastException("Couldn't convert __assembly__ value to string"); + } } - PyObject namespaceKey = new PyObject(Converter.ToPythonImplicit("__namespace__")); + var namespaceKey = new PyObject(Converter.ToPythonImplicit("__namespace__")); disposeList.Add(namespaceKey); if (0 != Runtime.PyMapping_HasKey(py_dict, namespaceKey.Handle)) { - PyObject pyNamespace = new PyObject(Runtime.PyDict_GetItem(py_dict, namespaceKey.Handle)); + var pyNamespace = new PyObject(Runtime.PyDict_GetItem(py_dict, namespaceKey.Handle)); disposeList.Add(pyNamespace); - if (!Converter.ToManagedValue(pyNamespace.Handle, typeof(String), out namespaceStr, false)) + if (!Converter.ToManagedValue(pyNamespace.Handle, typeof(string), out namespaceStr, false)) + { throw new InvalidCastException("Couldn't convert __namespace__ value to string"); + } } } finally { foreach (PyObject o in disposeList) + { o.Dispose(); + } } // create the new managed type subclassing the base managed type - ClassBase baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase; + var baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase; if (null == baseClass) { return Exceptions.RaiseTypeError("invalid base class, expected CLR class type"); @@ -264,9 +268,9 @@ internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr internal static IntPtr WriteMethodDef(IntPtr mdef, IntPtr name, IntPtr func, int flags, IntPtr doc) { Marshal.WriteIntPtr(mdef, name); - Marshal.WriteIntPtr(mdef, (1 * IntPtr.Size), func); - Marshal.WriteInt32(mdef, (2 * IntPtr.Size), flags); - Marshal.WriteIntPtr(mdef, (3 * IntPtr.Size), doc); + Marshal.WriteIntPtr(mdef, 1 * IntPtr.Size, func); + Marshal.WriteInt32(mdef, 2 * IntPtr.Size, flags); + Marshal.WriteIntPtr(mdef, 3 * IntPtr.Size, doc); return mdef + 4 * IntPtr.Size; } @@ -321,7 +325,7 @@ internal static IntPtr CreateMetaType(Type impl) // We need space for 3 PyMethodDef structs, each of them // 4 int-ptrs in size. - IntPtr mdef = Runtime.PyMem_Malloc(3 * (4 * IntPtr.Size)); + IntPtr mdef = Runtime.PyMem_Malloc(3 * 4 * IntPtr.Size); IntPtr mdefStart = mdef; mdef = WriteMethodDef( mdef, @@ -335,6 +339,7 @@ internal static IntPtr CreateMetaType(Type impl) Interop.GetThunk(typeof(MetaType).GetMethod("__subclasscheck__"), "BinaryFunc") ); + // FIXME: mdef is not used mdef = WriteMethodDefSentinel(mdef); Marshal.WriteIntPtr(type, TypeOffset.tp_methods, mdefStart); @@ -447,15 +452,14 @@ internal static IntPtr AllocateTypeObject(string name) /// internal static void InitializeSlots(IntPtr type, Type impl) { - Hashtable seen = new Hashtable(8); + var seen = new Hashtable(8); Type offsetType = typeof(TypeOffset); while (impl != null) { MethodInfo[] methods = impl.GetMethods(tbFlags); - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; string name = method.Name; if (!(name.StartsWith("tp_") || name.StartsWith("nb_") || @@ -473,7 +477,7 @@ internal static void InitializeSlots(IntPtr type, Type impl) } FieldInfo fi = offsetType.GetField(name); - int offset = (int)fi.GetValue(offsetType); + var offset = (int)fi.GetValue(offsetType); IntPtr slot = Interop.GetThunk(method); Marshal.WriteIntPtr(type, offset, slot); @@ -497,21 +501,20 @@ private static void InitMethods(IntPtr pytype, Type type) Type marker = typeof(PythonMethodAttribute); BindingFlags flags = BindingFlags.Public | BindingFlags.Static; - HashSet addedMethods = new HashSet(); + var addedMethods = new HashSet(); while (type != null) { MethodInfo[] methods = type.GetMethods(flags); - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; if (!addedMethods.Contains(method.Name)) { object[] attrs = method.GetCustomAttributes(marker, false); if (attrs.Length > 0) { string method_name = method.Name; - MethodInfo[] mi = new MethodInfo[1]; + var mi = new MethodInfo[1]; mi[0] = method; MethodObject m = new TypeMethod(type, method_name, mi); Runtime.PyDict_SetItemString(dict, method_name, m.pyHandle); diff --git a/src/runtime/typemethod.cs b/src/runtime/typemethod.cs index 50577f93d..946c769b2 100644 --- a/src/runtime/typemethod.cs +++ b/src/runtime/typemethod.cs @@ -21,15 +21,15 @@ public TypeMethod(Type type, string name, MethodInfo[] info, bool allow_threads) public override IntPtr Invoke(IntPtr ob, IntPtr args, IntPtr kw) { - MethodInfo mi = this.info[0]; - Object[] arglist = new Object[3]; + MethodInfo mi = info[0]; + var arglist = new object[3]; arglist[0] = ob; arglist[1] = args; arglist[2] = kw; try { - Object inst = null; + object inst = null; if (ob != IntPtr.Zero) { inst = GetManagedObject(ob);