diff --git a/Src/IronPython.Modules/_thread.cs b/Src/IronPython.Modules/_thread.cs index 4bde8c6b5..e8df1f394 100644 --- a/Src/IronPython.Modules/_thread.cs +++ b/Src/IronPython.Modules/_thread.cs @@ -228,9 +228,9 @@ public void Start() { try { #pragma warning disable 618 // TODO: obsolete if (_kwargs != null) { - PythonOps.CallWithArgsTupleAndKeywordDictAndContext(_context, _func, ArrayUtils.EmptyObjects, ArrayUtils.EmptyStrings, _args, _kwargs); + PythonOps.CallWithArgsTupleAndKeywordDictAndContext(_context, _func, [], [], _args, _kwargs); } else { - PythonOps.CallWithArgsTuple(_func, ArrayUtils.EmptyObjects, _args); + PythonOps.CallWithArgsTuple(_func, [], _args); } #pragma warning restore 618 } catch (SystemExitException) { diff --git a/Src/IronPython/Compiler/Ast/ClassDefinition.cs b/Src/IronPython/Compiler/Ast/ClassDefinition.cs index 1b126d4fe..8c68fab0b 100644 --- a/Src/IronPython/Compiler/Ast/ClassDefinition.cs +++ b/Src/IronPython/Compiler/Ast/ClassDefinition.cs @@ -15,7 +15,6 @@ using IronPython.Runtime; using Microsoft.Scripting; -using Microsoft.Scripting.Actions; using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -403,7 +402,7 @@ public static string[] FindNames(FunctionDefinition function) { if (parameters.Count == 0) { // no point analyzing function with no parameters - return ArrayUtils.EmptyStrings; + return []; } var finder = new SelfNameFinder(function, parameters[0]); diff --git a/Src/IronPython/Compiler/Ast/FunctionDefinition.cs b/Src/IronPython/Compiler/Ast/FunctionDefinition.cs index edc452a27..36e74b0bb 100644 --- a/Src/IronPython/Compiler/Ast/FunctionDefinition.cs +++ b/Src/IronPython/Compiler/Ast/FunctionDefinition.cs @@ -5,21 +5,20 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Text; using System.Threading; -using System.Runtime.CompilerServices; - -using Microsoft.Scripting; -using Microsoft.Scripting.Interpreter; -using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; -using MSAst = System.Linq.Expressions; +using Microsoft.Scripting; +using Microsoft.Scripting.Interpreter; +using Microsoft.Scripting.Utils; -using LightLambdaExpression = Microsoft.Scripting.Ast.LightLambdaExpression; using AstUtils = Microsoft.Scripting.Ast.Utils; +using LightLambdaExpression = Microsoft.Scripting.Ast.LightLambdaExpression; +using MSAst = System.Linq.Expressions; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; @@ -85,8 +84,7 @@ internal override MSAst.Expression LocalContext { internal override int ArgCount { get { int argCount = 0; - for (argCount = 0; argCount < _parameters.Length; argCount++) - { + for (argCount = 0; argCount < _parameters.Length; argCount++) { Parameter p = _parameters[argCount]; if (p.IsDictionary || p.IsList || p.IsKeywordOnly) break; } @@ -256,7 +254,7 @@ internal override void Bind(PythonNameBinder binder) { NeedsLocalsDictionary = true; } } - + internal override void FinishBind(PythonNameBinder binder) { foreach (var param in _parameters) { _variableMapping[param.PythonVariable] = param.FinishBind(forceClosureCell: ExposesLocalVariable(param.PythonVariable)); @@ -286,7 +284,7 @@ public override MSAst.Expression Reduce() { new SourceSpan(GlobalParent.IndexToLocation(StartIndex), GlobalParent.IndexToLocation(HeaderIndex)) ); } - + /// /// Returns an expression which creates the function object. /// @@ -542,7 +540,7 @@ public override int Run(InterpretedFrame frame) { defaults[i] = frame.Pop(); } } else { - defaults = ArrayUtils.EmptyObjects; + defaults = []; } object modName; @@ -779,7 +777,7 @@ internal override IList GetVarNames() { return res; } - + private void InitializeParameters(List init, bool needsWrapperMethod, MSAst.Expression[] parameters) { for (int i = 0; i < _parameters.Length; i++) { Parameter p = _parameters[i]; @@ -829,10 +827,10 @@ private static Type GetDelegateType(Parameter[] parameters, bool wrapper, out De internal override void RewriteBody(MSAst.ExpressionVisitor visitor) { _dlrBody = null; // clear the cached body if we've been reduced - + MSAst.Expression funcCode = GlobalParent.Constant(GetOrMakeFunctionCode()); FuncCodeExpr = funcCode; - + Body = new RewrittenBodyStatement(Body, visitor.Visit(Body)); } diff --git a/Src/IronPython/Compiler/Ast/ScopeStatement.cs b/Src/IronPython/Compiler/Ast/ScopeStatement.cs index 28d571804..55ddbee69 100644 --- a/Src/IronPython/Compiler/Ast/ScopeStatement.cs +++ b/Src/IronPython/Compiler/Ast/ScopeStatement.cs @@ -92,7 +92,7 @@ public abstract class ScopeStatement : Statement { /// /// It is used to ensure that the first argument is accessible through a closure cell. /// - internal bool ContainsSuperCall{ get; set; } + internal bool ContainsSuperCall { get; set; } public virtual string Name => ""; @@ -116,7 +116,7 @@ public abstract class ScopeStatement : Statement { internal bool NeedsLocalContext => NeedsLocalsDictionary || ContainsNestedFreeVariables || ContainsSuperCall; - internal virtual string[] ParameterNames => ArrayUtils.EmptyStrings; + internal virtual string[] ParameterNames => []; internal virtual int ArgCount => 0; @@ -439,7 +439,7 @@ private PythonVariable CreateNonlocalVariable(string name) { } internal void EnsureNonlocalVariable(string name, NonlocalStatement node) { - _nonlocalVars ??= new(); + _nonlocalVars ??= new(); if (!_nonlocalVars.ContainsKey(name)) { CreateNonlocalVariable(name); _nonlocalVars[name] = node; @@ -611,7 +611,7 @@ internal MSAst.Expression? FuncCodeExpr { internal MSAst.MethodCallExpression CreateLocalContext(MSAst.Expression parentContext, bool newNamespace = true) { var closureVariables = _closureVariables ?? Array.Empty(); - + int numFreeVars = FreeVariables?.Count ?? 0; int firstArgIdx = -1; if ((NeedsLocalsDictionary || ContainsSuperCall) && ArgCount > 0) { diff --git a/Src/IronPython/Compiler/Parser.cs b/Src/IronPython/Compiler/Parser.cs index ddbf3b02e..9161912bd 100644 --- a/Src/IronPython/Compiler/Parser.cs +++ b/Src/IronPython/Compiler/Parser.cs @@ -804,7 +804,7 @@ private ModuleName ParseRelativeModuleName() { dotCount++; } - string[] names = ArrayUtils.EmptyStrings; + string[] names = []; if (PeekToken() is NameToken) { names = ReadNames(); } diff --git a/Src/IronPython/Runtime/Binding/WarningInfo.cs b/Src/IronPython/Runtime/Binding/WarningInfo.cs index 616ecd3af..b00e665c4 100644 --- a/Src/IronPython/Runtime/Binding/WarningInfo.cs +++ b/Src/IronPython/Runtime/Binding/WarningInfo.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using System; using System.Dynamic; using System.Linq.Expressions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; -using Microsoft.Scripting.Utils; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -29,7 +29,7 @@ public WarningInfo(PythonType/*!*/ type, string/*!*/ message, Expression conditi codeContext, AstUtils.Constant(_type), AstUtils.Constant(_message), - AstUtils.Constant(ArrayUtils.EmptyObjects) + AstUtils.Constant(Array.Empty()) ); if (_condition != null) { diff --git a/Src/IronPython/Runtime/BuiltinPythonModule.cs b/Src/IronPython/Runtime/BuiltinPythonModule.cs index 65e973fd6..3ba2fe8be 100644 --- a/Src/IronPython/Runtime/BuiltinPythonModule.cs +++ b/Src/IronPython/Runtime/BuiltinPythonModule.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; + using IronPython.Compiler; + using Microsoft.Scripting.Utils; namespace IronPython.Runtime { @@ -50,7 +51,7 @@ protected internal virtual void Initialize(CodeContext/*!*/ codeContext, Diction /// direct access to global members. /// protected internal virtual IEnumerable/*!*/ GetGlobalVariableNames() { - return ArrayUtils.EmptyStrings; + return []; } /// diff --git a/Src/IronPython/Runtime/Converter.cs b/Src/IronPython/Runtime/Converter.cs index 8dc38890d..e8e860457 100644 --- a/Src/IronPython/Runtime/Converter.cs +++ b/Src/IronPython/Runtime/Converter.cs @@ -532,7 +532,7 @@ public static bool CanConvertFrom(Type fromType, Type toType, NarrowingLevel all private static TypeConverter GetTypeConverter(TypeConverterAttribute tca) { try { ConstructorInfo ci = Type.GetType(tca.ConverterTypeName).GetConstructor(ReflectionUtils.EmptyTypes); - if (ci != null) return ci.Invoke(ArrayUtils.EmptyObjects) as TypeConverter; + if (ci != null) return ci.Invoke([]) as TypeConverter; } catch (TargetInvocationException) { } return null; diff --git a/Src/IronPython/Runtime/Exceptions/PythonExceptions.cs b/Src/IronPython/Runtime/Exceptions/PythonExceptions.cs index be0a8567d..8ff54a605 100644 --- a/Src/IronPython/Runtime/Exceptions/PythonExceptions.cs +++ b/Src/IronPython/Runtime/Exceptions/PythonExceptions.cs @@ -6,11 +6,8 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; -using System.Dynamic; using System.IO; -using System.Linq.Expressions; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; @@ -122,7 +119,7 @@ public override string ToString() { } public partial class _OSError { - public static new object __new__(PythonType cls, [ParamDictionary]IDictionary kwArgs, params object[] args) { + public static new object __new__(PythonType cls, [ParamDictionary] IDictionary kwArgs, params object[] args) { if (cls == OSError && args.Length >= 1 && args[0] is int errno) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (args.Length >= 4 && args[3] is int winerror) { @@ -223,8 +220,7 @@ private static Error ErrnoToErrorEnum(int errno) { } private static PythonType ErrnoToPythonType(Error errno) { - var res = errno switch - { + var res = errno switch { Error.EPERM => PermissionError, Error.ENOENT => FileNotFoundError, Error.ESRCH => ProcessLookupError, @@ -239,8 +235,7 @@ private static PythonType ErrnoToPythonType(Error errno) { _ => null }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - res ??= errno switch - { + res ??= errno switch { // Windows or remapped OSX Error.WSAEWOULDBLOCK => BlockingIOError, Error.WSAEINPROGRESS => BlockingIOError, @@ -253,8 +248,7 @@ private static PythonType ErrnoToPythonType(Error errno) { _ => null }; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - res ??= errno switch - { + res ??= errno switch { // Linux Error.ECONNABORTED => ConnectionAbortedError, Error.ECONNRESET => ConnectionResetError, @@ -529,7 +523,7 @@ internal static int WinErrorToErrno(int winerror) { } public partial class _ImportError { - public void __init__([ParamDictionary]IDictionary kwargs, params object[] args) { + public void __init__([ParamDictionary] IDictionary kwargs, params object[] args) { base.__init__(args); foreach (var pair in kwargs) { @@ -702,7 +696,7 @@ internal static BaseException CreateBaseExceptionForRaise(CodeContext/*!*/ conte if (PythonOps.IsInstance(value, type)) { pyEx = value; } else if (value is PythonTuple) { - pyEx = PythonOps.CallWithArgsTuple(type, ArrayUtils.EmptyObjects, value); + pyEx = PythonOps.CallWithArgsTuple(type, [], value); } else if (value != null) { pyEx = PythonCalls.Call(context, type, value); } else { diff --git a/Src/IronPython/Runtime/FunctionCode.cs b/Src/IronPython/Runtime/FunctionCode.cs index bbaef9e05..b0310185e 100644 --- a/Src/IronPython/Runtime/FunctionCode.cs +++ b/Src/IronPython/Runtime/FunctionCode.cs @@ -2,27 +2,26 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; -using Microsoft.Scripting.Ast; - using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; +using IronPython.Compiler; +using IronPython.Runtime.Operations; +using IronPython.Runtime.Types; + using Microsoft.Scripting; +using Microsoft.Scripting.Ast; using Microsoft.Scripting.Debugging.CompilerServices; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Compiler; -using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; - namespace IronPython.Runtime { /// /// Represents a piece of code. This can reference either a CompiledCode @@ -601,7 +600,7 @@ internal object Call(CodeContext/*!*/ context) { return optimizedModuleCode(this); } - var func = new PythonFunction(context, this, null, ArrayUtils.EmptyObjects, null, null, new MutableTuple()); + var func = new PythonFunction(context, this, null, [], null, null, new MutableTuple()); CallSite> site = context.LanguageContext.FunctionCallSite; return site.Target(site, context, func); } @@ -772,7 +771,7 @@ private LambdaExpression GetGeneratorOrNormalLambdaTracing(PythonContext context ); } - + /// /// Gets the correct final LambdaExpression for this piece of code. /// @@ -784,8 +783,8 @@ private LightLambdaExpression GetGeneratorOrNormalLambda() { finalCode = Code; } else { finalCode = Code.ToGenerator( - _lambda.ShouldInterpret, - _lambda.EmitDebugSymbols, + _lambda.ShouldInterpret, + _lambda.EmitDebugSymbols, _lambda.GlobalParent.PyContext.Options.CompilationThreshold ); } @@ -838,7 +837,7 @@ private Delegate CompileLambda(LambdaExpression code, EventHandler || + if (finalTarget is Func || finalTarget is Func || finalTarget is LookupCompilationDelegate) { // no recursion enforcement on classes or modules @@ -1185,7 +1184,6 @@ public Dictionary LoopOrFinallyIds { return _loopIds; } } - } } } diff --git a/Src/IronPython/Runtime/ModuleDictionaryStorage.cs b/Src/IronPython/Runtime/ModuleDictionaryStorage.cs index e4a7887ee..d94f78e48 100644 --- a/Src/IronPython/Runtime/ModuleDictionaryStorage.cs +++ b/Src/IronPython/Runtime/ModuleDictionaryStorage.cs @@ -6,11 +6,12 @@ using System.Collections.Generic; using System.Diagnostics; using System.Reflection; + using IronPython.Compiler; using IronPython.Runtime.Types; + using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; namespace IronPython.Runtime { /// @@ -162,7 +163,7 @@ private bool TryGetLazyValue(string name, bool publish, out object value) { var propInfo = (PropertyInfo)members[0]; if ((propInfo.GetGetMethod() ?? propInfo.GetSetMethod()).IsStatic) { - value = ((PropertyInfo)members[0]).GetValue(null, ArrayUtils.EmptyObjects); + value = ((PropertyInfo)members[0]).GetValue(null, []); } else { throw new InvalidOperationException("instance property declared on module. Propreties should be declared as static, marked as PythonHidden, or you should use a PythonGlobal."); } @@ -217,7 +218,7 @@ public override bool TryGetValue(object key, out object value) { return value != Uninitialized.Instance; } - if(key is string strKey) { + if (key is string strKey) { return TryGetLazyValue(strKey, out value); } diff --git a/Src/IronPython/Runtime/Operations/ArrayOps.cs b/Src/IronPython/Runtime/Operations/ArrayOps.cs index 0134db996..bed297686 100644 --- a/Src/IronPython/Runtime/Operations/ArrayOps.cs +++ b/Src/IronPython/Runtime/Operations/ArrayOps.cs @@ -10,11 +10,11 @@ using System.Diagnostics; using System.Text; +using IronPython.Runtime.Types; + using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Types; - using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Operations { @@ -291,7 +291,7 @@ public static string __repr__(CodeContext/*!*/ context, [NotNone] Array/*!*/ sel } internal static object?[] GetSlice(object?[] data, int start, int stop) { - if (stop <= start) return ArrayUtils.EmptyObjects; + if (stop <= start) return []; var ret = new object?[stop - start]; int index = 0; @@ -309,7 +309,7 @@ public static string __repr__(CodeContext/*!*/ context, [NotNone] Array/*!*/ sel } int size = PythonOps.GetSliceCount(start, stop, step); - if (size <= 0) return ArrayUtils.EmptyObjects; + if (size <= 0) return []; var res = new object?[size]; for (int i = 0, index = start; i < res.Length; i++, index += step) { @@ -330,7 +330,7 @@ internal static Array GetSlice(Array data, int size, Slice slice) { if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) { if (data.GetType().GetElementType() == typeof(object)) - return ArrayUtils.EmptyObjects; + return Array.Empty(); return Array.CreateInstance(data.GetType().GetElementType()!, 0); } @@ -352,7 +352,7 @@ internal static Array GetSlice(Array data, int size, Slice slice) { } internal static object?[] CopyArray(object?[] data, int newSize) { - if (newSize == 0) return ArrayUtils.EmptyObjects; + if (newSize == 0) return []; var newData = new object?[newSize]; if (data.Length < 20) { diff --git a/Src/IronPython/Runtime/Operations/InstanceOps.cs b/Src/IronPython/Runtime/Operations/InstanceOps.cs index 2b6c6578f..bae065063 100644 --- a/Src/IronPython/Runtime/Operations/InstanceOps.cs +++ b/Src/IronPython/Runtime/Operations/InstanceOps.cs @@ -2,22 +2,19 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; - using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; +using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; - -using IronPython.Runtime.Exceptions; -using IronPython.Runtime.Types; namespace IronPython.Runtime.Operations { /// @@ -107,7 +104,7 @@ public static object DefaultNew(CodeContext context, PythonType type\u00F8, para return type\u00F8.CreateInstance(context); } - public static object DefaultNewClsKW(CodeContext context, PythonType type\u00F8, [ParamDictionary]IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static object DefaultNewClsKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { object res = DefaultNew(context, type\u00F8, args\u00F8); if (kwargs\u00F8.Count > 0) { @@ -127,13 +124,13 @@ public static object OverloadedNewBasic(CodeContext context, SiteLocalStorage kwargs\u00F8) { + public static object OverloadedNewKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - return overloads\u00F8.Call(context, null, null, ArrayUtils.EmptyObjects, kwargs\u00F8); + return overloads\u00F8.Call(context, null, null, [], kwargs\u00F8); } - public static object OverloadedNewClsKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary]IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static object OverloadedNewClsKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); if (args\u00F8 == null) args\u00F8 = new object[1]; @@ -145,7 +142,7 @@ public static void DefaultInit(CodeContext context, object self, params object[] } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kwargs\u00F8"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args\u00F8")] - public static void DefaultInitKW(CodeContext context, object self, [ParamDictionary]IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static void DefaultInitKW(CodeContext context, object self, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] @@ -158,23 +155,23 @@ public static object NonDefaultNew(CodeContext context, PythonType type\u00F8, p [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] [StaticExtensionMethod] - public static object NonDefaultNewKW(CodeContext context, PythonType type\u00F8, [ParamDictionary]IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static object NonDefaultNewKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); if (args\u00F8 == null) args\u00F8 = new object[1]; - string []names; + string[] names; GetKeywordArgs(kwargs\u00F8, args\u00F8, out args\u00F8, out names); return type\u00F8.CreateInstance(context, args\u00F8, names); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] [StaticExtensionMethod] - public static object NonDefaultNewKWNoParams(CodeContext context, PythonType type\u00F8, [ParamDictionary]IDictionary kwargs\u00F8) { + public static object NonDefaultNewKWNoParams(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); string[] names; object[] args; - GetKeywordArgs(kwargs\u00F8, ArrayUtils.EmptyObjects, out args, out names); + GetKeywordArgs(kwargs\u00F8, [], out args, out names); return type\u00F8.CreateInstance(context, args, names); } diff --git a/Src/IronPython/Runtime/Operations/PythonTypeOps.cs b/Src/IronPython/Runtime/Operations/PythonTypeOps.cs index 9edf44394..a96a60892 100644 --- a/Src/IronPython/Runtime/Operations/PythonTypeOps.cs +++ b/Src/IronPython/Runtime/Operations/PythonTypeOps.cs @@ -5,11 +5,13 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Reflection; using System.Dynamic; using System.Linq; +using System.Reflection; + using IronPython.Runtime.Binding; using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; @@ -56,7 +58,7 @@ internal static string GetModuleName(CodeContext/*!*/ context, Type type) { } internal static object CallParams(CodeContext/*!*/ context, PythonType cls, params object[] args\u03c4) { - if (args\u03c4 == null) args\u03c4 = ArrayUtils.EmptyObjects; + if (args\u03c4 == null) args\u03c4 = []; return CallWorker(context, cls, args\u03c4); } @@ -83,7 +85,7 @@ internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, IDict argNames[i++ - args.Length] = kvp.Key; } - return CallWorker(context, dt, new KwCallInfo(allArgs, argNames)); + return CallWorker(context, dt, new KwCallInfo(allArgs, argNames)); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, KwCallInfo args) { @@ -114,7 +116,7 @@ private static object GetInitMethod(CodeContext/*!*/ context, PythonType dt, obj PythonType cdt = dt.ResolutionOrder[i]; PythonTypeSlot dts; object value; - + if (cdt.TryLookupSlot(context, "__init__", out dts) && dts.TryGetValue(context, newObject, dt, out value)) { return value; @@ -170,7 +172,7 @@ private static bool ShouldInvokeInit(PythonType cls, PythonType newObjectType, i // or if this is the user doing type(x), or if it's a standard // .NET type which doesn't have an __init__ method (this is a perf optimization) return (!cls.IsSystemType || cls.IsPythonType) && - newObjectType.IsSubclassOf(cls) && + newObjectType.IsSubclassOf(cls) && (cls != TypeCache.PythonType || argCnt > 1); } @@ -230,7 +232,7 @@ internal static TrackerTypes GetMemberType(MemberGroup members) { group = FilterNewSlots(group); TrackerTypes tt = GetMemberType(group); - switch(tt) { + switch (tt) { case TrackerTypes.Method: bool checkStatic = false; List mems = new List(); @@ -241,37 +243,37 @@ internal static TrackerTypes GetMemberType(MemberGroup members) { } Type declType = group[0].DeclaringType; - MemberInfo[] memArray = mems.ToArray(); + MemberInfo[] memArray = mems.ToArray(); FunctionType ft = GetMethodFunctionType(declType, memArray, checkStatic); return GetFinalSlotForFunction(GetBuiltinFunction(declType, group[0].Name, name, ft, memArray)); - + case TrackerTypes.Field: return GetReflectedField(((FieldTracker)group[0]).Field); - + case TrackerTypes.Property: - return GetReflectedProperty((PropertyTracker)group[0], group, privateBinding); - + return GetReflectedProperty((PropertyTracker)group[0], group, privateBinding); + case TrackerTypes.Event: return GetReflectedEvent(((EventTracker)group[0])); - + case TrackerTypes.Type: TypeTracker type = (TypeTracker)group[0]; for (int i = 1; i < group.Count; i++) { type = TypeGroup.UpdateTypeEntity(type, (TypeTracker)group[i]); } - + if (type is TypeGroup) { return new PythonTypeUserDescriptorSlot(type, true); } return new PythonTypeUserDescriptorSlot(DynamicHelpers.GetPythonTypeFromType(type.Type), true); - + case TrackerTypes.Constructor: return GetConstructorFunction(group[0].DeclaringType, privateBinding); - + case TrackerTypes.Custom: return ((PythonCustomTracker)group[0]).GetSlot(); - + default: // if we have a new slot in the derived class filter out the // members from the base class. @@ -311,7 +313,7 @@ private static BuiltinFunction GetConstructorFunction(Type t, bool privateBindin return GetConstructor(t, ctorFunc, ctors); } - + internal static MethodBase[] GetConstructors(Type t, bool privateBinding, bool includeProtected = false) { MethodBase[] ctors = CompilerHelpers.GetConstructors(t, privateBinding, includeProtected); if (t.IsEnum) { @@ -320,7 +322,8 @@ internal static MethodBase[] GetConstructors(Type t, bool privateBinding, bool i } return ctors; } - // support for EnumType(number) + + // support for EnumType(number) private static T CreateEnum(object value) { if (value == null) { throw PythonOps.ValueError( @@ -364,7 +367,7 @@ internal static BuiltinFunction GetConstructorFunction(Type type, string name) { methods.Add(ci); } } - + if (type.IsValueType && !hasDefaultConstructor && type != typeof(void)) { try { methods.Add(typeof(ScriptingRuntimeHelpers).GetMethod(nameof(ScriptingRuntimeHelpers.CreateInstance), ReflectionUtils.EmptyTypes).MakeGenericMethod(type)); @@ -480,7 +483,7 @@ public static MemberInfo[] GetNonBaseHelperMemberInfos(MemberInfo[] members) { BuiltinFunction res = null; if (mems.Length != 0) { - FunctionType ft = funcType ?? GetMethodFunctionType(type, mems); + FunctionType ft = funcType ?? GetMethodFunctionType(type, mems); type = GetBaseDeclaringType(type, mems); BuiltinFunctionKey cache = new BuiltinFunctionKey(type, new ReflectionCache.MethodBaseCache(cacheName, GetNonBaseHelperMethodInfos(mems)), ft); @@ -540,7 +543,7 @@ private static Type GetCommonBaseType(Type xType, Type yType) { private static Type GetBaseDeclaringType(Type type, MemberInfo/*!*/[] mems) { // get the base most declaring type, first sort the list so that // the most derived class is at the beginning. - Array.Sort(mems, delegate(MemberInfo x, MemberInfo y) { + Array.Sort(mems, delegate (MemberInfo x, MemberInfo y) { if (x.DeclaringType.IsSubclassOf(y.DeclaringType)) { return -1; } else if (y.DeclaringType.IsSubclassOf(x.DeclaringType)) { @@ -602,7 +605,7 @@ internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*! if (mi.IsStatic && mi.IsSpecialName) { ParameterInfo[] pis = mi.GetParameters(); - if ((pis.Length == 2 && pis[0].ParameterType != typeof(CodeContext)) || + if ((pis.Length == 2 && pis[0].ParameterType != typeof(CodeContext)) || (pis.Length == 3 && pis[0].ParameterType == typeof(CodeContext))) { ft |= FunctionType.BinaryOperator; @@ -658,7 +661,7 @@ private static bool IsMethodAlwaysVisible(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ } } else if (type.IsAssignableFrom(typeof(int))) { // GH #52 // only show methods defined outside of int - foreach (MethodInfo mi in methods) { + foreach (MethodInfo mi in methods) { Debug.Assert(!mi.DeclaringType.IsInterface || typeof(int).GetInterfaces().Contains(mi.DeclaringType)); if (PythonBinder.IsPythonSupportingType(mi.DeclaringType) || mi.DeclaringType.IsInterface || @@ -675,7 +678,7 @@ private static bool IsMethodAlwaysVisible(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ /// a function is static if it's a static .NET method and it's defined on the type or is an extension method /// with StaticExtensionMethod decoration. /// - private static bool IsStaticFunction(Type type, MethodInfo mi) { + private static bool IsStaticFunction(Type type, MethodInfo mi) { return mi.IsStatic && // method must be truly static !mi.IsDefined(typeof(WrapperDescriptorAttribute), false) && // wrapper descriptors are instance methods (mi.DeclaringType.IsAssignableFrom(type) || mi.IsDefined(typeof(StaticExtensionMethodAttribute), false)); // or it's not an extension method or it's a static extension method @@ -814,7 +817,7 @@ internal static ReflectedGetterSetter GetReflectedProperty(PropertyTracker pt, M _propertyCache[pt] = rp; return rp; - } + } } private static MethodInfo FilterProtectedGetterOrSetter(MethodInfo info, bool privateBinding) { @@ -884,7 +887,7 @@ internal static bool TryInvokeTernaryOperator(CodeContext context, object o, obj /// internal static PythonTuple EnsureBaseType(PythonTuple bases) { bool hasInterface = false; - foreach (object baseClass in bases) { + foreach (object baseClass in bases) { PythonType dt = baseClass as PythonType; if (!dt.UnderlyingSystemType.IsInterface) { diff --git a/Src/IronPython/Runtime/Operations/TypeGroupOps.cs b/Src/IronPython/Runtime/Operations/TypeGroupOps.cs index 19354664c..5aa615cc7 100644 --- a/Src/IronPython/Runtime/Operations/TypeGroupOps.cs +++ b/Src/IronPython/Runtime/Operations/TypeGroupOps.cs @@ -13,15 +13,14 @@ using Microsoft.Scripting; using Microsoft.Scripting.Actions; -using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Operations { public static class TypeGroupOps { public static string __repr__(TypeGroup self) { StringBuilder sb = new StringBuilder(" dict, params object[] args) { + public object __call__(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, params object[] args) { return PythonCalls.CallWithKeywordArgs(context, this, args, dict); } @@ -417,7 +417,7 @@ internal Exception BadKeywordArgumentError(int count) { } #endregion - + #region Custom member lookup operators IList IMembersList.GetMemberNames() { @@ -471,7 +471,7 @@ internal PythonDictionary EnsureDict() { } return _dict; } - + internal static int AddRecursionDepth(int change) { // ManagedThreadId starts at 1 and increases as we get more threads. // Therefore we keep track of a limited number of threads in an array @@ -523,8 +523,7 @@ internal override bool TryGetValue(CodeContext context, object instance, PythonT } [PythonType("cell")] - public sealed class ClosureCell : ICodeFormattable - { + public sealed class ClosureCell : ICodeFormattable { [PythonHidden] public object Value; diff --git a/Src/IronPython/Runtime/PythonList.cs b/Src/IronPython/Runtime/PythonList.cs index 6c491ba2f..a2a2b5e33 100644 --- a/Src/IronPython/Runtime/PythonList.cs +++ b/Src/IronPython/Runtime/PythonList.cs @@ -12,15 +12,14 @@ using System.Text; using System.Threading; +using IronPython.Runtime.Operations; +using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Exceptions; -using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; - using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime { @@ -156,7 +155,7 @@ public PythonList(CodeContext context, [NotNone] object sequence) { internal PythonList(int capacity) { if (capacity == 0) { - _data = ArrayUtils.EmptyObjects; + _data = []; } else { _data = new object[capacity]; } @@ -953,7 +952,7 @@ private void DoSort(CodeContext/*!*/ context, IComparer cmp, object? key, bool r try { // make the list appear empty for the duration of the sort... - _data = ArrayUtils.EmptyObjects; + _data = []; _size = 0; if (key != null) { diff --git a/Src/IronPython/Runtime/Types/NewTypeMaker.cs b/Src/IronPython/Runtime/Types/NewTypeMaker.cs index ab32c8de0..3b19916ce 100644 --- a/Src/IronPython/Runtime/Types/NewTypeMaker.cs +++ b/Src/IronPython/Runtime/Types/NewTypeMaker.cs @@ -6,20 +6,20 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; +using System.Dynamic; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using System.Dynamic; using System.Text; +using IronPython.Runtime.Binding; +using IronPython.Runtime.Operations; + using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Binding; -using IronPython.Runtime.Operations; - namespace IronPython.Runtime.Types { /// /// Python class hierarchy is represented using the __class__ field in the object. It does not @@ -44,7 +44,7 @@ internal sealed class NewTypeMaker { private FieldInfo _dictField; private FieldInfo _slotsField; private FieldInfo _explicitMO; - + private ILGen _cctor; private int _site; @@ -70,7 +70,7 @@ internal sealed class NewTypeMaker { private static readonly Dictionary>> _overriddenMethods = new Dictionary>>(); [MultiRuntimeAware] private static readonly Dictionary>> _overriddenProperties = new Dictionary>>(); - + private NewTypeMaker(NewTypeInfo typeInfo) { _baseType = typeInfo.BaseType; @@ -105,7 +105,7 @@ private NewTypeMaker(NewTypeInfo typeInfo) { // creation code return new NewTypeMaker(typeInfo).CreateNewType(); }); - + return ret; } @@ -118,7 +118,7 @@ public static void SaveNewTypes(string assemblyName, IList types) { MethodBuilder mb = tb.DefineMethod(_constructorMethodName, MethodAttributes.Public | MethodAttributes.Static, typeof(CachedNewTypeInfo[]), ReflectionUtils.EmptyTypes); ILGenerator ilg = mb.GetILGenerator(); - + // new CachedTypeInfo[types.Count] // we leave this on the stack (duping it) and storing into it. EmitInt(ilg, types.Count); @@ -127,7 +127,7 @@ public static void SaveNewTypes(string assemblyName, IList types) { foreach (var v in types) { NewTypeInfo nti = NewTypeInfo.GetTypeInfo(String.Empty, v); - + var typeInfos = new NewTypeMaker(nti).SaveType(ag, "Python" + _typeCount++ + "$" + nti.BaseType.Name); // prepare for storing the element into our final array @@ -138,14 +138,14 @@ public static void SaveNewTypes(string assemblyName, IList types) { // load the type ilg.Emit(OpCodes.Ldtoken, typeInfos.Key); - ilg.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); + ilg.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); // create the dictionary of special names ilg.Emit(OpCodes.Newobj, typeof(Dictionary).GetConstructor(Array.Empty())); foreach (var specialName in typeInfos.Value) { // dup dict ilg.Emit(OpCodes.Dup); - + // emit key ilg.Emit(OpCodes.Ldstr, specialName.Key); @@ -161,7 +161,7 @@ public static void SaveNewTypes(string assemblyName, IList types) { } // assign to dict - ilg.Emit(OpCodes.Call, typeof(Dictionary).GetMethod("set_Item")); + ilg.Emit(OpCodes.Call, typeof(Dictionary).GetMethod("set_Item")); } // emit the interface types (if any) @@ -412,13 +412,13 @@ private void OverrideConstructor(ConstructorInfo parentConstructor) { // parameter based attribute logic if (pi.IsDefined(typeof(ParamArrayAttribute), false)) { pb.SetCustomAttribute(new CustomAttributeBuilder( - typeof(ParamArrayAttribute).GetConstructor(ReflectionUtils.EmptyTypes), ArrayUtils.EmptyObjects)); + typeof(ParamArrayAttribute).GetConstructor(ReflectionUtils.EmptyTypes), [])); } else if (pi.IsDefined(typeof(ParamDictionaryAttribute), false)) { pb.SetCustomAttribute(new CustomAttributeBuilder( - typeof(ParamDictionaryAttribute).GetConstructor(ReflectionUtils.EmptyTypes), ArrayUtils.EmptyObjects)); + typeof(ParamDictionaryAttribute).GetConstructor(ReflectionUtils.EmptyTypes), [])); } else if (pi.IsDefined(typeof(BytesLikeAttribute), false)) { pb.SetCustomAttribute(new CustomAttributeBuilder( - typeof(BytesLikeAttribute).GetConstructor(ReflectionUtils.EmptyTypes), ArrayUtils.EmptyObjects)); + typeof(BytesLikeAttribute).GetConstructor(ReflectionUtils.EmptyTypes), [])); } if ((pi.Attributes & ParameterAttributes.HasDefault) != 0) { @@ -465,7 +465,7 @@ private void OverrideConstructor(ConstructorInfo parentConstructor) { MethodInfo init = typeof(PythonOps).GetMethod(nameof(PythonOps.InitializeUserTypeSlots)); il.EmitLoadArg(0); - + il.EmitLoadArg(typeArg); il.EmitCall(init); @@ -564,7 +564,7 @@ private bool NeedsPythonObject { private void ImplementDynamicObject() { // true if the user has explicitly included IDynamicMetaObjectProvider in the list of interfaces - bool explicitDynamicObject = false; + bool explicitDynamicObject = false; foreach (Type t in _interfaceTypes) { if (t == typeof(IDynamicMetaObjectProvider)) { explicitDynamicObject = true; @@ -634,7 +634,7 @@ private void ImplementDynamicObject() { il.Emit(OpCodes.Dup); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Beq, retNull); - + // store the local value il.Emit(OpCodes.Stloc_S, retVal.LocalIndex); @@ -644,7 +644,7 @@ private void ImplementDynamicObject() { // user returned null, fallback to base impl il.MarkLabel(retNull); il.Emit(OpCodes.Pop); - + // no override exists il.MarkLabel(noOverride); @@ -665,7 +665,7 @@ private void ImplementDynamicObject() { il.EmitLoadArg(0); // this il.EmitLoadArg(1); // parameter - + // baseMetaObject if (baseIdo) { InterfaceMapping imap = _baseType.GetInterfaceMap(typeof(IDynamicMetaObjectProvider)); @@ -736,7 +736,7 @@ private void ImplementIPythonObject() { il.Emit(OpCodes.Ret); _tg.DefineMethodOverride(impl, decl); } - + // Types w/ DynamicBaseType attribute still need new slots implementation _slotsField = _tg.DefineField(SlotsAndWeakRefFieldName, typeof(object[]), FieldAttributes.Public); @@ -805,7 +805,7 @@ private void ImplementProtectedFieldAccessors(Dictionary speci // we need to create public helper methods that expose them. These methods are // used by the IDynamicMetaObjectProvider implementation (in MetaUserObject) - foreach (FieldInfo fi in _baseType.GetInheritedFields(flattenHierarchy: true)) { + foreach (FieldInfo fi in _baseType.GetInheritedFields(flattenHierarchy: true)) { if (!fi.IsProtected()) { continue; } @@ -901,13 +901,13 @@ private void OverrideMethods(Type type, Dictionary specialName added[key] = mi; } } - + if (type.IsAbstract && !type.IsInterface) { // abstract types can define interfaces w/o implementations foreach (Type iface in type.GetInterfaces()) { InterfaceMapping mapping = type.GetInterfaceMap(iface); for (int i = 0; i < mapping.TargetMethods.Length; i++) { - + if (mapping.TargetMethods[i] == null) { MethodInfo mi = mapping.InterfaceMethods[i]; @@ -1150,7 +1150,7 @@ private LocalBuilder EmitBaseClassCallCheckForProperties(ILGen il, MethodInfo ba // we're accessing a property return callTarget; } - + private MethodBuilder CreateVTableGetterOverride(MethodInfo mi, string name) { MethodBuilder impl; ILGen il; @@ -1274,7 +1274,7 @@ private MethodBuilder CreateVTableMethodOverride(MethodInfo mi, string name) { DefineVTableMethodOverride(mi, out impl, out il); //CompilerHelpers.GetArgumentNames(parameters)); TODO: Set names - LocalBuilder callTarget = EmitNonInheritedMethodLookup(name, il); + LocalBuilder callTarget = EmitNonInheritedMethodLookup(name, il); Label instanceCall = il.DefineLabel(); il.Emit(OpCodes.Brtrue, instanceCall); @@ -1603,7 +1603,7 @@ private static void AddBaseMethods(Type finishedType, Dictionary GetOverriddenProperties(Type typ } #endregion - } } diff --git a/Src/IronPython/Runtime/Types/ParameterInfoWrapper.cs b/Src/IronPython/Runtime/Types/ParameterInfoWrapper.cs index 683eb1bd5..7330204e5 100644 --- a/Src/IronPython/Runtime/Types/ParameterInfoWrapper.cs +++ b/Src/IronPython/Runtime/Types/ParameterInfoWrapper.cs @@ -4,8 +4,6 @@ using System; using System.Reflection; -using Microsoft.Scripting.Utils; -using System.Collections.Generic; namespace Microsoft.Scripting.Generation { /// @@ -41,11 +39,11 @@ public override string Name { } public override object[] GetCustomAttributes(bool inherit) { - return ArrayUtils.EmptyObjects; + return []; } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return ArrayUtils.EmptyObjects; + return []; } } } diff --git a/Src/IronPython/Runtime/Types/PythonType.cs b/Src/IronPython/Runtime/Types/PythonType.cs index 77e70c573..e8c78ade8 100644 --- a/Src/IronPython/Runtime/Types/PythonType.cs +++ b/Src/IronPython/Runtime/Types/PythonType.cs @@ -504,7 +504,7 @@ public object __call__(CodeContext context, params object[] args) { return PythonTypeOps.CallParams(context, this, args); } - public object __call__(CodeContext context, [ParamDictionary]IDictionary kwArgs, params object[] args) { + public object __call__(CodeContext context, [ParamDictionary] IDictionary kwArgs, params object[] args) { return PythonTypeOps.CallWorker(context, this, kwArgs, args); } @@ -575,8 +575,8 @@ public object this[string member] { public static object Get__module__(CodeContext/*!*/ context, PythonType self) { PythonTypeSlot pts; object res; - if (self._dict != null && - self._dict.TryGetValue("__module__", out pts) && + if (self._dict != null && + self._dict.TryGetValue("__module__", out pts) && pts.TryGetValue(context, self, DynamicHelpers.GetPythonType(self), out res)) { return res; } @@ -638,7 +638,7 @@ public static void Set__qualname__(PythonType type, string name) { type.QualName = name; } - public static PythonDictionary __prepare__([ParamDictionary]IDictionary kwargs, params object[] args) + public static PythonDictionary __prepare__([ParamDictionary] IDictionary kwargs, params object[] args) => new PythonDictionary(); public string/*!*/ __repr__(CodeContext/*!*/ context) { @@ -789,13 +789,13 @@ internal IList ResolutionOrder { /// internal static PythonType/*!*/ GetPythonType(Type type) { object res; - + if (!_pythonTypes.TryGetValue(type, out res)) { lock (_pythonTypes) { if (!_pythonTypes.TryGetValue(type, out res)) { res = new PythonType(type); - _pythonTypes.Add(type, res); + _pythonTypes.Add(type, res); } } } @@ -873,7 +873,7 @@ internal object CreateInstance(CodeContext context, params object[] args) { case 1: return _instanceCtor.CreateInstance(context, args[0]); case 2: return _instanceCtor.CreateInstance(context, args[0], args[1]); case 3: return _instanceCtor.CreateInstance(context, args[0], args[1], args[2]); - default: + default: return _instanceCtor.CreateInstance(context, args); } } @@ -908,7 +908,7 @@ internal bool TryGetLength(CodeContext context, object o, out int length) { PythonTypeSlot lenSlot = _lenSlot; if (lenSlot == null && !PythonOps.TryResolveTypeSlot(context, this, "__len__", out lenSlot)) { length = 0; - return false; + return false; } object func; @@ -973,7 +973,7 @@ internal CallSite> HashSite { } private void EnsureHashSite() { - if(_hashSite == null) { + if (_hashSite == null) { Interlocked.CompareExchange( ref _hashSite, CallSite>.Create( @@ -1169,7 +1169,7 @@ internal bool IsHiddenMember(string name) { return !TryResolveSlot(DefaultContext.Default, name, out _) && TryResolveSlot(DefaultContext.DefaultCLS, name, out _); } - + internal LateBoundInitBinder GetLateBoundInitBinder(CallSignature signature) { Debug.Assert(!IsSystemType); // going to hold onto a PythonContext, shouldn't ever be a system type Debug.Assert(_pythonContext != null); @@ -1178,7 +1178,7 @@ internal LateBoundInitBinder GetLateBoundInitBinder(CallSignature signature) { Interlocked.CompareExchange(ref _lateBoundInitBinders, new Dictionary(), null); } - lock(_lateBoundInitBinders) { + lock (_lateBoundInitBinders) { LateBoundInitBinder res; if (!_lateBoundInitBinders.TryGetValue(signature, out res)) { _lateBoundInitBinders[signature] = res = new LateBoundInitBinder(this, signature); @@ -1242,7 +1242,7 @@ internal bool TryResolveSlot(CodeContext context, string name, out PythonTypeSlo if (UnderlyingSystemType.IsInterface) { return TypeCache.Object.TryResolveSlot(context, name, out slot); } - + slot = null; return false; @@ -1339,7 +1339,7 @@ internal static PythonTypeSlot ToTypeSlot(object value) { } // We could do more checks for things which aren't descriptors - if (value != null) { + if (value != null) { return new PythonTypeUserDescriptorSlot(value); } @@ -1484,7 +1484,7 @@ internal bool TryGetNonCustomMember(CodeContext context, object instance, string PythonDictionary dict = sdo.Dict; hasValue = dict != null && dict.TryGetValue(name, out value); - } + } // then check through all the descriptors. If we have a data // descriptor it takes priority over the value we found in the @@ -1497,7 +1497,7 @@ internal bool TryGetNonCustomMember(CodeContext context, object instance, string if (!hasValue || slot.IsSetDescriptor(context, this)) { if (slot.TryGetValue(context, instance, this, out object newValue)) value = newValue; - return true; + return true; } } } @@ -1611,7 +1611,7 @@ internal bool TrySetMember(CodeContext context, object instance, string name, ob } setAttrSite.Target(setAttrSite, context, setattr, instance, name, value); - return true; + return true; } return TrySetNonCustomMember(context, instance, name, value); @@ -1641,8 +1641,7 @@ internal bool TrySetNonCustomMember(CodeContext context, object instance, string if ((iac = sdo.SetDict(iac)) == null) { return false; } - } - else { + } else { return false; } } @@ -1852,14 +1851,14 @@ private void InitializeUserType(CodeContext/*!*/ context, string name, PythonTup // if we directly inherit from 2 types with slots then the indexes would // conflict so inheritance isn't allowed. int slotCount = pt.GetUsedSlotCount(); - + if (slotCount != 0) { if (hasSlots) { throw PythonOps.TypeError("multiple bases have instance lay-out conflict"); } hasSlots = true; } - + pt.AddSubType(this); } @@ -1918,7 +1917,7 @@ private void InitializeUserType(CodeContext/*!*/ context, string name, PythonTup bool isPythonType = false; foreach (ConstructorInfo ci in ctors) { ParameterInfo[] pis = ci.GetParameters(); - if((pis.Length > 1 && pis[0].ParameterType == typeof(CodeContext) && pis[1].ParameterType == typeof(PythonType)) || + if ((pis.Length > 1 && pis[0].ParameterType == typeof(CodeContext) && pis[1].ParameterType == typeof(PythonType)) || (pis.Length > 0 && pis[0].ParameterType == typeof(PythonType))) { isPythonType = true; break; @@ -1965,7 +1964,7 @@ internal IList GetTypeSlots() { if (_dict != null && _dict.TryGetValue("__slots__", out pts) && pts is PythonTypeUserDescriptorSlot) { return SlotsToList(((PythonTypeUserDescriptorSlot)pts).Value); } - return ArrayUtils.EmptyStrings; + return []; } internal static List GetSlots(PythonDictionary dict) { @@ -2034,7 +2033,7 @@ private void UpdateObjectNewAndInit(CodeContext context) { Debug.Assert(pt._objectInit != null && pt._objectNew != null); if (!pt._objectNew.Value) { - _objectNew = false; + _objectNew = false; } if (!pt._objectInit.Value) { @@ -2092,7 +2091,7 @@ private void PopulateDictionary(CodeContext/*!*/ context, string name, PythonTup if (slots != null) { slots.Remove("__classcell__"); _slots = slots.ToArray(); - + int index = _originalSlotCount; string typeName = IronPython.Compiler.Parser.GetPrivatePrefix(name); @@ -2118,7 +2117,7 @@ private void PopulateDictionary(CodeContext/*!*/ context, string name, PythonTup if (CheckForSlotWithDefault(context, _resolutionOrder, slots, "__dict__")) { _attrs |= PythonTypeAttributes.HasDictionary; bool inheritsDict = false; - for (int i = 1; i<_resolutionOrder.Count; i++) { + for (int i = 1; i < _resolutionOrder.Count; i++) { PythonType pt = _resolutionOrder[i]; if (pt.TryResolveSlot(context, "__dict__", out _)) { inheritsDict = true; @@ -2228,7 +2227,7 @@ private static void EnsureModule(CodeContext context, PythonDictionary dict) { } } } - + #endregion #region System type initialization @@ -2280,7 +2279,7 @@ private void AddSystemBases() { Type newType; if (TryReplaceExtensibleWithBase(curType, out newType)) { mro.Add(DynamicHelpers.GetPythonTypeFromType(newType)); - } else if(!curType.IsDefined(typeof(PythonHiddenBaseClassAttribute), false)) { + } else if (!curType.IsDefined(typeof(PythonHiddenBaseClassAttribute), false)) { mro.Add(DynamicHelpers.GetPythonTypeFromType(curType)); } curType = curType.BaseType; @@ -2317,7 +2316,7 @@ private void AddSystemInterfaces(List mro) { mro.Add(DynamicHelpers.GetPythonTypeFromType(typeof(ICollection))); mro.Add(DynamicHelpers.GetPythonTypeFromType(typeof(IEnumerable))); return; - } + } Type[] interfaces = _underlyingSystemType.GetInterfaces(); Dictionary methodMap = new Dictionary(); @@ -2326,7 +2325,7 @@ private void AddSystemInterfaces(List mro) { PythonType[] bases = new PythonType[_bases.Length + interfaces.Length]; Array.Copy(_bases, bases, _bases.Length); - for(int i = 0; i < interfaces.Length; i++) { + for (int i = 0; i < interfaces.Length; i++) { bases[i + _bases.Length] = PythonType.GetPythonType(interfaces[i]); } @@ -2354,11 +2353,11 @@ private void AddSystemInterfaces(List mro) { #endif InterfaceMapping mapping = _underlyingSystemType.GetInterfaceMap(iface); - + // grab all the interface methods which would hide other members for (int i = 0; i < mapping.TargetMethods.Length; i++) { MethodInfo target = mapping.TargetMethods[i]; - + if (target == null) { continue; } @@ -2394,7 +2393,7 @@ private void AddSystemInterfaces(List mro) { // no collisions so far... methodMap[iTarget.Name] = iface; } - } + } } } } @@ -2492,7 +2491,7 @@ private void EnsureDict() { null); } } - + /// /// Internal helper function to add a subtype /// @@ -2548,7 +2547,7 @@ private enum PythonTypeAttributes { /// The type has a ctor which does not accept PythonTypes. This is used /// for user defined types which implement __clrtype__ /// - SystemCtor = 0x20 + SystemCtor = 0x20 } #endregion @@ -2607,7 +2606,7 @@ internal WeakReferenceProxy(PythonContext context, PythonType type) { } public WeakRefTracker GetWeakRef() { - if(type.IsSystemType) { + if (type.IsSystemType) { return context.GetSystemPythonTypeWeakRef(type); } @@ -2616,7 +2615,7 @@ public WeakRefTracker GetWeakRef() { } public void SetFinalizer(WeakRefTracker value) { - if(type.IsSystemType) { + if (type.IsSystemType) { context.SetSystemPythonTypeFinalizer(type, value); } else { IWeakReferenceable weakref = (IWeakReferenceable)type; @@ -2625,10 +2624,10 @@ public void SetFinalizer(WeakRefTracker value) { } public bool SetWeakRef(WeakRefTracker value) { - if(type.IsSystemType) { + if (type.IsSystemType) { return context.SetSystemPythonTypeWeakRef(type, value); } - + IWeakReferenceable weakref = (IWeakReferenceable)type; return weakref.SetWeakRef(value); } @@ -2651,7 +2650,7 @@ public bool SetWeakRef(WeakRefTracker value) { /// internal WeakReference/*!*/ GetSharedWeakReference() { if (_weakRef == null) { - _weakRef = new WeakReference(this); + _weakRef = new WeakReference(this); } return _weakRef; @@ -2667,7 +2666,7 @@ T IFastSettable.MakeSetBinding(CallSite site, PythonSetMemberBinder binder if (!IsSystemType && !TryGetCustomSetAttr(Context.SharedContext, out _)) { CodeContext context = PythonContext.GetPythonContext(binder).SharedContext; string name = binder.Name; - + // optimized versions for possible literals that can show up in code. Type setType = typeof(T); if (setType == typeof(Func)) { @@ -2726,7 +2725,7 @@ internal class DebugProxy { public DebugProxy(PythonType type) { _type = type; } - + public PythonType[] __bases__ { get { return ArrayUtils.ToArray(_type.BaseTypes); @@ -2835,8 +2834,8 @@ public GetMemberDelegates(OptimizedGetKind getKind, PythonType type, PythonGetMe _fallback = fallback; _isNoThrow = binder.IsNoThrow; _extMethods = extMethods; - var optNames = type.GetOptimizedInstanceNames(); - + var optNames = type.GetOptimizedInstanceNames(); + switch (getKind) { case OptimizedGetKind.SlotDict: if (optNames != null) { @@ -2845,7 +2844,7 @@ public GetMemberDelegates(OptimizedGetKind getKind, PythonType type, PythonGetMe if (optNames != null && _dictIndex != -1) { _func = SlotDictOptimized; - _dictVersion = type.GetOptimizedInstanceVersion(); + _dictVersion = type.GetOptimizedInstanceVersion(); } else { _func = SlotDict; } @@ -2868,13 +2867,13 @@ public GetMemberDelegates(OptimizedGetKind getKind, PythonType type, PythonGetMe _func = UserSlotDictGetAttr; } else { _func = UserSlotDict; - } + } break; case OptimizedGetKind.UserSlotOnly: if (_getattrSlot != null) { _func = UserSlotOnlyGetAttr; } else { - _func = UserSlotOnly; + _func = UserSlotOnly; } break; default: throw new InvalidOperationException(); @@ -3098,7 +3097,7 @@ internal class SetMemberDelegates : FastSetBase { private readonly CodeContext _context; private readonly int _index, _keysVersion; - public SetMemberDelegates(CodeContext context, PythonType type, OptimizedSetKind kind, string name, int version, PythonTypeSlot slot, SlotSetValue slotFunc) + public SetMemberDelegates(CodeContext context, PythonType type, OptimizedSetKind kind, string name, int version, PythonTypeSlot slot, SlotSetValue slotFunc) : base(version) { _slot = slot; _name = name; @@ -3147,7 +3146,7 @@ public object SetDictOptimized(CallSite site, object self, TValue value) { return Update(site, self, value); } - + public object SetDict(CallSite site, object self, TValue value) { if (self is IPythonObject ipo && ipo.PythonType.Version == _version && ShouldUseNonOptimizedSite) { _hitCount++; @@ -3438,7 +3437,7 @@ public override bool Equals(CachedGetKey other) { if (!(other is CachedGetIdWeakRefExtensionMethod obj)) { return false; } - return obj._extMethodSet.Target == _extMethodSet.Target && + return obj._extMethodSet.Target == _extMethodSet.Target && obj.Name == Name; } diff --git a/Src/IronPython/Runtime/Types/ReflectedExtensionProperty.cs b/Src/IronPython/Runtime/Types/ReflectedExtensionProperty.cs index 8e879de9b..ced8d925a 100644 --- a/Src/IronPython/Runtime/Types/ReflectedExtensionProperty.cs +++ b/Src/IronPython/Runtime/Types/ReflectedExtensionProperty.cs @@ -4,7 +4,7 @@ using System; using System.Reflection; -using Microsoft.Scripting.Utils; + using IronPython.Runtime.Operations; namespace IronPython.Runtime.Types { @@ -29,14 +29,14 @@ internal override bool TryGetValue(CodeContext context, object instance, PythonT return false; } - value = CallGetter(context, null, instance, ArrayUtils.EmptyObjects); + value = CallGetter(context, null, instance, []); return true; } internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { if (Setter.Length == 0 || instance == null) return false; - return CallSetter(context, null, instance, ArrayUtils.EmptyObjects, value); + return CallSetter(context, null, instance, [], value); } internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { diff --git a/Src/IronPython/Runtime/Types/ReflectedProperty.cs b/Src/IronPython/Runtime/Types/ReflectedProperty.cs index 558b172a6..31017a1a7 100644 --- a/Src/IronPython/Runtime/Types/ReflectedProperty.cs +++ b/Src/IronPython/Runtime/Types/ReflectedProperty.cs @@ -2,21 +2,19 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; - using System; using System.Diagnostics; using System.Dynamic; +using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; +using IronPython.Runtime.Binding; +using IronPython.Runtime.Operations; + using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; -using Microsoft.Scripting.Utils; - -using IronPython.Runtime.Binding; -using IronPython.Runtime.Operations; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -55,7 +53,7 @@ internal override bool TrySetValue(CodeContext context, object instance, PythonT if (instance == null) { foreach (MethodInfo mi in Setter) { - if(mi.IsStatic && DeclaringType != owner.UnderlyingSystemType) { + if (mi.IsStatic && DeclaringType != owner.UnderlyingSystemType) { return false; } else if (mi.IsProtected()) { throw PythonOps.TypeErrorForProtectedMember(owner.UnderlyingSystemType, _info.Name); @@ -69,7 +67,7 @@ internal override bool TrySetValue(CodeContext context, object instance, PythonT } } - return CallSetter(context, context.LanguageContext.GetGenericCallSiteStorage(), instance, ArrayUtils.EmptyObjects, value); + return CallSetter(context, context.LanguageContext.GetGenericCallSiteStorage(), instance, [], value); } internal override Type DeclaringType { @@ -198,7 +196,7 @@ internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*! ).Expression, typeof(object) ) - ); + ); } }