From 5eccd45a7ed9b4fddc9345fad1f7f63fa5d0adf3 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Thu, 10 Mar 2022 17:37:17 +0100 Subject: [PATCH 1/4] Use Py.GIL directly, now that it doesn't try to init anymore --- src/runtime/Loader.cs | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/src/runtime/Loader.cs b/src/runtime/Loader.cs index bfb6e0d6e..516b9ab9c 100644 --- a/src/runtime/Loader.cs +++ b/src/runtime/Loader.cs @@ -23,18 +23,8 @@ public unsafe static int Initialize(IntPtr data, int size) PythonDLL = null; } - var gs = PyGILState_Ensure(); - - try - { - // Console.WriteLine("Startup thread"); - PythonEngine.InitExt(); - // Console.WriteLine("Startup finished"); - } - finally - { - PyGILState_Release(gs); - } + using var _ = Py.GIL(); + PythonEngine.InitExt(); } catch (Exception exc) { @@ -55,15 +45,8 @@ public unsafe static int Shutdown(IntPtr data, int size) if (command == "full_shutdown") { - var gs = PyGILState_Ensure(); - try - { - PythonEngine.Shutdown(); - } - finally - { - PyGILState_Release(gs); - } + using var _ = Py.GIL(); + PythonEngine.Shutdown(); } } catch (Exception exc) From d2d3ba669f7f5a149d0077a7cc6b6e4872eb1bd7 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Wed, 30 Mar 2022 15:29:44 +0200 Subject: [PATCH 2/4] Modernise syntax a bit --- src/runtime/AssemblyManager.cs | 6 +- src/runtime/ClassManager.cs | 3 +- src/runtime/Codecs/DecoderGroup.cs | 2 +- src/runtime/Codecs/EncoderGroup.cs | 2 +- src/runtime/Codecs/PyObjectConversions.cs | 6 +- src/runtime/Converter.cs | 23 ++- src/runtime/DelegateManager.cs | 6 +- src/runtime/Exceptions.cs | 3 +- src/runtime/Finalizer.cs | 2 +- src/runtime/InternString.cs | 3 +- src/runtime/Interop.cs | 2 +- src/runtime/InteropConfiguration.cs | 2 +- src/runtime/MethodBinder.cs | 88 ++++-------- src/runtime/Native/BorrowedReference.cs | 2 +- src/runtime/Native/CustomMarshaler.cs | 8 +- src/runtime/Native/NewReference.cs | 2 +- src/runtime/Native/PyIdentifier_.cs | 132 +++++++++--------- src/runtime/Native/PyIdentifier_.tt | 120 ++++++++-------- src/runtime/Native/TypeOffset.cs | 2 +- src/runtime/Py.cs | 3 +- src/runtime/PythonEngine.cs | 4 +- src/runtime/PythonException.cs | 9 +- src/runtime/PythonTypes/PyDict.cs | 6 +- src/runtime/PythonTypes/PyFloat.cs | 10 +- src/runtime/PythonTypes/PyModule.cs | 40 +++--- src/runtime/PythonTypes/PyObject.cs | 38 ++--- src/runtime/Runtime.cs | 12 +- .../StateSerialization/MaybeMemberInfo.cs | 4 +- .../StateSerialization/MaybeMethodBase.cs | 6 +- src/runtime/StateSerialization/MaybeType.cs | 6 +- src/runtime/TypeManager.cs | 51 ++++--- src/runtime/Types/ArrayObject.cs | 21 +-- src/runtime/Types/ClassBase.cs | 36 ++--- src/runtime/Types/ClassDerived.cs | 59 ++++---- src/runtime/Types/ClassObject.cs | 15 +- src/runtime/Types/DelegateObject.cs | 19 +-- src/runtime/Types/EventBinding.cs | 2 +- src/runtime/Types/EventObject.cs | 4 +- src/runtime/Types/ExtensionType.cs | 2 +- src/runtime/Types/InterfaceObject.cs | 11 +- src/runtime/Types/Iterator.cs | 4 +- src/runtime/Types/MetaType.cs | 56 +++----- src/runtime/Types/MethodBinding.cs | 9 +- src/runtime/Types/MethodObject.cs | 3 +- src/runtime/Types/ModuleObject.cs | 3 +- src/runtime/Types/MpLengthSlot.cs | 3 +- src/runtime/Types/OperatorMethod.cs | 18 ++- src/runtime/Types/OverloadMapper.cs | 4 +- src/runtime/Util/CodeGenerator.cs | 4 +- src/runtime/Util/DebugUtil.cs | 7 +- src/runtime/Util/GenericUtil.cs | 62 +++----- src/runtime/Util/OpsHelper.cs | 2 + src/runtime/Util/ReflectionPolyfills.cs | 2 +- 53 files changed, 420 insertions(+), 529 deletions(-) diff --git a/src/runtime/AssemblyManager.cs b/src/runtime/AssemblyManager.cs index 56c70c13a..d09d2d76e 100644 --- a/src/runtime/AssemblyManager.cs +++ b/src/runtime/AssemblyManager.cs @@ -23,8 +23,8 @@ internal class AssemblyManager // than it can end up referring to assemblies that are already unloaded (default behavior after unload appDomain - // unless LoaderOptimization.MultiDomain is used); // So for multidomain support it is better to have the dict. recreated for each app-domain initialization - private static ConcurrentDictionary> namespaces = - new ConcurrentDictionary>(); + private static readonly ConcurrentDictionary> namespaces = + new(); #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. // domain-level handlers are initialized in Initialize @@ -33,7 +33,7 @@ internal class AssemblyManager #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. // updated only under GIL? - private static Dictionary probed = new Dictionary(32); + private static readonly Dictionary probed = new(32); // modified from event handlers below, potentially triggered from different .NET threads private static readonly ConcurrentQueue assemblies = new(); diff --git a/src/runtime/ClassManager.cs b/src/runtime/ClassManager.cs index 647cec3ed..6379f51de 100644 --- a/src/runtime/ClassManager.cs +++ b/src/runtime/ClassManager.cs @@ -247,10 +247,9 @@ internal static void InitClassBase(Type type, ClassBase impl, ReflectedClrType p Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, doc.Borrow()); } - var co = impl as ClassObject; // If this is a ClassObject AND it has constructors, generate a __doc__ attribute. // required that the ClassObject.ctors be changed to internal - if (co != null) + if (impl is ClassObject co) { if (co.NumCtors > 0 && !co.HasCustomNew()) { diff --git a/src/runtime/Codecs/DecoderGroup.cs b/src/runtime/Codecs/DecoderGroup.cs index 5b3d127ad..41e1f0494 100644 --- a/src/runtime/Codecs/DecoderGroup.cs +++ b/src/runtime/Codecs/DecoderGroup.cs @@ -10,7 +10,7 @@ namespace Python.Runtime.Codecs /// public sealed class DecoderGroup: IPyObjectDecoder, IEnumerable, IDisposable { - readonly List decoders = new List(); + readonly List decoders = new(); /// /// Add specified decoder to the group diff --git a/src/runtime/Codecs/EncoderGroup.cs b/src/runtime/Codecs/EncoderGroup.cs index 32b550eb9..63abf35a3 100644 --- a/src/runtime/Codecs/EncoderGroup.cs +++ b/src/runtime/Codecs/EncoderGroup.cs @@ -10,7 +10,7 @@ namespace Python.Runtime.Codecs /// public sealed class EncoderGroup: IPyObjectEncoder, IEnumerable, IDisposable { - readonly List encoders = new List(); + readonly List encoders = new(); /// /// Add specified encoder to the group diff --git a/src/runtime/Codecs/PyObjectConversions.cs b/src/runtime/Codecs/PyObjectConversions.cs index 94ed4cdc3..cde97c8c9 100644 --- a/src/runtime/Codecs/PyObjectConversions.cs +++ b/src/runtime/Codecs/PyObjectConversions.cs @@ -15,8 +15,8 @@ namespace Python.Runtime /// public static class PyObjectConversions { - static readonly DecoderGroup decoders = new DecoderGroup(); - static readonly EncoderGroup encoders = new EncoderGroup(); + static readonly DecoderGroup decoders = new(); + static readonly EncoderGroup encoders = new(); /// /// Registers specified encoder (marshaller) @@ -62,7 +62,7 @@ public static void RegisterDecoder(IPyObjectDecoder decoder) } static readonly ConcurrentDictionary - clrToPython = new ConcurrentDictionary(); + clrToPython = new(); static IPyObjectEncoder[] GetEncoders(Type type) { lock (encoders) diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index a99961aaa..f86ba7900 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -18,15 +18,15 @@ private Converter() { } - private static Type objectType; - private static Type stringType; - private static Type singleType; - private static Type doubleType; - private static Type int16Type; - private static Type int32Type; - private static Type int64Type; - private static Type boolType; - private static Type typeType; + private static readonly Type objectType; + private static readonly Type stringType; + private static readonly Type singleType; + private static readonly Type doubleType; + private static readonly Type int16Type; + private static readonly Type int32Type; + private static readonly Type int64Type; + private static readonly Type boolType; + private static readonly Type typeType; static Converter() { @@ -151,8 +151,7 @@ internal static NewReference ToPython(object? value, Type type) // it the type is a python subclass of a managed type then return the // underlying python object rather than construct a new wrapper object. - var pyderived = value as IPythonDerivedType; - if (null != pyderived) + if (value is IPythonDerivedType pyderived) { if (!IsTransparentProxy(pyderived)) return ClassDerivedObject.ToPython(pyderived); @@ -161,7 +160,7 @@ internal static NewReference ToPython(object? value, Type type) // ModuleObjects are created in a way that their wrapping them as // a CLRObject fails, the ClassObject has no tpHandle. Return the // pyHandle as is, do not convert. - if (value is ModuleObject modobj) + if (value is ModuleObject) { throw new NotImplementedException(); } diff --git a/src/runtime/DelegateManager.cs b/src/runtime/DelegateManager.cs index 092c9be1d..4343b9ab7 100644 --- a/src/runtime/DelegateManager.cs +++ b/src/runtime/DelegateManager.cs @@ -15,13 +15,13 @@ namespace Python.Runtime /// internal class DelegateManager { - private readonly Dictionary cache = new Dictionary(); + private readonly Dictionary cache = new(); private readonly Type basetype = typeof(Dispatcher); private readonly Type arrayType = typeof(object[]); private readonly Type voidtype = typeof(void); private readonly Type typetype = typeof(Type); private readonly Type pyobjType = typeof(PyObject); - private readonly CodeGenerator codeGenerator = new CodeGenerator(); + private readonly CodeGenerator codeGenerator = new(); private readonly ConstructorInfo arrayCtor; private readonly MethodInfo dispatch; @@ -309,7 +309,7 @@ protected Dispatcher(PyObject target, Type dtype) { tpName += $" of size {Runtime.PyTuple_Size(op)}"; } - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); if (!isVoid) sb.Append(rtype.FullName); for (int i = 0; i < pi.Length; i++) { diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index c3ac889ed..da095e030 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -196,8 +196,7 @@ public static bool SetError(Exception e) // might get a managed exception raised that is a wrapper for a // Python exception. In that case we'd rather have the real thing. - var pe = e as PythonException; - if (pe != null) + if (e is PythonException pe) { pe.Restore(); return true; diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index be17d62e3..e796cacd1 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -41,7 +41,7 @@ public ErrorArgs(Exception error) [DefaultValue(true)] public bool Enable { get; set; } = true; - private ConcurrentQueue _objQueue = new(); + private readonly ConcurrentQueue _objQueue = new(); private readonly ConcurrentQueue _derivedQueue = new(); private readonly ConcurrentQueue _bufferQueue = new(); private int _throttled; diff --git a/src/runtime/InternString.cs b/src/runtime/InternString.cs index 0780a0bb8..b6d9a0e4a 100644 --- a/src/runtime/InternString.cs +++ b/src/runtime/InternString.cs @@ -61,8 +61,7 @@ public static void Shutdown() public static string? GetManagedString(BorrowedReference op) { - string s; - if (TryGetInterned(op, out s)) + if (TryGetInterned(op, out string s)) { return s; } diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index bcf99bede..4aa4aa09b 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -139,7 +139,7 @@ internal static Type GetPrototype(MethodInfo method) } - internal static Dictionary allocatedThunks = new Dictionary(); + internal static Dictionary allocatedThunks = new(); internal static ThunkInfo GetThunk(MethodInfo method) { diff --git a/src/runtime/InteropConfiguration.cs b/src/runtime/InteropConfiguration.cs index 30c9a1c2c..781d0d01f 100644 --- a/src/runtime/InteropConfiguration.cs +++ b/src/runtime/InteropConfiguration.cs @@ -9,7 +9,7 @@ namespace Python.Runtime public sealed class InteropConfiguration: IDisposable { internal readonly PythonBaseTypeProviderGroup pythonBaseTypeProviders - = new PythonBaseTypeProviderGroup(); + = new(); /// Enables replacing base types of CLR types as seen from Python public IList PythonBaseTypeProviders => this.pythonBaseTypeProviders; diff --git a/src/runtime/MethodBinder.cs b/src/runtime/MethodBinder.cs index be4e8d0e5..ebbf4489e 100644 --- a/src/runtime/MethodBinder.cs +++ b/src/runtime/MethodBinder.cs @@ -242,52 +242,24 @@ internal static int ArgPrecedence(Type t) TypeCode tc = Type.GetTypeCode(t); // TODO: Clean up - switch (tc) + return tc switch { - case TypeCode.Object: - return 1; - - case TypeCode.UInt64: - return 10; - - case TypeCode.UInt32: - return 11; - - case TypeCode.UInt16: - return 12; - - case TypeCode.Int64: - return 13; - - case TypeCode.Int32: - return 14; - - case TypeCode.Int16: - return 15; - - case TypeCode.Char: - return 16; - - case TypeCode.SByte: - return 17; - - case TypeCode.Byte: - return 18; - - case TypeCode.Single: - return 20; - - case TypeCode.Double: - return 21; - - case TypeCode.String: - return 30; - - case TypeCode.Boolean: - return 40; - } - - return 2000; + TypeCode.Object => 1, + TypeCode.UInt64 => 10, + TypeCode.UInt32 => 11, + TypeCode.UInt16 => 12, + TypeCode.Int64 => 13, + TypeCode.Int32 => 14, + TypeCode.Int16 => 15, + TypeCode.Char => 16, + TypeCode.SByte => 17, + TypeCode.Byte => 18, + TypeCode.Single => 20, + TypeCode.Double => 21, + TypeCode.String => 30, + TypeCode.Boolean => 40, + _ => 2000, + }; } /// @@ -410,10 +382,6 @@ public MismatchedMethod(Exception exception, MethodBase mb) isGeneric = true; } ParameterInfo[] pi = mi.GetParameters(); - ArrayList? defaultArgList; - bool paramsArray; - int kwargsMatched; - int defaultsNeeded; bool isOperator = OperatorMethod.IsOperatorMethod(mi); // Binary operator methods will have 2 CLR args but only one Python arg // (unary operators will have 1 less each), since Python operator methods are bound. @@ -421,7 +389,7 @@ public MismatchedMethod(Exception exception, MethodBase mb) bool isReverse = isOperator && OperatorMethod.IsReverse((MethodInfo)mi); // Only cast if isOperator. if (isReverse && OperatorMethod.IsComparisonOp((MethodInfo)mi)) continue; // Comparison operators in Python have no reverse mode. - if (!MatchesArgumentCount(pynargs, pi, kwargDict, out paramsArray, out defaultArgList, out kwargsMatched, out defaultsNeeded) && !isOperator) + if (!MatchesArgumentCount(pynargs, pi, kwargDict, out bool paramsArray, out ArrayList? defaultArgList, out int kwargsMatched, out int defaultsNeeded) && !isOperator) { continue; } @@ -436,8 +404,7 @@ public MismatchedMethod(Exception exception, MethodBase mb) // We need to take the first CLR argument. pi = pi.Take(1).ToArray(); } - int outs; - var margs = TryConvertArguments(pi, paramsArray, args, pynargs, kwargDict, defaultArgList, outs: out outs); + var margs = TryConvertArguments(pi, paramsArray, args, pynargs, kwargDict, defaultArgList, outs: out int outs); if (margs == null) { var mismatchCause = PythonException.FetchCurrent(); @@ -495,7 +462,7 @@ public MismatchedMethod(Exception exception, MethodBase mb) { // Best effort for determining method to match on gives multiple possible // matches and we need at least one default argument - bail from this point - StringBuilder stringBuilder = new StringBuilder("Not enough arguments provided to disambiguate the method. Found:"); + var stringBuilder = new StringBuilder("Not enough arguments provided to disambiguate the method. Found:"); foreach (var matchedMethod in argMatchedMethods) { stringBuilder.AppendLine(); @@ -523,18 +490,20 @@ public MismatchedMethod(Exception exception, MethodBase mb) //CLRObject co = (CLRObject)ManagedType.GetManagedObject(inst); // InvalidCastException: Unable to cast object of type // 'Python.Runtime.ClassObject' to type 'Python.Runtime.CLRObject' - var co = ManagedType.GetManagedObject(inst) as CLRObject; // Sanity check: this ensures a graceful exit if someone does // something intentionally wrong like call a non-static method // on the class rather than on an instance of the class. // XXX maybe better to do this before all the other rigmarole. - if (co == null) + if (ManagedType.GetManagedObject(inst) is CLRObject co) + { + target = co.inst; + } + else { Exceptions.SetError(Exceptions.TypeError, "Invoked a non-static method with an invalid instance"); return null; } - target = co.inst; } return new Binding(mi, target, margs, outs); @@ -623,7 +592,7 @@ static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStar for (int paramIndex = 0; paramIndex < pi.Length; paramIndex++) { var parameter = pi[paramIndex]; - bool hasNamedParam = parameter.Name != null ? kwargDict.ContainsKey(parameter.Name) : false; + bool hasNamedParam = parameter.Name != null && kwargDict.ContainsKey(parameter.Name); if (paramIndex >= pyArgCount && !(hasNamedParam || (paramsArray && paramIndex == arrayStart))) { @@ -658,8 +627,7 @@ static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStar } } - bool isOut; - if (!TryConvertArgument(op, parameter.ParameterType, out margs[paramIndex], out isOut)) + if (!TryConvertArgument(op, parameter.ParameterType, out margs[paramIndex], out bool isOut)) { tempObject.Dispose(); return null; @@ -789,7 +757,7 @@ static bool MatchesArgumentCount(int positionalArgumentCount, ParameterInfo[] pa { defaultArgList = null; var match = false; - paramsArray = parameters.Length > 0 ? Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute)) : false; + paramsArray = parameters.Length > 0 && Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute)); kwargsMatched = 0; defaultsNeeded = 0; if (positionalArgumentCount == parameters.Length && kwargDict.Count == 0) diff --git a/src/runtime/Native/BorrowedReference.cs b/src/runtime/Native/BorrowedReference.cs index 98c151bab..fd1059a5f 100644 --- a/src/runtime/Native/BorrowedReference.cs +++ b/src/runtime/Native/BorrowedReference.cs @@ -19,7 +19,7 @@ public IntPtr DangerousGetAddress() /// Gets a raw pointer to the Python object public IntPtr DangerousGetAddressOrNull() => this.pointer; - public static BorrowedReference Null => new BorrowedReference(); + public static BorrowedReference Null => new(); /// /// Creates new instance of from raw pointer. Unsafe. diff --git a/src/runtime/Native/CustomMarshaler.cs b/src/runtime/Native/CustomMarshaler.cs index f544756d8..62c027150 100644 --- a/src/runtime/Native/CustomMarshaler.cs +++ b/src/runtime/Native/CustomMarshaler.cs @@ -47,9 +47,7 @@ internal class UcsMarshaler : MarshalerBase public override IntPtr MarshalManagedToNative(object managedObj) { - var s = managedObj as string; - - if (s == null) + if (managedObj is not string s) { return IntPtr.Zero; } @@ -152,9 +150,7 @@ internal class StrArrayMarshaler : MarshalerBase public override IntPtr MarshalManagedToNative(object managedObj) { - var argv = managedObj as string[]; - - if (argv == null) + if (managedObj is not string[] argv) { return IntPtr.Zero; } diff --git a/src/runtime/Native/NewReference.cs b/src/runtime/Native/NewReference.cs index 91ebbdb01..25145fc4f 100644 --- a/src/runtime/Native/NewReference.cs +++ b/src/runtime/Native/NewReference.cs @@ -124,7 +124,7 @@ public void Dispose() /// [Pure] public static NewReference DangerousFromPointer(IntPtr pointer) - => new NewReference {pointer = pointer}; + => new() { pointer = pointer}; [Pure] internal static IntPtr DangerousGetAddressOrNull(in NewReference reference) => reference.pointer; diff --git a/src/runtime/Native/PyIdentifier_.cs b/src/runtime/Native/PyIdentifier_.cs index 4884a81ad..1ea2b704c 100644 --- a/src/runtime/Native/PyIdentifier_.cs +++ b/src/runtime/Native/PyIdentifier_.cs @@ -1,69 +1,69 @@ -using System; - -namespace Python.Runtime -{ - static class PyIdentifier +using System; + +namespace Python.Runtime +{ + static class PyIdentifier { -#pragma warning disable CS0649 // indentifier is never assigned to (assigned with reflection) - static IntPtr f__name__; - public static BorrowedReference __name__ => new(f__name__); - static IntPtr f__dict__; - public static BorrowedReference __dict__ => new(f__dict__); - static IntPtr f__doc__; - public static BorrowedReference __doc__ => new(f__doc__); - static IntPtr f__class__; - public static BorrowedReference __class__ => new(f__class__); - static IntPtr f__clear_reentry_guard__; - public static BorrowedReference __clear_reentry_guard__ => new(f__clear_reentry_guard__); - static IntPtr f__module__; - public static BorrowedReference __module__ => new(f__module__); - static IntPtr f__file__; - public static BorrowedReference __file__ => new(f__file__); - static IntPtr f__slots__; - public static BorrowedReference __slots__ => new(f__slots__); - static IntPtr f__self__; - public static BorrowedReference __self__ => new(f__self__); - static IntPtr f__annotations__; - public static BorrowedReference __annotations__ => new(f__annotations__); - static IntPtr f__init__; - public static BorrowedReference __init__ => new(f__init__); - static IntPtr f__repr__; - public static BorrowedReference __repr__ => new(f__repr__); - static IntPtr f__import__; - public static BorrowedReference __import__ => new(f__import__); - static IntPtr f__builtins__; - public static BorrowedReference __builtins__ => new(f__builtins__); - static IntPtr fbuiltins; - public static BorrowedReference builtins => new(fbuiltins); - static IntPtr f__overloads__; - public static BorrowedReference __overloads__ => new(f__overloads__); - static IntPtr fOverloads; +#pragma warning disable CS0649 // indentifier is never assigned to (assigned with reflection) + static IntPtr f__name__; + public static BorrowedReference __name__ => new(f__name__); + static IntPtr f__dict__; + public static BorrowedReference __dict__ => new(f__dict__); + static IntPtr f__doc__; + public static BorrowedReference __doc__ => new(f__doc__); + static IntPtr f__class__; + public static BorrowedReference __class__ => new(f__class__); + static IntPtr f__clear_reentry_guard__; + public static BorrowedReference __clear_reentry_guard__ => new(f__clear_reentry_guard__); + static IntPtr f__module__; + public static BorrowedReference __module__ => new(f__module__); + static IntPtr f__file__; + public static BorrowedReference __file__ => new(f__file__); + static IntPtr f__slots__; + public static BorrowedReference __slots__ => new(f__slots__); + static IntPtr f__self__; + public static BorrowedReference __self__ => new(f__self__); + static IntPtr f__annotations__; + public static BorrowedReference __annotations__ => new(f__annotations__); + static IntPtr f__init__; + public static BorrowedReference __init__ => new(f__init__); + static IntPtr f__repr__; + public static BorrowedReference __repr__ => new(f__repr__); + static IntPtr f__import__; + public static BorrowedReference __import__ => new(f__import__); + static IntPtr f__builtins__; + public static BorrowedReference __builtins__ => new(f__builtins__); + static IntPtr fbuiltins; + public static BorrowedReference builtins => new(fbuiltins); + static IntPtr f__overloads__; + public static BorrowedReference __overloads__ => new(f__overloads__); + static IntPtr fOverloads; public static BorrowedReference Overloads => new(fOverloads); #pragma warning restore CS0649 // indentifier is never assigned to (assigned with reflection) - } - - - static partial class InternString - { - private static readonly string[] _builtinNames = new string[] - { - "__name__", - "__dict__", - "__doc__", - "__class__", - "__clear_reentry_guard__", - "__module__", - "__file__", - "__slots__", - "__self__", - "__annotations__", - "__init__", - "__repr__", - "__import__", - "__builtins__", - "builtins", - "__overloads__", - "Overloads", - }; - } -} + } + + + static partial class InternString + { + private static readonly string[] _builtinNames = new string[] + { + "__name__", + "__dict__", + "__doc__", + "__class__", + "__clear_reentry_guard__", + "__module__", + "__file__", + "__slots__", + "__self__", + "__annotations__", + "__init__", + "__repr__", + "__import__", + "__builtins__", + "builtins", + "__overloads__", + "Overloads", + }; + } +} diff --git a/src/runtime/Native/PyIdentifier_.tt b/src/runtime/Native/PyIdentifier_.tt index 03a26cb50..9350cde43 100644 --- a/src/runtime/Native/PyIdentifier_.tt +++ b/src/runtime/Native/PyIdentifier_.tt @@ -1,62 +1,62 @@ -<#@ template debug="true" hostSpecific="true" #> -<#@ output extension=".cs" #> -<# - string[] internNames = new string[] - { - "__name__", - "__dict__", - "__doc__", - "__class__", - "__clear_reentry_guard__", - "__module__", - "__file__", - "__slots__", - "__self__", - "__annotations__", - - "__init__", - "__repr__", - "__import__", - "__builtins__", - - "builtins", - - "__overloads__", - "Overloads", - }; -#> -using System; - -namespace Python.Runtime -{ - static class PyIdentifier +<#@ template debug="true" hostSpecific="true" #> +<#@ output extension=".cs" #> +<# + string[] internNames = new string[] { -#pragma warning disable CS0649 // indentifier is never assigned to (assigned with reflection) -<# - foreach (var name in internNames) - { -#> - static IntPtr f<#= name #>; - public static BorrowedReference <#= name #> => new(f<#= name #>); -<# - } + "__name__", + "__dict__", + "__doc__", + "__class__", + "__clear_reentry_guard__", + "__module__", + "__file__", + "__slots__", + "__self__", + "__annotations__", + + "__init__", + "__repr__", + "__import__", + "__builtins__", + + "builtins", + + "__overloads__", + "Overloads", + }; #> -#pragma warning restore CS0649 // indentifier is never assigned to (assigned with reflection) - } - - - static partial class InternString - { - private static readonly string[] _builtinNames = new string[] - { -<# - foreach (var name in internNames) - { -#> - "<#= name #>", -<# - } -#> - }; - } -} +using System; + +namespace Python.Runtime +{ + static class PyIdentifier + { +#pragma warning disable CS0649 // indentifier is never assigned to (assigned with reflection) +<# + foreach (var name in internNames) + { +#> + static IntPtr f<#= name #>; + public static BorrowedReference <#= name #> => new(f<#= name #>); +<# + } +#> +#pragma warning restore CS0649 // indentifier is never assigned to (assigned with reflection) + } + + + static partial class InternString + { + private static readonly string[] _builtinNames = new string[] + { +<# + foreach (var name in internNames) + { +#> + "<#= name #>", +<# + } +#> + }; + } +} diff --git a/src/runtime/Native/TypeOffset.cs b/src/runtime/Native/TypeOffset.cs index a1bae8253..59c5c3ee0 100644 --- a/src/runtime/Native/TypeOffset.cs +++ b/src/runtime/Native/TypeOffset.cs @@ -121,7 +121,7 @@ public static int GetSlotOffset(string slotName) public static string? GetSlotName(int offset) => SlotOffsets.FirstOrDefault(kv => kv.Value == offset).Key; - static readonly HashSet slotNames = new HashSet(); + static readonly HashSet slotNames = new(); internal static bool IsSupportedSlotName(string name) => slotNames.Contains(name); [Conditional("DEBUG")] diff --git a/src/runtime/Py.cs b/src/runtime/Py.cs index 4f3fbf6d4..ec991f971 100644 --- a/src/runtime/Py.cs +++ b/src/runtime/Py.cs @@ -77,8 +77,7 @@ public static KeywordArguments kw(params object?[] kv) } for (var i = 0; i < kv.Length; i += 2) { - var key = kv[i] as string; - if (key is null) + if (kv[i] is not string key) throw new ArgumentException("Keys must be non-null strings"); BorrowedReference value; diff --git a/src/runtime/PythonEngine.cs b/src/runtime/PythonEngine.cs index 1e82446cb..24e1bedeb 100644 --- a/src/runtime/PythonEngine.cs +++ b/src/runtime/PythonEngine.cs @@ -233,7 +233,7 @@ public static void Initialize(IEnumerable args, bool setSysArgv = true, // add the imported module to the clr module, and copy the API functions // and decorators into the main clr module. Runtime.PyDict_SetItemString(clr_dict, "_extras", module); - using (var keys = locals.Keys()) + using var keys = locals.Keys(); foreach (PyObject key in keys) { if (!key.ToString()!.StartsWith("_") || key.ToString()!.Equals("__version__")) @@ -374,7 +374,7 @@ public static void Shutdown() /// public delegate void ShutdownHandler(); - static List ShutdownHandlers = new List(); + static readonly List ShutdownHandlers = new(); /// /// Add a function to be called when the engine is shut down. diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 813d0e586..8d3330c7b 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -397,8 +397,13 @@ public string Format() } public PythonException Clone() - => new PythonException(type: Type, value: Value, traceback: Traceback, - Message, InnerException); + => new( + type: Type, + value: Value, + traceback: Traceback, + Message, + InnerException + ); #region Serializable [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] diff --git a/src/runtime/PythonTypes/PyDict.cs b/src/runtime/PythonTypes/PyDict.cs index 80b8c8c9f..272f7828f 100644 --- a/src/runtime/PythonTypes/PyDict.cs +++ b/src/runtime/PythonTypes/PyDict.cs @@ -72,10 +72,8 @@ public bool HasKey(PyObject key) /// public bool HasKey(string key) { - using (var str = new PyString(key)) - { - return HasKey(str); - } + using var str = new PyString(key); + return HasKey(str); } diff --git a/src/runtime/PythonTypes/PyFloat.cs b/src/runtime/PythonTypes/PyFloat.cs index 10104c10f..c09ec93ba 100644 --- a/src/runtime/PythonTypes/PyFloat.cs +++ b/src/runtime/PythonTypes/PyFloat.cs @@ -53,12 +53,10 @@ private static StolenReference FromString(string value) { if (value is null) throw new ArgumentNullException(nameof(value)); - using (var s = new PyString(value)) - { - NewReference val = Runtime.PyFloat_FromString(s.Reference); - PythonException.ThrowIfIsNull(val); - return val.Steal(); - } + using var s = new PyString(value); + NewReference val = Runtime.PyFloat_FromString(s.Reference); + PythonException.ThrowIfIsNull(val); + return val.Steal(); } /// diff --git a/src/runtime/PythonTypes/PyModule.cs b/src/runtime/PythonTypes/PyModule.cs index ada24c6cd..4549678ed 100644 --- a/src/runtime/PythonTypes/PyModule.cs +++ b/src/runtime/PythonTypes/PyModule.cs @@ -322,13 +322,11 @@ public PyModule Set(string name, object? value) private void SetPyValue(string name, BorrowedReference value) { Check(); - using (var pyKey = new PyString(name)) + using var pyKey = new PyString(name); + int r = Runtime.PyObject_SetItem(variables, pyKey.obj, value); + if (r < 0) { - int r = Runtime.PyObject_SetItem(variables, pyKey.obj, value); - if (r < 0) - { - throw PythonException.ThrowLastAsClrException(); - } + throw PythonException.ThrowLastAsClrException(); } } @@ -362,10 +360,8 @@ public bool Contains(string name) if (name is null) throw new ArgumentNullException(nameof(name)); Check(); - using (var pyKey = new PyString(name)) - { - return Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0; - } + using var pyKey = new PyString(name); + return Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0; } /// @@ -398,19 +394,17 @@ public bool TryGet(string name, out PyObject? value) if (name is null) throw new ArgumentNullException(nameof(name)); Check(); - using (var pyKey = new PyString(name)) + using var pyKey = new PyString(name); + if (Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0) { - if (Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0) - { - using var op = Runtime.PyObject_GetItem(variables, pyKey.obj); - value = new PyObject(op.StealOrThrow()); - return true; - } - else - { - value = null; - return false; - } + using var op = Runtime.PyObject_GetItem(variables, pyKey.obj); + value = new PyObject(op.StealOrThrow()); + return true; + } + else + { + value = null; + return false; } } @@ -445,7 +439,7 @@ public bool TryGet(string name, out T? value) var result = TryGet(name, out var pyObj); if (!result) { - value = default(T); + value = default; return false; } value = pyObj!.As(); diff --git a/src/runtime/PythonTypes/PyObject.cs b/src/runtime/PythonTypes/PyObject.cs index e0a17bed5..cfd3e7158 100644 --- a/src/runtime/PythonTypes/PyObject.cs +++ b/src/runtime/PythonTypes/PyObject.cs @@ -539,10 +539,8 @@ public virtual PyObject GetItem(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - using (var pyKey = new PyString(key)) - { - return GetItem(pyKey); - } + using var pyKey = new PyString(key); + return GetItem(pyKey); } @@ -556,10 +554,8 @@ public virtual PyObject GetItem(string key) /// public virtual PyObject GetItem(int index) { - using (var key = new PyInt(index)) - { - return GetItem(key); - } + using var key = new PyInt(index); + return GetItem(key); } @@ -597,10 +593,8 @@ public virtual void SetItem(string key, PyObject value) if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); - using (var pyKey = new PyString(key)) - { - SetItem(pyKey, value); - } + using var pyKey = new PyString(key); + SetItem(pyKey, value); } @@ -616,10 +610,8 @@ public virtual void SetItem(int index, PyObject value) { if (value == null) throw new ArgumentNullException(nameof(value)); - using (var pyindex = new PyInt(index)) - { - SetItem(pyindex, value); - } + using var pyindex = new PyInt(index); + SetItem(pyindex, value); } @@ -655,10 +647,8 @@ public virtual void DelItem(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); - using (var pyKey = new PyString(key)) - { - DelItem(pyKey); - } + using var pyKey = new PyString(key); + DelItem(pyKey); } @@ -672,10 +662,8 @@ public virtual void DelItem(string key) /// public virtual void DelItem(int index) { - using (var pyindex = new PyInt(index)) - { - DelItem(pyindex); - } + using var pyindex = new PyInt(index); + DelItem(pyindex); } @@ -1320,7 +1308,7 @@ public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg { using var _ = Py.GIL(); NewReference res; - if (!(arg is PyObject)) + if (arg is not PyObject) { arg = arg.ToPython(); } diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index d92f45afb..6ad1d459f 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -554,17 +554,17 @@ internal static void CheckExceptionOccurred() } ManagedType? mt = ManagedType.GetManagedObject(op); - if (mt is ClassBase) + if (mt is ClassBase b) { - MaybeType _type = ((ClassBase)mt).type; + var _type = b.type; t = _type.Valid ? _type.Value : null; } - else if (mt is CLRObject) + else if (mt is CLRObject ob) { - object inst = ((CLRObject)mt).inst; - if (inst is Type) + var inst = ob.inst; + if (inst is Type ty) { - t = inst as Type; + t = ty; } } else diff --git a/src/runtime/StateSerialization/MaybeMemberInfo.cs b/src/runtime/StateSerialization/MaybeMemberInfo.cs index aa369a5ed..b734bb070 100644 --- a/src/runtime/StateSerialization/MaybeMemberInfo.cs +++ b/src/runtime/StateSerialization/MaybeMemberInfo.cs @@ -12,10 +12,10 @@ internal struct MaybeMemberInfo : ISerializable where T : MemberInfo // The ReflectedType of the object const string SerializationType = "t"; const string SerializationMemberName = "n"; - MemberInfo? info; + readonly MemberInfo? info; [NonSerialized] - Exception? deserializationException; + readonly Exception? deserializationException; public string DeletedMessage { diff --git a/src/runtime/StateSerialization/MaybeMethodBase.cs b/src/runtime/StateSerialization/MaybeMethodBase.cs index 9fb8ae047..d196d5e88 100644 --- a/src/runtime/StateSerialization/MaybeMethodBase.cs +++ b/src/runtime/StateSerialization/MaybeMethodBase.cs @@ -24,11 +24,11 @@ internal struct MaybeMethodBase : ISerializable where T: MethodBase public static implicit operator MaybeMethodBase (T? ob) => new (ob); - string? name; - MethodBase? info; + readonly string? name; + readonly MethodBase? info; [NonSerialized] - Exception? deserializationException; + readonly Exception? deserializationException; public string DeletedMessage { diff --git a/src/runtime/StateSerialization/MaybeType.cs b/src/runtime/StateSerialization/MaybeType.cs index abb3a8fb6..f3c96e369 100644 --- a/src/runtime/StateSerialization/MaybeType.cs +++ b/src/runtime/StateSerialization/MaybeType.cs @@ -9,12 +9,12 @@ namespace Python.Runtime [Serializable] internal struct MaybeType : ISerializable { - public static implicit operator MaybeType (Type ob) => new MaybeType(ob); + public static implicit operator MaybeType (Type ob) => new(ob); // The AssemblyQualifiedName of the serialized Type const string SerializationName = "n"; - string name; - Type type; + readonly string name; + readonly Type type; public string DeletedMessage { diff --git a/src/runtime/TypeManager.cs b/src/runtime/TypeManager.cs index 84618df64..d9ca184f6 100644 --- a/src/runtime/TypeManager.cs +++ b/src/runtime/TypeManager.cs @@ -26,9 +26,9 @@ internal class TypeManager private const BindingFlags tbFlags = BindingFlags.Public | BindingFlags.Static; - private static Dictionary cache = new(); + private static readonly Dictionary cache = new(); - static readonly Dictionary _slotsHolders = new Dictionary(PythonReferenceComparer.Instance); + static readonly Dictionary _slotsHolders = new(PythonReferenceComparer.Instance); // Slots which must be set private static readonly string[] _requiredSlots = new string[] @@ -84,7 +84,7 @@ internal static void RestoreRuntimeData(TypeManagerState storage) var typeCache = storage.Cache; foreach (var entry in typeCache) { - Type type = entry.Key.Value;; + var type = entry.Key.Value; cache![type] = entry.Value; SlotsHolder holder = CreateSlotsHolder(entry.Value); InitializeSlots(entry.Value, type, holder); @@ -385,31 +385,30 @@ internal static NewReference CreateSubType(BorrowedReference py_name, BorrowedRe return Exceptions.RaiseTypeError("Couldn't convert __assembly__ value to string"); } - using (var namespaceKey = new PyString("__namespace__")) + using var namespaceKey = new PyString("__namespace__"); + var pyNamespace = Runtime.PyDict_GetItemWithError(dictRef, namespaceKey.Reference); + if (pyNamespace.IsNull) { - var pyNamespace = Runtime.PyDict_GetItemWithError(dictRef, namespaceKey.Reference); - if (pyNamespace.IsNull) - { - if (Exceptions.ErrorOccurred()) return default; - } - else if (!Converter.ToManagedValue(pyNamespace, typeof(string), out namespaceStr, true)) - { - return Exceptions.RaiseTypeError("Couldn't convert __namespace__ value to string"); - } + if (Exceptions.ErrorOccurred()) return default; + } + else if (!Converter.ToManagedValue(pyNamespace, typeof(string), out namespaceStr, true)) + { + return Exceptions.RaiseTypeError("Couldn't convert __namespace__ value to string"); } } // create the new managed type subclassing the base managed type - var baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase; - if (null == baseClass) + if (ManagedType.GetManagedObject(py_base_type) is ClassBase baseClass) + { + return ReflectedClrType.CreateSubclass(baseClass, name, + ns: (string?)namespaceStr, + assembly: (string?)assembly, + dict: dictRef); + } + else { return Exceptions.RaiseTypeError("invalid base class, expected CLR class type"); } - - return ReflectedClrType.CreateSubclass(baseClass, name, - ns: (string?)namespaceStr, - assembly: (string?)assembly, - dict: dictRef); } internal static IntPtr WriteMethodDef(IntPtr mdef, IntPtr name, IntPtr func, PyMethodFlags flags, IntPtr doc) @@ -526,7 +525,7 @@ internal static PyType CreateMetaType(Type impl, out SlotsHolder slotsHolder) internal static SlotsHolder SetupMetaSlots(Type impl, PyType type) { // Override type slots with those of the managed implementation. - SlotsHolder slotsHolder = new SlotsHolder(type); + var slotsHolder = new SlotsHolder(type); InitializeSlots(type, impl, slotsHolder); // We need space for 3 PyMethodDef structs. @@ -683,7 +682,7 @@ private static void SetRequiredSlots(PyType type, HashSet seen) static void InitializeSlot(BorrowedReference type, ThunkInfo thunk, string name, SlotsHolder? slotsHolder) { - if (!Enum.TryParse(name, out var id)) + if (!Enum.TryParse(name, out _)) { throw new NotSupportedException("Bad slot name " + name); } @@ -741,10 +740,10 @@ class SlotsHolder { public delegate void Resetor(PyType type, int offset); - private Dictionary _slots = new Dictionary(); - private List _keepalive = new List(); - private Dictionary _customResetors = new Dictionary(); - private List _deallocators = new List(); + private readonly Dictionary _slots = new(); + private readonly List _keepalive = new(); + private readonly Dictionary _customResetors = new(); + private readonly List _deallocators = new(); private bool _alreadyReset = false; private readonly PyType Type; diff --git a/src/runtime/Types/ArrayObject.cs b/src/runtime/Types/ArrayObject.cs index 3ca09ddce..bda717e56 100644 --- a/src/runtime/Types/ArrayObject.cs +++ b/src/runtime/Types/ArrayObject.cs @@ -63,14 +63,16 @@ public static NewReference tp_new(BorrowedReference tp, BorrowedReference args, return NewInstance(arrType.GetElementType(), tp, dimensions); } } - object? result; // this implements casting to Array[T] - if (!Converter.ToManaged(op, arrType, out result, true)) + if (Converter.ToManaged(op, arrType, out object? result, true)) + { + return CLRObject.GetReference(result!, tp); + } + else { return default; } - return CLRObject.GetReference(result!, tp); } static NewReference CreateMultidimensional(Type elementType, long[] dimensions, BorrowedReference shapeTuple, BorrowedReference pyType) @@ -250,7 +252,6 @@ public static int mp_ass_subscript(BorrowedReference ob, BorrowedReference idx, Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; long index; - object? value; if (items.IsReadOnly) { @@ -258,7 +259,7 @@ public static int mp_ass_subscript(BorrowedReference ob, BorrowedReference idx, return -1; } - if (!Converter.ToManaged(v, itemType, out value, true)) + if (!Converter.ToManaged(v, itemType, out object? value, true)) { return -1; } @@ -353,9 +354,8 @@ public static int sq_contains(BorrowedReference ob, BorrowedReference v) var obj = (CLRObject)GetManagedObject(ob)!; Type itemType = obj.inst.GetType().GetElementType(); var items = (IList)obj.inst; - object? value; - if (!Converter.ToManaged(v, itemType, out value, false)) + if (!Converter.ToManaged(v, itemType, out object? value, false)) { return 0; } @@ -397,7 +397,8 @@ static int GetBuffer(BorrowedReference obj, out Py_buffer buffer, PyBUF flags) try { gcHandle = GCHandle.Alloc(self, GCHandleType.Pinned); - } catch (ArgumentException ex) + } + catch (ArgumentException ex) { Exceptions.SetError(Exceptions.BufferError, ex.Message); return -1; @@ -410,7 +411,7 @@ static int GetBuffer(BorrowedReference obj, out Py_buffer buffer, PyBUF flags) { buf = gcHandle.AddrOfPinnedObject(), obj = new NewReference(obj).DangerousMoveToPointer(), - len = (IntPtr)(self.LongLength*itemSize), + len = (IntPtr)(self.LongLength * itemSize), itemsize = (IntPtr)itemSize, _readonly = false, ndim = self.Rank, @@ -476,7 +477,7 @@ static unsafe IntPtr ToUnmanaged(T[] array) where T : unmanaged return result; } - static readonly Dictionary ItemFormats = new Dictionary + static readonly Dictionary ItemFormats = new() { [typeof(byte)] = "B", [typeof(sbyte)] = "b", diff --git a/src/runtime/Types/ClassBase.cs b/src/runtime/Types/ClassBase.cs index 6066e5fec..1e3c325cc 100644 --- a/src/runtime/Types/ClassBase.cs +++ b/src/runtime/Types/ClassBase.cs @@ -41,7 +41,7 @@ internal virtual bool CanSubclass() return !type.Value.IsEnum; } - public readonly static Dictionary CilToPyOpMap = new Dictionary + public readonly static Dictionary CilToPyOpMap = new() { ["op_Equality"] = Runtime.Py_EQ, ["op_Inequality"] = Runtime.Py_NE, @@ -153,8 +153,7 @@ public static NewReference tp_richcompare(BorrowedReference ob, BorrowedReferenc { return Exceptions.RaiseTypeError("Cannot get managed object"); } - var co1Comp = co1.inst as IComparable; - if (co1Comp == null) + if (co1.inst is not IComparable co1Comp) { Type co1Type = co1.GetType(); return Exceptions.RaiseTypeError($"Cannot convert object of type {co1Type} to IComparable"); @@ -215,15 +214,13 @@ public static NewReference tp_richcompare(BorrowedReference ob, BorrowedReferenc /// static NewReference tp_iter_impl(BorrowedReference ob) { - var co = GetManagedObject(ob) as CLRObject; - if (co == null) + if (GetManagedObject(ob) is not CLRObject co) { return Exceptions.RaiseTypeError("invalid object"); } - var e = co.inst as IEnumerable; IEnumerator? o; - if (e != null) + if (co.inst is IEnumerable e) { o = e.GetEnumerator(); } @@ -239,7 +236,7 @@ static NewReference tp_iter_impl(BorrowedReference ob) var elemType = typeof(object); var iterType = co.inst.GetType(); - foreach(var ifc in iterType.GetInterfaces()) + foreach (var ifc in iterType.GetInterfaces()) { if (ifc.IsGenericType) { @@ -261,13 +258,15 @@ static NewReference tp_iter_impl(BorrowedReference ob) /// public static nint tp_hash(BorrowedReference ob) { - var co = GetManagedObject(ob) as CLRObject; - if (co == null) + if (GetManagedObject(ob) is CLRObject co) + { + return co.inst.GetHashCode(); + } + else { Exceptions.RaiseTypeError("unhashable type"); return 0; } - return co.inst.GetHashCode(); } @@ -298,8 +297,7 @@ public static NewReference tp_str(BorrowedReference ob) public static NewReference tp_repr(BorrowedReference ob) { - var co = GetManagedObject(ob) as CLRObject; - if (co == null) + if (GetManagedObject(ob) is not CLRObject co) { return Exceptions.RaiseTypeError("invalid object"); } @@ -307,11 +305,17 @@ public static NewReference tp_repr(BorrowedReference ob) { //if __repr__ is defined, use it var instType = co.inst.GetType(); - System.Reflection.MethodInfo methodInfo = instType.GetMethod("__repr__"); + var methodInfo = instType.GetMethod("__repr__"); if (methodInfo != null && methodInfo.IsPublic) { - var reprString = methodInfo.Invoke(co.inst, null) as string; - return reprString is null ? new NewReference(Runtime.PyNone) : Runtime.PyString_FromString(reprString); + if (methodInfo.Invoke(co.inst, null) is string reprString) + { + return Runtime.PyString_FromString(reprString); + } + else + { + return new NewReference(Runtime.PyNone); + } } //otherwise use the standard object.__repr__(inst) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 6c2c81b13..dd1f4595f 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -107,7 +107,8 @@ internal static NewReference ToPython(IPythonDerivedType obj) try { self = GetPyObj(obj).CheckRun(); - } catch (RuntimeShutdownException e) + } + catch (RuntimeShutdownException e) { Exceptions.SetError(e); return default; @@ -197,22 +198,19 @@ internal static Type CreateDerivedType(string name, if (py_dict != null && Runtime.PyDict_Check(py_dict)) { using var dict = new PyDict(py_dict); - using (PyIterable keys = dict.Keys()) + using var keys = dict.Keys(); + foreach (PyObject pyKey in keys) { - foreach (PyObject pyKey in keys) + using var value = dict[pyKey]; + if (value.HasAttr("_clr_property_type_")) { - using (PyObject value = dict[pyKey]) - { - if (value.HasAttr("_clr_property_type_")) - { - string propertyName = pyKey.ToString()!; - pyProperties.Add(propertyName); + string propertyName = pyKey.ToString()!; + pyProperties.Add(propertyName); - // Add the property to the type - AddPythonProperty(propertyName, value, typeBuilder); - } - } + // Add the property to the type + AddPythonProperty(propertyName, value, typeBuilder); } + pyKey.Dispose(); } } @@ -245,27 +243,24 @@ internal static Type CreateDerivedType(string name, if (py_dict != null && Runtime.PyDict_Check(py_dict)) { using var dict = new PyDict(py_dict); - using (PyIterable keys = dict.Keys()) + using var keys = dict.Keys(); + foreach (PyObject pyKey in keys) { - foreach (PyObject pyKey in keys) + using var value = dict[pyKey]; + if (value.HasAttr("_clr_return_type_") && value.HasAttr("_clr_arg_types_")) { - using (PyObject value = dict[pyKey]) - { - if (value.HasAttr("_clr_return_type_") && value.HasAttr("_clr_arg_types_")) - { - string methodName = pyKey.ToString()!; + string methodName = pyKey.ToString()!; - // if this method has already been redirected to the python method skip it - if (virtualMethods.Contains(methodName)) - { - continue; - } - - // Add the method to the type - AddPythonMethod(methodName, value, typeBuilder); - } + // if this method has already been redirected to the python method skip it + if (virtualMethods.Contains(methodName)) + { + continue; } + + // Add the method to the type + AddPythonMethod(methodName, value, typeBuilder); } + pyKey.Dispose(); } } @@ -868,10 +863,8 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s try { using var pyself = new PyObject(self.CheckRun()); - using (PyObject pyvalue = pyself.GetAttr(propertyName)) - { - return pyvalue.As(); - } + using var pyvalue = pyself.GetAttr(propertyName); + return pyvalue.As(); } finally { diff --git a/src/runtime/Types/ClassObject.cs b/src/runtime/Types/ClassObject.cs index 5ba83c25e..04613afa5 100644 --- a/src/runtime/Types/ClassObject.cs +++ b/src/runtime/Types/ClassObject.cs @@ -53,12 +53,10 @@ internal NewReference GetDocString() /// static NewReference tp_new_impl(BorrowedReference tp, BorrowedReference args, BorrowedReference kw) { - var self = GetManagedObject(tp) as ClassObject; - // Sanity check: this ensures a graceful error if someone does // something intentially wrong like use the managed metatype for // a class that is not really derived from a managed class. - if (self == null) + if (GetManagedObject(tp) is not ClassObject self) { return Exceptions.RaiseTypeError("invalid object"); } @@ -224,8 +222,15 @@ public override NewReference type_subscript(BorrowedReference idx) { return Exceptions.RaiseTypeError("type expected"); } - var c = GetManagedObject(idx) as ClassBase; - Type? t = c != null ? c.type.Value : Converter.GetTypeByAlias(idx); + Type? t; + if (GetManagedObject(idx) is ClassBase c) + { + t = c.type.Value; + } + else + { + t = Converter.GetTypeByAlias(idx); + } if (t == null) { return Exceptions.RaiseTypeError("type expected"); diff --git a/src/runtime/Types/DelegateObject.cs b/src/runtime/Types/DelegateObject.cs index 43a75aba7..cbc32696e 100644 --- a/src/runtime/Types/DelegateObject.cs +++ b/src/runtime/Types/DelegateObject.cs @@ -11,7 +11,7 @@ namespace Python.Runtime [Serializable] internal class DelegateObject : ClassBase { - private MethodBinder binder; + private readonly MethodBinder binder; internal DelegateObject(Type tp) : base(tp) { @@ -25,8 +25,7 @@ internal DelegateObject(Type tp) : base(tp) /// private static Delegate? GetTrueDelegate(BorrowedReference op) { - var o = GetManagedObject(op) as CLRObject; - if (o != null) + if (GetManagedObject(op) is CLRObject o) { var d = o.inst as Delegate; return d; @@ -83,20 +82,12 @@ public static NewReference tp_call(BorrowedReference ob, BorrowedReference args, // TODO: add fast type check! BorrowedReference pytype = Runtime.PyObject_TYPE(ob); var self = (DelegateObject)GetManagedObject(pytype)!; - var o = GetManagedObject(ob) as CLRObject; - if (o == null) + if (GetManagedObject(ob) is CLRObject o && o.inst is Delegate _) { - return Exceptions.RaiseTypeError("invalid argument"); + return self.binder.Invoke(ob, args, kw); } - - var d = o.inst as Delegate; - - if (d == null) - { - return Exceptions.RaiseTypeError("invalid argument"); - } - return self.binder.Invoke(ob, args, kw); + return Exceptions.RaiseTypeError("invalid argument"); } diff --git a/src/runtime/Types/EventBinding.cs b/src/runtime/Types/EventBinding.cs index 69ca8f88e..9eb2382ec 100644 --- a/src/runtime/Types/EventBinding.cs +++ b/src/runtime/Types/EventBinding.cs @@ -12,7 +12,7 @@ internal class EventBinding : ExtensionType { private readonly string name; private readonly EventHandlerCollection e; - private PyObject? target; + private readonly PyObject? target; public EventBinding(string name, EventHandlerCollection e, PyObject? target) { diff --git a/src/runtime/Types/EventObject.cs b/src/runtime/Types/EventObject.cs index 90346f2d2..a682bfebd 100644 --- a/src/runtime/Types/EventObject.cs +++ b/src/runtime/Types/EventObject.cs @@ -57,9 +57,7 @@ public static NewReference tp_descr_get(BorrowedReference ds, BorrowedReference /// public static int tp_descr_set(BorrowedReference ds, BorrowedReference ob, BorrowedReference val) { - var e = GetManagedObject(val) as EventBinding; - - if (e != null) + if (GetManagedObject(val) is EventBinding _) { return 0; } diff --git a/src/runtime/Types/ExtensionType.cs b/src/runtime/Types/ExtensionType.cs index 439bd3314..305fdc15d 100644 --- a/src/runtime/Types/ExtensionType.cs +++ b/src/runtime/Types/ExtensionType.cs @@ -40,7 +40,7 @@ public virtual NewReference Alloc() return py; } - public PyObject AllocObject() => new PyObject(Alloc().Steal()); + public PyObject AllocObject() => new(Alloc().Steal()); // "borrowed" references internal static readonly HashSet loadedExtensions = new(); diff --git a/src/runtime/Types/InterfaceObject.cs b/src/runtime/Types/InterfaceObject.cs index b7e865b62..2d82392bf 100644 --- a/src/runtime/Types/InterfaceObject.cs +++ b/src/runtime/Types/InterfaceObject.cs @@ -27,7 +27,7 @@ internal InterfaceObject(Type tp) : base(tp) return comClass?.CoClass.GetConstructor(Type.EmptyTypes); } - private static Type cc_attr; + private static readonly Type cc_attr; static InterfaceObject() { @@ -51,15 +51,16 @@ public static NewReference tp_new(BorrowedReference tp, BorrowedReference args, if (nargs == 1) { BorrowedReference inst = Runtime.PyTuple_GetItem(args, 0); - var co = GetManagedObject(inst) as CLRObject; - if (co == null || !type.IsInstanceOfType(co.inst)) + if (GetManagedObject(inst) is CLRObject co && type.IsInstanceOfType(co.inst)) + { + obj = co.inst; + } + else { Exceptions.SetError(Exceptions.TypeError, $"object does not implement {type.Name}"); return default; } - - obj = co.inst; } else if (nargs == 0 && self.ctor != null) diff --git a/src/runtime/Types/Iterator.cs b/src/runtime/Types/Iterator.cs index 829ff8a7a..49145d2c3 100644 --- a/src/runtime/Types/Iterator.cs +++ b/src/runtime/Types/Iterator.cs @@ -9,8 +9,8 @@ namespace Python.Runtime /// internal class Iterator : ExtensionType { - private IEnumerator iter; - private Type elemType; + private readonly IEnumerator iter; + private readonly Type elemType; public Iterator(IEnumerator e, Type elemType) { diff --git a/src/runtime/Types/MetaType.cs b/src/runtime/Types/MetaType.cs index 1543711f6..5b59f5139 100644 --- a/src/runtime/Types/MetaType.cs +++ b/src/runtime/Types/MetaType.cs @@ -100,8 +100,7 @@ public static NewReference tp_new(BorrowedReference tp, BorrowedReference args, // Ensure that the reflected type is appropriate for subclassing, // disallowing subclassing of delegates, enums and array types. - var cb = GetManagedObject(base_type) as ClassBase; - if (cb != null) + if (GetManagedObject(base_type) is ClassBase cb) { try { @@ -128,12 +127,10 @@ public static NewReference tp_new(BorrowedReference tp, BorrowedReference args, // into python. if (null != dict) { - using (var clsDict = new PyDict(dict)) + using var clsDict = new PyDict(dict); + if (clsDict.HasKey("__assembly__") || clsDict.HasKey("__namespace__")) { - if (clsDict.HasKey("__assembly__") || clsDict.HasKey("__namespace__")) - { - return TypeManager.CreateSubType(name, base_type, clsDict); - } + return TypeManager.CreateSubType(name, base_type, clsDict); } } @@ -259,8 +256,7 @@ public static int tp_setattro(BorrowedReference tp, BorrowedReference name, Borr /// public static NewReference mp_subscript(BorrowedReference tp, BorrowedReference idx) { - var cb = GetManagedObject(tp) as ClassBase; - if (cb != null) + if (GetManagedObject(tp) is ClassBase cb) { return cb.type_subscript(idx); } @@ -310,44 +306,30 @@ public static void tp_dealloc(NewReference lastRef) private static NewReference DoInstanceCheck(BorrowedReference tp, BorrowedReference args, bool checkType) { - var cb = GetManagedObject(tp) as ClassBase; - - if (cb == null || !cb.type.Valid) + if (GetManagedObject(tp) is not ClassBase cb || !cb.type.Valid) { return new NewReference(Runtime.PyFalse); } - using (var argsObj = new PyList(args)) + using var argsObj = new PyList(args); + if (argsObj.Length() != 1) { - if (argsObj.Length() != 1) - { - return Exceptions.RaiseTypeError("Invalid parameter count"); - } - - PyObject arg = argsObj[0]; - PyObject otherType; - if (checkType) - { - otherType = arg; - } - else - { - otherType = arg.GetPythonType(); - } + return Exceptions.RaiseTypeError("Invalid parameter count"); + } - if (Runtime.PyObject_TYPE(otherType) != PyCLRMetaType) - { - return new NewReference(Runtime.PyFalse); - } + PyObject arg = argsObj[0]; + var otherType = checkType ? arg : arg.GetPythonType(); - var otherCb = GetManagedObject(otherType) as ClassBase; - if (otherCb == null || !otherCb.type.Valid) - { - return new NewReference(Runtime.PyFalse); - } + if (Runtime.PyObject_TYPE(otherType) != PyCLRMetaType) + { + return new NewReference(Runtime.PyFalse); + } + if (GetManagedObject(otherType) is ClassBase otherCb && otherCb.type.Valid) + { return Converter.ToPython(cb.type.Value.IsAssignableFrom(otherCb.type.Value)); } + return new NewReference(Runtime.PyFalse); } public static NewReference __instancecheck__(BorrowedReference tp, BorrowedReference args) diff --git a/src/runtime/Types/MethodBinding.cs b/src/runtime/Types/MethodBinding.cs index 6d21af01e..334d705a6 100644 --- a/src/runtime/Types/MethodBinding.cs +++ b/src/runtime/Types/MethodBinding.cs @@ -172,7 +172,6 @@ public static NewReference tp_call(BorrowedReference ob, BorrowedReference args, var info = self.info.Value; if (info.IsGenericMethod) { - var len = Runtime.PyTuple_Size(args); //FIXME: Never used Type[]? sigTp = Runtime.PythonArgsToTypeArray(args, true); if (sigTp != null) { @@ -220,15 +219,13 @@ public static NewReference tp_call(BorrowedReference ob, BorrowedReference args, var inst = GetManagedObject(target) as CLRObject; if (inst?.inst is IPythonDerivedType) { - var baseType = GetManagedObject(self.targetType!) as ClassBase; - if (baseType != null && baseType.type.Valid) + if (GetManagedObject(self.targetType!) is ClassBase baseType && baseType.type.Valid) { - string baseMethodName = "_" + baseType.type.Value.Name + "__" + self.m.name; + var baseMethodName = $"_{baseType.type.Value.Name}__{self.m.name}"; using var baseMethod = Runtime.PyObject_GetAttrString(target, baseMethodName); if (!baseMethod.IsNull()) { - var baseSelf = GetManagedObject(baseMethod.Borrow()) as MethodBinding; - if (baseSelf != null) + if (GetManagedObject(baseMethod.Borrow()) is MethodBinding baseSelf) { self = baseSelf; } diff --git a/src/runtime/Types/MethodObject.cs b/src/runtime/Types/MethodObject.cs index b0fda49d3..0bdd11ac2 100644 --- a/src/runtime/Types/MethodObject.cs +++ b/src/runtime/Types/MethodObject.cs @@ -186,8 +186,7 @@ public static NewReference tp_descr_get(BorrowedReference ds, BorrowedReference // this descriptor was defined on then it will be because the base class method // is being called via super(Derived, self).method(...). // In which case create a MethodBinding bound to the base class. - var obj = GetManagedObject(ob) as CLRObject; - if (obj != null + if (GetManagedObject(ob) is CLRObject obj && obj.inst.GetType() != self.type.Value && obj.inst is IPythonDerivedType && self.type.Value.IsInstanceOfType(obj.inst)) diff --git a/src/runtime/Types/ModuleObject.cs b/src/runtime/Types/ModuleObject.cs index 1cc9f04b2..a9e8c9937 100644 --- a/src/runtime/Types/ModuleObject.cs +++ b/src/runtime/Types/ModuleObject.cs @@ -499,8 +499,7 @@ public static Assembly AddReference(string name) { AssemblyManager.UpdatePath(); var origNs = AssemblyManager.GetNamespaces(); - Assembly? assembly = null; - assembly = AssemblyManager.FindLoadedAssembly(name); + Assembly? assembly = AssemblyManager.FindLoadedAssembly(name); if (assembly == null) { assembly = AssemblyManager.LoadAssemblyPath(name); diff --git a/src/runtime/Types/MpLengthSlot.cs b/src/runtime/Types/MpLengthSlot.cs index 9e4865fe0..4cf15f221 100644 --- a/src/runtime/Types/MpLengthSlot.cs +++ b/src/runtime/Types/MpLengthSlot.cs @@ -32,8 +32,7 @@ public static bool CanAssign(Type clrType) /// internal static nint impl(BorrowedReference ob) { - var co = ManagedType.GetManagedObject(ob) as CLRObject; - if (co == null) + if (ManagedType.GetManagedObject(ob) is not CLRObject co) { Exceptions.RaiseTypeError("invalid object"); return -1; diff --git a/src/runtime/Types/OperatorMethod.cs b/src/runtime/Types/OperatorMethod.cs index abe6ded1a..0c6127f65 100644 --- a/src/runtime/Types/OperatorMethod.cs +++ b/src/runtime/Types/OperatorMethod.cs @@ -148,7 +148,7 @@ public static string GetPyMethodName(string clrName) private static string GenerateDummyCode() { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.AppendLine("class OperatorMethod(object):"); foreach (var item in OpMethodMap.Values) { @@ -160,15 +160,13 @@ private static string GenerateDummyCode() private static PyObject GetOperatorType() { - using (PyDict locals = new PyDict()) - { - // A hack way for getting typeobject.c::slotdefs - string code = GenerateDummyCode(); - // The resulting OperatorMethod class is stored in a PyDict. - PythonEngine.Exec(code, null, locals); - // Return the class itself, which is a type. - return locals.GetItem("OperatorMethod"); - } + using var locals = new PyDict(); + // A hack way for getting typeobject.c::slotdefs + string code = GenerateDummyCode(); + // The resulting OperatorMethod class is stored in a PyDict. + PythonEngine.Exec(code, null, locals); + // Return the class itself, which is a type. + return locals.GetItem("OperatorMethod"); } public static string ReversePyMethodName(string pyName) diff --git a/src/runtime/Types/OverloadMapper.cs b/src/runtime/Types/OverloadMapper.cs index 20939f4c6..8f6e30478 100644 --- a/src/runtime/Types/OverloadMapper.cs +++ b/src/runtime/Types/OverloadMapper.cs @@ -9,8 +9,8 @@ namespace Python.Runtime /// internal class OverloadMapper : ExtensionType { - private MethodObject m; - private PyObject? target; + private readonly MethodObject m; + private readonly PyObject? target; public OverloadMapper(MethodObject m, PyObject? target) { diff --git a/src/runtime/Util/CodeGenerator.cs b/src/runtime/Util/CodeGenerator.cs index d0079fabb..35a637113 100644 --- a/src/runtime/Util/CodeGenerator.cs +++ b/src/runtime/Util/CodeGenerator.cs @@ -14,8 +14,8 @@ namespace Python.Runtime /// internal class CodeGenerator { - private AssemblyBuilder aBuilder; - private ModuleBuilder mBuilder; + private readonly AssemblyBuilder aBuilder; + private readonly ModuleBuilder mBuilder; internal CodeGenerator() { diff --git a/src/runtime/Util/DebugUtil.cs b/src/runtime/Util/DebugUtil.cs index eb9facb3c..0eecc87b0 100644 --- a/src/runtime/Util/DebugUtil.cs +++ b/src/runtime/Util/DebugUtil.cs @@ -57,7 +57,6 @@ internal static void DumpType(BorrowedReference type) var slots = TypeOffset.GetOffsets(); - int size = IntPtr.Size; foreach (var entry in slots) { @@ -99,7 +98,7 @@ internal static void DumpInst(BorrowedReference ob) } [Conditional("DEBUG")] - internal static void debug(string msg) + internal static void Debug(string msg) { var st = new StackTrace(1, true); StackFrame sf = st.GetFrame(0); @@ -138,13 +137,13 @@ public static void PrintHexBytes(byte[] bytes) public static void AssertHasReferences(BorrowedReference obj) { nint refcount = Runtime.Refcount(obj); - Debug.Assert(refcount > 0, "Object refcount is 0 or less"); + System.Diagnostics.Debug.Assert(refcount > 0, "Object refcount is 0 or less"); } [Conditional("DEBUG")] public static void EnsureGIL() { - Debug.Assert(HaveInterpreterLock(), "GIL must be acquired"); + System.Diagnostics.Debug.Assert(HaveInterpreterLock(), "GIL must be acquired"); } public static bool HaveInterpreterLock() => Runtime.PyGILState_Check() == 1; diff --git a/src/runtime/Util/GenericUtil.cs b/src/runtime/Util/GenericUtil.cs index 74db54af1..907a3a616 100644 --- a/src/runtime/Util/GenericUtil.cs +++ b/src/runtime/Util/GenericUtil.cs @@ -32,15 +32,13 @@ internal static void Register(Type t) return; } - Dictionary> nsmap; - if (!mapping.TryGetValue(t.Namespace, out nsmap)) + if (!mapping.TryGetValue(t.Namespace, out var nsmap)) { nsmap = new Dictionary>(); mapping[t.Namespace] = nsmap; } string basename = GetBasename(t.Name); - List gnames; - if (!nsmap.TryGetValue(basename, out gnames)) + if (!nsmap.TryGetValue(basename, out var gnames)) { gnames = new List(); nsmap[basename] = gnames; @@ -53,17 +51,11 @@ internal static void Register(Type t) /// public static List? GetGenericBaseNames(string ns) { - Dictionary> nsmap; - if (!mapping.TryGetValue(ns, out nsmap)) + if (mapping.TryGetValue(ns, out var nsmap)) { - return null; + return nsmap.Keys.ToList(); } - var names = new List(); - foreach (string key in nsmap.Keys) - { - names.Add(key); - } - return names; + return null; } /// @@ -79,28 +71,21 @@ internal static void Register(Type t) /// public static Type? GenericByName(string ns, string basename, int paramCount) { - Dictionary> nsmap; - if (!mapping.TryGetValue(ns, out nsmap)) - { - return null; - } - - List names; - if (!nsmap.TryGetValue(GetBasename(basename), out names)) - { - return null; - } - - foreach (string name in names) + if (mapping.TryGetValue(ns, out var nsmap)) { - string qname = ns + "." + name; - Type o = AssemblyManager.LookupTypes(qname).FirstOrDefault(); - if (o != null && o.GetGenericArguments().Length == paramCount) + if (nsmap.TryGetValue(GetBasename(basename), out var names)) { - return o; + foreach (string name in names) + { + string qname = $"{ns}.{name}"; + Type o = AssemblyManager.LookupTypes(qname).FirstOrDefault(); + if (o != null && o.GetGenericArguments().Length == paramCount) + { + return o; + } + } } } - return null; } @@ -109,16 +94,13 @@ internal static void Register(Type t) /// public static string? GenericNameForBaseName(string ns, string name) { - Dictionary> nsmap; - if (!mapping.TryGetValue(ns, out nsmap)) + if (mapping.TryGetValue(ns, out var nsmap)) { - return null; - } - List gnames; - nsmap.TryGetValue(name, out gnames); - if (gnames?.Count > 0) - { - return gnames[0]; + nsmap.TryGetValue(name, out var gnames); + if (gnames?.Count > 0) + { + return gnames[0]; + } } return null; } diff --git a/src/runtime/Util/OpsHelper.cs b/src/runtime/Util/OpsHelper.cs index ab623f3de..12d0c7aa6 100644 --- a/src/runtime/Util/OpsHelper.cs +++ b/src/runtime/Util/OpsHelper.cs @@ -46,10 +46,12 @@ internal static class FlagEnumOps where T : Enum static readonly Func invert = UnaryOp(Expression.OnesComplement); +#pragma warning disable IDE1006 public static T op_BitwiseAnd(T a, T b) => and(a, b); public static T op_BitwiseOr(T a, T b) => or(a, b); public static T op_ExclusiveOr(T a, T b) => xor(a, b); public static T op_OnesComplement(T value) => invert(value); +#pragma warning restore IDE1006 static Expression FromNumber(Expression number) => Expression.Convert(number, typeof(T)); diff --git a/src/runtime/Util/ReflectionPolyfills.cs b/src/runtime/Util/ReflectionPolyfills.cs index 36bd39cef..b33698509 100644 --- a/src/runtime/Util/ReflectionPolyfills.cs +++ b/src/runtime/Util/ReflectionPolyfills.cs @@ -7,7 +7,7 @@ namespace Python.Runtime { internal static class ReflectionPolyfills { - public static AssemblyBuilder DefineDynamicAssembly(this AppDomain appDomain, AssemblyName assemblyName, AssemblyBuilderAccess assemblyBuilderAccess) + public static AssemblyBuilder DefineDynamicAssembly(this AppDomain _, AssemblyName assemblyName, AssemblyBuilderAccess assemblyBuilderAccess) { return AssemblyBuilder.DefineDynamicAssembly(assemblyName, assemblyBuilderAccess); } From d8990839a8eaf87ed885cba75427736cffc38353 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Wed, 30 Mar 2022 15:38:30 +0200 Subject: [PATCH 3/4] Fix Py.SetArgv for systems that don't support GetCommandLineArgs --- src/runtime/Py.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/runtime/Py.cs b/src/runtime/Py.cs index ec991f971..1fcce5110 100644 --- a/src/runtime/Py.cs +++ b/src/runtime/Py.cs @@ -122,11 +122,7 @@ public static void SetArgv() args = Enumerable.Empty(); } - SetArgv( - new[] { "" }.Concat( - Environment.GetCommandLineArgs().Skip(1) - ) - ); + SetArgv(new[] { "" }.Concat(args.Skip(1))); } public static void SetArgv(params string[] argv) From aa5b54bf7f27970275b89764140dccf0b44d38e2 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Wed, 30 Mar 2022 15:39:15 +0200 Subject: [PATCH 4/4] Modernise syntax in ClassDerived --- src/runtime/Types/ClassDerived.cs | 236 +++++++++++++++--------------- 1 file changed, 115 insertions(+), 121 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index dd1f4595f..02288faee 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -469,100 +469,100 @@ private static void AddPythonMethod(string methodName, PyObject func, TypeBuilde methodName = pyMethodName.As() ?? throw new ArgumentNullException(methodNameAttribute); } - using (PyObject pyReturnType = func.GetAttr("_clr_return_type_")) - using (var pyArgTypes = PyIter.GetIter(func.GetAttr("_clr_arg_types_"))) + using var pyReturnType = func.GetAttr("_clr_return_type_"); + using var pyArgTypes = func.GetAttr("_clr_arg_types_"); + using var pyArgTypesIter = PyIter.GetIter(pyArgTypes); + var returnType = pyReturnType.AsManagedObject(typeof(Type)) as Type; + if (returnType == null) { - var returnType = pyReturnType.AsManagedObject(typeof(Type)) as Type; - if (returnType == null) - { - returnType = typeof(void); - } + returnType = typeof(void); + } - var argTypes = new List(); - foreach (PyObject pyArgType in pyArgTypes) + var argTypes = new List(); + foreach (PyObject pyArgType in pyArgTypesIter) + { + var argType = pyArgType.AsManagedObject(typeof(Type)) as Type; + if (argType == null) { - var argType = pyArgType.AsManagedObject(typeof(Type)) as Type; - if (argType == null) - { - throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types"); - } - argTypes.Add(argType); + throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types"); } + argTypes.Add(argType); + pyArgType.Dispose(); + } - // add the method to call back into python - MethodAttributes methodAttribs = MethodAttributes.Public | - MethodAttributes.Virtual | - MethodAttributes.ReuseSlot | - MethodAttributes.HideBySig; + // add the method to call back into python + MethodAttributes methodAttribs = MethodAttributes.Public | + MethodAttributes.Virtual | + MethodAttributes.ReuseSlot | + MethodAttributes.HideBySig; - MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, - methodAttribs, - returnType, - argTypes.ToArray()); + MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName, + methodAttribs, + returnType, + argTypes.ToArray()); - ILGenerator il = methodBuilder.GetILGenerator(); + ILGenerator il = methodBuilder.GetILGenerator(); - il.DeclareLocal(typeof(object[])); - il.DeclareLocal(typeof(RuntimeMethodHandle)); + il.DeclareLocal(typeof(object[])); + il.DeclareLocal(typeof(RuntimeMethodHandle)); - // this - il.Emit(OpCodes.Ldarg_0); + // this + il.Emit(OpCodes.Ldarg_0); - // Python method to call - il.Emit(OpCodes.Ldstr, methodName); + // Python method to call + il.Emit(OpCodes.Ldstr, methodName); - // original method name - il.Emit(OpCodes.Ldnull); // don't fall back to the base type's method + // original method name + il.Emit(OpCodes.Ldnull); // don't fall back to the base type's method - // create args array - il.Emit(OpCodes.Ldc_I4, argTypes.Count); - il.Emit(OpCodes.Newarr, typeof(object)); - il.Emit(OpCodes.Stloc_0); + // create args array + il.Emit(OpCodes.Ldc_I4, argTypes.Count); + il.Emit(OpCodes.Newarr, typeof(object)); + il.Emit(OpCodes.Stloc_0); - // fill args array - for (var i = 0; i < argTypes.Count; ++i) + // fill args array + for (var i = 0; i < argTypes.Count; ++i) + { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldc_I4, i); + il.Emit(OpCodes.Ldarg, i + 1); + var type = argTypes[i]; + if (type.IsByRef) { - il.Emit(OpCodes.Ldloc_0); - il.Emit(OpCodes.Ldc_I4, i); - il.Emit(OpCodes.Ldarg, i + 1); - var type = argTypes[i]; - if (type.IsByRef) - { - type = type.GetElementType(); - il.Emit(OpCodes.Ldobj, type); - } - if (type.IsValueType) - { - il.Emit(OpCodes.Box, type); - } - il.Emit(OpCodes.Stelem, typeof(object)); + type = type.GetElementType(); + il.Emit(OpCodes.Ldobj, type); + } + if (type.IsValueType) + { + il.Emit(OpCodes.Box, type); } + il.Emit(OpCodes.Stelem, typeof(object)); + } - // args array - il.Emit(OpCodes.Ldloc_0); + // args array + il.Emit(OpCodes.Ldloc_0); - // method handle for the base method is null - il.Emit(OpCodes.Ldloca_S, 1); - il.Emit(OpCodes.Initobj, typeof(RuntimeMethodHandle)); - il.Emit(OpCodes.Ldloc_1); + // method handle for the base method is null + il.Emit(OpCodes.Ldloca_S, 1); + il.Emit(OpCodes.Initobj, typeof(RuntimeMethodHandle)); + il.Emit(OpCodes.Ldloc_1); #pragma warning disable CS0618 // PythonDerivedType is for internal use only - // invoke the method - if (returnType == typeof(void)) - { - il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(InvokeMethodVoid))); - } - else - { - il.Emit(OpCodes.Call, - typeof(PythonDerivedType).GetMethod(nameof(InvokeMethod)).MakeGenericMethod(returnType)); - } + // invoke the method + if (returnType == typeof(void)) + { + il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(InvokeMethodVoid))); + } + else + { + il.Emit(OpCodes.Call, + typeof(PythonDerivedType).GetMethod(nameof(InvokeMethod)).MakeGenericMethod(returnType)); + } - CodeGenerator.GenerateMarshalByRefsBack(il, argTypes); + CodeGenerator.GenerateMarshalByRefsBack(il, argTypes); #pragma warning restore CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Ret); - } + il.Emit(OpCodes.Ret); } /// @@ -581,68 +581,62 @@ private static void AddPythonProperty(string propertyName, PyObject func, TypeBu MethodAttributes.HideBySig | MethodAttributes.SpecialName; - using (PyObject pyPropertyType = func.GetAttr("_clr_property_type_")) + using var pyPropertyType = func.GetAttr("_clr_property_type_"); + var propertyType = pyPropertyType.AsManagedObject(typeof(Type)) as Type; + if (propertyType == null) { - var propertyType = pyPropertyType.AsManagedObject(typeof(Type)) as Type; - if (propertyType == null) - { - throw new ArgumentException("_clr_property_type must be a CLR type"); - } + throw new ArgumentException("_clr_property_type must be a CLR type"); + } - PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, - PropertyAttributes.None, - propertyType, - null); + PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, + PropertyAttributes.None, + propertyType, + null); - if (func.HasAttr("fget")) + if (func.HasAttr("fget")) + { + using var pyfget = func.GetAttr("fget"); + if (pyfget.IsTrue()) { - using (PyObject pyfget = func.GetAttr("fget")) - { - if (pyfget.IsTrue()) - { - MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + propertyName, - methodAttribs, - propertyType, - null); - - ILGenerator il = methodBuilder.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldstr, propertyName); + MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + propertyName, + methodAttribs, + propertyType, + null); + + ILGenerator il = methodBuilder.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldstr, propertyName); #pragma warning disable CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Call, - typeof(PythonDerivedType).GetMethod("InvokeGetProperty").MakeGenericMethod(propertyType)); + il.Emit(OpCodes.Call, + typeof(PythonDerivedType).GetMethod("InvokeGetProperty").MakeGenericMethod(propertyType)); #pragma warning restore CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Ret); + il.Emit(OpCodes.Ret); - propertyBuilder.SetGetMethod(methodBuilder); - } - } + propertyBuilder.SetGetMethod(methodBuilder); } + } - if (func.HasAttr("fset")) + if (func.HasAttr("fset")) + { + using var pyset = func.GetAttr("fset"); + if (pyset.IsTrue()) { - using (PyObject pyset = func.GetAttr("fset")) - { - if (pyset.IsTrue()) - { - MethodBuilder methodBuilder = typeBuilder.DefineMethod("set_" + propertyName, - methodAttribs, - null, - new[] { propertyType }); - - ILGenerator il = methodBuilder.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldstr, propertyName); - il.Emit(OpCodes.Ldarg_1); + MethodBuilder methodBuilder = typeBuilder.DefineMethod("set_" + propertyName, + methodAttribs, + null, + new[] { propertyType }); + + ILGenerator il = methodBuilder.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldstr, propertyName); + il.Emit(OpCodes.Ldarg_1); #pragma warning disable CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Call, - typeof(PythonDerivedType).GetMethod("InvokeSetProperty").MakeGenericMethod(propertyType)); + il.Emit(OpCodes.Call, + typeof(PythonDerivedType).GetMethod("InvokeSetProperty").MakeGenericMethod(propertyType)); #pragma warning restore CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Ret); + il.Emit(OpCodes.Ret); - propertyBuilder.SetSetMethod(methodBuilder); - } - } + propertyBuilder.SetSetMethod(methodBuilder); } } } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy