diff --git a/src/runtime/AssemblyManager.cs b/src/runtime/AssemblyManager.cs index 56c70c1..d09d2d7 100644 --- a/src/runtime/AssemblyManager.cs +++ b/src/runtime/AssemblyManager.cs @@ -23,8 +23,8 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime #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 647cec3..6379f51 100644 --- a/src/runtime/ClassManager.cs +++ b/src/runtime/ClassManager.cs @@ -247,10 +247,9 @@ namespace Python.Runtime 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 5b3d127..41e1f04 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 32b550e..63abf35 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 94ed4cd..cde97c8 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 @@ namespace Python.Runtime } 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 a99961a..f86ba79 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -18,15 +18,15 @@ namespace Python.Runtime { } - 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 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime // 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 092c9be..4343b9a 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 @@ namespace Python.Runtime { 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 c3ac889..da095e0 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -196,8 +196,7 @@ namespace Python.Runtime // 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 be17d62..e796cac 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -41,7 +41,7 @@ namespace Python.Runtime [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 0780a0b..b6d9a0e 100644 --- a/src/runtime/InternString.cs +++ b/src/runtime/InternString.cs @@ -61,8 +61,7 @@ namespace Python.Runtime 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 bcf99be..4aa4aa0 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -139,7 +139,7 @@ namespace Python.Runtime } - 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 30c9a1c..781d0d0 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 be4e8d0..ebbf448 100644 --- a/src/runtime/MethodBinder.cs +++ b/src/runtime/MethodBinder.cs @@ -242,52 +242,24 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime { // 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 @@ namespace Python.Runtime //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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime } } - 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 @@ namespace Python.Runtime { 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 98c151b..fd1059a 100644 --- a/src/runtime/Native/BorrowedReference.cs +++ b/src/runtime/Native/BorrowedReference.cs @@ -19,7 +19,7 @@ namespace Python.Runtime /// 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 f544756..62c0271 100644 --- a/src/runtime/Native/CustomMarshaler.cs +++ b/src/runtime/Native/CustomMarshaler.cs @@ -47,9 +47,7 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 91ebbdb..25145fc 100644 --- a/src/runtime/Native/NewReference.cs +++ b/src/runtime/Native/NewReference.cs @@ -124,7 +124,7 @@ namespace Python.Runtime /// [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 4884a81..1ea2b70 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 03a26cb..9350cde 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 a1bae82..59c5c3e 100644 --- a/src/runtime/Native/TypeOffset.cs +++ b/src/runtime/Native/TypeOffset.cs @@ -121,7 +121,7 @@ namespace Python.Runtime 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 4f3fbf6..ec991f9 100644 --- a/src/runtime/Py.cs +++ b/src/runtime/Py.cs @@ -77,8 +77,7 @@ public static class Py } 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 1e82446..24e1bed 100644 --- a/src/runtime/PythonEngine.cs +++ b/src/runtime/PythonEngine.cs @@ -233,7 +233,7 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime /// 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 813d0e5..8d3330c 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -397,8 +397,13 @@ namespace Python.Runtime } 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 80b8c8c..272f782 100644 --- a/src/runtime/PythonTypes/PyDict.cs +++ b/src/runtime/PythonTypes/PyDict.cs @@ -72,10 +72,8 @@ namespace Python.Runtime /// 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 10104c1..c09ec93 100644 --- a/src/runtime/PythonTypes/PyFloat.cs +++ b/src/runtime/PythonTypes/PyFloat.cs @@ -53,12 +53,10 @@ namespace Python.Runtime { 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 ada24c6..4549678 100644 --- a/src/runtime/PythonTypes/PyModule.cs +++ b/src/runtime/PythonTypes/PyModule.cs @@ -322,13 +322,11 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 e0a17be..cfd3e71 100644 --- a/src/runtime/PythonTypes/PyObject.cs +++ b/src/runtime/PythonTypes/PyObject.cs @@ -539,10 +539,8 @@ namespace Python.Runtime { 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime { 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 @@ namespace Python.Runtime { 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime { 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 d92f45a..6ad1d45 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -554,17 +554,17 @@ namespace Python.Runtime } 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 aa369a5..b734bb0 100644 --- a/src/runtime/StateSerialization/MaybeMemberInfo.cs +++ b/src/runtime/StateSerialization/MaybeMemberInfo.cs @@ -12,10 +12,10 @@ namespace Python.Runtime // 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 9fb8ae0..d196d5e 100644 --- a/src/runtime/StateSerialization/MaybeMethodBase.cs +++ b/src/runtime/StateSerialization/MaybeMethodBase.cs @@ -24,11 +24,11 @@ namespace Python.Runtime 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 abb3a8f..f3c96e3 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 84618df..d9ca184 100644 --- a/src/runtime/TypeManager.cs +++ b/src/runtime/TypeManager.cs @@ -26,9 +26,9 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime { 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 3ca09dd..bda717e 100644 --- a/src/runtime/Types/ArrayObject.cs +++ b/src/runtime/Types/ArrayObject.cs @@ -63,14 +63,16 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime Type itemType = obj.inst.GetType().GetElementType(); int rank = items.Rank; long index; - object? value; if (items.IsReadOnly) { @@ -258,7 +259,7 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime { 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 @@ namespace Python.Runtime 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 6066e5f..1e3c325 100644 --- a/src/runtime/Types/ClassBase.cs +++ b/src/runtime/Types/ClassBase.cs @@ -41,7 +41,7 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime { 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime { //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 6c2c81b..dd1f459 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -107,7 +107,8 @@ namespace Python.Runtime try { self = GetPyObj(obj).CheckRun(); - } catch (RuntimeShutdownException e) + } + catch (RuntimeShutdownException e) { Exceptions.SetError(e); return default; @@ -197,22 +198,19 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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]) + string methodName = pyKey.ToString()!; + + // if this method has already been redirected to the python method skip it + if (virtualMethods.Contains(methodName)) { - if (value.HasAttr("_clr_return_type_") && value.HasAttr("_clr_arg_types_")) - { - 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); - } + continue; } + + // Add the method to the type + AddPythonMethod(methodName, value, typeBuilder); } + pyKey.Dispose(); } } @@ -868,10 +863,8 @@ namespace Python.Runtime 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 5ba83c2..04613af 100644 --- a/src/runtime/Types/ClassObject.cs +++ b/src/runtime/Types/ClassObject.cs @@ -53,12 +53,10 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime { 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 43a75ab..cbc3269 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime // 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 69ca8f8..9eb2382 100644 --- a/src/runtime/Types/EventBinding.cs +++ b/src/runtime/Types/EventBinding.cs @@ -12,7 +12,7 @@ namespace Python.Runtime { 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 90346f2..a682bfe 100644 --- a/src/runtime/Types/EventObject.cs +++ b/src/runtime/Types/EventObject.cs @@ -57,9 +57,7 @@ namespace Python.Runtime /// 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 439bd33..305fdc1 100644 --- a/src/runtime/Types/ExtensionType.cs +++ b/src/runtime/Types/ExtensionType.cs @@ -40,7 +40,7 @@ namespace Python.Runtime 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 b7e865b..2d82392 100644 --- a/src/runtime/Types/InterfaceObject.cs +++ b/src/runtime/Types/InterfaceObject.cs @@ -27,7 +27,7 @@ namespace Python.Runtime return comClass?.CoClass.GetConstructor(Type.EmptyTypes); } - private static Type cc_attr; + private static readonly Type cc_attr; static InterfaceObject() { @@ -51,15 +51,16 @@ namespace Python.Runtime 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 829ff8a..49145d2 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 1543711..5b59f51 100644 --- a/src/runtime/Types/MetaType.cs +++ b/src/runtime/Types/MetaType.cs @@ -100,8 +100,7 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime // 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime 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"); - } + return Exceptions.RaiseTypeError("Invalid parameter count"); + } - PyObject arg = argsObj[0]; - PyObject otherType; - if (checkType) - { - otherType = arg; - } - else - { - otherType = arg.GetPythonType(); - } + PyObject arg = argsObj[0]; + var otherType = checkType ? arg : arg.GetPythonType(); - if (Runtime.PyObject_TYPE(otherType) != PyCLRMetaType) - { - return new NewReference(Runtime.PyFalse); - } - - 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 6d21af0..334d705 100644 --- a/src/runtime/Types/MethodBinding.cs +++ b/src/runtime/Types/MethodBinding.cs @@ -172,7 +172,6 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 b0fda49..0bdd11a 100644 --- a/src/runtime/Types/MethodObject.cs +++ b/src/runtime/Types/MethodObject.cs @@ -186,8 +186,7 @@ namespace Python.Runtime // 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 1cc9f04..a9e8c99 100644 --- a/src/runtime/Types/ModuleObject.cs +++ b/src/runtime/Types/ModuleObject.cs @@ -499,8 +499,7 @@ namespace Python.Runtime { 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 9e4865f..4cf15f2 100644 --- a/src/runtime/Types/MpLengthSlot.cs +++ b/src/runtime/Types/MpLengthSlot.cs @@ -32,8 +32,7 @@ namespace Python.Runtime.Slots /// 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 abe6ded..0c6127f 100644 --- a/src/runtime/Types/OperatorMethod.cs +++ b/src/runtime/Types/OperatorMethod.cs @@ -148,7 +148,7 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime 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 20939f4..8f6e304 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 d0079fa..35a6371 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 eb9facb..0eecc87 100644 --- a/src/runtime/Util/DebugUtil.cs +++ b/src/runtime/Util/DebugUtil.cs @@ -57,7 +57,6 @@ namespace Python.Runtime var slots = TypeOffset.GetOffsets(); - int size = IntPtr.Size; foreach (var entry in slots) { @@ -99,7 +98,7 @@ namespace Python.Runtime } [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 @@ namespace Python.Runtime 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 74db54a..907a3a6 100644 --- a/src/runtime/Util/GenericUtil.cs +++ b/src/runtime/Util/GenericUtil.cs @@ -32,15 +32,13 @@ namespace Python.Runtime 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 @@ namespace Python.Runtime /// 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 @@ namespace Python.Runtime /// public static Type? GenericByName(string ns, string basename, int paramCount) { - Dictionary> nsmap; - if (!mapping.TryGetValue(ns, out nsmap)) + if (mapping.TryGetValue(ns, out var nsmap)) { - return null; - } - - List names; - if (!nsmap.TryGetValue(GetBasename(basename), out names)) - { - return null; - } - - foreach (string name in names) - { - 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 @@ namespace Python.Runtime /// 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 ab623f3..12d0c7a 100644 --- a/src/runtime/Util/OpsHelper.cs +++ b/src/runtime/Util/OpsHelper.cs @@ -46,10 +46,12 @@ namespace Python.Runtime 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 36bd39c..b336985 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); }