Skip to content

Commit 37f1235

Browse files
authored
Merge pull request #1760 from filmor/misc-fixes
Miscellaneous fixes and cleanups
2 parents bbfa252 + aa5b54b commit 37f1235

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+540
-676
lines changed

src/runtime/AssemblyManager.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ internal class AssemblyManager
2323
// than it can end up referring to assemblies that are already unloaded (default behavior after unload appDomain -
2424
// unless LoaderOptimization.MultiDomain is used);
2525
// So for multidomain support it is better to have the dict. recreated for each app-domain initialization
26-
private static ConcurrentDictionary<string, ConcurrentDictionary<Assembly, string>> namespaces =
27-
new ConcurrentDictionary<string, ConcurrentDictionary<Assembly, string>>();
26+
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<Assembly, string>> namespaces =
27+
new();
2828

2929
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
3030
// domain-level handlers are initialized in Initialize
@@ -33,7 +33,7 @@ internal class AssemblyManager
3333
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
3434

3535
// updated only under GIL?
36-
private static Dictionary<string, int> probed = new Dictionary<string, int>(32);
36+
private static readonly Dictionary<string, int> probed = new(32);
3737

3838
// modified from event handlers below, potentially triggered from different .NET threads
3939
private static readonly ConcurrentQueue<Assembly> assemblies = new();

src/runtime/ClassManager.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -247,10 +247,9 @@ internal static void InitClassBase(Type type, ClassBase impl, ReflectedClrType p
247247
Runtime.PyDict_SetItem(dict, PyIdentifier.__doc__, doc.Borrow());
248248
}
249249

250-
var co = impl as ClassObject;
251250
// If this is a ClassObject AND it has constructors, generate a __doc__ attribute.
252251
// required that the ClassObject.ctors be changed to internal
253-
if (co != null)
252+
if (impl is ClassObject co)
254253
{
255254
if (co.NumCtors > 0 && !co.HasCustomNew())
256255
{

src/runtime/Codecs/DecoderGroup.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ namespace Python.Runtime.Codecs
1010
/// </summary>
1111
public sealed class DecoderGroup: IPyObjectDecoder, IEnumerable<IPyObjectDecoder>, IDisposable
1212
{
13-
readonly List<IPyObjectDecoder> decoders = new List<IPyObjectDecoder>();
13+
readonly List<IPyObjectDecoder> decoders = new();
1414

1515
/// <summary>
1616
/// Add specified decoder to the group

src/runtime/Codecs/EncoderGroup.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ namespace Python.Runtime.Codecs
1010
/// </summary>
1111
public sealed class EncoderGroup: IPyObjectEncoder, IEnumerable<IPyObjectEncoder>, IDisposable
1212
{
13-
readonly List<IPyObjectEncoder> encoders = new List<IPyObjectEncoder>();
13+
readonly List<IPyObjectEncoder> encoders = new();
1414

1515
/// <summary>
1616
/// Add specified encoder to the group

src/runtime/Codecs/PyObjectConversions.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ namespace Python.Runtime
1515
/// </summary>
1616
public static class PyObjectConversions
1717
{
18-
static readonly DecoderGroup decoders = new DecoderGroup();
19-
static readonly EncoderGroup encoders = new EncoderGroup();
18+
static readonly DecoderGroup decoders = new();
19+
static readonly EncoderGroup encoders = new();
2020

2121
/// <summary>
2222
/// Registers specified encoder (marshaller)
@@ -62,7 +62,7 @@ public static void RegisterDecoder(IPyObjectDecoder decoder)
6262
}
6363

6464
static readonly ConcurrentDictionary<Type, IPyObjectEncoder[]>
65-
clrToPython = new ConcurrentDictionary<Type, IPyObjectEncoder[]>();
65+
clrToPython = new();
6666
static IPyObjectEncoder[] GetEncoders(Type type)
6767
{
6868
lock (encoders)

src/runtime/Converter.cs

+11-12
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,15 @@ private Converter()
1818
{
1919
}
2020

21-
private static Type objectType;
22-
private static Type stringType;
23-
private static Type singleType;
24-
private static Type doubleType;
25-
private static Type int16Type;
26-
private static Type int32Type;
27-
private static Type int64Type;
28-
private static Type boolType;
29-
private static Type typeType;
21+
private static readonly Type objectType;
22+
private static readonly Type stringType;
23+
private static readonly Type singleType;
24+
private static readonly Type doubleType;
25+
private static readonly Type int16Type;
26+
private static readonly Type int32Type;
27+
private static readonly Type int64Type;
28+
private static readonly Type boolType;
29+
private static readonly Type typeType;
3030

3131
static Converter()
3232
{
@@ -151,8 +151,7 @@ internal static NewReference ToPython(object? value, Type type)
151151

152152
// it the type is a python subclass of a managed type then return the
153153
// underlying python object rather than construct a new wrapper object.
154-
var pyderived = value as IPythonDerivedType;
155-
if (null != pyderived)
154+
if (value is IPythonDerivedType pyderived)
156155
{
157156
if (!IsTransparentProxy(pyderived))
158157
return ClassDerivedObject.ToPython(pyderived);
@@ -161,7 +160,7 @@ internal static NewReference ToPython(object? value, Type type)
161160
// ModuleObjects are created in a way that their wrapping them as
162161
// a CLRObject fails, the ClassObject has no tpHandle. Return the
163162
// pyHandle as is, do not convert.
164-
if (value is ModuleObject modobj)
163+
if (value is ModuleObject)
165164
{
166165
throw new NotImplementedException();
167166
}

src/runtime/DelegateManager.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ namespace Python.Runtime
1515
/// </summary>
1616
internal class DelegateManager
1717
{
18-
private readonly Dictionary<Type,Type> cache = new Dictionary<Type, Type>();
18+
private readonly Dictionary<Type,Type> cache = new();
1919
private readonly Type basetype = typeof(Dispatcher);
2020
private readonly Type arrayType = typeof(object[]);
2121
private readonly Type voidtype = typeof(void);
2222
private readonly Type typetype = typeof(Type);
2323
private readonly Type pyobjType = typeof(PyObject);
24-
private readonly CodeGenerator codeGenerator = new CodeGenerator();
24+
private readonly CodeGenerator codeGenerator = new();
2525
private readonly ConstructorInfo arrayCtor;
2626
private readonly MethodInfo dispatch;
2727

@@ -309,7 +309,7 @@ protected Dispatcher(PyObject target, Type dtype)
309309
{
310310
tpName += $" of size {Runtime.PyTuple_Size(op)}";
311311
}
312-
StringBuilder sb = new StringBuilder();
312+
var sb = new StringBuilder();
313313
if (!isVoid) sb.Append(rtype.FullName);
314314
for (int i = 0; i < pi.Length; i++)
315315
{

src/runtime/Exceptions.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,7 @@ public static bool SetError(Exception e)
196196
// might get a managed exception raised that is a wrapper for a
197197
// Python exception. In that case we'd rather have the real thing.
198198

199-
var pe = e as PythonException;
200-
if (pe != null)
199+
if (e is PythonException pe)
201200
{
202201
pe.Restore();
203202
return true;

src/runtime/Finalizer.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public ErrorArgs(Exception error)
4141
[DefaultValue(true)]
4242
public bool Enable { get; set; } = true;
4343

44-
private ConcurrentQueue<PendingFinalization> _objQueue = new();
44+
private readonly ConcurrentQueue<PendingFinalization> _objQueue = new();
4545
private readonly ConcurrentQueue<PendingFinalization> _derivedQueue = new();
4646
private readonly ConcurrentQueue<Py_buffer> _bufferQueue = new();
4747
private int _throttled;

src/runtime/InternString.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,7 @@ public static void Shutdown()
6161

6262
public static string? GetManagedString(BorrowedReference op)
6363
{
64-
string s;
65-
if (TryGetInterned(op, out s))
64+
if (TryGetInterned(op, out string s))
6665
{
6766
return s;
6867
}

src/runtime/Interop.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ internal static Type GetPrototype(MethodInfo method)
139139
}
140140

141141

142-
internal static Dictionary<IntPtr, Delegate> allocatedThunks = new Dictionary<IntPtr, Delegate>();
142+
internal static Dictionary<IntPtr, Delegate> allocatedThunks = new();
143143

144144
internal static ThunkInfo GetThunk(MethodInfo method)
145145
{

src/runtime/InteropConfiguration.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Python.Runtime
99
public sealed class InteropConfiguration: IDisposable
1010
{
1111
internal readonly PythonBaseTypeProviderGroup pythonBaseTypeProviders
12-
= new PythonBaseTypeProviderGroup();
12+
= new();
1313

1414
/// <summary>Enables replacing base types of CLR types as seen from Python</summary>
1515
public IList<IPythonBaseTypeProvider> PythonBaseTypeProviders => this.pythonBaseTypeProviders;

src/runtime/Loader.cs

+4-21
Original file line numberDiff line numberDiff line change
@@ -23,18 +23,8 @@ public unsafe static int Initialize(IntPtr data, int size)
2323
PythonDLL = null;
2424
}
2525

26-
var gs = PyGILState_Ensure();
27-
28-
try
29-
{
30-
// Console.WriteLine("Startup thread");
31-
PythonEngine.InitExt();
32-
// Console.WriteLine("Startup finished");
33-
}
34-
finally
35-
{
36-
PyGILState_Release(gs);
37-
}
26+
using var _ = Py.GIL();
27+
PythonEngine.InitExt();
3828
}
3929
catch (Exception exc)
4030
{
@@ -55,15 +45,8 @@ public unsafe static int Shutdown(IntPtr data, int size)
5545

5646
if (command == "full_shutdown")
5747
{
58-
var gs = PyGILState_Ensure();
59-
try
60-
{
61-
PythonEngine.Shutdown();
62-
}
63-
finally
64-
{
65-
PyGILState_Release(gs);
66-
}
48+
using var _ = Py.GIL();
49+
PythonEngine.Shutdown();
6750
}
6851
}
6952
catch (Exception exc)

src/runtime/MethodBinder.cs

+28-60
Original file line numberDiff line numberDiff line change
@@ -242,52 +242,24 @@ internal static int ArgPrecedence(Type t)
242242

243243
TypeCode tc = Type.GetTypeCode(t);
244244
// TODO: Clean up
245-
switch (tc)
245+
return tc switch
246246
{
247-
case TypeCode.Object:
248-
return 1;
249-
250-
case TypeCode.UInt64:
251-
return 10;
252-
253-
case TypeCode.UInt32:
254-
return 11;
255-
256-
case TypeCode.UInt16:
257-
return 12;
258-
259-
case TypeCode.Int64:
260-
return 13;
261-
262-
case TypeCode.Int32:
263-
return 14;
264-
265-
case TypeCode.Int16:
266-
return 15;
267-
268-
case TypeCode.Char:
269-
return 16;
270-
271-
case TypeCode.SByte:
272-
return 17;
273-
274-
case TypeCode.Byte:
275-
return 18;
276-
277-
case TypeCode.Single:
278-
return 20;
279-
280-
case TypeCode.Double:
281-
return 21;
282-
283-
case TypeCode.String:
284-
return 30;
285-
286-
case TypeCode.Boolean:
287-
return 40;
288-
}
289-
290-
return 2000;
247+
TypeCode.Object => 1,
248+
TypeCode.UInt64 => 10,
249+
TypeCode.UInt32 => 11,
250+
TypeCode.UInt16 => 12,
251+
TypeCode.Int64 => 13,
252+
TypeCode.Int32 => 14,
253+
TypeCode.Int16 => 15,
254+
TypeCode.Char => 16,
255+
TypeCode.SByte => 17,
256+
TypeCode.Byte => 18,
257+
TypeCode.Single => 20,
258+
TypeCode.Double => 21,
259+
TypeCode.String => 30,
260+
TypeCode.Boolean => 40,
261+
_ => 2000,
262+
};
291263
}
292264

293265
/// <summary>
@@ -410,18 +382,14 @@ public MismatchedMethod(Exception exception, MethodBase mb)
410382
isGeneric = true;
411383
}
412384
ParameterInfo[] pi = mi.GetParameters();
413-
ArrayList? defaultArgList;
414-
bool paramsArray;
415-
int kwargsMatched;
416-
int defaultsNeeded;
417385
bool isOperator = OperatorMethod.IsOperatorMethod(mi);
418386
// Binary operator methods will have 2 CLR args but only one Python arg
419387
// (unary operators will have 1 less each), since Python operator methods are bound.
420388
isOperator = isOperator && pynargs == pi.Length - 1;
421389
bool isReverse = isOperator && OperatorMethod.IsReverse((MethodInfo)mi); // Only cast if isOperator.
422390
if (isReverse && OperatorMethod.IsComparisonOp((MethodInfo)mi))
423391
continue; // Comparison operators in Python have no reverse mode.
424-
if (!MatchesArgumentCount(pynargs, pi, kwargDict, out paramsArray, out defaultArgList, out kwargsMatched, out defaultsNeeded) && !isOperator)
392+
if (!MatchesArgumentCount(pynargs, pi, kwargDict, out bool paramsArray, out ArrayList? defaultArgList, out int kwargsMatched, out int defaultsNeeded) && !isOperator)
425393
{
426394
continue;
427395
}
@@ -436,8 +404,7 @@ public MismatchedMethod(Exception exception, MethodBase mb)
436404
// We need to take the first CLR argument.
437405
pi = pi.Take(1).ToArray();
438406
}
439-
int outs;
440-
var margs = TryConvertArguments(pi, paramsArray, args, pynargs, kwargDict, defaultArgList, outs: out outs);
407+
var margs = TryConvertArguments(pi, paramsArray, args, pynargs, kwargDict, defaultArgList, outs: out int outs);
441408
if (margs == null)
442409
{
443410
var mismatchCause = PythonException.FetchCurrent();
@@ -495,7 +462,7 @@ public MismatchedMethod(Exception exception, MethodBase mb)
495462
{
496463
// Best effort for determining method to match on gives multiple possible
497464
// matches and we need at least one default argument - bail from this point
498-
StringBuilder stringBuilder = new StringBuilder("Not enough arguments provided to disambiguate the method. Found:");
465+
var stringBuilder = new StringBuilder("Not enough arguments provided to disambiguate the method. Found:");
499466
foreach (var matchedMethod in argMatchedMethods)
500467
{
501468
stringBuilder.AppendLine();
@@ -523,18 +490,20 @@ public MismatchedMethod(Exception exception, MethodBase mb)
523490
//CLRObject co = (CLRObject)ManagedType.GetManagedObject(inst);
524491
// InvalidCastException: Unable to cast object of type
525492
// 'Python.Runtime.ClassObject' to type 'Python.Runtime.CLRObject'
526-
var co = ManagedType.GetManagedObject(inst) as CLRObject;
527493

528494
// Sanity check: this ensures a graceful exit if someone does
529495
// something intentionally wrong like call a non-static method
530496
// on the class rather than on an instance of the class.
531497
// XXX maybe better to do this before all the other rigmarole.
532-
if (co == null)
498+
if (ManagedType.GetManagedObject(inst) is CLRObject co)
499+
{
500+
target = co.inst;
501+
}
502+
else
533503
{
534504
Exceptions.SetError(Exceptions.TypeError, "Invoked a non-static method with an invalid instance");
535505
return null;
536506
}
537-
target = co.inst;
538507
}
539508

540509
return new Binding(mi, target, margs, outs);
@@ -623,7 +592,7 @@ static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStar
623592
for (int paramIndex = 0; paramIndex < pi.Length; paramIndex++)
624593
{
625594
var parameter = pi[paramIndex];
626-
bool hasNamedParam = parameter.Name != null ? kwargDict.ContainsKey(parameter.Name) : false;
595+
bool hasNamedParam = parameter.Name != null && kwargDict.ContainsKey(parameter.Name);
627596

628597
if (paramIndex >= pyArgCount && !(hasNamedParam || (paramsArray && paramIndex == arrayStart)))
629598
{
@@ -658,8 +627,7 @@ static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStar
658627
}
659628
}
660629

661-
bool isOut;
662-
if (!TryConvertArgument(op, parameter.ParameterType, out margs[paramIndex], out isOut))
630+
if (!TryConvertArgument(op, parameter.ParameterType, out margs[paramIndex], out bool isOut))
663631
{
664632
tempObject.Dispose();
665633
return null;
@@ -789,7 +757,7 @@ static bool MatchesArgumentCount(int positionalArgumentCount, ParameterInfo[] pa
789757
{
790758
defaultArgList = null;
791759
var match = false;
792-
paramsArray = parameters.Length > 0 ? Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute)) : false;
760+
paramsArray = parameters.Length > 0 && Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute));
793761
kwargsMatched = 0;
794762
defaultsNeeded = 0;
795763
if (positionalArgumentCount == parameters.Length && kwargDict.Count == 0)

src/runtime/Native/BorrowedReference.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public IntPtr DangerousGetAddress()
1919
/// <summary>Gets a raw pointer to the Python object</summary>
2020
public IntPtr DangerousGetAddressOrNull() => this.pointer;
2121

22-
public static BorrowedReference Null => new BorrowedReference();
22+
public static BorrowedReference Null => new();
2323

2424
/// <summary>
2525
/// Creates new instance of <see cref="BorrowedReference"/> from raw pointer. Unsafe.

0 commit comments

Comments
 (0)